body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I am using OpenCV 3.3 to implement a project. My project allows to detect pedestrian and car using background subtraction from video sequence which get from camera. First, I detect the object region and then apply blob tracking method to locate the location of the moving object individually.</p> <ol> <li>How to improve the tracking of any object as it is not able to track the object for a very long period of time.which means the same object is assigned with new tracking id.</li> </ol> <p>Could you see my code and give me some optimal way to make tracking better?</p> <pre><code>int main(void) { VideoCapture capVideo; Mat frame; std::vector&lt;Blob&gt; blobs; bool blnFirstFrame = true; int frameCount = 2; CvScalar color; Point center =Point(0,0); std::vector&lt;Blob&gt; currentFrameBlobs; Mat frameCopy; Mat imgFrame2Copy; VideoCapture cap("/home/pawan/Downloads/4.mp4"); if (!cap.isOpened()) // if not success, exit program { cout &lt;&lt; "Cannot open the video cam" &lt;&lt; endl; return -1; } double dWidth = cap.get(CV_CAP_PROP_FRAME_WIDTH); //get the width of frames of the video double dHeight = cap.get(CV_CAP_PROP_FRAME_HEIGHT); //get the height of frames of the video cout &lt;&lt; "Frame size : " &lt;&lt; dWidth &lt;&lt; " x " &lt;&lt; dHeight &lt;&lt; endl; while(1){ Mat frame; // Capture frame-by-frame cap &gt;&gt; frame; frameCopy = frame; // If the frame is empty, break immediately if (frame.empty()) break; Mat gray; setMouseCallback( "Output", onMouse, 0 ); if (startPoint == true and endPoint == true) { frame = draw_polylines(frame,dWidth,dHeight); cvtColor(frame, gray, CV_BGR2GRAY); equalizeHist(gray,gray); GaussianBlur(gray, gray, cvSize(21, 21), 0); if (bFirstFrame == false) { // cout &lt;&lt; "Refresh"&lt;&lt;endl; FirstFrame = gray; bFirstFrame = true; continue; } absdiff(FirstFrame, gray, FrameDelta); threshold(FrameDelta, thresh, 15, 255, THRESH_BINARY); dilate(thresh, thresh, structuringElement5x5); dilate(thresh, thresh, structuringElement5x5); erode(thresh, thresh, structuringElement5x5); imshow("thresh",thresh); std::vector&lt;std::vector&lt;cv::Point&gt; &gt; contours; findContours(thresh, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE); drawAndShowContours(thresh.size(), contours, "imgContours"); std::vector&lt;std::vector&lt;cv::Point&gt; &gt; convexHulls(contours.size()); for (unsigned int i = 0; i &lt; contours.size(); i++) { cv::convexHull(contours[i], convexHulls[i]); } drawAndShowContours(thresh.size(), convexHulls, "imgConvexHulls"); for (auto &amp;convexHull : convexHulls) { Blob possibleBlob(convexHull); if (possibleBlob.currentBoundingRect.area() &gt; 1000 ) { currentFrameBlobs.push_back(possibleBlob); text = "OCCUPIED"; if(c &gt; 0 ){ c--; fr = FastRefreshTime; }else{ c = RefreshTime; blnFirstFrame = false; fr = FastRefreshTime; } }else { text = "UNOCCUPIED"; if(fr &gt; 0){ fr --; c= RefreshTime; }else{ fr = FastRefreshTime ; blnFirstFrame = false; c= RefreshTime; currentFrameBlobs.clear(); } } } int intFontFace = CV_FONT_HERSHEY_SIMPLEX; double dblFontScale = 1; int intFontThickness = 2; cv::putText(frame, text,Point (10,40),intFontFace, dblFontScale, SCALAR_GREEN, intFontThickness); drawAndShowContours(thresh.size(), currentFrameBlobs, "imgCurrentFrameBlobs"); if (blnFirstFrame == true) { for (auto &amp;currentFrameBlob : currentFrameBlobs) { blobs.push_back(currentFrameBlob); } } else { matchCurrentFrameBlobsToExistingBlobs(blobs, currentFrameBlobs); } drawAndShowContours(thresh.size(), blobs, "imgBlobs"); imgFrame2Copy = frame.clone(); // get another copy of frame 2 since we changed the previous frame 2 copy in the processing above drawBlobInfoOnImage(blobs, frameCopy); bool blnAtLeastOneBlobCrossedTheLine = checkIfBlobsCrossedTheLine(blobs); if (blnAtLeastOneBlobCrossedTheLine == true) { cv::line(frame, startingPoint, endingPoint, SCALAR_BLACK, 2); } else { cv::line(frame, startingPoint, endingPoint, SCALAR_GREEN, 2); } // drawCarCountOnImage(carCount, frameCopy); frame = frameCopy.clone(); //frame = detect(frame,dWidth,dHeight); } cv::imshow("Output", frame); // now we prepare for the next iteration currentFrameBlobs.clear(); blnFirstFrame = false; frameCount++; char c=(char)waitKey(25); if(c==27) break; } // note that if the user did press esc, we don't need to hold the windows open, we can simply let the program end which will close the windows } void matchCurrentFrameBlobsToExistingBlobs(std::vector&lt;Blob&gt; &amp;existingBlobs, std::vector&lt;Blob&gt; &amp;currentFrameBlobs) { for (auto &amp;existingBlob : existingBlobs) { existingBlob.blnCurrentMatchFoundOrNewBlob = false; existingBlob.predictNextPosition(); } for (auto &amp;currentFrameBlob : currentFrameBlobs) { int intIndexOfLeastDistance = 0; double dblLeastDistance = 100.0; for (unsigned int i = 0; i &lt; existingBlobs.size(); i++) { if (existingBlobs[i].blnStillBeingTracked == true) { double dblDistance = distanceBetweenPoints(currentFrameBlob.centerPositions.back(), existingBlobs[i].predictedNextPosition); if (dblDistance &lt; dblLeastDistance) { dblLeastDistance = dblDistance; intIndexOfLeastDistance = i; } } } if (dblLeastDistance &lt; currentFrameBlob.dblCurrentDiagonalSize * 0.5) { addBlobToExistingBlobs(currentFrameBlob, existingBlobs, intIndexOfLeastDistance); } else { addNewBlob(currentFrameBlob, existingBlobs); } } for (auto &amp;existingBlob : existingBlobs) { if (existingBlob.blnCurrentMatchFoundOrNewBlob == false) { existingBlob.intNumOfConsecutiveFramesWithoutAMatch++; } if (existingBlob.intNumOfConsecutiveFramesWithoutAMatch &gt;= 10) { existingBlob.blnStillBeingTracked = false; } } } void addBlobToExistingBlobs(Blob &amp;currentFrameBlob, std::vector&lt;Blob&gt; &amp;existingBlobs, int &amp;intIndex) { existingBlobs[intIndex].currentContour = currentFrameBlob.currentContour; existingBlobs[intIndex].currentBoundingRect = currentFrameBlob.currentBoundingRect; existingBlobs[intIndex].centerPositions.push_back(currentFrameBlob.centerPositions.back()); existingBlobs[intIndex].dblCurrentDiagonalSize = currentFrameBlob.dblCurrentDiagonalSize; existingBlobs[intIndex].dblCurrentAspectRatio = currentFrameBlob.dblCurrentAspectRatio; existingBlobs[intIndex].blnStillBeingTracked = true; existingBlobs[intIndex].blnCurrentMatchFoundOrNewBlob = true; } /////////////////////////////////////////////////////////////////////////////////////////////////// void addNewBlob(Blob &amp;currentFrameBlob, std::vector&lt;Blob&gt; &amp;existingBlobs) { currentFrameBlob.blnCurrentMatchFoundOrNewBlob = true; existingBlobs.push_back(currentFrameBlob); } double distanceBetweenPoints(cv::Point point1, cv::Point point2) { int intX = abs(point1.x - point2.x); int intY = abs(point1.y - point2.y); return(sqrt(pow(intX, 2) + pow(intY, 2))); } /////////////////////////////////////////////////////////////////////////////////////////////////// void drawAndShowContours(cv::Size imageSize, std::vector&lt;std::vector&lt;cv::Point&gt; &gt; contours, std::string strImageName) { cv::Mat image(imageSize, CV_8UC3, SCALAR_BLACK); cv::drawContours(image, contours, -1, SCALAR_WHITE, -1); //cv::imshow(strImageName, image); } void drawAndShowContours(cv::Size imageSize, std::vector&lt;Blob&gt; blobs, std::string strImageName) { cv::Mat image(imageSize, CV_8UC3, SCALAR_BLACK); std::vector&lt;std::vector&lt;cv::Point&gt; &gt; contours; for (auto &amp;blob : blobs) { if (blob.blnStillBeingTracked == true) { contours.push_back(blob.currentContour); } } cv::drawContours(image, contours, -1, SCALAR_WHITE, -1); // cv::imshow(strImageName, image); } bool checkIfBlobsCrossedTheLine(std::vector&lt;Blob&gt; &amp;blobs) { bool blnAtLeastOneBlobCrossedTheLine = false; for (auto blob : blobs) { if (blob.blnStillBeingTracked == true &amp;&amp; blob.centerPositions.size() &gt;= 2) { int prevFrameIndex = (int)blob.centerPositions.size() - 2; int currFrameIndex = (int)blob.centerPositions.size() - 1; // if (text == "Occupied") { if (fenceSide == "left") { //the object detected object is passing from outer area to inner area of the fence so action need to be taken //the object detected object is passing from inner area to outer area of the fence no action has to taken if (blob.centerPositions[prevFrameIndex].x &gt; startingPoint.x &amp;&amp; blob.centerPositions[currFrameIndex].x &lt;= startingPoint.x &amp;&amp; blob.centerPositions[currFrameIndex].y &gt; startingPoint.y &amp;&amp; blob.centerPositions[prevFrameIndex].y &gt; startingPoint.y) { status = "Intruder Alert!Alarm is triggered"; cout &lt;&lt; status &lt;&lt; endl; blob.lastDetectStatus = blob.detectArea; blnAtLeastOneBlobCrossedTheLine = true; // bAlarm = true; } else if (blob.centerPositions[prevFrameIndex].x &lt; startingPoint.x &amp;&amp; blob.centerPositions[currFrameIndex].x &gt;= startingPoint.x &amp;&amp; blob.centerPositions[currFrameIndex].y &gt; startingPoint.y &amp;&amp; blob.centerPositions[prevFrameIndex].y &gt; startingPoint.y) { status = "No Intruder alert"; cout &lt;&lt; status &lt;&lt; endl; blob.lastDetectStatus = blob.detectArea; } //Detection in the inner area if (blob.centerPositions[prevFrameIndex].x &lt; startingPoint.x &amp;&amp; blob.centerPositions[currFrameIndex].x &lt;= startingPoint.x &amp;&amp; blob.centerPositions[currFrameIndex].y &gt; startingPoint.y &amp;&amp; blob.centerPositions[prevFrameIndex].y &gt; startingPoint.y) { status = "Detected object is in inner Area"; cout &lt;&lt; status &lt;&lt; endl; blob.detectArea = "inner"; } else if (blob.centerPositions[prevFrameIndex].x &gt; endingPoint.x &amp;&amp; blob.centerPositions[currFrameIndex].x &gt;= endingPoint.x &amp;&amp; blob.centerPositions[currFrameIndex].y &gt; startingPoint.y &amp;&amp; blob.centerPositions[prevFrameIndex].y &gt; startingPoint.y) { status = "Detected object is in outer Area"; cout &lt;&lt; status &lt;&lt; endl; blob.detectArea = "outer"; // bPrealarm = true; } if (blob.lastDetectStatus == "") { blob.lastDetectStatus = blob.detectArea; } } else if (fenceSide == "right") { if (blob.centerPositions[prevFrameIndex].x &lt; startingPoint.x &amp;&amp; blob.centerPositions[currFrameIndex].x &gt;= startingPoint.x &amp;&amp; blob.centerPositions[currFrameIndex].y &gt; startingPoint.y &amp;&amp; blob.centerPositions[prevFrameIndex].y &gt; startingPoint.y) { status = "Intruder Alert!Alarm is triggered"; cout &lt;&lt; status &lt;&lt; endl; blob.lastDetectStatus = blob.detectArea; blnAtLeastOneBlobCrossedTheLine = true; // bAlarm = true; } //the object detected object is passing from inner area to outer area of the fence no action has to taken else if (blob.centerPositions[prevFrameIndex].x &gt; startingPoint.x &amp;&amp; blob.centerPositions[currFrameIndex].x &lt;= startingPoint.x &amp;&amp; blob.centerPositions[currFrameIndex].y &gt; startingPoint.y &amp;&amp; blob.centerPositions[prevFrameIndex].y &gt; startingPoint.y) status = "No Intruder alert"; cout &lt;&lt; status &lt;&lt; endl; blob.lastDetectStatus = blob.detectArea; //Detection in the inner area if (blob.centerPositions[prevFrameIndex].x &gt; endingPoint.x &amp;&amp; blob.centerPositions[currFrameIndex].x &gt;= endingPoint.x &amp;&amp; blob.centerPositions[currFrameIndex].y &gt; startingPoint.y &amp;&amp; blob.centerPositions[prevFrameIndex].y &gt; startingPoint.y) { status = "Detected object is in inner Area"; cout &lt;&lt; status &lt;&lt; endl; blob.detectArea = "inner"; } //#Detection in the outer area else if (blob.centerPositions[prevFrameIndex].x &lt; startingPoint.x &amp;&amp; blob.centerPositions[currFrameIndex].x &lt;= startingPoint.x &amp;&amp; blob.centerPositions[currFrameIndex].y &gt; startingPoint.y &amp;&amp; blob.centerPositions[prevFrameIndex].y &gt; startingPoint.y) { status = "Detected object is in outer Area"; cout &lt;&lt; status &lt;&lt; endl; blob.detectArea = "outer"; //bPrealarm = true; } if (blob.lastDetectStatus == "") { blob.lastDetectStatus = blob.detectArea; } } else if (fenceSide == "Horizontal") { if (blob.centerPositions[prevFrameIndex].y &gt; startingPoint.y &amp;&amp; blob.centerPositions[currFrameIndex].y &lt;= startingPoint.y) { status = "Intruder Alert!Alarm is triggered"; cout &lt;&lt; status &lt;&lt; endl; blob.lastDetectStatus = blob.detectArea; blnAtLeastOneBlobCrossedTheLine = true; // bAlarm = true; } //the object detected object is passing from inner area to outer area of the fence no action has to taken else if (blob.centerPositions[prevFrameIndex].y &lt; startingPoint.y &amp;&amp; blob.centerPositions[currFrameIndex].y &gt;= startingPoint.y) { status = "No Intruder alert"; cout &lt;&lt; status &lt;&lt; endl; blob.lastDetectStatus = blob.detectArea; }//Detection in the inner area if (blob.centerPositions[prevFrameIndex].y &gt; startingPoint.y &amp;&amp; blob.centerPositions[currFrameIndex].y &gt;= startingPoint.y) { status = "Detected object is in inner Area"; cout &lt;&lt; status &lt;&lt; endl; blob.detectArea = "inner"; } else if (blob.centerPositions[prevFrameIndex].y &lt; startingPoint.y &amp;&amp; blob.centerPositions[currFrameIndex].y &lt;= startingPoint.y) { status = "Detected object is in outer Area"; cout &lt;&lt; status &lt;&lt; endl; blob.detectArea = "outer"; // bPrealarm = true; } if (blob.lastDetectStatus == "") { blob.lastDetectStatus = blob.detectArea; } } } /* if (blob.centerPositions[prevFrameIndex].y &gt; intHorizontalLinePosition &amp;&amp; blob.centerPositions[currFrameIndex].y &lt;= intHorizontalLinePosition) { carCount++; blnAtLeastOneBlobCrossedTheLine = true; }*/ } return blnAtLeastOneBlobCrossedTheLine; } void drawBlobInfoOnImage(std::vector&lt;Blob&gt; &amp;blobs, cv::Mat &amp;imgFrame2Copy) { for (unsigned int i = 0; i &lt; blobs.size(); i++) { if (blobs[i].blnStillBeingTracked == true) { cv::rectangle(imgFrame2Copy, blobs[i].currentBoundingRect, SCALAR_RED, 2); int intFontFace = CV_FONT_HERSHEY_SIMPLEX; double dblFontScale = 1; int intFontThickness = 1; //(int)std::round(dblFontScale * 1.0); cv::putText(imgFrame2Copy, std::to_string(i), blobs[i].centerPositions.back(), intFontFace, dblFontScale, SCALAR_GREEN, intFontThickness); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T22:04:49.840", "Id": "395158", "Score": "0", "body": "`if(c > 0 ){` ... `}else{` ... `}else {` ... `cv::putText(frame, text,Point (` ... what editor/IDE are you using? Don't get me wrong, but the effort you get is often proportional...
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T10:55:52.313", "Id": "204761", "Score": "2", "Tags": [ "c++", "opencv" ], "Title": "Real time object Detection and tracking" }
204761
<p>The below script detects whether we are in Jira, and if it is run in Jira it will add a button. Clicking that button will use the REST API of Jira to create an issue, and navigate to the recently created issue.</p> <pre><code>// ==UserScript== // @name Tell Jira I did a thing // @namespace http://demuyt.net/ // @version 0.1 // @description try to take over the world! // @author Tom J Demuyt // @match https://jira* // @match https://jira.it.aenetworks.com/* // @grant none // ==/UserScript== //Documentation //https://docs.atlassian.com/software/jira/docs/api/REST/7.12.0/ //https://developer.atlassian.com/server/jira/platform/jira-rest-api-examples/ (function() { 'use strict'; let userName = ""; let projectCode = "CF"; let fixVersion = "15484"; //The id of the create button is `create_link`, dont show up if that button is not there let createButton = document.getElementById('create_link'); //Leave quietly if we cannot find that button if(!createButton){ return; } //Get the parent (&lt;ul&gt;) of the &lt;li&gt; that holds the &lt;a&gt; let createButtonParent = createButton.parentNode.parentNode; //Add a button for the user var node = document.createElement("LI"); node.innerHTML = '&lt;li style="padding-left: 20px; text-decoration: underline; cursor: pointer;"&gt;&lt;div id="idat"&gt;Log activity&lt;/div&gt;&lt;/li&gt;'; createButtonParent.appendChild(node); //Get a reference to the button let idat = document.getElementById("idat"); //Make it listen to clicks; idat.addEventListener("click", recordTheThing); //Try and build a ticket function recordTheThing(){ //Prep a call to Jira let xhr = new XMLHttpRequest(), url = '/rest/api/2/issue/'; //Ask what the user did var thing = window.prompt("Describe the activity performed?",""); //Get out if the user got cold feet if(!thing){ return; } //Start prepping the http request xhr.open('POST', url, true); //Use JSON since we will not fill in a form xhr.setRequestHeader("Content-Type", "application/json"); //Prep the navigation to the new issue xhr.onreadystatechange = function () { debugger; //readyState:3 //response: {"id":"125529","key":"CF-10282","self":"https://jira.it.aenetworks.com/rest/api/2/issue/125529"} //HTTP/REST return code 201 means created if (xhr.readyState === 4 &amp;&amp; xhr.status === 201) { var json = JSON.parse(xhr.responseText); window.location.href = 'https://jira.it.aenetworks.com/browse/' + json.key; } }; //The heart of the thing var data = JSON.stringify({ "fields": { "project": { "key": projectCode }, "summary": thing, "description": thing, "issuetype": { "name": "Task" }, "assignee": { "name": userName }, //15484 -&gt; Busines As Usual "fixVersions": [{ "id": fixVersion}], } }); //Finalize the REST call xhr.send(data); }//Record the thing //Find from the load/start the user id let xhr = new XMLHttpRequest(), url = '/rest/api/2/mypermissions/'; //Prep to extract the username from the call header //200 -&gt; OK xhr.onreadystatechange = function () { if(xhr.readyState == 4 &amp;&amp; xhr.status == 200){ userName = xhr.getResponseHeader("X-AUSERNAME"); } } //Shoot and pray xhr.open('GET', url, true); xhr.send(); })(); </code></pre> <p>Please review for cleanliness, readability, standards, the usual..</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T13:26:56.720", "Id": "394938", "Score": "0", "body": "To begin with... you're separating your `let` statements with comments, even though comments don't break anything." } ]
[ { "body": "<p>The code is well commented. The indentation in most places seems to be four spaces but the last few lines have indentation of two spaces so that could be made more consistent. The last comment is a bit humorous...</p>\n\n<p>It seems that if the button isn't found by the id attribute, it just bails...
{ "AcceptedAnswerId": "204857", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T12:19:24.570", "Id": "204768", "Score": "2", "Tags": [ "javascript", "ecmascript-6", "userscript" ], "Title": "TamperMonkey script to add a button to Jira" }
204768
<p>I was solving <a href="https://www.codechef.com/problems/PSPLIT" rel="nofollow noreferrer">this problem</a> in Python3 on the Codechef website. Here I've to split an array such that the absolute difference between the maximum of both the arrays is maximum.</p> <p>For example, if the input array is [1, 3, -3] then it can be split in two ways:</p> <p><strong>Way-1:</strong></p> <p>[1] and [3,-3] --> Absolute difference between max of arrays is 3-1 = 2</p> <p><strong>Way-2:</strong></p> <p>[1,3] and [-3] --> Absolute difference between max of arrays is 3 - (-3) = 6</p> <p>So the max difference is 6, which is the answer.</p> <p>Below is my code:</p> <pre><code>def max_difference(a): max_diff = 0 for i in range(len(a) -1): local_diff = abs(max(a[:i+1]) - max(a[i+1:])) if max_diff &lt; local_diff: max_diff = local_diff return max_diff if __name__ == '__main__': arr_count = int(input()) arr = list(map(int, input().rstrip().split())) res = max_difference(arr) print(res) </code></pre> <p>Can you please tell me if this code fine? What improvements can be done? </p>
[]
[ { "body": "<pre><code>local_diff = abs(max(a[:i+1]) - max(a[i+1:]))\n</code></pre>\n\n<p>For every i the entire aray is walked through to find left and right maxima.\nThis is complexity <strong>O(N²)</strong>.</p>\n\n<p>One could have two arrays with left_maxima and right_maxima, <strong>O(N)</strong>, so</p>\n...
{ "AcceptedAnswerId": "204783", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T13:41:56.433", "Id": "204772", "Score": "3", "Tags": [ "python", "python-3.x", "programming-challenge" ], "Title": "Make a perfect Split based on absolute difference between max of two arrays" }
204772
<p>The link is to the example sheet of what I have done</p> <p>This code solves the problem of shifting large amounts of specific data in a google spreadsheet. The data is shifted to the right by one column, but only the data containing the specified substring (in this case, "PO"). It is intended to shift the leftmost row over by one column.</p> <p><a href="https://docs.google.com/spreadsheets/d/12w4rGArGi1I1wlpm5yJJtT5AAlMM4LcZC31_DpP6jZQ/edit?usp=sharing" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/12w4rGArGi1I1wlpm5yJJtT5AAlMM4LcZC31_DpP6jZQ/edit?usp=sharing</a></p> <p>I shifted the rows that contain "PO" in my data selection. (see shift function)</p> <p>It was suggested to me that I use array functions to made the code better, but I am honestly not sure how to refactor it. I am still very much a beginner.</p> <p>I'm guessing I can more easily do this instead of trying to reassign array index values.</p> <p>Here is my current script:</p> <pre><code>function shift() { try{ var ss = SpreadsheetApp.getActiveSpreadsheet(); var as = ss.getActiveSheet(); var ar = as.getActiveRange(); var vals = ar.getValues(); var r; //variable for rows // in this first section, I've already stored the active range (my selection) into a two dimensional array. for (r = 0; r &lt; vals.length; r++){ // for each row, up to the last row (iterate over all rows from top to bottom) if((vals[r][0].indexOf("PO") != -1)||(vals[r][0].indexOf("P0") != -1)){ // if first column in each row contains "PO" var c; // variable for columns var cols = []; // array to store all data temporarily (will be uses to set new values later) for (c = 0; c &lt; vals[r].length; c++){ // then iterate over each column(cell) in the row if(c == 0){ // if it is the first row, cols[c+1] = vals[r][c]; // assign second index of the array with the PO value (to simulate a shift) cols[c] = ""; // assign the first index of the array a blank string } else{ // if it is not the first row cols[c+1] = vals[r][c]; // assign each additional column value to the next index (+1) of the array } } for (c = 0; c &lt; vals[r].length; c++){ // once the array is finished, loop through the columns again foreach row vals[r][c] = cols[c]; // this time, assigning the new values to the corresponding array indices } } } ar.setValues(vals); // now, set the values that you reassinged to the array } catch(err){ SpreadsheetApp.getUi().alert(err); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T14:25:51.060", "Id": "394944", "Score": "0", "body": "Welcome to Code Review! Your question is missing something important: what does your code do? As in, what problem does it solve?" }, { "ContentLicense": "CC BY-SA 4.0", ...
[ { "body": "<p>Just as a general note, you could avoid the temporary array by copying the array from the end. I would also use a temporary variable for simplicity:</p>\n\n<pre><code>for (r = 0; r &lt; vals.length; r++) { \n var row = vals[r], first=row[0];\n if(first.indexOf(\"PO\") != -1)||first.indexOf(\"P...
{ "AcceptedAnswerId": "204785", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T14:12:26.250", "Id": "204778", "Score": "0", "Tags": [ "javascript", "google-apps-script", "google-sheets" ], "Title": "Google Apps Script shifting columns containing specified substring - using array functions" }
204778
<p>I recently did <a href="https://github.com/NickGowdy/Refactor-Exercise/tree/28765df04fc366daa37c13df41eefe5594b3bf23" rel="nofollow noreferrer">a programming exercise for a company</a> which I didn't pass. I didn't get any good feedback from my test so I wanted some advice/opinions for what I did wrong and what I could have done better. I had to refactor this class:</p> <blockquote> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace App { public class CustomerService { public bool AddCustomer(string firname, string surname, string email, DateTime dateOfBirth, int companyId) { if (string.IsNullOrEmpty(firname) || string.IsNullOrEmpty(surname)) { return false; } if (!email.Contains("@") &amp;&amp; !email.Contains(".")) { return false; } var now = DateTime.Now; int age = now.Year - dateOfBirth.Year; if (now.Month &lt; dateOfBirth.Month || (now.Month == dateOfBirth.Month &amp;&amp; now.Day &lt; dateOfBirth.Day)) age--; if (age &lt; 21) { return false; } var companyRepository = new CompanyRepository(); var company = companyRepository.GetById(companyId); var customer = new Customer { Company = company, DateOfBirth = dateOfBirth, EmailAddress = email, Firstname = firname, Surname = surname }; if (company.Name == "VeryImportantClient") { // Skip credit check customer.HasCreditLimit = false; } else if (company.Name == "ImportantClient") { // Do credit check and double credit limit customer.HasCreditLimit = true; using (var customerCreditService = new CustomerCreditServiceClient()) { var creditLimit = customerCreditService.GetCreditLimit(customer.Firstname, customer.Surname, customer.DateOfBirth); creditLimit = creditLimit*2; customer.CreditLimit = creditLimit; } } else { // Do credit check customer.HasCreditLimit = true; using (var customerCreditService = new CustomerCreditServiceClient()) { var creditLimit = customerCreditService.GetCreditLimit(customer.Firstname, customer.Surname, customer.DateOfBirth); customer.CreditLimit = creditLimit; } } if (customer.HasCreditLimit &amp;&amp; customer.CreditLimit &lt; 500) { return false; } CustomerDataAccess.AddCustomer(customer); return true; } } } </code></pre> </blockquote> <p>Also there is the caveat that you cannot change their test harness file:</p> <blockquote> <pre><code>using System; using App; namespace Harness { public class Customer { public static void ProveAddCustomer(string[] args) { /* * You MUST NOT change this code. This is an existing consumer of the CustomerService and you must maintain * backwards compatibility. */ var custService = new CustomerService(); var addResult = custService.AddCustomer("Joe", "Bloggs", "joe.bloggs@adomain.com", new DateTime(1980, 3, 27), 4); Console.WriteLine("Adding Joe Bloggs was " + (addResult ? "successful" : "unsuccessful")); } } } </code></pre> </blockquote> <p>This is what I did:</p> <pre><code>using System; using System.Text.RegularExpressions; using App.DataAccess; using App.Entities; using App.Repositories; namespace App.Services { public class CustomerService { public virtual bool AddCustomer(string firstName, string surname, string email, DateTime dateOfBirth, int companyId) { // Validate customer fields before going further if (!IsValidCustomerHelper(firstName, surname, email, dateOfBirth)) return false; var company = GetCustomerCompanyHelper(companyId); var customer = new Customer { Company = company, DateOfBirth = dateOfBirth, EmailAddress = email, Firstname = firstName, Surname = surname }; SetCreditValuesHelper(company, customer); GetCreditLimitHelper(customer); if (customer.HasCreditLimit &amp;&amp; customer.CreditLimit &lt; 500) { return false; } CustomerDataAccess.AddCustomer(customer); return true; } protected virtual Company GetCustomerCompanyHelper(int companyId) { var companyRepository = new CompanyRepository(); var company = companyRepository.GetById(companyId); return company; } protected virtual void GetCreditLimitHelper(Customer customer) { using (var customerCreditService = new CustomerCreditServiceClient()) { var creditLimit = customerCreditService.GetCreditLimit(customer.Firstname, customer.Surname, customer.DateOfBirth); customer.CreditLimit = creditLimit; } } /// &lt;summary&gt; /// Set /// &lt;/summary&gt; /// &lt;param name="company"&gt;&lt;/param&gt; /// &lt;param name="customer"&gt;&lt;/param&gt; protected virtual void SetCreditValuesHelper(Company company, Customer customer) { if (company.Name == "VeryImportantClient") { // Skip credit check customer.HasCreditLimit = false; } else if (company.Name == "ImportantClient") { // Do credit check and double credit limit customer.HasCreditLimit = true; using (var customerCreditService = new CustomerCreditServiceClient()) { var creditLimit = customerCreditService.GetCreditLimit(customer.Firstname, customer.Surname, customer.DateOfBirth); creditLimit = creditLimit * 2; customer.CreditLimit = creditLimit; } } else { // Do credit check customer.HasCreditLimit = true; } } protected virtual bool IsValidCustomerHelper(string firstName, string surname, string email, DateTime dateOfBirth) { if (string.IsNullOrEmpty(firstName) || string.IsNullOrEmpty(surname)) { return false; } var isValidEmail = Regex.IsMatch(email, @"^(?("")("".+?(?&lt;!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&amp;'\*\+/=\?\^`\{\}\|~\w])*)(?&lt;=[0-9a-z])@))" + @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-0-9a-z]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$", RegexOptions.IgnoreCase); // use regular expression because this can break easily if (!isValidEmail) { return false; } var now = DateTime.Now; var age = DateTime.Now.Year - dateOfBirth.Year; if (now.Month &lt; dateOfBirth.Month || now.Month == dateOfBirth.Month &amp;&amp; now.Day &lt; dateOfBirth.Day) age--; return age &gt;= 21; } } } </code></pre> <p>I added a new class that inherits from this class so I could do dependency injection:</p> <pre><code>using System; using App.Entities; using App.Interfaces.Repositories; using App.Interfaces.Services; using App.Interfaces.Wrappers; namespace App.Services { /// &lt;summary&gt; /// Refactored CustomerService to CustomerCompanyService /// This version has de-coupled dependencies to make it easier to unit test /// and swap out implementations via interfaces /// &lt;/summary&gt; public class CustomerCompanyService : CustomerService, ICustomerService { private readonly ICustomerCreditService _customerCreditService; private readonly ICompanyRepository _companyRepository; private readonly ICustomerDataAccessWrapper _customerDataAccessWrapper; public CustomerCompanyService(ICustomerCreditService customerCreditService, ICompanyRepository companyRepository, ICustomerDataAccessWrapper customerDataAccessWrapper) { _customerCreditService = customerCreditService; _companyRepository = companyRepository; _customerDataAccessWrapper = customerDataAccessWrapper; } public override bool AddCustomer(string firstName, string surname, string email, DateTime dateOfBirth, int companyId) { // Validate customer fields before going further if (!IsValidCustomerHelper(firstName, surname, email, dateOfBirth)) return false; var company = GetCustomerCompanyHelper(companyId); var customer = new Customer { Company = company, DateOfBirth = dateOfBirth, EmailAddress = email, Firstname = firstName, Surname = surname }; SetCreditValuesHelper(company, customer); GetCreditLimitHelper(customer); if (customer.HasCreditLimit &amp;&amp; customer.CreditLimit &lt; 500) { return false; } _customerDataAccessWrapper.AddCustomer(customer); return true; } protected override Company GetCustomerCompanyHelper(int companyId) { var company = _companyRepository.GetById(companyId); return company; } protected override void GetCreditLimitHelper(Customer customer) { //TODO: NG - removed using (have to make sure IDisposable is still being used correctly var creditLimit = _customerCreditService.GetCreditLimit(customer.Firstname, customer.Surname, customer.DateOfBirth); customer.CreditLimit = creditLimit; } /// &lt;summary&gt; /// Refactored SetCreditValuesHelper /// Reduced line count /// &lt;/summary&gt; /// &lt;param name="company"&gt;&lt;/param&gt; /// &lt;param name="customer"&gt;&lt;/param&gt; protected override void SetCreditValuesHelper(Company company, Customer customer) { // Has limit if not VeryImportantClient. // Could re-factor further and remove magic string customer.HasCreditLimit = company.Name != "VeryImportantClient"; // Do credit check and double credit limit if (!customer.HasCreditLimit) return; var creditLimit = _customerCreditService.GetCreditLimit(customer.Firstname, customer.Surname, customer.DateOfBirth); creditLimit = creditLimit * 2; customer.CreditLimit = creditLimit; } } } </code></pre> <p>I also had to make this wrapper class so I could use their static class but also inject it as a dependency:</p> <pre><code>using App.DataAccess; using App.Entities; using App.Interfaces.Wrappers; namespace App.Wrappers { public class CustomerDataAccessWrapper : ICustomerDataAccessWrapper { /// &lt;summary&gt; /// This is a wrapper so we can mock adding customer without /// changing legacy CustomerDataAccess class. /// &lt;/summary&gt; /// &lt;param name="customer"&gt;&lt;/param&gt; public void AddCustomer(Customer customer) { CustomerDataAccess.AddCustomer(customer); } } } </code></pre> <p>Keep in mind, this test was about refactoring legacy code but also changing the code to where it can be unit testable. This is the full description of the task:</p> <ol> <li><p>The most common mistakes come from candidates not following the instructions so please make sure you read them clearly and do not divert away from what is being asked </p></li> <li><p>Make sure you don’t “over-engineer” the test and stick to the 2 hour limit, if the test is over engineered you will not be progressed </p></li> <li><p>Ensure that you maintain and apply basic engineering principles such as SOLID, DRY, YAGNI and KISS</p></li> </ol> <p>The only conclusion I could reach is AddCustomer should return an object with the credit limit so we can write tests around the calculation being correct. I also believe that maybe I should of added a new constructor to CustomerService which would use the dependency injection. That way I wouldn't have to make a second class (CustomerCompanyService).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T14:36:39.913", "Id": "394948", "Score": "1", "body": "The current question title applies to too many questions on this site to be useful. **The site standard is for the title to simply state the task accomplished by the code.** Plea...
[ { "body": "<p>Offering useful feedback is tricky. It's so dependent on what the company setting the test thinks is \"over engineering\" and what they mean by the casual statement \"<em>Ensure that you maintain and apply basic engineering principles such as SOLID, DRY, YAGNI and KISS</em>\". It's quite likely fo...
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T14:12:31.963", "Id": "204779", "Score": "2", "Tags": [ "c#", "unit-testing", "interview-questions" ], "Title": "Exercise to refactor a class with various credit limit rules" }
204779
<p>I'm trying to build a lottery-like game in Python 3.6 where a function selects a winner from a participant list where every participant has a winning chance weighted by the value of the tickets they bought. I'm using the SystemRandom class in order to avoid software-state-dependency. Is this a good practice regarding good enough randomness? How could this code be improved? Also, does the shuffling does add anything to the randomness?</p> <pre><code>import random # Randomly selects an element from a choice list using weighted probabilities def randomWeightedSelection(choices, weights): # Build index list indices = list(range(len(choices))) # Shuffle indices random.shuffle(indices) # Shuffle weights accordingly shuffled_weights = [weights[i] for i in indices] # Create random generator rng = random.SystemRandom() # Select element selected_index = rng.choices(indices, weights=shuffled_weights, k=1)[0] return [choices[selected_index], selected_index] </code></pre>
[]
[ { "body": "<p>According to the Python documentation <a href=\"https://docs.python.org/3.6/library/random.html#alternative-generator\" rel=\"nofollow noreferrer\"><code>random.SystemRandom()</code></a> uses <a href=\"https://docs.python.org/3.6/library/os.html#os.urandom\" rel=\"nofollow noreferrer\"><code>os.ur...
{ "AcceptedAnswerId": "204806", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T15:05:10.343", "Id": "204781", "Score": "3", "Tags": [ "python", "python-3.x", "random" ], "Title": "Good randomness in Python code for a lottery-like game" }
204781
<p>I have a df with artist names in one column, I want to find how many times the artists repeats through the column.</p> <p>Example:</p> <pre><code>df = pd.DataFrame({"Artist":["Tim Maia","Jorge Ben","Tim Maia", "Tim Maia","Jorge Ben","Roberto Carlos", "Roberto Carlos","Roberto Carlos", "Roberto Carlos", "Dire Straits"]}) </code></pre> <p>I've already had some success using <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.itertuples.html" rel="nofollow noreferrer">itertuples()</a>, so that was my starting point for this function:</p> <pre><code>def artist_streak(df): # created to check if artists repeats, not returned artists = [] # this will be returned streaks = [] # since each observation counts, makes sense to start at 1 count=1 for row in df.itertuples(): # artists[-1] in an empty list will raise IndexError: try: # Checking if current artist is the same as the last appended if artists[-1] == row.Artist: count += 1 artists.append(row.Artist) streaks.append(count) else: # The artist does not repeated count = 1 artists.append(row.Artist) streaks.append(count) # Here we set things right for the first iteration except IndexError: artists.append(row.Artist) streaks.append(count) return streaks </code></pre> <p>Usage:</p> <pre><code>df["Result"] = artist_streak(df) </code></pre> <p>My concerns about this code are:</p> <p><strong>1. The artists list [ ]:</strong></p> <p>It is the way I could think of checking the current iterator item vs. the previous one, I don't know if it is a good way.</p> <p><strong>2. The try/except part:</strong></p> <p>As it addresses the specific case of list artists being empty, I don't know if it hurts performance (i.e. there is a faster way to do it).</p> <p>Any other suggestions on how to make it faster, cleaner, or even pythonic will be welcome.</p>
[]
[ { "body": "<p>For starter, your implementation is too tightly tied to your data, making it not reusable for other kind of dataframe where you would want to count streaks. If you provided a column (<code>pd.Series</code>) to the function instead, it would be much more versatile; allowing calls such as <code>coun...
{ "AcceptedAnswerId": "204789", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T15:05:19.460", "Id": "204782", "Score": "2", "Tags": [ "python", "pandas" ], "Title": "Function for setting a streak of strings in a Pandas" }
204782
<p>One of the projects I'm working on requires logging a <em>huge</em> amount of information (basically, every function call). The problem is obviously that logging a lot of information has a few side-effects, notably high disk-use (both IO's and amount); tends to require lookup-tables if you're trying to keep things small (i.e. an "integer to page" conversion, etc.); often isn't atomic, that is, concurrency can often become a high target-factor for threaded logging.</p> <p>To fix some (most) of this, I've worked up a binary encoding for our logs. Basically, it allows us to store a huge amount of information in a tight format, and also allows us to do so atomically and without any concurrency issues. As a result, we can have high-performance logging that doesn't bog anything down. It has a small drawback: encoding of names and some values are "lossy", that is to say, we don't take the entire thing into account.</p> <p>The specification is a notepad document, which is below:</p> <blockquote> <pre><code>HEADBYTE (1) 00000001 - IP Version 00000010 - Page Name Supplied (1 if supplied) 01111100 - Parameter Count (Up to 32) 10000000 - Always 0, indicates "V1", if 1 then there's another headbyte for the next version IPBYTES (4 or 16) If IP Version = 0 Then 4 bytes (IPv4) Else 16 bytes (IPv6) DATETIME (8) Unix EPOCH Time in UTC USERID (5) 00000011 - User Type 4 bytes: Integer user ID PAGENAME (0 or 16) If Page Name = 0 Then 0 bytes (not supplied) Else 16 bytes for MD5 hash of URL + Folder + Page name FUNCTION NAME (16) 16 bytes for MD5 hash of Namespace + Module + Function name PARAMETERS (0 or *) If Parameter Count = 0 Then 0 bytes (not supplied) Else Parameters PARAMETER (&lt;= 37) 1-byte for config: PARAMETER CONFIG 00000001 - 0 = Ref, 1 = Val 00001110 - Type: 0 = Non-numeric type, # = 2^(n - 1) size bytes 00010000 - Type Extension: If Type is non-numeric, 1 indicates data is string, 0 indicates custom class If Type is numeric, then 1 = Signed, 0 = Unsigned 10000000 - Always 0, indicates "V1", if 1 then there's another byte(s) for the next version 16 bytes for MD5 hash of parameter name If Type &gt; 0 Then # bytes of actual numeric value Else If Type Extension = 1 Then 4 bytes for string length Else 16 bytes for MD5 hash of parameter type name (Full type name) </code></pre> </blockquote> <p>We can encode most of our data in less than 500 bytes, and much of it can be encoded in less than 200 bytes. By using the MD5 hash of the names / values, we can guarantee that there is not lookup or contention over storing them to any sort of "persistent" format, and it means we can build the lookup-table on-the-fly, so-to-speak. (We can store name + hash in the database, but it's no longer required for the logger to do it's job. We can fill it on a regular basis.) We use an MD5 hash for the speed, and the fact that, realistically, there are so few collisions on my use-case that it's not a big deal. Close counts, here.</p> <p>An example (hexadecimal) log format might look like the following:</p> <blockquote> <pre><code>0f000000000000000000000000000000 01000001662b4bf83801000000c0c694 689b671598d0809e2935e7ccf4b6fa5c dcf6485054f1bcd699050864f2d505a5 0691680602baa24206181b31ceb3c201 011029a5b77a07118ffbdbecfac18b73 f7c50000000100b05a9ad34ddf60cadf 2ba9dac8fa3a345592700a1f3b26e424 bc7fe95e50f703 </code></pre> </blockquote> <p>Which, once line-breaks are stripped, can be decoded into the resulting type structure:</p> <pre><code>type MD5Hash = byte [] type Header = { IPV6 : bool PageNameSupplied : bool ParameterCount : byte } type IP = | V4 of System.Net.IPAddress | V6 of System.Net.IPAddress type UserType = | Client | Vendor | Admin type DateTime = uint64 type UserId = UserType * uint32 type Number = | Byte of byte | SByte of sbyte | UInt16 of uint16 | Int16 of int16 | UInt32 of uint32 | Int32 of int32 | UInt64 of uint64 | Int64 of int64 type ParameterValue = | CustomClass of MD5Hash | String of int | Numeric of Number type Parameter = { ValueType : bool ParameterName : MD5Hash ParameterValue : ParameterValue } type LogMessage = { IP : IP DateTime : DateTime UserId : UserId PageName : MD5Hash option FunctionName : MD5Hash Parameters : Parameter list } </code></pre> <p>To encode and decode we have some utility functions:</p> <pre><code>let md5Hash (str : string) : MD5Hash = use md5 = System.Security.Cryptography.MD5.Create() str |&gt; System.Text.Encoding.UTF8.GetBytes |&gt; md5.ComputeHash let byteToUserType = function | 0b00000000uy -&gt; UserType.Client | 0b00000001uy -&gt; UserType.Vendor | 0b00000011uy -&gt; UserType.Admin | _ -&gt; failwith "Invalid User Type" let userTypeToByte = function | UserType.Client -&gt; 0b00000000uy | UserType.Vendor -&gt; 0b00000001uy | UserType.Admin -&gt; 0b00000011uy let byteArrayToByte = function | [|b1|] -&gt; b1 | _ -&gt; failwith "Byte may only have a single element byte-array" let byteArrayToSByte = function | [|b1|] -&gt; b1 |&gt; sbyte | _ -&gt; failwith "SByte may only have a single element byte-array" let byteArrayToUInt16 = function | [|b1; b2|] -&gt; (b1 |&gt; uint16) &lt;&lt;&lt; 8 ||| (b2 |&gt; uint16) | _ -&gt; failwith "UInt16 may only have a 2 element byte-array" let byteArrayToInt16 = function | [|b1; b2|] -&gt; (b1 |&gt; int16) &lt;&lt;&lt; 8 ||| (b2 |&gt; int16) | _ -&gt; failwith "Int16 may only have a 2 element byte-array" let byteArrayToUInt32 = function | [|b1; b2; b3; b4|] -&gt; (b1 |&gt; uint32) &lt;&lt;&lt; 24 ||| (b2 |&gt; uint32) &lt;&lt;&lt; 16 ||| (b3 |&gt; uint32) &lt;&lt;&lt; 8 ||| (b4 |&gt; uint32) | _ -&gt; failwith "UInt32 may only have a 4 element byte-array" let byteArrayToInt32 = function | [|b1; b2; b3; b4|] -&gt; (b1 |&gt; int32) &lt;&lt;&lt; 24 ||| (b2 |&gt; int32) &lt;&lt;&lt; 16 ||| (b3 |&gt; int32) &lt;&lt;&lt; 8 ||| (b4 |&gt; int32) | _ -&gt; failwith "Int32 may only have a 4 element byte-array" let byteArrayToUInt64 = function | [|b1; b2; b3; b4; b5; b6; b7; b8|] -&gt; (b1 |&gt; uint64) &lt;&lt;&lt; 54 ||| (b2 |&gt; uint64) &lt;&lt;&lt; 48||| (b3 |&gt; uint64) &lt;&lt;&lt; 40 ||| (b4 |&gt; uint64) &lt;&lt;&lt; 32 ||| (b5 |&gt; uint64) &lt;&lt;&lt; 24 ||| (b6 |&gt; uint64) &lt;&lt;&lt; 16 ||| (b7 |&gt; uint64) &lt;&lt;&lt; 8 ||| (b8 |&gt; uint64) | _ -&gt; failwith "UInt64 may only have a 8 element byte-array" let byteArrayToInt64 = function | [|b1; b2; b3; b4; b5; b6; b7; b8|] -&gt; (b1 |&gt; int64) &lt;&lt;&lt; 54 ||| (b2 |&gt; int64) &lt;&lt;&lt; 48||| (b3 |&gt; int64) &lt;&lt;&lt; 40 ||| (b4 |&gt; int64) &lt;&lt;&lt; 32 ||| (b5 |&gt; int64) &lt;&lt;&lt; 24 ||| (b6 |&gt; int64) &lt;&lt;&lt; 16 ||| (b7 |&gt; int64) &lt;&lt;&lt; 8 ||| (b8 |&gt; int64) | _ -&gt; failwith "Int64 may only have a 8 element byte-array" let byteArrayToNumber signature (bytes : byte []) = match bytes, signature with | [|b1|], false -&gt; bytes |&gt; byteArrayToByte |&gt; Byte | [|b1|], true -&gt; bytes |&gt; byteArrayToSByte |&gt; SByte | [|b1; b2|], false -&gt; bytes |&gt; byteArrayToUInt16 |&gt; UInt16 | [|b1; b2|], true -&gt; bytes |&gt; byteArrayToInt16 |&gt; Int16 | [|b1; b2; b3; b4|], false -&gt; bytes |&gt; byteArrayToUInt32 |&gt; UInt32 | [|b1; b2; b3; b4|], true -&gt; bytes |&gt; byteArrayToInt32 |&gt; Int32 | [|b1; b2; b3; b4; b5; b6; b7; b8|], false -&gt; bytes |&gt; byteArrayToUInt64 |&gt; UInt64 | [|b1; b2; b3; b4; b5; b6; b7; b8|], true -&gt; bytes |&gt; byteArrayToInt64 |&gt; Int64 | _ -&gt; failwith "Number must have a 1, 2, 4, or 8 element byte-array" let byteToByteArray n = [|n|] let sbyteToByteArray n = [|n |&gt; byte|] let uint16ToByteArray n = [|(n &gt;&gt;&gt; 8) |&gt; byte; (n) |&gt; byte|] let int16ToByteArray n = [|(n &gt;&gt;&gt; 8) |&gt; byte; (n) |&gt; byte|] let uint32ToByteArray n = [|(n &gt;&gt;&gt; 24) |&gt; byte; (n &gt;&gt;&gt; 16) |&gt; byte; (n &gt;&gt;&gt; 8) |&gt; byte; (n) |&gt; byte|] let int32ToByteArray n = [|(n &gt;&gt;&gt; 24) |&gt; byte; (n &gt;&gt;&gt; 16) |&gt; byte; (n &gt;&gt;&gt; 8) |&gt; byte; (n) |&gt; byte|] let uint64ToByteArray n = [|(n &gt;&gt;&gt; 56) |&gt; byte; (n &gt;&gt;&gt; 48) |&gt; byte; (n &gt;&gt;&gt; 40) |&gt; byte; (n &gt;&gt;&gt; 32) |&gt; byte; (n &gt;&gt;&gt; 24) |&gt; byte; (n &gt;&gt;&gt; 16) |&gt; byte; (n &gt;&gt;&gt; 8) |&gt; byte; (n) |&gt; byte|] let int64ToByteArray n = [|(n &gt;&gt;&gt; 56) |&gt; byte; (n &gt;&gt;&gt; 48) |&gt; byte; (n &gt;&gt;&gt; 40) |&gt; byte; (n &gt;&gt;&gt; 32) |&gt; byte; (n &gt;&gt;&gt; 24) |&gt; byte; (n &gt;&gt;&gt; 16) |&gt; byte; (n &gt;&gt;&gt; 8) |&gt; byte; (n) |&gt; byte|] let numberToByteArray = function | Byte n -&gt; false, (n |&gt; byteToByteArray) | SByte n -&gt; true, (n |&gt; sbyteToByteArray) | UInt16 n -&gt; false, (n |&gt; uint16ToByteArray) | Int16 n -&gt; true, (n |&gt; int16ToByteArray) | UInt32 n -&gt; false, (n |&gt; uint32ToByteArray) | Int32 n -&gt; true, (n |&gt; int32ToByteArray) | UInt64 n -&gt; false, (n |&gt; uint64ToByteArray) | Int64 n -&gt; true, (n |&gt; int64ToByteArray) </code></pre> <p>Then, we finally get to the heart of the encoding and decoding:</p> <pre><code>let readLogMessage (bytes : byte []) : Result&lt;byte [] * LogMessage, string&gt; = let readLogHeader (bytes : byte []) : Result&lt;byte [] * Header, string&gt; = let headerByte = bytes.[0] if (headerByte &amp;&amp;&amp; 0b10000000uy) &gt; 0uy then Error "Only V1 is supported." else let remBytes = bytes.[1..] let ipVersion = headerByte &amp;&amp;&amp; 0b00000001uy &gt; 0uy let pageNameSupplied = headerByte &amp;&amp;&amp; 0b00000010uy &gt; 0uy let parameterCount = headerByte &amp;&amp;&amp; 0b01111100uy &gt;&gt;&gt; 2 (remBytes, { Header.IPV6 = ipVersion; PageNameSupplied = pageNameSupplied; ParameterCount = parameterCount }) |&gt; Ok match bytes |&gt; readLogHeader with | Ok (bytes, header) -&gt; let bytes, ip = match header.IPV6 with | false -&gt; bytes.[4..], V4 (bytes.[..3] |&gt; System.Net.IPAddress) | true -&gt; bytes.[16..], V6 (bytes.[..15] |&gt; System.Net.IPAddress) let bytes, datetime = bytes.[8..], bytes.[..7] let bytes, userType = bytes.[1..], ((bytes.[0] &amp;&amp;&amp; 0b00000011uy) |&gt; byteToUserType) let bytes, userid = bytes.[4..], bytes.[..3] let bytes, pageName = match header.PageNameSupplied with | false -&gt; bytes, None | true -&gt; bytes.[16..], (bytes.[..15] |&gt; Some) let bytes, functionName = bytes.[16..], bytes.[..15] let rec readParameters (bytes : byte []) ps rem = match rem with | 0 -&gt; ps | r -&gt; let bytes, head = bytes.[1..], bytes.[0] let valueType = head &amp;&amp;&amp; 0b00000001uy &gt; 0uy let typeVal = head &amp;&amp;&amp; 0b00001110uy &gt;&gt;&gt; 1 let typeExt = head &amp;&amp;&amp; 0b00010000uy &gt; 0uy let bytes, parameterName = bytes.[16..], bytes.[..15] let bytes, value = match typeVal, typeExt with | 0uy, false -&gt; bytes.[16..], CustomClass (bytes.[..15]) | 0uy, true -&gt; bytes.[4..], String (bytes.[..3] |&gt; byteArrayToInt32) | i, signed -&gt; bytes.[i |&gt; int..], Numeric (bytes.[..(pown 2 ((i |&gt; int) - 1)) - 1] |&gt; byteArrayToNumber signed) let ps = { ValueType = valueType; ParameterName = parameterName; ParameterValue = value } :: ps readParameters bytes ps (r - 1) Ok (bytes, { IP = ip DateTime = datetime |&gt; byteArrayToUInt64 UserId = userType, (userid |&gt; byteArrayToUInt32) PageName = pageName FunctionName = functionName Parameters = readParameters bytes [] (header.ParameterCount |&gt; int) |&gt; List.rev }) | Error e -&gt; Error e let writeLogMessage (msg : LogMessage) : Result&lt;byte [], string&gt; = let headerByte = match msg.IP with | V4 _ -&gt; 0b00000000uy | V6 _ -&gt; 0b00000001uy let headerByte = headerByte ||| match msg.PageName with | Some _ -&gt; 0b00000010uy | None -&gt; 0b00000000uy let headerByte = headerByte ||| ((msg.Parameters.Length &lt;&lt;&lt; 3) |&gt; byte &gt;&gt;&gt; 1) let result = [|headerByte|] let result = match msg.IP with | V4 ip -&gt; ip.GetAddressBytes() | V6 ip -&gt; ip.GetAddressBytes() |&gt; Array.append result let result = msg.DateTime |&gt; uint64ToByteArray |&gt; Array.append result let result = let t, id = msg.UserId id |&gt; uint32ToByteArray |&gt; Array.append [|0uy ||| (t |&gt; userTypeToByte)|] |&gt; Array.append result let result = match msg.PageName with | Some h -&gt; h | None -&gt; [| |] |&gt; Array.append result let result = msg.FunctionName |&gt; Array.append result let rec writeParameters (bytes : byte []) ps = match ps with | [] -&gt; bytes | head::ps -&gt; let headByte = 0uy let headByte = headByte ||| if head.ValueType then 0b00000001uy else 0b00000000uy let addHeadByte, data = match head.ParameterValue with | CustomClass hash -&gt; 0b00000000uy, hash | String length -&gt; 0b00010000uy, (length |&gt; int32ToByteArray) | Numeric n -&gt; let signed, bytes = n |&gt; numberToByteArray (if signed then 0b00010000uy else 0b00000000uy) ||| ((log (bytes.Length |&gt; float) / log 2. + 1.) |&gt; byte &lt;&lt;&lt; 1), bytes let headByte = headByte ||| addHeadByte let result = [|headByte|] let result = head.ParameterName |&gt; Array.append result let result = data |&gt; Array.append result writeParameters (result |&gt; Array.append bytes) ps msg.Parameters |&gt; writeParameters [| |] |&gt; Array.append result |&gt; Ok </code></pre> <p>And we can verify the whole thing with a simple script:</p> <blockquote> <pre><code>let input = [| //0b00001110uy // IPv4 0b00001111uy // IPv6 //0b01111111uy; 0b00000000uy; 0b00000000uy; 0b00000001uy // IPv4 0b00000000uy; 0b00000000uy; 0b00000000uy; 0b00000000uy; 0b00000000uy; 0b00000000uy; 0b00000000uy; 0b00000000uy; 0b00000000uy; 0b00000000uy; 0b00000000uy; 0b00000000uy; 0b00000000uy; 0b00000000uy; 0b00000000uy; 0b00000001uy // IPv6 0b00000000uy; 0b00000000uy; 0b00000001uy; 0b01100110uy; 0b00101011uy; 0b01001011uy; 0b11111000uy; 0b00111000uy // DateTime Stamp 0b00000001uy; 0b00000000uy; 0b00000000uy; 0b00000000uy; 0b11000000uy // User ID 0b11000110uy; 0b10010100uy; 0b01101000uy; 0b10011011uy; 0b01100111uy; 0b00010101uy; 0b10011000uy; 0b11010000uy; 0b10000000uy; 0b10011110uy; 0b00101001uy; 0b00110101uy; 0b11100111uy; 0b11001100uy; 0b11110100uy; 0b10110110uy // Page Name 0b11111010uy; 0b01011100uy; 0b11011100uy; 0b11110110uy; 0b01001000uy; 0b01010000uy; 0b01010100uy; 0b11110001uy; 0b10111100uy; 0b11010110uy; 0b10011001uy; 0b00000101uy; 0b00001000uy; 0b01100100uy; 0b11110010uy; 0b11010101uy // Function Name 0b00000101uy; 0b10100101uy; 0b00000110uy; 0b10010001uy; 0b01101000uy; 0b00000110uy; 0b00000010uy; 0b10111010uy; 0b10100010uy; 0b01000010uy; 0b00000110uy; 0b00011000uy; 0b00011011uy; 0b00110001uy; 0b11001110uy; 0b10110011uy; 0b11000010uy; 0b00000001uy; 0b00000001uy // Parameter 1 0b00010000uy; 0b00101001uy; 0b10100101uy; 0b10110111uy; 0b01111010uy; 0b00000111uy; 0b00010001uy; 0b10001111uy; 0b11111011uy; 0b11011011uy; 0b11101100uy; 0b11111010uy; 0b11000001uy; 0b10001011uy; 0b01110011uy; 0b11110111uy; 0b11000101uy; 0b00000000uy; 0b00000000uy; 0b00000000uy; 0b00000001uy // Parameter 2 0b00000000uy; 0b10110000uy; 0b01011010uy; 0b10011010uy; 0b11010011uy; 0b01001101uy; 0b11011111uy; 0b01100000uy; 0b11001010uy; 0b11011111uy; 0b00101011uy; 0b10101001uy; 0b11011010uy; 0b11001000uy; 0b11111010uy; 0b00111010uy; 0b00110100uy; 0b01010101uy; 0b10010010uy; 0b01110000uy; 0b00001010uy; 0b00011111uy; 0b00111011uy; 0b00100110uy; 0b11100100uy; 0b00100100uy; 0b10111100uy; 0b01111111uy; 0b11101001uy; 0b01011110uy; 0b01010000uy; 0b11110111uy; 0b00000011uy // Parameter 3 |] let outMessage = readLogMessage input let message = { //IP = "127.0.0.1" |&gt; System.Net.IPAddress.Parse |&gt; V4 // IPv4 IP = "::1" |&gt; System.Net.IPAddress.Parse |&gt; V6 // IPv6 DateTime = System.DateTimeOffset(2018, 9, 30, 16, 24, 51, System.TimeSpan()).ToUnixTimeMilliseconds() |&gt; uint64 UserId = UserType.Vendor, 192u PageName = "Dir/Page.aspx" |&gt; md5Hash |&gt; Some FunctionName = "Page_Load" |&gt; md5Hash Parameters = [{ ValueType = true ParameterName = "Parameter 1" |&gt; md5Hash ParameterValue = 257us |&gt; UInt16 |&gt; Numeric } { ValueType = false ParameterName = "Parameter 2" |&gt; md5Hash ParameterValue = 1 |&gt; String } { ValueType = false ParameterName = "Parameter 3" |&gt; md5Hash ParameterValue = "Class Type" |&gt; md5Hash |&gt; CustomClass } ] } let output = writeLogMessage message input |&gt; Array.iter (printf "%02x") printfn "" match output with | Ok o -&gt; o |&gt; Array.iter (printf "%02x") printfn "" Seq.fold2 (fun res b1 b2 -&gt; res &amp;&amp; b1 = b2) true input o | Error e -&gt; false </code></pre> </blockquote> <p>This shows us what the function writing a log would look like (the <code>writeLogMessage</code> part), and what reading a log looks like (the <code>readLogMessage</code> part).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T19:10:47.503", "Id": "394986", "Score": "0", "body": "Is there a protobuf library for F#? It was designed for your usecase." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T19:21:47.287", "Id": "39...
[ { "body": "<p>At a quick glance, I could nitpick about how I think K&amp;R (Java) style braces are cleaner for type definitions or that hex literals are better than binary literals, but that’s really my own personal preference. For an explanation on why hex is better than binary see <a href=\"https://codereview...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T16:52:07.763", "Id": "204791", "Score": "5", "Tags": [ "performance", ".net", "f#", "logging" ], "Title": "Encoding and decoding log entries in a Lossy Binary Format" }
204791
<p>I was able to make a program that parse my samtools output file into a table that can be viewed easily in excel. While I was able to get the final result, is there a recommended improvements that be done for my code. I am trying to improve my python skills and transferring over from C and C++.</p> <p>The strategy I used was to split the data I need based on the "+" sign and make it into an array. Then select the elements of the array that were the information that I needed and write it to my file.</p> <h3>My example input:</h3> <pre><code>15051874 + 0 in total (QC-passed reads + QC-failed reads) 1998052 + 0 secondary 0 + 0 supplementary 0 + 0 duplicates 13457366 + 0 mapped (89.41% : N/A) 13053822 + 0 paired in sequencing 6526911 + 0 read1 6526911 + 0 read2 10670914 + 0 properly paired (81.75% : N/A) 10947288 + 0 with itself and mate mapped 512026 + 0 singletons (3.92% : N/A) 41524 + 0 with mate mapped to a different chr 31302 + 0 with mate mapped to a different chr (mapQ&gt;=5) </code></pre> <h3>My output:</h3> <pre><code>FileName Total Secondary Supplementary duplicates mapped paired in sequencing read1 read2 properly paired with itself and mate mapped singletons with mate mapped to a different chr with mate mapped to a different chr (mapQ&gt;=5) 10_HK_S22.merged.samtools.flag.txt 26541257 2332283 0 0 22895440 24208974 12104487 12104487 19003826 19632880 930277 69030 52261 </code></pre> <h3>My Program:</h3> <pre><code>outFile = open("output.count.txt", "w+") #windows platform add the r os.chdir(r"Susceptible\featurecounts") #open the output file to be able to write output. outFile.write("FileName\tTotal\tSecondary\tSupplementary\tduplicates\tmapped\tpaired in sequencing\tread1\t" "read2\tproperly paired\twith itself and mate mapped\tsingletons\twith mate mapped to a different chr\twith mate mapped to a different chr (mapQ&gt;=5)\n") #Iterate through files in directory with the following ending for file in glob.glob(".flag.txt"): #open file after retrieving the name. with open(file, 'r') as counts_file: #empty list/array for storing the outputs list = [] #add the file name to array. list.append(file) #get values from output file. for line in counts_file: list.append(line.split('+')[0]) #write list to file for item in list: outFile.write("%s\t" % item) #write a newline outFile.write("\n") #close the output file outFile.close() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T18:17:57.710", "Id": "394977", "Score": "1", "body": "Your example output doesn't seem to correspond to your example input?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T18:31:42.677", "Id": "39...
[ { "body": "<p>Use <code>with ... as ...:</code> statements to open files, and automatically close them.\nThen you don't have to clutter up your program with explicit close statements.</p>\n\n<pre><code>outFile = open(\"output.count.txt\", \"w+\")\n\n# ... code here\n\n#close the output file \noutFile.close...
{ "AcceptedAnswerId": "204796", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T17:41:37.777", "Id": "204792", "Score": "-2", "Tags": [ "python", "python-3.x" ], "Title": "Parsing of text file to a table" }
204792
<p><strong>Background</strong></p> <p>I receive dataframes from several sources (below I call these sources <code>s1</code>, <code>s2</code> and <code>s3</code>). I first want to check whether the provided data meets certain requirements and if so, the data will be further processed; below I only provide the code for the check whether the provided data is correct.</p> <p><strong>Approach</strong></p> <p>For each column in each dataframe I create an own function that returns a Boolean variable depending on the evaluation of a regular expression. The regular expression depends on the data source and the column name.</p> <p><strong>Input - output</strong></p> <p>An example could look like this (coming from source <code>s1</code>):</p> <pre><code> ID content x fo_stuff.s1orig_0987 ABBBCCCCBB y cool_abc.s1orig CCBBAABBTY z er_something.illegal.foo BABCACCB </code></pre> <p>In <code>ID</code> the regex evaluates to <code>True</code> if an element consists of</p> <pre><code>(2 letters)_(arbitrary number of letters/numbers/underscores).(s1orig)(optional: underscore and four digits) </code></pre> <p>So, in this case only the entry in <code>x</code> is correct.</p> <p>In <code>content</code> the regular expression evaluates to <code>True</code> if the string consists of either only <code>A</code>, <code>B</code>, <code>C</code> or <code>a</code>, <code>b</code>, <code>c</code> (arbitrary many), so <code>x</code> and <code>z</code> are correct, <code>y</code> is not as it contains a <code>T</code> and a <code>Y</code>.</p> <p>If I run the code from below, I then get my expected outcome:</p> <pre><code>test = ProcessDataTables(df, "s1") test.get_invalid_entries() print(test.invalid_entries) # {'ID': ['y', 'z'], 'content': ['y']} </code></pre> <p>So, I get a dictionary that has as keys the column headers and as values a list of indices that correspond to invalid data.</p> <p><strong>Questions</strong></p> <ol> <li><p>Is there a better way of organizing the code? Now it kind of violates the DRY principle. On the other hand, having individual function for each data source and column is quite flexible if regular expressions have to change/additional columns need to be considered.</p></li> <li><p>Is there are a better way of applying the <code>is_valid_***</code> functions to the dataframe columns? Using <code>__get_mapping_dict</code> works but looks rather strange to pass functions around like this.</p></li> <li><p>Is there a straightforward way to have all the <code>is_valid_***</code> functions inside the class?</p></li> </ol> <p>This is the entire code:</p> <pre><code>import re import pandas as pd class ProcessDataTables(object): def __init__(self, data_table, data_source): self.data = data_table if data_source in {'s1', 's2', 's3'}: self.source = data_source else: raise ValueError(f"{data_source} is not a valid data source.") self._mapping_dict = self.__get_mapping_dict() self.invalid_entries = None if not set(self._mapping_dict).issubset(self.data.columns): raise ValueError("Please check your columns names!") def get_invalid_entries(self): # apply the passed functions to the respective columns and filter all # values that are False (meaning that they have a wrong format) temp = {ci: self.data.index[~self.data[ci].apply(fi)].tolist() for ci, fi in self._mapping_dict.items()} self.invalid_entries = temp def __get_mapping_dict(self): if self.source == "s1": return {'ID': is_valid_name_s1, 'content': is_valid_sequence} elif self.source == "s2": return {'ID': is_valid_name_s2, 'content': is_valid_sequence} elif self.source == "s3": return {'ID': is_valid_name_s3, 'content': is_valid_sequence} def is_valid_name_s1(name): """ This function checks whether *name* matches the following pattern: (2letters)_(arbitrary number of letters/numbers/underscores). (s1orig)(optional: underscore and for digits) *name*: a string return: True if *name matches the pattern, False if not """ regex_name = re.compile(r'^[A-Za-z]{2}_([A-Za-z0-9_]+)\.(s1orig)(_\d{4})?$') if regex_name.match(name) is not None: return True return False def is_valid_name_s2(name): """ This function checks whether *name* matches the following pattern: (2 or 4 letters)_(arbitrary number of letters/numbers/underscores). (s2orig)(optional: underscore and for digits) *name*: a string return: True if *name matches the pattern, False if not """ regex_name = re.compile(r'^([A-Za-z]{2}|[A-Za-z]{4})_([A-Za-z0-9_]+)\.(s2orig)(_\d{4})?$') if regex_name.match(name) is not None: return True return False def is_valid_name_s3(name): """ This function checks whether *name* matches the following pattern: (3 letters)_(arbitrary number of letters/numbers/underscores). (s3orig)(optional: underscore and for digits) *name*: a string return: True if *name matches the pattern, False if not """ regex_name = re.compile(r'^[A-Za-z]{3}_([A-Za-z0-9_]+)\.(s3orig)(_\d{4})?$') if regex_name.match(name) is not None: return True return False def is_valid_sequence(sequence): """ True if string consists of either only A, B, C or a, b, c """ regex_seq = re.compile(r'^([ABC]+|[abc]+)$') if regex_seq.match(sequence) is not None: return True return False if __name__ == '__main__': df = pd.DataFrame({'ID': ["fo_stuff.s1orig_0987", "cool_abc.s1orig", "er_something.illegal.foo"], 'content': ['ABBBCCCCBB', 'CCBBAABBTY', 'BABCACCB']}, index=list('xyz')) test = ProcessDataTables(df, "s1") test.get_invalid_entries() print(test.invalid_entries) </code></pre>
[]
[ { "body": "<h2>Object-oriented design</h2>\n\n<p>This usage is awkward:</p>\n\n<blockquote>\n<pre><code>test = ProcessDataTables(df, \"s1\")\ntest.get_invalid_entries()\nprint(test.invalid_entries)\n</code></pre>\n</blockquote>\n\n<p>Specifically:</p>\n\n<ul>\n<li>\"ProcessDataTables\" is a vague name that does...
{ "AcceptedAnswerId": "204811", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T19:22:32.380", "Id": "204797", "Score": "2", "Tags": [ "python", "object-oriented", "regex", "validation", "pandas" ], "Title": "Check values in datatables, with validation rules that vary according to the data source" }
204797
<p>I am writing test cases in JavaScript and jQuery, the framework is Jasmine and Karma.</p> <pre><code>describe('When a user selects a multiple-response Hotspot response', function () { it('Then allow highlighting multiple responses', function (done) { utils.clickHotspotElementAtIndex(view, 1, function() {}); utils.clickHotspotElementAtIndex(view, 0, function() {}); utils.clickHotspotElementAtIndex(view, 2, function() {}); setTimeout(function() { expect(utils.verifyHotSpotHasBeenHiglightedAtIndex(view, 0)).toBe('true'); expect(utils.verifyHotSpotHasBeenHiglightedAtIndex(view, 1)).toBe('true'); expect(utils.verifyHotSpotHasBeenHiglightedAtIndex(view, 2)).toBe('true'); done(); }), 2000}); }); </code></pre> <p>What it does is:</p> <ol> <li>click on element 1, sync action</li> <li>click on element 0, sync action</li> <li>click on element 2. sync action</li> <li>When the main thread is free, wait for 2 seconds and then</li> <li>expect element 0 has been highlighted</li> <li>expect element 1 has been highlighted</li> <li>expect element 2 has been highlighted</li> </ol> <p>Is there a more elegant way to do this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T05:19:57.093", "Id": "395021", "Score": "0", "body": "@200_success, thanks, this question has nothing to do with jQuery directly. Most of the methods use jQuery in their helper files." } ]
[ { "body": "<p>The anonymous functions and hardcoded values can be abstracted. For example:</p>\n\n<pre><code>function click(value){\n utils.clickHotspotElementAtIndex(view, value, Function);\n}\n\nfunction tests(value){\n expect(utils.verifyHotSpotHasBeenHiglightedAtIndex(view, value)).toBe('true');\n}\n\...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T23:22:23.313", "Id": "204809", "Score": "3", "Tags": [ "javascript", "jasmine" ], "Title": "Jasmine test involving a sequence of actions" }
204809
<p>As an exercise, I decided to write a program that spells out numbers.</p> <p>For example:</p> <pre><code>(stringify-int 12345) =&gt; "twelve thousand three hundred forty-five" </code></pre> <p>It ended up both being simpler and more difficult than I thought. Once I realized that you can break the number down into 3-digit chunks, then just add the appropriate suffixes to each chunk, it was pretty straightforward. The number of corner cases all over the place made some things difficult. I got more than half of it written before I realized that I had no idea how I was going to handle 10. I ended up shimming it into an existing mechanism. </p> <p>The general algorithm:</p> <ul> <li>Break the number into 3-digit chunks, padded with 0s</li> <li>Use the values in the hundreds, tens and one place of each chunk to index vectors containing the names of the place</li> <li>Attach the appropriate place suffixes to each chunk</li> <li>Join the chunks together</li> </ul> <p>I'd like general input on anything here. I'd especially like suggestions on how to handle 10 better.</p> <p>General helpers used in core and tests:</p> <pre><code>(ns number-to.words.helpers) (defn div-mod [numer denom] ((juxt quot mod) numer denom)) (defn parse-int [n] (try (Long/parseLong n) (catch NumberFormatException _ nil))) (defn str-num "Returns a string representing a number indicated by scientific notation-ish arguments. (str-num 4 5) =&gt; \"400000\"" [tens-mult n-zeros] (str (str tens-mult) (apply str (repeat n-zeros "0")))) </code></pre> <p>Tests:</p> <pre><code>(ns number-to.words.try1-test (:require [clojure.test :refer :all] [number-to.words.try1 :refer :all] [number-to.words.helpers :as h])) ; https://www.grammarbook.com/numbers/numbers.asp ; "Rule 2a. Hyphenate all compound numbers from twenty-one through ninety-nine." (defmacro are-correct [f &amp; pairs] `(are [n# w#] (= (~f n#) w#) ~@pairs)) (deftest stringify-chunk-test (testing "arbitary numbers" (are-correct stringify-chunk 4 "four" 12 "twelve" 15 "fifteen" 25 "twenty-five" 36 "thirty-six" 50 "fifty" 69 "sixty-nine" 88 "eighty-eight" 95 "ninety-five" 125 "one hundred twenty-five" 174 "one hundred seventy-four" 468 "four hundred sixty-eight" 750 "seven hundred fifty" 987 "nine hundred eighty-seven"))) (deftest stringify-test (testing "even base names are correct" (are-correct stringify-int 1 "one" 10 "ten" 1e2 "one hundred" 1e3 "one thousand" 1e4 "ten thousand" 1e5 "one hundred thousand" 1e6 "one million" 1e7 "ten million" 1e8 "one hundred million" 1e9 "one billion" 1e12 "one trillion" 1e15 "one quadrillion" 1e18 "one quintillion" (bigint (h/str-num 5 24)) "five septillion" (+ (bigint (h/str-num 2 37)) 99306) "twenty undecillion ninety-nine thousand three hundred six" (+ (bigint (h/str-num 7 41)) 36) "seven hundred duodecillion thirty-six")) (testing "arbitary numbers" (are-correct stringify-int 2 "two" 11 "eleven" 16 "sixteen" 23 "twenty-three" 42 "forty-two" 99 "ninety-nine" 123 "one hundred twenty-three" 1234 "one thousand two hundred thirty-four" 5000 "five thousand" 9999 "nine thousand nine hundred ninety-nine" 54321 "fifty-four thousand three hundred twenty-one" (+ (long 2e15) 12345) "two quadrillion twelve thousand three hundred forty-five" (+ (long 5e18) 5000 23) "five quintillion five thousand twenty-three"))) </code></pre> <p>Code:</p> <pre><code>(ns number-to.words.try1 (:require [criterium.core :as cc] [number-to.words.helpers :as h] [clojure.string :as s])) (def digit-names ["one" "two" "three" "four" "five" "six" "seven" "eight" "nine"]) (def digit-prefixes ["thir" "four" "fif" "six" "seven" "eigh" "nine"]) (def teen-names (-&gt;&gt; digit-prefixes (mapv #(str % "teen")) (into ["eleven" "twelve"]))) (def tens-names (as-&gt; digit-prefixes d (assoc d 1 "for") ; forty drops the "u" for some reason (into ["twen"] d) (mapv #(str % "ty") d))) ; Can only get to quintillion anyways before we exceed what a long can hold. ; TODO: Adapt to allow big nums, or remove excess place-names (def place-names ["" "thousand" "million" "billion" "trillion" "quadrillion" "quintillion" "sextillion" "septillion" "octillion" "nonillion" "decillion" "undecillion" "duodecillion"]) (def places-chunk-size 3) (def max-represntable-number (bigint (apply str (repeat 41 9)))) (defn- reverse-chunk-n "Chunks the number into chunk-size many places. Returns the chunks in reverse order. (reverse-chunk-n 1234 3) =&gt; [234 1]" [n chunk-size] (-&gt;&gt; n (str) (reverse) (partition chunk-size chunk-size (repeat 0)) (mapv #(-&gt;&gt; % (reverse) (apply str) h/parse-int)))) (defn- stringify-ones [digit] {:pre (&lt;= 1 digit 9)} (if (zero? digit) "" (digit-names (dec digit)))) (defn- stringify-teen [teen-n] {:pre [(&lt;= 11 teen-n 19)]} (teen-names (- teen-n 11))) (defn- stringify-tens-place [tens-place] {:pre [(or (&lt;= 2 tens-place 9) (zero? tens-place))]} (if (zero? tens-place) "" (tens-names (- tens-place 2)))) (defn- stringify-mid-less-than-hundred [chunk] {:pre [(&lt;= 20 chunk 99)]} (let [[tens ones] (h/div-mod chunk 10)] (str (stringify-tens-place tens) (if (or (zero? tens) (zero? ones)) "" "-") (stringify-ones ones)))) (declare stringify-chunk) (defn- stringify-greater-hundred [chunk] {:pre [(&lt;= 100 chunk 999)]} (let [[hundreds tens-and-ones] (h/div-mod chunk 100)] (str (stringify-ones hundreds) " hundred" (if (zero? tens-and-ones) "" (str " " (stringify-chunk tens-and-ones)))))) (defn stringify-chunk [chunk] {:pre [(&lt;= 0 chunk 999)]} (let [f (condp &gt; chunk 10 stringify-ones 11 (constantly "ten") ; TODO: Eww 20 stringify-teen 100 stringify-mid-less-than-hundred stringify-greater-hundred)] (f chunk))) (defn stringify-int [n] {:pre [(&lt;= 0 n max-represntable-number)]} (let [std-n (if (float? n) (long n) n)] (if (zero? std-n) "zero" (-&gt;&gt; (reverse-chunk-n std-n places-chunk-size) (mapv vector place-names) (mapv (fn [[s n]] (if (zero? n) "" (let [sep (if (empty? s) "" " ")] (str (stringify-chunk n) sep s))))) (remove empty?) ; 0s stringify to empty strings, and need to be removed (reverse) (s/join " "))))) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-02T23:30:26.537", "Id": "204810", "Score": "1", "Tags": [ "clojure", "numbers-to-words" ], "Title": "Number Stringifier in Clojure" }
204810
<p>This is an assignment and I'm trying to improve upon the design factor. Honestly the task seems very trivial to use inheritance so I kind of did it for the sake of doing it. The problem description should be quite clear in the comments provided above the <code>Main</code> class, but do let me know how I can make the question clearer.</p> <p><strong>Main class</strong></p> <pre><code>import java.util.Scanner; import java.util.ArrayList; import java.util.HashMap; /** * Main class that models an OrderManager. * This class fulfills its responsibility as follows: * (i)Taking in inputs to create a sequence of Food or Combo objects, * (ii) Prints the items in the required sequence according to their types, * (iii)Taking in creation ids after "end" to create an order sequence to be printed, * along with the total price of all items in the order sequence */ public class Main { /** * This field holds an ArrayList of burgers, * to allow for ease in printing burgers together. */ private static ArrayList&lt;Burger&gt; burgers = new ArrayList&lt;&gt;(); /** * This field holds an ArrayList of snacks, * to allow for ease in printing snacks together. */ private static ArrayList&lt;Snack&gt; snacks = new ArrayList&lt;&gt;(); /** * This field holds an ArrayList of drinks, * to allow for ease in printing drinks together. */ private static ArrayList&lt;Drink&gt; drinks = new ArrayList&lt;&gt;(); /** * This field holds a HashMap of food objects, which allows easy referencing in (iii). */ private static HashMap&lt;Integer,Food&gt; foods = new HashMap&lt;&gt;(); /** * This field holds a HashMap of combos, * which allows easy referencing in (iii). */ private static HashMap&lt;Integer, Combo&gt; combos = new HashMap&lt;&gt;(); /** * This field contains an ArrayList of keys, * to print out multiple combos in their creation sequence. */ private static ArrayList&lt;Integer&gt; comboSeq = new ArrayList&lt;&gt;(); /** * Reads inputs using a scanner, creates Food or legal Combo objects, * based on the initial inputs collected. */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int counter = 0; while (sc.hasNext()) { String cmd = sc.next(); if (cmd.equals("add")){ String type = sc.next(); if (type.equals("Combo")){ int c1 = sc.nextInt(); int c2 = sc.nextInt(); int c3 = sc.nextInt(); if (!foods.containsKey(c1) || !foods.containsKey(c2) || !foods.containsKey(c3)) { System.out.println("Error: Invalid combo input "+c1+' '+ c2+ ' '+ c3); continue; }else if (c1 &gt;= c2 || c2 &gt;= c3) { System.out.println("Error: Invalid combo input "+c1+' '+ c2+ ' '+ c3); continue; } else { ArrayList&lt;Food&gt; trf = new ArrayList&lt;&gt;(); trf.add(foods.get(c1)); trf.add(foods.get(c2)); trf.add(foods.get(c3)); Combo tempCombo = new Combo(trf, counter); combos.put(counter,tempCombo); comboSeq.add(counter); } }else { String desc = sc.next(); int price = sc.nextInt(); if (type.equals("Burger")){ Burger temp = new Burger(desc,price,counter); burgers.add(temp); foods.put(counter,temp); } else if (type.equals("Snack")){ Snack temp = new Snack(desc,price,counter); snacks.add(temp); foods.put(counter, temp); } else if (type.equals("Drink")) { Drink temp = new Drink(desc,price,counter); drinks.add(temp); foods.put(counter, temp); } } counter++; } else if (cmd.equals("end")){ break; } } printSequence(); printOrders(sc); } /** * Prints the created items in the sequence of burgers, snacks, * drinks and combos. */ public static void printSequence(){ for (Burger tempBurger: burgers) { System.out.println(tempBurger); } for (Snack tempSnack: snacks) { System.out.println(tempSnack); } for (Drink tempDrink: drinks) { System.out.println(tempDrink); } for (int tempInt: comboSeq) { Combo tempCombo = combos.get(tempInt); tempCombo.internalPrint(); } } /** * Reads creation ids using a scanner, * and prints the objects associated with the creation id * The total price of all items printed will also be printed at the end. */ public static void printOrders(Scanner sc){ int sum = 0; System.out.println("--- Order ---"); while (sc.hasNext()){ int num = sc.nextInt(); if (foods.containsKey(num)) { Food tempFood = foods.get(num); System.out.println(tempFood); sum += tempFood.getPrice(); } else { Combo tempCombo = combos.get(num); tempCombo.internalPrint(); sum += tempCombo.getPrice(); } } System.out.println("Total: " + sum); } } </code></pre> <p><strong>Food class</strong> </p> <pre><code>public class Food { private String name; private int price; private int orderNum; public Food(String name, int price, int orderNum){ this.name = name; this.orderNum = orderNum; this.price= price; } public String getName(){ return this.name; } public int getPrice(){ return this.price; } public int getOrderNum(){ return this.orderNum; } } </code></pre> <p><strong>Burger class</strong> </p> <pre><code>/** * This is a subclass of the Food class, * which contains a identity field of "Burger", * to differentiate between other Food objects. * This class also overrides the toString method to print out the burger. */ public class Burger extends Food { private String name; private int price; private int orderNum; private String type = "Burger"; public Burger(String name, int price, int orderNum){ super(name,price,orderNum); } public String toString() { return "#"+this.getOrderNum()+' '+this.type+": "+this.getName() + " ("+this.getPrice()+')'; } } </code></pre> <p><strong>Drink class</strong></p> <pre><code>public class Drink extends Food { private String name; private int price; private int orderNum; private String type = "Drink"; public Drink(String name, int price, int orderNum){ super(name,price,orderNum); } public String toString() { return "#"+this.getOrderNum()+' '+this.type+": "+this.getName() + " ("+this.getPrice()+')'; } } </code></pre> <p><strong>Snack class</strong></p> <pre><code>public class Snack extends Food { private String name; private int price; private int orderNum; private String type = "Snack"; public Snack(String name, int price, int orderNum){ super(name,price,orderNum); } public String toString() { return "#"+this.getOrderNum()+' '+this.type+": "+this.getName() + " ("+this.getPrice()+')'; } } </code></pre> <p><strong>Combo class</strong></p> <pre><code>import java.util.ArrayList; public class Combo { ArrayList&lt;Food&gt; foodParts = new ArrayList&lt;&gt;(); private int orderNum; private String type = "Combo"; public Combo(ArrayList&lt;Food&gt; foodParts, int orderNum){ this.foodParts = foodParts; this.orderNum = orderNum; } public void internalPrint(){ System.out.println("#"+this.orderNum+' '+this.type + " ("+this.getPrice()+')'); for (Food tempFood : this.foodParts) { System.out.println(" "+tempFood); } } public int getPrice(){ int sum = 0; for (Food tempFood : this.foodParts) { sum += tempFood.getPrice(); } return sum-50; } public int getOrderNum(){ return this.orderNum; } } </code></pre> <p><strong>Test input</strong></p> <pre><code>add Burger Hamburger 399 add Snack Fries 189 add Combo 0 1 2 add Drink SoftDrink 149 add Combo 0 2 1 add Combo 0 1 2 add Snack Drumlets 169 add Burger CheeseBurger 200 add Drink OrangeJuice 209 end 2 1 4 3 0 </code></pre> <p><strong>Expected output to be fulfilled</strong></p> <pre><code>Error: Invalid combo input 0 1 2 Error: Invalid combo input 0 2 1 #0 Burger: Hamburger (399) #5 Burger: CheeseBurger (200) #1 Snack: Fries (189) #4 Snack: Drumlets (169) #2 Drink: SoftDrink (149) #6 Drink: OrangeJuice (209) #3 Combo (687) #0 Burger: Hamburger (399) #1 Snack: Fries (189) #2 Drink: SoftDrink (149) --- Order --- #2 Drink: SoftDrink (149) #1 Snack: Fries (189) #4 Snack: Drumlets (169) #3 Combo (687) #0 Burger: Hamburger (399) #1 Snack: Fries (189) #2 Drink: SoftDrink (149) #0 Burger: Hamburger (399) Total: 1593 </code></pre> <p>While writing this code, even though it's simple, I am in a dilemma whether combo should be distinguished from a Food object. In the first place Food doesn't offer much extensibility benefits, but having a subclass Food object that contains other Food objects didn't make any sense to me, so I didn't do it, but many of the functions seems duplicated. Can anyone help me with this? Any other comments on my code are also accepted. Thank you.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-05T10:31:40.940", "Id": "399270", "Score": "0", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply stat...
[ { "body": "<p>Consider renaming <code>Food</code> to <code>OrderableItem</code> or something similar. Among other things, that will remove the cognitive dissonance of making <code>Combo</code> and <code>Drink</code> each a <code>Food</code>. </p>\n\n<p>In most situations, you would prefer <code>OrderableItem<...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T04:28:32.520", "Id": "204820", "Score": "3", "Tags": [ "java", "simulation" ], "Title": "Extending Combo from Food in FoodOrder Simulator" }
204820
<p>This prints out a triple layer circle with 12 points per circle and finds the points across a grid.</p> <p>I had a really hard time with this and I'm planning to implement a lot more code but I don't want to spoil my end result. I'm new so take it easy on me but feel free to criticize as I am looking to improve my coding and syntax.</p> <pre><code>#include &lt;iostream&gt; #include &lt;algorithm&gt; #include &lt;cmath&gt; struct vec2{ double circ; double x; double y; } v[36]; void circle(){ double pi = 3.141; double r = 6.75; for (int i = 0; i &lt; 3; i++) { v[i].circ = (2*pi)*r; std::cout &lt;&lt; "circ # " &lt;&lt; i+1 &lt;&lt; ": " &lt;&lt; v[i].circ &lt;&lt; std::endl; for (int j = 0; j &lt; 12; j++) { int w = 19; int h = 12; int comp = j*30; double rad = comp * (pi / 180); double x = w + (r * cos(rad)) * 5/3; double y = h + (r * sin(rad)); int fact = i*12+j; v[fact].x=x; v[fact].y=y; } r += 2; std::cout &lt;&lt; std::endl; }} bool vecfind(int row, int col){ for(int i = 0; i&lt;36; i++){ if(v[i].x &gt;= col &amp;&amp; v[i].x &lt; col+1 &amp;&amp; v[i].y &gt;= row &amp;&amp; v[i].y &lt; row+1) { return true;} } return false; } void square(){ for(int row = 0; row &lt; 23; row++){ for(int col = 0; col &lt; 39;col++){ if (vecfind(row, col)){std::cout &lt;&lt; "x";} else{std::cout &lt;&lt; " ";}} std::cout &lt;&lt; std::endl;} return;} int main() { circle(); square(); return 0;} </code></pre> <p>output:</p> <pre><code>circ # 1: 42.4035 circ # 2: 54.9675 circ # 3: 67.5315 x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T01:28:28.623", "Id": "395178", "Score": "0", "body": "I edited my post. Can this post be unheld?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T03:58:55.687", "Id": "395200", "Score": "1", ...
[ { "body": "<p>There's a lot that can be improved in your code, especially if you are using C++. The more advanced features of C++ actually help you organize your code better, help you write less code to do what you want, and remove a lot of tedium that you find in C-style code.</p>\n\n<h2>Use proper names for v...
{ "AcceptedAnswerId": "204926", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T05:23:09.003", "Id": "204822", "Score": "1", "Tags": [ "c++", "beginner", "matrix", "computational-geometry", "ascii-art" ], "Title": "Drawing concentric circles to console" }
204822
<p><strong>IMPORTANT</strong>: giving too big combination of node count and edge/neighbor count can overflow your RAM and swap file very quickly, thus I recommend staying below 500 on node count and below 50 on neighbor count.</p> <h2>Background</h2> <p>I had an assignment on generating multi dimensional maze, which I didn't submit in time. The assignment required Python 2.7 only with standard library and I had no idea what algorithm to choose. </p> <p>Feeling miserable, I went to a lecture which explained backtracking with some node/value selection strategies (which turns out have been covered before). And after a few hours of sinking in the lecture, I was able to apply it on the problem.</p> <h2>Problem</h2> <blockquote> <p>Generate a maze with \$N\$ nodes, \$K &lt; N\$ of which are border nodes. Each border must have degree of \$m\$, and each non-border node must have degree of \$p&gt;m\$. The generated maze must be a minimally connected graph.</p> <p>After generation of the graph is done, assign wall, hole, monster and gold properties to each node. Wall or hole has no effect on the graph structure of the maze! Every property has value of either \$1\$ or \$0\$. If monster is present on the node, make smell present as well. If there is hole in the node, make wind present as well.</p> </blockquote> <hr> <h2>Solution (algorithm)</h2> <p>Generate the nodes, assigning indices in increasing order. Partition the generated nodes, making first \$K\$ nodes border nodes, and the rest non-border nodes. At each step:</p> <ol> <li><p>Sort nodes (prefer nodes which have highest neighbor count filled in, and if the same, prefer border nodes, as this will put more constraining nodes first)</p></li> <li><p>Create a copy of nodes with satisfied nodes removed (the ones which have required degree), name it <code>remaining</code></p></li> <li><p>Pick the front node (it is the most constraining node to start from, thus it allows to exit from erroneous branch of decision tree quicker), name it <code>current_node</code></p></li> <li><p><code>first = remaining.rbegin()</code>, <code>last = prev(remaining.rend())</code></p></li> <li><p>While <code>first != last</code></p> <p>5.1. Set next neighbor of <code>current_node</code> to <code>*first</code>, and neighbor of <code>*first</code> to <code>current_node</code>.</p> <p>5.2. Go to 1, save result in <code>result</code>.</p> <p>5.3 If <code>result</code> is not empty, it is the solution. Return it propagating from every level of recursion.</p> <p>5.4 If <code>result</code> is empty, pop a neighbor from <code>current_node</code> and <code>*first</code></p> <p>5.5 Advance <code>first</code>.</p></li> <li><p>Return empty result</p></li> </ol> <p>Do note that since neighbor is chosen from the least connected nodes, it guarantees that graph is minimally connected (well, at least I believe so).</p> <hr> <h2>Code</h2> <p><strong>graph_node.hpp</strong>:</p> <pre><code>#ifndef MAZE_GENERATOR_GRAPH_NODE_HPP #define MAZE_GENERATOR_GRAPH_NODE_HPP #include &lt;cstddef&gt; #include &lt;vector&gt; #include &lt;ostream&gt; #include &lt;algorithm&gt; namespace shino { struct graph_node { std::size_t index; std::vector&lt;std::size_t&gt; neighbor_indices; std::size_t border_count; int gold; bool wall; double wind; double smell; bool monster; bool hole; }; bool is_border_node(const graph_node&amp; node) { return node.index &lt; node.border_count; } bool operator&gt;(const graph_node&amp; lhs, const graph_node&amp; rhs) { if (lhs.neighbor_indices.size() == rhs.neighbor_indices.size()) { bool is_lhs_border = is_border_node(lhs); bool is_rhs_border = is_border_node(rhs); return is_lhs_border &gt; is_rhs_border; //prefer borders } else { return lhs.neighbor_indices.size() &lt; rhs.neighbor_indices.size(); } } bool operator&lt;(const graph_node&amp; lhs, const graph_node&amp; rhs) { return rhs &gt; lhs; } std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const graph_node&amp; node) { os &lt;&lt; "index: " &lt;&lt; node.index &lt;&lt; ' ' &lt;&lt; "is border: " &lt;&lt; is_border_node(node) &lt;&lt; ", neighbors:{"; if (node.neighbor_indices.empty()) return os &lt;&lt; '}'; os &lt;&lt; node.neighbor_indices.front(); for (std::size_t i = 1; i &lt; node.neighbor_indices.size(); ++i) { os &lt;&lt; ',' &lt;&lt; node.neighbor_indices[i]; } return os &lt;&lt; '}'; } bool is_satisfied(const graph_node&amp; node, std::size_t border_neighbor_count, std::size_t node_neighbor_count) { if (is_border_node(node)) return node.neighbor_indices.size() == border_neighbor_count; else return node.neighbor_indices.size() == node_neighbor_count; } bool has_this_neighbor(const graph_node&amp; node, std::size_t neighbor_index) { return !node.neighbor_indices.empty() and std::find_if(node.neighbor_indices.begin(), node.neighbor_indices.end(), [neighbor_index](auto&amp;&amp; neighbor){ return neighbor == neighbor_index; }) != node.neighbor_indices.end(); } } #endif //MAZE_GENERATOR_GRAPH_NODE_HPP </code></pre> <p><strong>main.cpp:</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;queue&gt; #include &lt;optional&gt; #include &lt;algorithm&gt; #include &lt;iterator&gt; #include &lt;random&gt; #include "graph_node.hpp" template &lt;typename Compare = std::less&lt;&gt;&gt; using ranking = std::priority_queue&lt;shino::graph_node, std::vector&lt;shino::graph_node&gt;, Compare&gt;; using maze = std::vector&lt;shino::graph_node&gt;; template &lt;typename T&gt; std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const std::vector&lt;T&gt;&amp; v) { os &lt;&lt; "-----\n"; for (auto&amp;&amp; elem: v) { os &lt;&lt; elem &lt;&lt; '\n'; } return os &lt;&lt; "-----\n\n"; } maze generate_nodes(std::size_t node_count, std::size_t border_count) { maze nodes(node_count); for (std::size_t index = 0; index &lt; node_count; ++index) { nodes[index].index = index; nodes[index].border_count = border_count; } return nodes; } std::optional&lt;maze&gt; generate_maze(const maze&amp; nodes, std::size_t border_neighbor_count, std::size_t node_neighbor_count) { if (border_neighbor_count == 0) return {}; auto new_nodes = nodes; auto remaining = new_nodes; auto new_end = std::remove_if(remaining.begin(), remaining.end(), [border_neighbor_count, node_neighbor_count](auto&amp;&amp; node) { return shino::is_satisfied(node, border_neighbor_count, node_neighbor_count); }); remaining.erase(new_end, remaining.end()); std::sort(remaining.begin(), remaining.end()); if (remaining.empty()) return new_nodes; auto&amp; current_node = new_nodes[remaining.front().index]; auto first = remaining.rbegin(); auto last = std::prev(remaining.rend()); while (first != last) { if (shino::has_this_neighbor(current_node, first-&gt;index)) { ++first; continue; } auto&amp; candidate_neighbor = new_nodes[first-&gt;index]; current_node.neighbor_indices.push_back(candidate_neighbor.index); candidate_neighbor.neighbor_indices.push_back(current_node.index); auto result = generate_maze(new_nodes, border_neighbor_count, node_neighbor_count); if (result.has_value()) return result; current_node.neighbor_indices.pop_back(); candidate_neighbor.neighbor_indices.pop_back(); ++first; } return {}; //no solution found } void assign_properties(maze&amp; nodes, double wall_probability, double hole_probability, double monster_probability, double gold_probability) { std::mt19937 twister(std::random_device{}()); std::bernoulli_distribution wall_distribution(wall_probability); std::bernoulli_distribution hole_distribution(hole_probability); std::bernoulli_distribution monster_distribution(monster_probability); std::bernoulli_distribution gold_distribution(gold_probability); for (auto&amp;&amp; node: nodes) { node.wall = wall_distribution(twister); node.hole = hole_distribution(twister); node.wind = node.hole; node.monster = monster_distribution(twister); node.smell = node.monster; node.gold = gold_distribution(twister); } } int main(int argc, char* argv[]) { if (argc != 9) { std::cerr &lt;&lt; "usage: program node_count border_count border_edge_count non_border_edge_count " "wall_probability hole_probability monster_probability gold_probability" &lt;&lt; '\n'; return -1; } std::size_t node_count = std::stoul(argv[1]); std::size_t border_count = std::stoul(argv[2]); std::size_t border_edge_count = std::stoul(argv[3]); std::size_t non_border_edge_count = std::stoul(argv[4]); //sometimes also referred as just node edge count double wall_probability = std::stod(argv[5], nullptr); double hole_probability = std::stod(argv[6], nullptr); double monster_probability = std::stod(argv[7], nullptr); double gold_probability = std::stod(argv[8], nullptr); auto nodes = generate_nodes(node_count, border_count); std::cout &lt;&lt; nodes &lt;&lt; '\n'; auto found_solution = generate_maze(nodes, border_edge_count, non_border_edge_count); if (found_solution.has_value()) { auto solution = std::move(found_solution.value()); assign_properties(solution, wall_probability, hole_probability, monster_probability, gold_probability); std::cout &lt;&lt; "solution is:\n" &lt;&lt; solution &lt;&lt; '\n'; } else { std::cout &lt;&lt; "solution not found\n"; } } </code></pre> <hr> <h2>Concerns</h2> <ol> <li><p>It passes each node combination by value, and since recursion is quite deep, it overflows memory very quickly.</p></li> <li><p>Recursion depth is bound by edge count, which is much bigger than vertex count.</p></li> <li><p>In general performs more operations than necessary, but I didn't find any way to reduce those.</p></li> <li><p>It is extremely slow to detect absence of solution.</p></li> </ol> <p>Feel free to comment on anything else!</p>
[]
[ { "body": "<p>Generally, this is a well-written program, so it was hard to find much fault with it. However, here are a few things that might help you improve your program.</p>\n\n<h2>Don't over-use <code>const</code></h2>\n\n<p>I don't know if I've ever given this advice here. Much more frequently, I advise ...
{ "AcceptedAnswerId": "204853", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T06:20:54.120", "Id": "204827", "Score": "5", "Tags": [ "c++", "random", "graph", "c++17" ], "Title": "Generate multi dimensional maze with borders and fixed degree on each node type" }
204827
<h2>Intention</h2> <p>I came with the idea of generic, portable, highly reliable, and further customizable function for Shell scripts, written in <a href="https://en.wikipedia.org/wiki/POSIX" rel="nofollow noreferrer">POSIX</a>, for error handling.</p> <h2>Purpose</h2> <p>The function shall find out, if the terminal has color support, and act accordingly. If it has, then I highlight the <em>error origin</em> and the <em>exit code</em> with different colors. The main message shall be tabbed from the left, all for the best readability.</p> <h2>Example function call and error handler output (<strong>textual</strong>) + Explanation</h2> <p><code>print_usage_and_exit</code> is a self-explanatory function, which watches over the number of given arguments, it accepts exactly one, let's give it some more:</p> <p><strong>Example function:</strong></p> <pre><code>print_usage_and_exit() { # check if exactly one argument has been passed [ "${#}" -eq 1 ] || print_error_and_exit 1 "print_usage_and_exit" "Exactly one argument has not been passed!\\n\\tPassed: ${*}" # check if the argument is a number is_number "${1}" || print_error_and_exit 1 "print_usage_and_exit" "The argument is not a number! Exit code expected." echo "Usage: ${0} [-1]" echo " -1: One-time coin collect." echo "Default: Repeat coin collecting until interrupted." exit "${1}" } </code></pre> <p><strong>Example function call - erroneous:</strong></p> <pre><code>print_usage_and_exit a b c 1 2 3 </code></pre> <p><strong>Example output:</strong></p> <pre><code>print_usage_and_exit() Exactly one argument has not been passed! Passed: a b c 1 2 3 exit code = 1 </code></pre> <h2>Example error handler output (visual)</h2> <p><a href="https://i.stack.imgur.com/P429k.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/P429k.png" alt="Example error handler output (visual)"></a></p> <h2>The actual error handler function code</h2> <pre><code>print_error_and_exit() # expected arguments: # $1 = exit code # $2 = error origin (usually function name) # $3 = error message { # check if exactly 3 arguments have been passed # if not, print out an internal error without colors if [ "${#}" -ne 3 ] then printf "print_error_and_exit() internal error\\n\\n\\tWrong number of arguments has been passed: %b!\\n\\tExpected the following 3:\\n\\t\\t<span class="math-container">\$1 - exit code\\n\\t\\t\$</span>2 - error origin\\n\\t\\t\$3 - error message\\n\\nexit code = 1\\n" "${#}" 1&gt;&amp;2 exit 1 fi # check if the first argument is a number # if not, print out an internal error without colors if ! [ "${1}" -eq "${1}" ] 2&gt; /dev/null then printf "print_error_and_exit() internal error\\n\\n\\tThe first argument is not a number: %b!\\n\\tExpected an exit code from the script.\\n\\nexit code = 1\\n" "${1}" 1&gt;&amp;2 exit 1 fi # check if we have color support if [ -x /usr/bin/tput ] &amp;&amp; tput setaf 1 &gt; /dev/null 2&gt;&amp;1 then # colors definitions readonly bold=$(tput bold) readonly red=$(tput setaf 1) readonly yellow=$(tput setaf 3) readonly nocolor=$(tput sgr0) # combinations to reduce the number of printf references readonly bold_red="${bold}${red}" readonly bold_yellow="${bold}${yellow}" # here we do have color support, so we highlight the error origin and the exit code printf "%b%b()\\n\\n\\t%b%b%b\\n\\nexit code = %b%b\\n" "${bold_yellow}" "${2}" "${nocolor}" "$3" "${bold_red}" "${1}" "${nocolor}" 1&gt;&amp;2 exit "$1" else # here we do not have color support printf "%b()\\n\\n\\t%b\\n\\nexit code = %b\\n" "${2}" "${3}" "${1}" 1&gt;&amp;2 exit "$1" fi } </code></pre> <h2>EDIT</h2> <p>I realized the <code>tput</code> could very well be anywhere else than in <code>/usr/bin/</code>.</p> <p>So, while keeping the original code untouched, I have changed the line:</p> <pre><code>if [ -x /usr/bin/tput ] &amp;&amp; tput setaf 1 &gt; /dev/null 2&gt;&amp;1 </code></pre> <p>to a more plausible check:</p> <pre><code>if command -v tput &gt; /dev/null 2&gt;&amp;1 &amp;&amp; tput setaf 1 &gt; /dev/null 2&gt;&amp;1 </code></pre>
[]
[ { "body": "<p>I'm a big fan of <code>tput</code>, which many script authors seem to overlook, for generating appropriate terminal escapes. Perhaps my enthusiasm started back in the early '90s, when using idiosyncratic (non-ANSI) terminals, but it still glows bright whenever I run a command in an Emacs buffer o...
{ "AcceptedAnswerId": "204845", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T06:32:32.257", "Id": "204828", "Score": "3", "Tags": [ "error-handling", "linux", "sh", "posix" ], "Title": "Generic error handler function for POSIX shell scripts" }
204828
<p>I am implementing observer pattern(refering codeproject) for stock quote update. I have created an interface for Subject and Observer. I have created instances for Subject and Observer and also the functionality to register, notify and update. Kindly let me know the approach is correct</p> <pre><code>public interface IObserver { void update(double value); } } </code></pre> <p>//subject</p> <pre><code>public interface ISubject { void Register(IObserver o); void UnRegister(IObserver o); void notify(); } </code></pre> <p>//Observer instance</p> <pre><code>public class InfosysStock : IObserver { private ISubject _subject; private double _latestvalue = 0; public InfosysStock(ISubject subject) { _subject = subject; _subject.Register(this); } public void update(double value) { _latestvalue = value; display(); } private void display() { Console.WriteLine("The latest value is : " + _latestvalue); } public void unsubscribe() { _subject.UnRegister(this); } } </code></pre> <p>//Subject Instance</p> <pre><code>public class StockMarket : ISubject { List&lt;IObserver&gt; observers = new List&lt;IObserver&gt;(); public int _stockvalue = 0; public void setValue(int v) { _stockvalue = v; notify(); } public void notify() { foreach (var observer in observers) { observer.update(_stockvalue); } } public void Register(IObserver o) { observers.Add(o); } public void UnRegister(IObserver o) { int idx = observers.IndexOf(o); observers.RemoveAt(idx); } } </code></pre> <p>Finally the main class</p> <pre><code>StockMarket stockmarket = new StockMarket(); InfosysStock infy = new InfosysStock(stockmarket); stockmarket.setValue(15); stockmarket.setValue(21); infy.unsubscribe(); Console.ReadLine(); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T06:15:01.627", "Id": "395207", "Score": "0", "body": "This is not how it is supposed to be used. `setValue` should automatiacally _notify_ listeners. Having to call `notify` manually is pointless and makes the whole pattern unnecess...
[ { "body": "<h2>1. If you are implementing this pattern for learning, then it is OK.</h2>\n\n<p>Otherwise, you can use built-in <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/events/how-to-implement-an-observer\" rel=\"nofollow noreferrer\">Observer Pattern of C#.</a></p>\n\n<h2>2. Think about readab...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T07:02:13.310", "Id": "204829", "Score": "0", "Tags": [ "c#", "observer-pattern" ], "Title": "Apply stock quote changes using observer pattern" }
204829
<p>Python script to output status information to a small OLED screen connected to a Raspberry Pi.</p> <p>I'm relatively new at writing python so although the app works and outputs correct information it is far from the clean code I encountered when looking at other people's code. </p> <p>I think I covered most of PEP8. I am most interested in code structure, 'the python way', refactoring and cleanup.</p> <pre><code># -*- coding:UTF-8 -*- # # | file : showStats.py # | version : V1.0 # | date : 2018-10-01 # | function : Show statistics on Waveshare 1.5inch OLED # | To preserve OLED screen life the display is turned off unless # | motion is detected in the server room. (via MQTT). # | - Listens on MQTT topic # | + home/basement/serverroom/motionsensor # # Requires psUtil. Install: sudo apt-get python-psutil # Requires pahoMQTT. Install: sudo apt install python-pip # pip install paho-mqtt # # INFO: # Collects various information about the system and displays the info on the screen # # Logging import logging import logging.config import commands import os import psutil import platform import datetime import time # MQTT import paho.mqtt.client as paho # RPI import RPi.GPIO as GPIO # specific to OLED screen import DEV_Config import OLED_Driver import Image import ImageDraw import ImageFont import ImageColor # CONSTANTS LOGGING_CONFIG_FILE = "logging_config.ini" MQTT_SUBSCRIBE_TOPIC = "home/basement/serverroom/motionsensor" MQTT_BROKER = ("192.168.1.170", 1883, 60) # (host, port, timeout) REFRESH_INTERVAL = 2 # seconds #GLOBAL OLED = None mqtt_client = None show_on_screen = False # Logging setup logging.config.fileConfig(fname=LOGGING_CONFIG_FILE, disable_existing_loggers=True) logger = logging.getLogger() try: def main(): logging.addLevelName(100, 'START') logging.log(100, "============================") logging.log(100, "STARTING UP") logger.info("Initialize OLED screen") global OLED OLED = OLED_Driver.OLED() oled_scan_dir = OLED_Driver.SCAN_DIR_DFT # SCAN_DIR_DFT = D2U_L2R OLED.OLED_Init(oled_scan_dir) OLED.OLED_Clear() DEV_Config.Driver_Delay_ms(500) global mqtt_client mqtt_client = paho.Client(client_id="RPI-A_OLEDScreen", clean_session=False, userdata=None) mqtt_client.enable_logger(logger) mqtt_client.on_connect = on_connect mqtt_client.on_subscribe = on_subscribe mqtt_client.on_message = on_message mqtt_client.connect(MQTT_BROKER[0], MQTT_BROKER[1], MQTT_BROKER[2]) mqtt_client.loop_start() logger.info("Setting up OLED display area") DEV_Config.Driver_Delay_ms(500) image = Image.new("L", (OLED.OLED_Dis_Column, OLED.OLED_Dis_Page), 0) # grayscale (luminance) ImageDraw.Draw(image) # draw = ImageDraw.Draw(image) logger.info("Fetch platform info once@startup") os_name, name, version, _, _, _ = platform.uname() boot_time = datetime.datetime.fromtimestamp(psutil.boot_time()) mac_address = get_mac_address('eth0') logging.log(100, "OS: " + os_name) logging.log(100, "Device name: " + name) logging.log(100, "version: " + version) logging.log(100, "Logging config file: " + LOGGING_CONFIG_FILE) logging.log(100, "============================") while True: update_display(os_name, name, version, boot_time, mac_address, show_on_screen) time.sleep(REFRESH_INTERVAL) # seconds def on_connect(client, userdata, flags, rc): logger.info("CONNACK received with code %d." % rc) client.subscribe(MQTT_SUBSCRIBE_TOPIC, qos=1) def on_subscribe(client, userdata, mid, granted_qos): logger.info("Subscribed: " + str(mid) + " " + str(granted_qos)) def on_message(client, userdata, msg): global show_on_screen logger.info(msg.topic + " " + str(msg.qos) + " " + str(msg.payload)) if msg.topic == MQTT_SUBSCRIBE_TOPIC and msg.payload == "motion": show_on_screen = True else: show_on_screen = False def update_display(os_name, name, version, boot_time, mac_address, show_on_screen): if not show_on_screen: OLED.OLED_Clear() return else: ip_address = None fs_total, fs_used, fs_free, fs_percent = (None, None, None, None) # update values every loop current_time = datetime.datetime.now() cpu_percent = str(psutil.cpu_percent()) + "%" # first run gives a wrong value due to CPU load while initializing PSUTIL cpu_temp = get_cpu_temperature() # update every hour if current_time.minute % 59: ip_address = commands.getoutput('hostname -I') if current_time.hour % 23: # update every day fs_total, fs_used, fs_free, fs_percent = psutil.disk_usage("/") # temporary debug code. Replace with 'draw.text()' and 'draw.line()' print(os_name, name, version) print("Local IP address: " + ip_address) print("MAC: " + mac_address) print("CPU %:", cpu_percent) print("CPU temp:", cpu_temp) print(sizeof_fmt(fs_used), "of", sizeof_fmt(fs_total), "(", fs_percent, "%)") print("up time:", friendly_time_delta(boot_time, current_time)) logger.info("Done updating OLED screen") # Return friendly TimeDelta string # Example: "4 days, 8 hours 2 minutes" def friendly_time_delta(start, end=datetime.datetime.now()): up_time = end - start years, reminder = divmod(up_time.total_seconds(), 31556926) days, reminder = divmod(reminder, 86400) hours, reminder = divmod(reminder, 3600) minutes, seconds = divmod(reminder, 60) ret = "" if years &gt; 1: ret = str(int(years)) + " years, " elif years == 1: ret = "1 year, " if days &gt; 1: ret += str(int(days)) + " days, " elif days == 1: ret += "1 day, " if hours &gt; 1: ret += str(int(hours)) + " hours" elif hours == 1: ret += str(int(hours)) + " hour" if ret == "" and minutes &gt; 0: ret += str(int(minutes)) + " minutes" if ret == "" and seconds &gt; 0: ret += str(int(seconds)) + " seconds" return ret # Return the MAC address of the specified interface def get_mac_address(interface='eth0'): try: raw_address = open('/sys/class/net/%s/address' % interface).read() except: raw_address = "00:00:00:00:00:00" return raw_address[0:17] # return friendly byte size string. # Example: 1024 -&gt; 1KiB def sizeof_fmt(num, suffix='B'): for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) &lt; 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix) # Return CPU temperature as a character string def get_cpu_temperature(): res = os.popen('vcgencmd measure_temp').readline() return res.replace("temp=", "").replace("'C\n", "") if __name__ == "__main__": main() except KeyboardInterrupt: logger.info("exiting program") except: logger.error('Exception occurred', exc_info=True) raise finally: GPIO.cleanup() # this ensures a clean exit mqtt_client.loop_stop() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T13:43:48.810", "Id": "395095", "Score": "0", "body": "Please check your indentation. The easiest way to post code is to paste it into the question editor, highlight it, and press Ctrl-K to mark it as a code block." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T07:10:18.967", "Id": "204830", "Score": "3", "Tags": [ "python", "beginner", "python-2.x", "raspberry-pi" ], "Title": "OLED display application for Raspberry Pi" }
204830
<p>I recently didn't pass a take-home code test for a job interview - and one of the reasons for this was that the code was not as idiomatic as it could be. </p> <p>The premise is in the title - but below details the instructions in the readme to get an idea of how it works typing in commands to get desired result:</p> <p>I N M - Create a new M x N image with all pixels coloured white (O).</p> <p>L X Y C - Colours the pixel (X,Y) with colour C.</p> <p>V X Y1 Y2 C - Draw a vertical segment of colour C in column X between rows Y1 and Y2 (inclusive).</p> <p>The code works and all tests pass (don't want to just paste the entire project on here) - but I would like to get feedback on whether the approach I've taken (i.e - OOP approach having 2 classes and updating their attributes throughout / using a case statement to accept input and validate with regex) is good practice - and anywhere where I may have slipped away from a native and idiomatic ruby approach.</p> <p>Many thanks in advance for any feedback.</p> <p>This is the code for the main bitmap editor program that runs and accepts the commands:</p> <pre><code>class BitmapEditor require 'pry' require './lib/bitmap_matrix' attr_accessor :running def initialize(running) @running = running end def run puts "Please enter your command here" while @running # STORE VARIABLE FOR USER INPUT command = STDIN.gets.chomp # EVALUATE CASE STATEMENT evaluate_command(command) end end # CREATE CASE STATEMENT TO RECOGNIZE THE INPUT def evaluate_command(command) puts "evaluating command" # CHECK IF BITMAP EXISTS IF THE COMMAND IS NOT TO CREATE A BITMAP OR QUIT PROGRAM if bitmap_required(command.rstrip) # STRIP END SPACE FROM COMMAND case command.rstrip when /I\s\d+\s\d+\z/ @bitmap_matrix = create_bitmap(*split_command(command)) when 'Q' puts 'Quitting Program' @running = false when 'C' @bitmap_matrix&amp;.clear when /L\s\d+\s\d+\s[a-zA-Z]\z/ @bitmap_matrix&amp;.color_single_pixel(*split_command(command)) when /V\s\d+\s\d+\s\d+\s[a-zA-Z]\z/ @bitmap_matrix&amp;.color_vertical_segment(*split_command(command)) when /H\s\d+\s\d+\s\d+\s[a-zA-Z]\z/ @bitmap_matrix&amp;.color_horizontal_segment(*split_command(command)) when 'S' @bitmap_matrix&amp;.draw else puts 'Command not recognized!' end else puts "Please draw Bitmap first" end end def create_bitmap(rows, columns) @bitmap_matrix = BitmapMatrix.new(rows.to_i, columns.to_i) end # METHOD TO DYNAMICALLY TAKE THE PARAMETERS OF COMMAND AFTER FIRST LETTER AND CONVERT THEM INTO ARGUMENTS FOR PROCESSING BITMAP QUERY def split_command(command) stripped = command.split(" ") stripped.delete(stripped[0]) stripped.map{|char| self.is_numeric?(char)} end def bitmap_required(command) command_doesnt_require_bitmap = command.match(/I\s\d+\s\d+\z/) || command == "Q" @bitmap_matrix || command_doesnt_require_bitmap end #IF COMMAND CHAR IS AN INTEGER - CONVERT TO INTEGER TO BE COMPATIBLE WITH BITMAP MATRIX def is_numeric?(char) char =~ /[0-9]/ ? char.to_i : char end end </code></pre> <p>This is the bitmap matrix class that builds the bitmap and applies the instructions specified in the above class:</p> <pre><code>class BitmapMatrix attr_accessor :row_count, :column_count, :matrix, :valid_request def initialize(columns, rows) @row_count = rows @column_count = columns @matrix = row_initialize(columns, rows) @valid_request = true puts 'BitMap created!' end def draw @matrix.values.map{|row| puts row.join(" ")} end def color_single_pixel(x, y, color) # VALIDATE COORDINATE ARE IN RANGE AND REASSIGN SPECIFIC VALUE IN HASH TO REPRESENT PIXEL COLORING if @matrix[y] @matrix[y][x-1] ? @matrix[y][x-1] = color : invalid_coordinates puts "Pixel Drawn" else invalid_coordinates end end def color_vertical_segment(column, y1, y2, color) # VALIDATE WHETHER GIVEN COLUMS AND ROWS ARE IN RANGE if @matrix[y1] &amp;&amp; @matrix[y2] valid = (@matrix[y1][column-1] &amp;&amp; @matrix[y2][column-1]) # LOOP GIVEN RANGE AND REASSIGN HASH VALUE TO REPRESENT PIXEL DRAWN valid ? line_drawing(y1, y2, 'row', column, color) : invalid_coordinates else invalid_coordinates end end def color_horizontal_segment( x1, x2, row, color) # VALIDATE WHETHER GIVEN COLUMS AND ROWS ARE IN RANGE if @matrix[row] valid = (@matrix[row][x1-1] &amp;&amp; @matrix[row][x2-1]) # LOOP GIVEN RANGE AND REASSIGN HASH VALUE TO REPRESENT PIXEL DRAWN valid ? line_drawing(x1, x2, 'column', row, color) : invalid_coordinates else invalid_coordinates end end # REINITIALIZING GRID HASH RESETS ALL TO O def clear @matrix = row_initialize(@column_count, @row_count) puts 'Grid cleared!' end def line_drawing(c1, c2, row_or_column, static_value, color) static_coordinate = row_or_column == "row" ? true : false sorted = [c1, c2].sort (sorted[0]..sorted[1]).to_a.map{|row_or_column| static_coordinate ? @matrix[row_or_column][static_value-1] = color : @matrix[static_value][row_or_column-1] = color} puts 'Pixel Line Drawn' end #CREATE A HASH THAT REPRESENTS ALL THE GRID POINTS def row_initialize(columns, rows) @matrix= {} rows.times do |row| row_array = [] columns.times{|n| row_array.push("O")} @matrix[row+1] = row_array end @matrix end def invalid_coordinates puts "Not valid coordinates" end end </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T07:27:25.820", "Id": "204831", "Score": "1", "Tags": [ "performance", "object-oriented", "ruby", "validation" ], "Title": "Ruby - Create a bitmap editor that accepts user input to plot a matrix grid, points and lines" }
204831
<p>I have a class that contains 2 properties of the same type. <code>decimal NetAmount</code> and <code>decimal GrossAmount</code></p> <p>I would like to initialize it using either <code>GrossAmount</code> or <code>NetAmount</code> and based on the one specified calculate the second one.</p> <p>Which way is the most elegant and why? (parameter validation is omitted for brevity)</p> <h1>1</h1> <pre><code>public class TaxedPrice { private TaxedPrice() { } public decimal NetAmount { get; private set; } public decimal GrossAmount { get; private set; } public static TaxedPrice FromNet(decimal netAmount, decimal taxRate) { return new TaxedPrice { NetAmount = decimal.Round(netAmount, 2, MidpointRounding.AwayFromZero), GrossAmount = decimal.Round(netAmount.ApplyTax(taxRate), 2, MidpointRounding.AwayFromZero) }; } public static TaxedPrice FromGross(decimal grossAmount, decimal taxRate) { return new TaxedPrice { GrossAmount = decimal.Round(grossAmount, 2, MidpointRounding.AwayFromZero), NetAmount = decimal.Round(grossAmount.RemoveTax(taxRate), 2, MidpointRounding.AwayFromZero) }; } } </code></pre> <h1>2</h1> <pre><code>public class TaxedPrice { public TaxedPrice(decimal netAmount, decimal grossAmount, decimal taxRate) { if (grossAmount != default) { GrossAmount = decimal.Round(grossAmount, 2, MidpointRounding.AwayFromZero); NetAmount = decimal.Round(grossAmount.RemoveTax(taxRate), 2, MidpointRounding.AwayFromZero); } else if (netAmount != default) { NetAmount = decimal.Round(netAmount, 2, MidpointRounding.AwayFromZero); GrossAmount = decimal.Round(netAmount.ApplyTax(taxRate), 2, MidpointRounding.AwayFromZero); } else { throw new InvalidOperationException($"Either {nameof(netAmount)} or {grossAmount} must be set."); } } public decimal NetAmount { get; } public decimal GrossAmount { get; } } </code></pre> <h1>3</h1> <pre><code>public class TaxedPrice { public enum Type { Gross, Net } public TaxedPrice(decimal amount, Type type, decimal taxRate) { if (type == Type.Gross) { GrossAmount = decimal.Round(amount, 2, MidpointRounding.AwayFromZero); NetAmount = decimal.Round(amount.RemoveTax(taxRate), 2, MidpointRounding.AwayFromZero); } else if (type == Type.Net) { NetAmount = decimal.Round(amount, 2, MidpointRounding.AwayFromZero); GrossAmount = decimal.Round(amount.ApplyTax(taxRate), 2, MidpointRounding.AwayFromZero); } } public decimal NetAmount { get; } public decimal GrossAmount { get; } } </code></pre> <h1>4</h1> <pre><code>public class TaxedPrice { public TaxedPrice(decimal amount, bool fromGross, decimal taxRate) { if (fromGross) { GrossAmount = decimal.Round(amount, 2, MidpointRounding.AwayFromZero); NetAmount = decimal.Round(amount.RemoveTax(taxRate), 2, MidpointRounding.AwayFromZero); } else { NetAmount = decimal.Round(amount, 2, MidpointRounding.AwayFromZero); GrossAmount = decimal.Round(amount.ApplyTax(taxRate), 2, MidpointRounding.AwayFromZero); } } public decimal NetAmount { get; } public decimal GrossAmount { get; } } </code></pre> <p>How it looks like from caller's side:</p> <pre><code>// 1 var taxedPrice = TaxedPrice.FromNet(2.123m, 0.23m); // 2 var taxedPrice = new TaxedPrice(2.123m, default, 0.23m); // uses the first one to calculate the second one var taxedPrice2 = new TaxedPrice(2.123m, 1.11m, 0.23m); // uses the first one to calculate the second one var taxedPrice3 = new TaxedPrice(default, 1.11m, 0.23m); // uses the second one to calculate the first one // 3 var taxedPrice = new TaxedPrice(2.123m, TaxedPrice.Type.Net, 0.23m); // 4 var taxedPrice = new TaxedPrice(2.123m, false, 0.23m); </code></pre> <p>Extensions for tax:</p> <pre><code>public static class TaxExtensions { public static decimal ApplyTax(this decimal netPrice, decimal taxRate) { return netPrice * (taxRate + 1); } public static decimal RemoveTax(this decimal grossPrice, decimal taxRate) { return grossPrice / (taxRate + 1); } } </code></pre> <h1>Mapping perspective</h1> <p>In my upper layer I pass those prices in POCOs/DTOs like:</p> <pre><code>public class PriceDTO { public decimal NetAmount { get; set; } public decimal GrossAmount { get; set; } } </code></pre> <p>And I have to check there as well which one was passed to decide from which to calculate. So in case of 1 mapping would look like:</p> <pre><code>if (priceDto.GrossAmount != default) return TaxedPrice.FromGross(priceDto.GrossAmount, taxRate); else if (priceDto.NetAmount != default) return TaxedPrice.FromNet(priceDto.NetAmount, taxRate); else // error </code></pre> <p>In case of 2 (no need to check in the mapping code)</p> <pre><code>return new TaxedPrice(priceDto.NetAmount, priceDto.GrossAmount, taxRate) </code></pre> <p>3 - there's a check as well</p> <p>4 - same like 1 and 3</p> <p>And I agree this could be a <code>struct</code> instead.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T07:56:57.053", "Id": "395047", "Score": "0", "body": "There are some methods missing: `RemoveTax` and `ApplyTax`. Are these methods extensions?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T07:57:13...
[ { "body": "<p>In my opinion, you should go for number 1 (with one small change). </p>\n\n<p><strong>Reasons for choosing this one:</strong></p>\n\n<ol>\n<li>Easy to modify - you can add new <code>FromX</code> method</li>\n<li>Clear - it states exactly what do you calculate </li>\n<li>Doesn't require explanatio...
{ "AcceptedAnswerId": "204851", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T07:53:39.107", "Id": "204832", "Score": "7", "Tags": [ "c#", "comparative-review", "finance" ], "Title": "Reversible tax calculator class" }
204832
<p>I made a short snippet for applying a function <code>f</code> that takes two arguments (vectors) to columns of two matrices producing all possible combinations of those columns.</p> <pre><code>function V = cross_apply(f, V1, V2) % Apply function f to columns of V1 and V2 producing % a matrix where V(i, j) = f(V1(:,i), V2(:,j)) s1 = size(V1, 2); s2 = size(V2, 2); V = zeros(s1, s2); for i = 1:s1 for j = 1:s2 V(i, j) = f(V1(:, i), V2(:, j)); end end end </code></pre> <p>An example of a use of this function could include approximating a function with a polynomial using a custom inner product (not a traditional dot product) here <code>ip</code> and defined as a kind of integral.</p> <pre><code>close all f = @(x) log(x); P = @(x) x.^(0:3); ip = @(x, y) trapz(x.*y) / (size(x, 1)-1); t = linspace(1, 2, 10)'; V = P(t); % Inner product matrices A = cross_apply(ip, V, V); b = cross_apply(ip, V, f(t)); % Coefficients for the polynomial rr = rref([A, b]) coef = rr(:, end); % Plot ln(t) and polynomial fit t_ = linspace(1, 3, 1000)'; figure() plot(t_, P(t_)*coef, 'r--') grid on, hold on plot(t_, f(t_), 'b:') legend('fit', 'f(t)', 'Location', 'best') </code></pre> <p>Not using this function, one would write a whole bunch of inner products (<code>ip</code> in the code) for matrices <code>A</code> and <code>b</code>. I didn't find a built-in function that does this, so I'm after two things:</p> <ul> <li>Is this already an implemented function in Matlab built-ins or some toolbox?</li> <li>Is there some improvement to be made to the function?</li> </ul>
[]
[ { "body": "<p>Your code is clear and concise, there is not much to complain about it, except for one small thing:</p>\n\n<blockquote>\n<pre><code>t = linspace(1, 2, 10)';\n</code></pre>\n</blockquote>\n\n<p>In MATLAB, <code>'</code> is the complex conjugate transpose, whereas <code>.'</code> is the non-conjugat...
{ "AcceptedAnswerId": "205056", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T08:33:22.450", "Id": "204834", "Score": "2", "Tags": [ "matrix", "matlab" ], "Title": "Applying a function to columns of two matrices producing their combinations" }
204834
<p>I have an array of arrays and I want to create an array of objects from it. There are custom properties to which I want to associate the sub-array values. I have the following array:</p> <pre><code>var testArray = [[1,5,10], [10,20,7], [11,10,25]]; </code></pre> <p>I am modifying it to create the following</p> <pre><code>[{ coordinates: [1, 5], reach: 10, power: 0 }, { coordinates: [10, 20], reach: 7, power: 0 }, { coordinates: [11, 10], reach: 25, power: 0 }] </code></pre> <p>For this I have written the following code. </p> <pre><code>function modifyArray(array) { return array.map(array =&gt; { return Object.assign({}, { coordinates: array.slice(0, 2), reach: array[2], power: 0 }); }); } </code></pre> <p>I get the desired result. My question is if this is a good way to modify this type of data performance wise, since the function has two return statements. How can I improve on this code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T11:55:33.600", "Id": "395070", "Score": "0", "body": "But can the original array be modified or not ? Do you have to preserve the original ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T12:17:24.56...
[ { "body": "<h1>Overview</h1>\n\n<ul>\n<li>You're overwriting the name <code>array</code> in defining the mapping param.</li>\n<li>You don't need to assign to a new object. This is done for you.</li>\n</ul>\n\n<h1>Rewrite</h1>\n\n<pre><code>function modifyArray(arrays) {\n return arrays.map(array =&gt; {\n ...
{ "AcceptedAnswerId": "204849", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T10:47:45.937", "Id": "204841", "Score": "3", "Tags": [ "javascript" ], "Title": "Modify array of arrays to create custom array of objects" }
204841
<p>I have written the following Reflection code:</p> <pre><code>static Class&lt;?&gt; craftWorld; static Class&lt;?&gt; worldServer; static Class&lt;?&gt; movingObjPosClass; static Class&lt;?&gt; blockPosClass; static Class&lt;?&gt; vec3DClass; static Class&lt;?&gt; genAccessClass; static Class&lt;?&gt; craftBlockClass; static boolean use112 = false; public GetTargetBlock113() { try { craftWorld = Class.forName("org.bukkit.craftbukkit." + Main.m.getServerVersion() + "CraftWorld"); worldServer = Class.forName("net.minecraft.server." + Main.m.getServerVersion() + "WorldServer"); movingObjPosClass = Class .forName("net.minecraft.server." + getServerVersion() + "MovingObjectPosition"); blockPosClass = Class .forName("net.minecraft.server." + getServerVersion() + "BlockPosition"); vec3DClass = Class.forName("net.minecraft.server." + Main.m.getServerVersion() + "Vec3D"); try { genAccessClass = Class .forName("net.minecraft.server." + getServerVersion() + "GeneratorAccess"); } catch (ClassNotFoundException e) { //Error is thrown if on older Minecraft versions //Ignore as error is expected. } craftBlockClass = Class .forName("org.bukkit.craftbukkit." + Main.m.getServerVersion() + "block.CraftBlock"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Block getBlockLookingAt(Player player, int reach) { if (player == null) { throw new IllegalArgumentException("player cannot be null"); } if (reach &lt; 1 || reach &gt; 120) { throw new IllegalArgumentException("reach must be between 1-120"); } Location startLoc = player.getLocation().add(0, player.getEyeHeight(), 0); Vector start = startLoc.toVector(); Vector direction = startLoc.getDirection().normalize().multiply(reach); Vector end = start.clone().add(direction); try { Constructor&lt;?&gt; con = vec3DClass.getConstructor(double.class, double.class, double.class); Object from = con.newInstance(start.getX(), start.getY(), start.getZ()); Object to = con.newInstance(end.getX(), end.getY(), end.getZ()); Object converted = craftWorld.cast(player.getWorld()); Method handle = converted.getClass().getMethod("getHandle"); Object worldServObj = handle.invoke(converted); Object convertedToWorldServer = worldServer.cast(worldServObj); Class&lt;?&gt;[] rayTraceArgs = new Class&lt;?&gt;[] { vec3DClass, vec3DClass }; Method pingField = convertedToWorldServer.getClass().getMethod("rayTrace", rayTraceArgs); Object[] args = new Object[] { from, to }; Object movingObjPos = pingField.invoke(worldServObj, args); if (movingObjPos == null) { return null; } Method getBlockPos = movingObjPosClass.getMethod("a"); Object blockPos = getBlockPos.invoke(movingObjPos); Block b; if (genAccessClass != null &amp;&amp; !use112) { Class&lt;?&gt;[] worldPos = new Class&lt;?&gt;[] { genAccessClass, blockPosClass }; Method blockAt = craftBlockClass.getMethod("at", worldPos); Object[] args2 = new Object[] { worldServObj, blockPos }; b = (Block) blockAt.invoke(blockPos, args2); }else { Method getBlockPos1 = blockPosClass.getMethod("getX"); Method getBlockPos2 = blockPosClass.getMethod("getY"); Method getBlockPos3 = blockPosClass.getMethod("getZ"); b = new Location(player.getWorld(), (int) getBlockPos1.invoke(blockPos), (int) getBlockPos2.invoke(blockPos), (int) getBlockPos3.invoke(blockPos)).getBlock(); } //System.out.println("Found block: " + b.getType()); return b; } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } return null; /* WorldServer world = ((CraftWorld) player.getWorld()).getHandle(); MovingObjectPosition rayTrace = world.rayTrace( new Vec3D(start.getX(), start.getY(), start.getZ()), new Vec3D(end.getX(), end.getY(), end.getZ())); BlockPosition pos = rayTrace.a(); pos. return rayTrace == null ? null : CraftBlock.at(world, pos);*/ } </code></pre> <p>The purpose of it is to get the target block in a Minecraft Bukkit plugin. It is necessary to do this with Reflection due to the varying class names of new versions, and the impossibility of importing them all.</p> <p>However, this code is quite laggy.</p> <p>How could the code to be optimised to be more efficient?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T13:36:16.943", "Id": "395093", "Score": "1", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for ...
[ { "body": "<p>The provided code sample is incomplete, so I don't know the control flow at runtime.<br>\nHowever, this is what I noticed:<br>\nThe variables are static and so is <code>getBlockLookingAt()</code> method. However, the reflection code is done in the constructor of <code>GetTargetBlock113</code> cla...
{ "AcceptedAnswerId": "204914", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T11:19:00.813", "Id": "204844", "Score": "-2", "Tags": [ "java", "performance", "reflection", "minecraft" ], "Title": "Using Reflection to call multiple methods and cast various classes" }
204844
<p>I am developing <a href="https://github.com/KYHSGeekCode/Android-Disassembler" rel="nofollow noreferrer">Android-Disassembler.</a> I need to optimize the loop below.</p> <p>It is currectly calling native method for each instructions(about 4 bytes). So this loop will be looped about <strong>millions</strong> of times while disassembling the entire code section.</p> <p>The code below is what I was using.</p> <pre><code>private void DisassembleFile() { Toast.makeText(this, "started", 2).show(); Log.v(TAG, "Strted disassm"); //final ProgressDialog dialog= showProgressDialog("Disassembling..."); disasmResults.clear(); mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mBuilder = new Notification.Builder(this); mBuilder.setContentTitle("Disassembler") .setContentText("Disassembling in progress") .setSmallIcon(R.drawable.cell_shape) .setOngoing(true) .setProgress(100, 0, false); workerThread = new Thread(new Runnable(){ @Override public void run() { long start=elfUtil.getCodeSectionOffset(); long index=start; long limit=elfUtil.getCodeSectionLimit(); long addr=elfUtil.getCodeSectionVirtAddr(); Log.v(TAG, "code section point :" + Long.toHexString(index)); HashMap xrefComments=new HashMap(); for (;;) { Capstone.CsInsn[] insns=cs.disasm(filecontent,index,addr,1); Capstone.CsInsn insn=insns[0]; final ListViewItem lvi=new ListViewItem(insn); if (insn.size == 0) { insn.size = 4; insn.mnemonic = "db"; //insn.bytes = new byte[]{filecontent[(int)index],filecontent[(int)index + 1],filecontent[(int)index + 2],filecontent[(int)index + 3]}; insn.opStr = ""; Log.e(TAG, "Dar.size==0, breaking?"); //break; } runOnUiThread(new Runnable(){ @Override public void run() { adapter.addItem(lvi); adapter.notifyDataSetChanged(); return ; } }); //Log.v(TAG, "i=" + index + "lvi=" + lvi.toString()); if (index &gt;= limit) { Log.i(TAG, "index is " + index + ", breaking"); break; } Log.i(TAG, "" + index + " out of " + (limit - start)); if ((index - start) % 320 == 0) { mBuilder.setProgress((int)(limit - start), (int)(index - start), false); // Displays the progress bar for the first time. mNotifyManager.notify(0, mBuilder.build()); runOnUiThread(new Runnable(){ @Override public void run() { //adapter.notifyDataSetChanged(); listview.requestLayout(); } }); } index += insn.size; addr += insn.size; //dialog.setProgress((int)((float)(index-start) * 100 / (float)(limit-start))); //dialog.setTitle("Disassembling.."+(index-start)+" out of "+(limit-start)); } mNotifyManager.cancel(0); final int len=disasmResults.size(); runOnUiThread(new Runnable(){ @Override public void run() { listview.requestLayout(); tab2.invalidate(); Toast.makeText(MainActivity.this, "done", 2).show(); } }); Log.v(TAG, "disassembly done"); } }); workerThread.start(); } </code></pre> <p><strong>Information</strong></p> <ul> <li><p>The entire <a href="https://github.com/KYHSGeekCode/Android-Disassembler/blob/master/app/src/main/java/com/kyhsgeekcode/disassembler/MainActivity.java" rel="nofollow noreferrer">source is here</a>, but I think it not needed. </p></li> <li><p>Prototype of cs.disasm: <code>cs.disasm(bytes,file_offset,virtual_address_to_be_displayed,num_of_instructions_to_be_disassembled);</code></p></li> <li><p>returns: Array_of_disassembled_info.</p></li> <li><p>The code of cs_disasm(I modified the method to let it support file_offset)</p> <pre><code>public CsInsn[] disasm(byte[] code,long offset, long length,long address, long count) { PointerByReference insnRef = new PointerByReference(); NativeLong c = cs.cs_disasm2(ns.csh, code,new NativeLong(offset), new NativeLong(length), address, new NativeLong(count), insnRef); if (0 == c.intValue()) { return EMPTY_INSN; } Pointer p = insnRef.getValue(); _cs_insn byref = new _cs_insn(p); CsInsn[] allInsn = fromArrayRaw((_cs_insn[]) byref.toArray(c.intValue())); // free allocated memory // cs.cs_free(p, c); // FIXME(danghvu): Can't free because memory is still inside CsInsn return allInsn; } </code></pre></li> </ul> <p><strong>Problem</strong></p> <ul> <li>The <code>cs.disasm</code> is called millions of times with file_offset increasing by 4 every loop.</li> <li>It is a very <strong>EXPENSIVE</strong> call, as it uses JNA without direct mapping.</li> </ul> <p><strong>What I tried</strong></p> <blockquote> <ul> <li>Call cs.disasm with last argument 256, and increase file_offset and virtual_address by processed_bytes, which is calculated while processing the returned array.</li> <li>Use <code>final Runnable</code> so that it doesn't get created every loop.</li> </ul> </blockquote> <p><strong>If you want to see the code I wrote to achieve above, please comment or see edit history. I deleted to make this question more easily readable.</strong></p> <p><strong>Conditions</strong></p> <ol> <li>I need to show progress so that users won't get annoyed.</li> </ol> <p><strong>Goal</strong></p> <p>Is to optimize the above loop.</p> <p><strong>Just to add, which is faster, calling C from java or calling java from C??</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T19:31:50.227", "Id": "395141", "Score": "1", "body": "Did you profile your code? Is it really the `cs.disasm()` call consuming the time? It might as well be the `runOnUiThread()` or some other part of your loop." }, { "Conte...
[ { "body": "<h1>It was better not to use JNA in speed-critical loops.</h1>\n\n<p>I built a JNI function that performs the loop in JNI, throwing away JNA. And it <strong>saved 12 minutes.</strong></p>\n\n<pre><code>JNIEXPORT void JNICALL Java_com_kyhsgeekcode_disassembler_DisasmIterator_getAll(JNIEnv * env, jobje...
{ "AcceptedAnswerId": "205065", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T12:21:36.873", "Id": "204847", "Score": "1", "Tags": [ "java", "performance", "android", "batch", "jni" ], "Title": "Optimizing loop - Reducing native calls" }
204847
<p>@Serge Bellesta suggested that once my program works correctly, I should consider posting it in Code Review to get interesting comments on it.</p> <p>Problem statement(<a href="https://drive.google.com/file/d/1RnhUCxKIYUZRoN9WpQ0V8esduiJgF78S/view?usp=sharing" rel="nofollow noreferrer">pdf</a>): I would like my code to be more effiicient and guaranteed not to have some bad coding, e.g., when I press "enter" without typing in anything during the second question, it goes back to the question, but skips to the next iteration. I think(?) I set it back to the previous iteration, but no cigar:</p> <pre><code>for (i = 0; i &lt; total_shops; i++) { printf("\nYou are at shop #%d.\n", i+1); printf("\nHow many ingredients are needed at shop #%d?\n\nInput Specifications: Please type a positive integer and press the 'Enter' or the 'return' key when finished.\n", i+1); fgets(line, sizeof(line), stdin); line[strlen(line)-1] = '\0'; int sscanf_result = sscanf(line, "%d", &amp;quantity_ingredients); if ((sscanf_result == 0) | (sscanf_result == EOF)) { printf ("\nInput Error: Please carefully read the input specifications that are provided after each question prompt and then try again.\n\n"); --i; continue; } </code></pre> <p>Nevertheless, the program works 100% if the user doesn't make any errors :) </p> <p>This is the program in its entirety:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; int main(void) { int i, j, k, n; char line[128]; /* the input line */ int total_shops; /* declare a variable for the total number of shops that will be visited */ total_shops = 0; int quantity_ingredients; /* declare a variable for the quantity of ingredients that will be purchased */ quantity_ingredients = 0; double **cost_ingredients_ptr; /* declare an 2D array for the cost of each ingredient purchased */ cost_ingredients_ptr = (double**)calloc(128, sizeof(double*)); for (i = 0; i &lt; 128; i++) { cost_ingredients_ptr[i] = (double*)calloc(128, sizeof(double)); } double *total_cost_ingredients_ptr; total_cost_ingredients_ptr = (double*)calloc(128, sizeof(double)); int location_cheapest_order = 1; while (total_shops == 0) { printf("How many shops will be visited?\n\nInput Specifications: Please type a positive integer and press the 'Enter' or the 'return' key when finished.\n"); fgets(line, sizeof(line), stdin); line[strlen(line)-1] = '\0'; /* trim off last character */ int sscanf_result = sscanf(line, "%d", &amp;total_shops); if ( (sscanf_result == 0) | (sscanf_result == EOF) ) { /* either a non-integer entered or an end-of-line */ printf ("\nInput Error: Please carefully read the input specifications that are provided after each question prompt and then try again.\n\n"); total_shops = 0; continue; } } for (i = 0; i &lt; total_shops; i++) { printf("\nYou are at shop #%d.\n", i+1); printf("\nHow many ingredients are needed at shop #%d?\n\nInput Specifications: Please type a positive integer and press the 'Enter' or the 'return' key when finished.\n", i+1); fgets(line, sizeof(line), stdin); line[strlen(line)-1] = '\0'; int sscanf_result = sscanf(line, "%d", &amp;quantity_ingredients); if ((sscanf_result == 0) | (sscanf_result == EOF)) { printf ("\nInput Error: Please carefully read the input specifications that are provided after each question prompt and then try again.\n\n"); --i; continue; } int offset; for (j = 0; j &lt; quantity_ingredients; j++) { printf("\nWhat is the cost of ingredient #%d?\n\nInput Specifications: Please type a real number in currency format, i.e., XXX.XX, and press the 'Enter' or the 'return' key when finished.", j+1); fgets(line, sizeof(line), stdin); line[strlen(line)-1] = '\0'; if (sscanf(line, "%lf%n", &amp;cost_ingredients_ptr[i][j], &amp;offset) != 1) { return 1; } total_cost_ingredients_ptr[i] += cost_ingredients_ptr[i][j]; /* computation of the total cost of ingredients*/ } printf("\nThe total cost at shop #%d is $%0.2f.\n", i+1, total_cost_ingredients_ptr[i]); if (i == total_shops-1) { double cheapest_order; cheapest_order = total_cost_ingredients_ptr[0]; for (k = 1; k &lt; total_shops; k++) { if (total_cost_ingredients_ptr[k] &lt; cheapest_order) { cheapest_order = total_cost_ingredients_ptr[k]; location_cheapest_order = k + 1; } printf("\nThe cheapest order placed was at shop #%d, and the total cost of the order placed was $%0.2f.\n", location_cheapest_order, cheapest_order); } } } for (n = 0; n &lt; 128; n++){ free(cost_ingredients_ptr[n]); /* releases allocated block on heap */ } free(cost_ingredients_ptr); free(total_cost_ingredients_ptr); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T14:42:53.510", "Id": "395099", "Score": "0", "body": "Please provide a description of the problem (i.e. a problem statement) to help us understand what you're trying to do. I went looking for a question asked on Stack Overflow since...
[ { "body": "<h1>Code formatting</h1>\n<p>I recommend you use an &quot;indent&quot; tool to align your code consistently with its brace level. That makes it much easier to read and to reason about.</p>\n<hr />\n<h1>Variable declarations</h1>\n<p>Back in pre-Standard C (and in the first version of the Standard), ...
{ "AcceptedAnswerId": "204868", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T14:20:29.767", "Id": "204855", "Score": "1", "Tags": [ "c" ], "Title": "Find the cheapest order placed out of all of the stores visited" }
204855
<p>I needed a general-purpose function that accepts some <code>sequence_container&lt;sequence_container&lt;T&gt;&gt;</code> and iterates all permutations of the inner container. To be more precise, the outer <code>sequence_container</code> should be described by an iterator pair to easily allow selecting parts of it.</p> <p>For example <code>{{1,2},{},{3,4}}</code> shall iterate <code>{1,?,3},{1,?,4},{2,?,3},{2,?,4}</code>. The function provides a callback to deal with each of these 4 permutations. The callback has two parameters:</p> <ul> <li>a vector of indices, giving in each iteration one of <code>{0,-1,0},{0,-1,1},{1,-1,0},{1,-1,1}</code> in above example</li> <li>a vector of values, giving in each iteration one of <code>{1,?,3},{1,?,4},{2,?,3},{2,?,4}</code> in above example</li> </ul> <p>Through <code>-1</code>, the user can check whether the value should be checked or not. This might be helpful if the original indices should be retained.</p> <p>I have written the following code that accomplishes it. It works both for <code>const</code> and <code>non-const</code> containers, albeit only <code>const</code> containers should actually be fine since we cannot change anything in the container so far. Usage is <code>nestedFor::run(beginIterator, endIterator, callback)</code>.</p> <p>Roast me, glad for any feedback!</p> <pre><code>#include &lt;iterator&gt; #include &lt;vector&gt; namespace nestedFor { // helper to check if an iterator is const template&lt;typename Iterator&gt; struct isConstIterator { typedef typename std::iterator_traits&lt;Iterator&gt;::pointer pointer; static const bool value = std::is_const&lt;typename std::remove_pointer&lt;pointer&gt;::type&gt;::value; }; // helper to get const_iterator or iterator, whatever applicable, for nested type template&lt;typename OuterItT, typename=void&gt; struct retrieveConstCorrectIterator { using iterator = typename OuterItT::value_type::iterator; }; template&lt;typename OuterItT&gt; struct retrieveConstCorrectIterator&lt;OuterItT, std::enable_if_t&lt;isConstIterator&lt;OuterItT&gt;::value&gt;&gt; { using iterator = typename OuterItT::value_type::const_iterator; }; // given a container&lt;container&lt;T&gt;&gt;, loops all combinations of inner vector; // Func should be of type: // void func(const std::vector&lt;int&gt;&amp; indices, std::vector&lt;T&gt;&amp; values); // in each iteration, func is called with indices showing the position // and respective values; // note that empty inner vectors are allowed, the respective index is -1, then template&lt;typename OuterItT, typename Func&gt; void run(OuterItT begin, OuterItT end, Func func) { using InnerItT = typename retrieveConstCorrectIterator&lt;OuterItT&gt;::iterator; using ItVecT = std::vector&lt;InnerItT&gt;; using ItVecItT = typename ItVecT::iterator; // idx -1 means that there is no valid entry using IdxVecT = std::vector&lt;int&gt;; using ValueVecT = std::vector&lt;typename InnerItT::value_type&gt;; using IdxVecItT = typename IdxVecT::iterator; using ValueVecItT = typename ValueVecT::iterator; const typename std::iterator_traits&lt;OuterItT&gt;::difference_type numInnerVecs = std::distance(begin, end); IdxVecT idxVec(numInnerVecs, -1); ValueVecT valueVec(numInnerVecs); ItVecT runIterators(numInnerVecs), startIterators(numInnerVecs), endIterators(numInnerVecs); ItVecItT runItVecIt = runIterators.begin(), startItVecIt = startIterators.begin(), endItVecIt = endIterators.begin(); IdxVecItT runIdxIterators = idxVec.begin(), runValueIterators = valueVec.begin(); for(OuterItT it = begin; it != end; ++it, ++runItVecIt, ++startItVecIt, ++endItVecIt, ++runIdxIterators, ++runValueIterators) { *runItVecIt = it-&gt;begin(); *startItVecIt = it-&gt;begin(); *endItVecIt = it-&gt;end(); if(it-&gt;begin() == it-&gt;end()) { *runIdxIterators = -1; // value idx undefined then } else { *runIdxIterators = 0; *runValueIterators = *(*startItVecIt); } } while(true) { func(idxVec, valueVec); ItVecItT itToMove = runIterators.begin(), itToMoveStart = startIterators.begin(), itToMoveEnd = endIterators.begin(); IdxVecItT idxIt = idxVec.begin(); ValueVecItT valueIt = valueVec.begin(); bool bigBreak = false; ++*itToMove; if(*itToMove != *itToMoveEnd) { ++*idxIt; *valueIt = **itToMove; } while(*itToMove == *itToMoveEnd) { *itToMove = *itToMoveStart; if(*itToMove != *itToMoveEnd) { *idxIt = 0; *valueIt = **itToMoveStart; } ++itToMove; ++itToMoveStart; ++itToMoveEnd; ++idxIt; ++valueIt; if(itToMove == runIterators.end()) { bigBreak = true; break; } if(*itToMove != *itToMoveEnd) { ++*itToMove; ++*idxIt; *valueIt = **itToMove; } }; if(bigBreak) break; } } } #endif </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T15:42:59.093", "Id": "395110", "Score": "0", "body": "@Deduplicator yes, good point. The function accepts `iterator`s but a bare array won't work... `std::array` would, though" } ]
[ { "body": "<ul>\n<li><p><strong>Naming</strong>. What <code>run</code> iterates over is known as a direct (or Cartesian) product. It seems that <code>namespace direct_product</code> is more descriptive than <code>nestedFor</code>.</p></li>\n<li><p><strong>Parallel arrays</strong> (<code>runIterators, startItera...
{ "AcceptedAnswerId": "204866", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T15:23:44.960", "Id": "204856", "Score": "6", "Tags": [ "c++", "combinatorics", "iterator" ], "Title": "General nested for" }
204856
<p>I built an application that extracts and updates data from multiple ecommerces websites. Each eCommerce is either built using platforms/frameworks such as Shopify, Prestashop or WooCommerce. This being said, each <code>Shop</code> has a different webservice that I invoke using <code>Shop-&gt;getWebservice()</code>. This method returns a different class depending on the platform/framework used by a Shop.</p> <p>So when I call <code>Shop-&gt;getWebservice()</code> I can get either get <code>ShopifyFactory</code>, <code>WooCommerceFactory</code> or <code>PrestashopFactory</code>. All of these three classes extend the ShopFrameworkFactory that dictates which methods all these three classes must implement.</p> <p>The aspect I'm focusing on is running the function <code>updatedOrderStatesFromShop</code> which updates the different states an order can have in a given a <code>Shop</code>. An order state is the status of an order, for instance it can be : awaiting payment, paid, prepared, shipped, delivered, cancelled, etc.</p> <p>So the process is as follows:</p> <ol> <li>Invoke <code>updateOrderStatesFromShop(Shop $shop)</code> with a shop object.</li> <li><code>Shop-&gt;getWebservice</code> returns an instance of (for the example) <code>PrestashopFactory</code></li> <li><code>PrestashopFactory-&gt;getOrderStatuses</code> which should return an array of value objects called <code>ShopOrderState</code> that encapsulate the information of an Order State</li> <li>The method <code>PrestashopFactory-&gt;getOrderStatuses</code> iterates through an array of XML objects, instantiates a new ShopOrderState Value Object and runs <code>ShopOrderState-&gt;hydratePrestashop()</code> which <strong>parses the XML object to itself</strong></li> <li>I retrive all known Order States of given <code>Shop</code> from the database</li> <li>I iterate through the array of <code>ShopOrderState</code> from bullet 3</li> <li>I try to find a match comparing <code>ShopOrderState-&gt;getId()</code> method from the value object with <code>OrderState-&gt;getShopOrderId()</code> method from the Entity.</li> <li>If there is a match I invoke a method from the entity <code>OrderState-&gt;hydrateOrderStateVO(ShopOrderState)</code> which <strong>updates each value from the value object to itself</strong></li> <li>I save changes made by the update</li> </ol> <p>My concerns are around the bold in bullet 5 and bullet 8, see how the XML Object is then parsed to a Value Object and then this value object is then parsed to the Entity.</p> <p>I have stripped away a lot of code in order to get the essentials of what's the reasoning here. There are actually 3 functions in my <code>ShopOrderState</code> Value Object that hydrate depending on the platform. <code>hydratePrestashop</code> the one shown here, there is also <code>hydrateWoocommerce</code> and <code>hydrateShopify</code>. Each hydrate the object differently because they come with different names and formats and these hydrate function are used as an adapter in order to convert the information given by a platform to the standards of my application.</p> <p>Shouldn't these hydrate functions be in a separate service in my application ? Is there some sort of pattern design for such process ?</p> <p>As a matter of fact, there are many other things that are updated from the eCommerces to my application, I focused on one to illustrate the issue but other such as sales, carts, products, etc are also updated. I wonder if there isn't a different approach to do this as it seems pretty difficult to mantain and explain how it works.</p> <p>The service :</p> <pre><code>class OrderStateLogic { private $em; public function __construct(EntityManagerInterface $entityManager) { $this-&gt;em = $entityManager; } public function updateOrderStatesFromShop(Shop $shop) { try { $shopOrderStates = $shop-&gt;getWebservice()-&gt;getOrderStatuses(); } catch (\Exception $exception) { return false; } if (! is_array($shopOrderStates) || empty($shopOrderStates)) { return false; } $orderStates = $this-&gt;em-&gt;getRepository(OrderState::class)-&gt;findBy(['shop' =&gt; $shop]); foreach ($shopOrderStates as $shopOrderState) { if (! $shopOrderState instanceof ShopOrderState) { continue; } $updated = false; if (is_array($orderStates) &amp;&amp; ! empty($orderStates)) { foreach ($orderStates as $orderState) { if ($shopOrderState-&gt;getId() === $orderState-&gt;getShopOrderId()) { $orderState-&gt;hydrateOrderStateVO($shopOrderState); $updated = true; } } } if(!$updated){ $newOrderState = new OrderState(); $newOrderState-&gt;hydrateOrderStateVO($shopOrderState); $newOrderState-&gt;setShop($shop); $this-&gt;em-&gt;persist($newOrderState); } } $this-&gt;em-&gt;flush(); return true; } } </code></pre> <p>The ShopOrderState is the Value Object used to have a common object between all different platforms</p> <pre><code> class ShopOrderState { private $id; private $name; private $paid; private $delivered; private $shipped; // Getter and setters public function hydratePrestashop($prestashopEntity): self { $this-&gt;setId((int)$prestashopEntity-&gt;id); $this-&gt;setDelivered((int)$prestashopEntity-&gt;delivery); $this-&gt;setPaid((int)$prestashopEntity-&gt;paid); $this-&gt;setShipped((int)$prestashopEntity-&gt;shipped); $this-&gt;setName((string)$prestashopEntity-&gt;name-&gt;language[ 0 ]); return $this; } } </code></pre> <p>The OrderState is the Entity.</p> <pre><code>class OrderState { private $id; private $shopOrderId; private $name; private $paid; private $delivered; private $shipped; private $createdAt; private $updatedAt; private $shop; // Setter and getters /** * Hydrates the object from the OrderState Value Object. * * @param ShopOrderState $orderState * * @return $this */ public function hydrateOrderStateVO(ShopOrderState $orderState) :self { $this-&gt;setShopOrderId($orderState-&gt;getId()); $this-&gt;setName($orderState-&gt;getName()); $this-&gt;setPaid($orderState-&gt;isPaid()); $this-&gt;setDelivered($orderState-&gt;isDelivered()); $this-&gt;setShipped($orderState-&gt;isShipped()); return $this; } } </code></pre> <p>The Shop Entity looks like this.</p> <p>As you can see depending on the $platform value it will return a different class.</p> <pre><code>class Shop { private $id; private $shopName; private $domain; private $platform; private $apiKey; private $createdAt; private $updatedAt; // Getters and setters public function getWebservice(): ShopFrameworkFactory { switch ($this-&gt;getPlatform()){ case ShopFrameworkFactory::SHOPIFY : return new ShopifyFactory($this); break; case ShopFrameworkFactory::WOOCOMMERCE : return new WooCommerceFactory($this); break; case ShopFrameworkFactory::PRESTASHOP : return new PrestashopFactory($this); break; default : return new PrestashopFactory($this); break; } } } </code></pre> <p>Here is the ShopFrameworkFactory that draws what each webservice should return</p> <pre><code>abstract class ShopFrameworkFactory { public const SHOPIFY = 1; public const PRESTASHOP = 2; public const WOOCOMMERCE = 3; private $shop; private $debug; public function __construct (Shop $shop, $debug = false) { $this-&gt;shop = $shop; $this-&gt;debug = $debug; } abstract public function getOrderStatuses(); } </code></pre> <p>And lastly one of the 3 ecommerce platforms bridge</p> <pre><code>class PrestashopFactory extends ShopFrameworkFactory { public function getOrderStatuses() { try { /** * @var $configuration \SimpleXMLElement */ $orderStates = $this-&gt;ws-&gt;get( array ( 'resource' =&gt; 'order_states', 'display' =&gt; 'full' ) ); } catch (\PrestaShopWebserviceException $exception) { return $exception; } $orderStatesFormatted = []; foreach ($orderStates-&gt;order_states-&gt;order_state as $orderState) { $orderStateVO = new ShopOrderState(); $orderStateVO-&gt;hydratePrestashop($orderState); $orderStatesFormatted[] = $orderStateVO; } return $orderStatesFormatted; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T17:45:50.200", "Id": "395128", "Score": "2", "body": "I will speak purely for myself: I find your explanation and code quite confusing. I am missing a basic and clear explanation, at the beginning of your question, of what your code...
[]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T15:58:30.270", "Id": "204858", "Score": "2", "Tags": [ "php", "design-patterns", "api", "ddd", "symfony3" ], "Title": "Best approach to parse data from multiple APIs to Entities in PHP" }
204858
<p>I have a function that receives an array of numbers and operations</p> <pre><code>Ex: userEntry = [3,+,3,x,3] -&gt; returns 12 </code></pre> <p>It is a calculator that adheres to the proper order of operations, therefore multiply/divide behaves differently than addition/subtraction. I have one redundant line of code:</p> <pre><code>userEntry = calculatorOperations .calculationSequence(operationsMD[i], indexOfOperand, userEntry); </code></pre> <p>is similar to:</p> <pre><code> userEntry = calculatorOperations .calculationSequence(userEntry[1], indexOfOperand, userEntry); </code></pre> <p>With different behavior between operations, is it possible to remove this redundant line or is it neccesary?</p> <pre><code>function operateOnEntry(userEntry) { //this is where the calculations occur when hitting = const operationsMD = ['x', '/']; let indexOfOperand; let operation; while (userEntry.includes('x') || userEntry.includes('/')) { let i = 0; if (!userEntry.includes('x')) { i++; } indexOfOperand = userEntry.indexOf(operationsMD[i]); userEntry = calculatorOperations .calculationSequence(operationsMD[i], indexOfOperand, userEntry); } while (userEntry.includes('+') || userEntry.includes('-')) { indexOfOperand = 1; userEntry = calculatorOperations .calculationSequence(userEntry[1], indexOfOperand, userEntry); } return userEntry; } let calculatorOperations = { 'x': (arg1, arg2) =&gt; { return arg1 * arg2; }, '/': (arg1, arg2) =&gt; { return arg1 / arg2; }, '+': (arg1, arg2) =&gt; { return arg1 + arg2; }, '-': (arg1, arg2) =&gt; { return arg1 - arg2; }, returnIndexOfEntry: (index, userEntry) =&gt; { let arg1 = Number(userEntry[index - 1]); let arg2 = Number(userEntry[index + 1]); return [arg1, arg2]; }, returnSpliced: (index, newTotal, userEntry) =&gt; { userEntry.splice((index - 1), 3, newTotal); return userEntry; }, calculationSequence: (operation, indexOfOperand, userEntry) =&gt; { let getArgs = calculatorOperations.returnIndexOfEntry(indexOfOperand, userEntry); let newTotalForEntry = calculatorOperations[operation](getArgs[0], getArgs[1]); let newUserEntry = calculatorOperations.returnSpliced(indexOfOperand, newTotalForEntry, userEntry); return newUserEntry; } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T20:31:19.933", "Id": "395146", "Score": "1", "body": "`operationsMD` seems superfluous. If a `x` or `/` is found in `userEntry`, well there it is. Why have a separate array for these operators - and then only these operators." }, ...
[ { "body": "<h1>Overview</h1>\n\n<ul>\n<li>If you are using ES6, you should use the full ability of arrow functions: <code>(args) =&gt; returnVal</code></li>\n<li>In addition, some of the methods don't need to be defined as a property.</li>\n<li><code>calculatorOperations</code> should be a constant.</li>\n<li>Y...
{ "AcceptedAnswerId": "204882", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T16:03:51.620", "Id": "204859", "Score": "2", "Tags": [ "javascript", "calculator", "ecmascript-6", "math-expression-eval" ], "Title": "JS calculator, respecting order of operations" }
204859
<p>For a small project, I had to implement Caesar encryption in Swift(4). I'm mainly looking for performance optimizations.</p> <p>This whole code should be copy and pasteable in a playground and is functioning as expected as far as I can see.</p> <pre><code>import Foundation let caesarNumber:Int = 7; let alphabet_array:[Character] = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] func encode(inputString: String) -&gt; String { var resultString:String = "" for char in inputString { for i in 0...(alphabet_array.count-1) { if (char == alphabet_array[i]) { if (i + caesarNumber &lt; alphabet_array.count-1) { resultString.append(alphabet_array[i+caesarNumber]) } else { let subscripture:Int = (i+caesarNumber)%alphabet_array.count resultString.append(alphabet_array[subscripture]) } } } } return resultString } func decode(inputString: String) -&gt; String { var resultString:String = "" for char in inputString { for i in 0...(alphabet_array.count-1) { if (char == alphabet_array[i]) { if (i - caesarNumber &gt;= 0) { resultString.append(alphabet_array[i-caesarNumber]) } else { resultString.append( alphabet_array[alphabet_array.count+(i-caesarNumber)]) } } } } return resultString } let encodedString = encode(inputString: "zacharias") let decodeString = decode(inputString: encodedString); </code></pre>
[]
[ { "body": "<h3>Naming</h3>\n\n<p>According to the <a href=\"https://swift.org/documentation/api-design-guidelines/\" rel=\"nofollow noreferrer\">Swift API Design Guidelines</a>, variable names are lower camel case (not <code>alphabet_array</code>),\nand types should not be part of the variable name (not <code>c...
{ "AcceptedAnswerId": "204884", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T17:13:56.397", "Id": "204863", "Score": "1", "Tags": [ "swift", "caesar-cipher" ], "Title": "Caesar encryption and decryption" }
204863
<p>I have the following C++ code snippet that randomly samples a single row in an array called <code>pop</code> with <code>num_specs</code> columns and <code>perms</code> rows. In addition, <code>K</code> = 1. The triply-nested <code>for</code> loop uses a pointer for referencing.</p> <p>Some of the below syntax (such as <code>IntegerVector</code>) is from Rcpp, an R package to integrate C++ code with R code.</p> <pre class="lang-c++ prettyprint-override"><code>// [[Rcpp::depends(RcppArmadillo)]] // [[Rcpp::depends(RcppProgress)]] #define ARMA_DONT_PRINT_OPENMP_WARNING #include &lt;RcppArmadillo.h&gt; #include &lt;RcppArmadilloExtensions/sample.h&gt; #include &lt;set&gt; using namespace Rcpp; int sample_one(int n) { return n * unif_rand(); } int sample_n_distinct(const IntegerVector&amp; x, int k, const int * pop_ptr) { IntegerVector ind_index = RcppArmadillo::sample(x, k, false); std::set&lt;int&gt; distinct_container; for (int i = 0; i &lt; k; i++) { distinct_container.insert(pop_ptr[ind_index[i]]); } return distinct_container.size(); } // [[Rcpp::export]] arma::Cube&lt;int&gt; accumulate(const arma::Cube&lt;int&gt;&amp; pop, const IntegerVector&amp; specs, int perms, int K) { int num_specs = specs.size(); arma::Cube&lt;int&gt; res(perms, num_specs, K); IntegerVector specs_C = specs - 1; const int * pop_ptr; int i, j, k; for (i = 0; i &lt; K; i++) { for (k = 0; k &lt; num_specs; k++) { for (j = 0; j &lt; perms; j++) { pop_ptr = &amp;(pop(sample_one(perms), 0, sample_one(K))); res(j, k, i) = sample_n_distinct(specs_C, k + 1, pop_ptr); } } } return res; } </code></pre> <p>While loops in compiled languages aren't bad, it is possible to write slow code. </p> <p>I'm not a native C++ programmer, so I don't know all the tricks of the trade. </p> <p>Is there a way to reduce the number of levels in the triply-nested <code>for</code> loop above, possibly by employing modular arithmetic in order to see a gain in speed for large input values?</p> <p>The R code is below:</p> <pre class="lang-r prettyprint-override"><code>## Set up container to hold the identity of each individual from each permutation ## num.specs &lt;- N ## Create an ID for each tag ## tags &lt;- 1:h ## Assign individuals (N) ## specs &lt;- 1:num.specs ## Generate permutations. Assume each permutation has N individuals, and sample those # individuals' tags from the probabilities ## gen.perms &lt;- function() { sample(tags, size = num.specs, replace = TRUE, prob = probs) } pop &lt;- array(dim = c(perms, num.specs, K)) for (i in 1:K) { pop[,, i] &lt;- replicate(perms, gen.perms()) } ## Perform accumulation ## HAC.mat &lt;- accumulate(pop, specs, perms, K) ## Example K &lt;- 1 N &lt;- 100 h &lt;- 5 probs &lt;- rep(1/h, h) perms &lt;- 100 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T17:30:04.767", "Id": "395124", "Score": "2", "body": "This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about [what your code does](//coderev...
[ { "body": "<p>I can only comment on the C++ code, as I've never used R nor Rcpp.</p>\n\n<p>For an ignorant reader such as myself, it would have helped to omit the <code>using namespace Rcpp;</code>, so that I could see which names come from that library (I did quite a bit of external reading to even understand ...
{ "AcceptedAnswerId": "204945", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T17:26:45.110", "Id": "204869", "Score": "1", "Tags": [ "c++", "performance", "algorithm", "r", "rcpp" ], "Title": "Efficiently sample a single row of an array at random" }
204869
<p>Here are the commands I ran to start setting up a database I need.</p> <pre><code>CREATE TABLE user ( id smallint unsigned not null auto_increment, constraint pk_user primary key (id) ); CREATE TABLE discord_user ( id varchar(20) not null, owner smallint unsigned, constraint pk_discord_user primary key (id), constraint fk_discord_user_owner foreign key (owner) references user(id) ); CREATE TABLE player ( uuid varchar(36) not null, owner smallint unsigned, constraint pk_player primary key (uuid), constraint fk_player_owner foreign key (owner) references user(id) ); CREATE TABLE kit (id mediumint unsigned not null auto_increment, designer smallint unsigned, name varchar(30) not null, disguise enum('ARMOR_STAND','ARROW','BAT','BLAZE','BOAT','CAVE_SPIDER','CHICKEN','COW','CREEPER','DONKEY','DROPPED_ITEM','EGG','ELDER_GUARDIAN','ENDER_CRYSTAL','ENDER_DRAGON','ENDER_PEARL','ENDER_SIGNAL','ENDERMAN','ENDERMITE','EXPERIENCE_ORB','FALLING_BLOCK','FIREBALL','FIREWORK','FISHING_HOOK','GHAST','GIANT','GUARDIAN','HORSE','IRON_GOLEM','ITEM_FRAME','LEASH_HITCH','MAGMA_CUBE','MINECART','MINECART_CHEST','MINECART_COMMAND','MINECART_FURNACE','MINECART_HOPPER','MINECART_MOB_SPAWNER','MINECART_TNT','MULE','MUSHROOM_COW','OCELOT','PAINTING','PIG','PIG_ZOMBIE','PLAYER','PRIMED_TNT','RABBIT','SHEEP','SILVERFISH','SKELETON','SKELETON_HORSE','SLIME','SMALL_FIREBALL','SNOWBALL','SNOWMAN','SPIDER','SPLASH_POTION','SQUID','THROWN_EXP_BOTTLE','UNDEAD_HORSE','VILLAGER','WITCH','WITHER','WITHER_SKELETON','WITHER_SKULL','WOLF','ZOMBIE','ZOMBIE_VILLAGER') not null, helmet enum('CHAINMAIL_HELMET','DIAMOND_HELMET','GOLD_HELMET','IRON_HELMET','LEATHER_HELMET'), chestplate enum('CHAINMAIL_CHESTPLATE','DIAMOND_CHESTPLATE','GOLD_CHESTPLATE','IRON_CHESTPLATE','LEATHER_CHESTPLATE'), leggings enum('CHAINMAIL_LEGGINGS','DIAMOND_LEGGINGS','GOLD_LEGGINGS','IRON_LEGGINGS','LEATHER_LEGGINGS'), boots enum('CHAINMAIL_BOOTS','DIAMOND_BOOTS','GOLD_BOOTS','IRON_BOOTS','LEATHER_BOOTS'), base_melee_damage tinyint unsigned not null, base_arrow_damage tinyint unsigned, base_knockback_taken_multiplier float(4,2) not null, base_melee_knockback_dealt_multiplier float(4,2) not null, constraint pk_kit primary key (id), constraint fk_kit_designer foreign key (designer) references user(id)); </code></pre> <p>I want to move them all into one file and run them as an SQL program to create this database automatically in the future.</p> <p>I don't actually know what SQL should look like, style-wise. </p> <ol> <li><p>Where do I break lines? </p></li> <li><p>How are my naming conventions? </p></li> <li><p>How are comments used in SQL?</p></li> <li><p>Do my datatypes look suitable or are there better ways for me to represent the objects I want?</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T03:51:40.797", "Id": "395198", "Score": "2", "body": "\"I don't know how to write SQL\" — so did you write this code yourself or not?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T21:00:16.713", ...
[ { "body": "<ol>\n<li>For formatting, I would download the following tool, <a href=\"https://marketplace.visualstudio.com/items?itemName=TaoKlerks.PoorMansT-SqlFormatterSSMSVSExtension\" rel=\"nofollow noreferrer\">Poor Man's T-Sql Formatter</a> and on <a href=\"https://github.com/TaoK/PoorMansTSqlFormatter\" re...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T17:59:58.017", "Id": "204870", "Score": "-5", "Tags": [ "sql", "mysql", "formatting", "database" ], "Title": "How to write SQL in a industry standard style" }
204870
<p>I wrote code that parses a table header string in order to obtain two string tags, one for variable name (like <code>GDP</code>) and another for unit of measurement (like <code>bln_rub</code>). The tags collectively make a unique identifier for the table data.</p> <p>Perhaps something can be done better/shorter/more easily readable?</p> <pre><code>import Data.List (isInfixOf) type Label = Maybe String data Variable = Variable { name :: Label, unit :: Label } deriving (Show, Eq) makeVariable :: String -&gt; String -&gt; Variable makeVariable name unit = Variable (Just name) (Just unit) isDefined:: Variable -&gt; Bool isDefined var = (name var /= Nothing) &amp;&amp; (unit var /= Nothing) isIdentical:: Variable -&gt; String -&gt; String -&gt; Bool isIdentical var name unit = (makeVariable name unit) == var -- Map allows a readable view of tuple-like -- associative structure. data Map = Map { label :: String, texts :: [String] -- note: can use non-empty List } deriving (Show) nameMaps = [ Map "GDP" ["Gross domestic product"] , Map "INDPRO" ["Industrial production"] ] unitMaps = [ Map "bln_rub" ["bln rub", "billion ruble"] , Map "rog" ["% change to previous period"] -- rate of growth ] -- COMMENT: code below converts nameMaps and unitMaps -- to list of tuples which are used for searching a header asTuples :: Map -&gt; [(String, String)] asTuples (Map label texts) = [(text, label) | text &lt;- texts] findAllKeys :: [(String, String)] -&gt; String -&gt; [String] findAllKeys mapper header = [key | tup@(text, key) &lt;- mapper, text `isInfixOf` header] getLabel :: [Map] -&gt; String -&gt; Label getLabel maps' header = case findAllKeys (flatten' maps') header of [] -&gt; Nothing (x:_) -&gt; Just x where flatten' = concatMap asTuples getName = getLabel nameMaps getUnit = getLabel unitMaps parseHeader text = Variable (getName text) (getUnit text) x = parseHeader "Gross domestic product, bln rub" flag = (isDefined x) &amp;&amp; (isIdentical x "GDP" "bln_rub") raise x = error ("Something wrong with: " ++ show x) main = do if flag then putStrLn $ show x else raise x return () </code></pre>
[]
[ { "body": "<blockquote>\n <p>Perhaps something can be done <strong>shorter</strong></p>\n</blockquote>\n\n<p>A trick that I often use to avoid creating \"filled\" objects is simply matching on <code>Just</code>:</p>\n\n<pre><code>isIdentical:: Variable -&gt; String -&gt; String -&gt; Bool\nisIdentical (Variabl...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T18:21:42.650", "Id": "204872", "Score": "4", "Tags": [ "strings", "parsing", "haskell" ], "Title": "Find labels in string in Haskell" }
204872
<p>I'm looking for a review of a recent project I finished for school. It is an app that functions like Twitter. It includes an Express server and Routes. Instead of using databases, it uses JSON files. Users can create, edit, and delete 'chirps' (tweets) with fetch requests. Specific instructions for the project are included on the README.</p> <p>Please leave any feedback from small mistakes/improvements to big picture stuff like structure and organization. Thank you</p> <p>My app: <a href="https://github.com/ChristyCakes/CovalenceReactBoilerPlate" rel="nofollow noreferrer">https://github.com/ChristyCakes/CovalenceReactBoilerPlate</a></p> <p>app.jsx</p> <pre><code>import React, { Component, Fragment } from 'react'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import { Home, Chirp, Edit, Delete } from './components'; import './styles.css'; class App extends Component { render() { return ( &lt;Router&gt; &lt;Fragment&gt; &lt;Switch&gt; &lt;Route exact path="/" component={Home} /&gt; &lt;Route path="/:id/edit" component={Edit} /&gt; &lt;Route path="/:id/delete" component={Delete} /&gt; &lt;Route path="/:id" component={Chirp} /&gt; &lt;/Switch&gt; &lt;/Fragment&gt; &lt;/Router&gt; ) } } export default App; </code></pre> <p>home.jsx</p> <pre><code>import React, { Component } from 'react'; import 'isomorphic-fetch'; import Current from './current' import logo from './logo.png' import NewChirp from './newChirp' class Home extends Component { constructor() { super(); this.state = { chirps: {} } } componentDidMount() { fetch('http://127.0.0.1:3000/api/chirps') .then(response =&gt; response.json()) .then(data =&gt; { this.setState({ chirps: data }) }) .catch(err =&gt; console.log(err)) } render() { return ( &lt;div&gt; &lt;div className="panel"&gt; &lt;img src={logo} alt="logo" height="300px" /&gt; &lt;h1&gt;Chirper&lt;/h1&gt; &lt;/div&gt; &lt;NewChirp /&gt; &lt;Current chirps={this.state.chirps} /&gt; &lt;/div&gt; ); } } export { Home }; </code></pre> <p>chirp.jsx</p> <pre><code>import React, { Component, Fragment } from 'react'; import { BrowserRouter as Router, Link } from 'react-router-dom'; import 'isomorphic-fetch'; class Chirp extends Component { constructor() { super(); this.state = { user: "", text: "", } } componentDidMount() { fetch(`http://127.0.0.1:3000/api/chirps/${this.props.match.params.id}`) .then(response =&gt; response.json()) .then(data =&gt; { this.setState({ user: data.user, text: data.text }) }) .catch(err =&gt; console.log(err)) } render() { return ( &lt;div&gt; &lt;Fragment &gt; &lt;Link to="/" className="homelink" style={{ textDecoration: "none" }}&gt;Home&lt;/Link&gt; &lt;/Fragment&gt; &lt;div className="current"&gt; &lt;div className="flex-column"&gt; &lt;div className='chirps'&gt; &lt;p&gt;{this.state.user}: {this.state.text}&lt;/p&gt; &lt;Fragment &gt; &lt;Link to={{ pathname: `/${this.props.match.params.id}/edit`, state: { user: this.state.user, text: this.state.text } }}&gt; &lt;button onClick={this.editClick}&gt;Edit&lt;/button&gt; &lt;/Link&gt; &lt;Link to={`/${this.props.match.params.id}/delete`}&gt;&lt;button className="delete"&gt;x&lt;/button&gt;&lt;/Link&gt; &lt;/Fragment&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ) } } export { Chirp }; </code></pre> <p>edit.jsx</p> <pre><code>import React, { Component, Fragment } from 'react'; import { BrowserRouter as Router, Link } from 'react-router-dom'; import 'isomorphic-fetch'; class Edit extends Component { constructor() { super(); this.state = { user: "", text: "" } this.editChirp = this.editChirp.bind(this); this.inputHandler = this.inputHandler.bind(this) } inputHandler(e) { this.setState({ [e.target.name]: e.target.value }) } editChirp(e) { e.preventDefault(); fetch(`http://127.0.0.1:3000/api/chirps/${this.props.match.params.id}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ user: this.state.user, text: this.state.text }) }) .then(() =&gt; this.props.history.push('/')) .catch(err =&gt; console.log(err)) } render() { const user = this.props.location.state.user; const text = this.props.location.state.text; return ( &lt;div&gt; &lt;Fragment&gt; &lt;Link to="/" className="homelink" style={{ textDecoration: "none" }}&gt;Home&lt;/Link&gt; &lt;/Fragment&gt; &lt;h2&gt;Edit Your Chirp&lt;/h2&gt; &lt;div className="input"&gt; &lt;form action=""&gt; &lt;input type="text" placeholder={user} size="10" id="user" name="user" onChange={this.inputHandler} value={this.state.user} /&gt; &lt;input type="text" placeholder={text} size="60" id="text" name="text" onChange={this.inputHandler} value={this.state.text} /&gt; &lt;button onClick={this.editChirp} id="submit"&gt; Update &lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; ) } } export { Edit }; </code></pre>
[]
[ { "body": "<h3>Superfluous Fragments</h3>\n\n<p>You don't need to wrap anything in a <code>&lt;Fragment&gt;</code>. <a href=\"https://reactjs.org/docs/fragments.html\" rel=\"nofollow noreferrer\">Fragments are just used for when you want to return multiple elements without adding anything extra to the DOM</a>.<...
{ "AcceptedAnswerId": "204881", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T19:37:31.123", "Id": "204875", "Score": "2", "Tags": [ "javascript", "ecmascript-6", "react.js", "express.js", "jsx" ], "Title": "Request for improvements on a simple React app" }
204875
<p>I am learning about templates in C++ so I decided to implement an N-dimensional vector. The code seems to work fine, but there are a few things that I am unsure about.</p> <p>To stop <code>GetW()</code> being called on a 3-dimensional vector, I used <code>std::enable_if</code>. This works, but the error message given when it's misused isn't as helpful as I'd like: <code>error: no type named ‘type’ in ‘struct std::enable_if&lt;false, void&gt;’</code>. It would be better if I could make it into something friendlier like: <code>error: attempted to get 4th component of a 3d vector</code> instead.</p> <p>I am also unsure about the best practices with templates, so any feedback would be appreciated. Thank you :)</p> <hr> <pre><code>#include &lt;array&gt; #include &lt;cassert&gt; #include &lt;cmath&gt; #include &lt;type_traits&gt; template&lt; typename T, int num_components, typename = typename std::enable_if&lt;std::is_arithmetic&lt;T&gt;::value, T&gt;::type, typename = typename std::enable_if&lt;(num_components &gt;= 2)&gt;::type &gt; class Vector { using this_t = Vector&lt;T, num_components&gt;; public: Vector() : components{0} {} Vector(std::array&lt;T, num_components&gt; components) : components(components) {} template&lt;int idx&gt; inline T Get() const { typename std::enable_if&lt;(num_components &gt;= idx)&gt;::type(); return this-&gt;components[idx]; } inline T Get(int idx) const { assert(idx &lt;= num_components); return this-&gt;components[idx]; } inline T GetX() const { return this-&gt;components[0]; } inline T GetY() const { return this-&gt;components[1]; } inline T GetZ() const { typename std::enable_if&lt;(num_components &gt;= 3)&gt;::type(); return this-&gt;components[2]; } inline T GetW() const { typename std::enable_if&lt;(num_components &gt;= 4)&gt;::type(); return this-&gt;components[3]; } template&lt;int idx&gt; inline void Set(T value) { typename std::enable_if&lt;(num_components &gt;= idx)&gt;::type(); this-&gt;components[idx] = value; } inline void Set(int idx, T value) { assert(idx &gt;= num_components); this-&gt;components[idx] = value; } inline void SetX(T value) { this-&gt;components[0] = value; } inline void SetY(T value) { this-&gt;components[1] = value; } inline void SetZ(T value) { typename std::enable_if&lt;(num_components &gt;= 3)&gt;::type(); this-&gt;components[2] = value; } inline void SetW(T value) { typename std::enable_if&lt;(num_components &gt;= 4)&gt;::type(); this-&gt;components[3] = value; } double LengthSquared() const { double ret = 0; for (int i = 0; i &lt; num_components; i++) { const T value = this-&gt;components[i]; ret += value * value; } return ret; } double Length() const { return std::sqrt(this-&gt;LengthSquared()); } void Normalise() { const double length = this-&gt;Length(); for (int i = 0; i &lt; num_components; i++) { this-&gt;Set(i, this-&gt;Get(i) / length); } } this_t Normalised() const { const double length = this-&gt;Length(); std::array&lt;T, num_components&gt; new_components; for (int i = 0; i &lt; num_components; i++) { new_components[i] = this-&gt;Get(i) / length; } return this_t(std::move(new_components)); } void Negate() { for (int i = 0; i &lt; num_components; i++) { this-&gt;components[i] = -this-&gt;Get(i); } } this_t Negated() const { std::array&lt;T, num_components&gt; new_components; for (int i = 0; i &lt; num_components; i++) { new_components[i] = -this-&gt;Get(i); } return this_t(std::move(new_components)); } this_t operator+(const this_t &amp;r) const { std::array&lt;T, num_components&gt; new_components; for (int i = 0; i &lt; num_components; i++) { new_components[i] = this-&gt;Get(i) + r.Get(i); } return this_t(std::move(new_components)); } this_t operator-(const this_t &amp;r) const { std::array&lt;T, num_components&gt; new_components; for (int i = 0; i &lt; num_components; i++) { new_components[i] = this-&gt;Get(i) - r.Get(i); } return this_t(std::move(new_components)); } this_t operator*(const this_t &amp;r) const { std::array&lt;T, num_components&gt; new_components; for (int i = 0; i &lt; num_components; i++) { new_components[i] = this-&gt;Get(i) * r.Get(i); } return this_t(std::move(new_components)); } this_t operator*(T s) const { std::array&lt;T, num_components&gt; new_components; for (int i = 0; i &lt; num_components; i++) { new_components[i] = this-&gt;Get(i) * s; } return this_t(std::move(new_components)); } bool operator=(const this_t &amp;r) const { for (int i = 0; i &lt; num_components; i++) { if (this-&gt;Get(i) != r.Get(i)) return false; } return true; } this_t Cross(const this_t &amp;r) const { // pretend that cross product is only defined for a 3-dimensional vector typename std::enable_if&lt;(num_components == 3)&gt;::type(); std::array&lt;T, num_components&gt; new_components; new_components[0] = this-&gt;GetY() * r.GetZ() - this-&gt;GetZ() * r.GetY(); new_components[1] = this-&gt;GetZ() * r.GetX() - this-&gt;GetX() * r.GetZ(); new_components[2] = this-&gt;GetX() * r.GetY() - this-&gt;GetY() * r.GetX(); return this_t(std::move(new_components)); } T Dot(const this_t &amp;r) const { T ret = 0; for (int i = 0; i &lt; num_components; i++) { ret += this-&gt;Get(i) * r.Get(i); } return ret; } private: std::array&lt;T, num_components&gt; components; }; using Vector2d = Vector&lt;double, 2&gt;; using Vector2f = Vector&lt;float, 2&gt;; using Vector2i = Vector&lt;int, 2&gt;; using Vector3d = Vector&lt;double, 3&gt;; using Vector3f = Vector&lt;float, 3&gt;; using Vector3i = Vector&lt;int, 3&gt;; using Vector4d = Vector&lt;double, 4&gt;; using Vector4f = Vector&lt;float, 4&gt;; using Vector4i = Vector&lt;int, 4&gt;; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T11:12:17.777", "Id": "395255", "Score": "1", "body": "It looks a lot like what the GLM library (https://glm.g-truc.net/) does. It might be helpful to have a look at its implementation." } ]
[ { "body": "<h2>Comments:</h2>\n\n<blockquote>\n <p>I am learning about templates in C++ so I decided to implement an N-dimensional vector.</p>\n</blockquote>\n\n<p>It's not an N-dimensional vector. It's a 1-D vector with <code>N</code> elements.</p>\n\n<p>OK. Now I have read this for a while. I am starting to ...
{ "AcceptedAnswerId": "204898", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T21:23:45.450", "Id": "204879", "Score": "3", "Tags": [ "c++", "template", "coordinate-system" ], "Title": "C++ Vector with templates" }
204879
<p>I have some code which saves a mongoose model from the submitted form data. However the user might also upload an image along with the form, which needs to be saved on the server (moved from the buffer).</p> <p>Here is my first attempt:</p> <pre><code>// Save a new job to the database. exports.save = function(req, res, next) { // If the request contains a file, generate a file name for it. if (req.file) req.body.logoImage = generateFileName(req.file.mimetype) // Save the job to the database. Job.create(req.body) .then(job =&gt; { // Move the file from the buffer to the uploads folder. if (job.logoImage) { moveFile(req.file.buffer, job.logoImage).then(() =&gt; { res.json({ status: 'Uploaded job successfully.' }) }) } else { res.json({ status: 'Uploaded job successfully.' }) } }) .catch(error =&gt; next(error)) } </code></pre> <p><strong>I would like to avoid having to write duplicate code for sending the response.</strong> </p> <p>The problem is that <code>moveFile</code> return a <code>Promise</code> so simply doing this won't work, because the response will be sent before the file is moved (<strong>and moving it might fail</strong>)!</p> <pre><code>if (job.logoImage) { moveFile(req.file.buffer, job.logoImage) } res.json({ status: 'Uploaded job successfully.' }) </code></pre> <p>To get around this, I came up with the following code:</p> <pre><code>// Save a new job to the database. exports.save = function(req, res, next) { // If the request contains a file, generate a file name for it. if (req.file) req.body.logoImage = generateFileName(req.file.mimetype) // Save the job to the database. Job.create(req.body) .then(job =&gt; { // Move the file from the buffer to the uploads folder. if (job.logoImage) { return moveFile(req.file.buffer, job.logoImage) } return Promise.resolve() }) .then(() =&gt; { res.json({ status: 'Uploaded job successfully.' }) }) .catch(error =&gt; next(error)) } </code></pre> <p>Would there be a better way maybe?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T23:48:43.807", "Id": "395166", "Score": "0", "body": "Welcome to Code Review! What task does this code accomplish? Please tell us, and also make that the title of the question via [edit]. Maybe you missed the placeholder on the titl...
[ { "body": "<p>Your modified code is better, but you can simplify this method even more. If you don't return anything from a function in a promise, it will be resolved with no value. There's no need to do <code>return Promise.resolve()</code>.</p>\n\n<p><code>.catch(error =&gt; next(error))</code> is equivalent ...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T22:17:17.627", "Id": "204887", "Score": "1", "Tags": [ "javascript", "promise", "network-file-transfer", "mongoose" ], "Title": "Saving a submitted Mongoose model, possibly with an uploaded image" }
204887
<p>I was trying to use <a href="https://numerics.mathdotnet.com/matrix.html" rel="nofollow noreferrer">Math.Net's dense matrix class</a>. But, it doesn't support <code>int</code>. So, I have to create a wrapper for a jagged 2d array.</p> <p>I knew that jagged arrays have <a href="https://www.codeproject.com/Articles/1064915/A-Generic-Fast-implementation-of-a-dimensional-de" rel="nofollow noreferrer">better performance</a>.</p> <pre class="lang-none prettyprint-override"><code>Data Size : 966 x 345 Naked 2d Array : 10 milliseconds Naked Jagged Array : 6 milliseconds Jagged Wrapper : 82 milliseconds Dense Wrapper : 88 milliseconds 2d Wrapper : 62 milliseconds </code></pre> <p>According to my test results, a naked jagged array is the fastest of all. But, in terms of wrapper, the 2d wrapper is relatively faster. </p> <p>Now, I have two questions: </p> <ol> <li>Why is the jagged wrapper slower than 2d wrapper?</li> <li>How can I make my wrapper classes work faster, so that they can run as fast as their naked counterparts?</li> </ol> <hr> <h1>Source Code</h1> <h2>Test Code</h2> <pre><code>Bitmap bmpImage = DataConverter2d.ReadGray("image.jpg"); int[][] intNakedJagged = DataConverter2d.ToInteger(bmpImage); int[,] intNaked2d = JagMatrix&lt;int&gt;.To2d(intNakedJagged); JagMatrix&lt;int&gt; intJaggedWrapper = new JagMatrix&lt;int&gt;(intNakedJagged); DenMatrix&lt;int&gt; intDenWrapper = new DenMatrix&lt;int&gt;(intNaked2d); Matrix&lt;int&gt; int2dWrapper = new Matrix&lt;int&gt;(intNaked2d); Stopwatch sw1 = new Stopwatch(); sw1.Start(); double[,] dImage = DataConverter2d.ToDouble(intNaked2d); sw1.Stop(); Console.WriteLine("Naked 2d Array : " + sw1.ElapsedMilliseconds.ToString() + " milliseconds", "Elapsed time"); Stopwatch sw2 = new Stopwatch(); sw2.Start(); double[][] dImageJagged = DataConverter2d.ToDouble(intNakedJagged); sw2.Stop(); Console.WriteLine("Naked Jagged Array : " + sw2.ElapsedMilliseconds.ToString() + " milliseconds", "Elapsed time"); Stopwatch sw3 = new Stopwatch(); sw3.Start(); JagMatrix&lt;double&gt; dJagArray2d = DataConverter2d.ToDouble(intJaggedWrapper); sw3.Stop(); Console.WriteLine("Jagged Wrapper : " + sw3.ElapsedMilliseconds.ToString() + " milliseconds", "Elapsed time"); Stopwatch sw4 = new Stopwatch(); sw4.Start(); DenMatrix&lt;double&gt; dDenArray2d = DataConverter2d.ToDouble(intDenWrapper); sw4.Stop(); Console.WriteLine("Dense Wrapper : " + sw4.ElapsedMilliseconds.ToString() + " milliseconds", "Elapsed time"); Stopwatch sw5 = new Stopwatch(); sw5.Start(); Matrix&lt;double&gt; dArray2d = DataConverter2d.ToDouble(int2dWrapper); sw5.Stop(); Console.WriteLine("2d Wrapper : " + sw5.ElapsedMilliseconds.ToString() + " milliseconds", "Elapsed time"); Console.ReadKey(); </code></pre> <h2>2d Matrix</h2> <pre><code>public class Matrix&lt;T&gt; : IDisposable where T : struct , IComparable&lt;T&gt; { private T[,] __array2d; public int Width { get; set; } public int Height { get; set; } public bool IsEmpty { get { if (__array2d == null) return true; else return false; } } public Matrix() { } public Matrix(T[,] data) { this.Set(data); } public Matrix(int rows, int cols) { Width = rows; Height = cols; __array2d = new T[Width, Height]; } public T Get(int x, int y) { if (__array2d == null) { throw new Exception("array is empty"); } if (x &lt; Width &amp;&amp; y &lt; Height) { if (__array2d != null) { return __array2d[x, y]; } else { throw new Exception("array is null"); } } else { string message = string.Empty; if (x &gt;= Width) message = "x-value exceeds Width "; if (y &gt;= Height) message += "y-value exceeds Height "; message += "in Array2d.Get(x,y)."; throw new Exception(message); } } public void Set(int x, int y, T val) { if (__array2d == null) { __array2d = new T[Width, Height]; } else { if (Width != __array2d.GetLength(0)) { __array2d = null; __array2d = new T[Width, Height]; } } if (x &lt; Width &amp;&amp; y &lt; Height) { __array2d[x, y] = val; } else { throw new Exception(x + ", " + Width + "," + y + "," + Height); } } public T this[int x, int y] { get { return Get(x, y); } set { Set(x, y, value); } } public void Set(T[,] arr) { if (arr != null) { int rows = arr.GetLength(0); int cols = arr.GetLength(1); __array2d = arr; Width = rows; Height = cols; } else { throw new Exception("array is null"); } } #region IDisposable implementation ~Matrix() { this.Dispose(false); } protected bool Disposed { get; private set; } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.Disposed) { if (disposing) { // Perform managed cleanup here. //IDisposable disp = (IDisposable)_2dArray; __array2d = null; } // Perform unmanaged cleanup here. Width = 0; Height = 0; this.Disposed = true; } } #endregion } </code></pre> <h2>2d Jagged Matrix</h2> <pre><code>public class JagMatrix&lt;T&gt; : IDisposable where T : struct , IComparable&lt;T&gt; { private T[][] __array2d; public int Width { get; set; } public int Height { get; set; } public bool IsEmpty { get { if (__array2d == null) return true; else return false; } } public JagMatrix() { } public JagMatrix(T[][] data) { this.Set(data); } public JagMatrix(int rows, int cols) { Width = rows; Height = cols; __array2d = new T[Width][]; for (int i = 0; i &lt; Width; i++) { __array2d[i] = new T[Height]; } } public T Get(int x, int y) { if (__array2d == null) { throw new Exception("array is empty"); } if (x &lt; Width &amp;&amp; y &lt; Height) { if (__array2d != null) { return __array2d[x][y]; } else { throw new Exception("array is null"); } } else { string message = string.Empty; if (x &gt;= Width) message = "x-value exceeds Width "; if (y &gt;= Height) message += "y-value exceeds Height "; message += "in Array2d.Get(x,y)."; throw new Exception(message); } } public void Set(int x, int y, T val) { if (__array2d == null) { __array2d = new T[Width][]; for (int i = 0; i &lt; Width; i++) { __array2d[i] = new T[Height]; } } else { if (Width != __array2d.GetLength(0)) { __array2d = null; __array2d = new T[Width][]; for (int i = 0; i &lt; Width; i++) { __array2d[i] = new T[Height]; } } } if (x &lt; Width &amp;&amp; y &lt; Height) { __array2d[x][y] = val; } else { throw new Exception(x + ", " + Width + "," + y + "," + Height); } } public static T[,] To2d(T[][] source) { T[,] dest = new T[source.Length, source[0].Length]; for (int i = 0; i &lt; source.Length; i++) { for (int j = 0; j &lt; source[0].Length; j++) { dest[i,j] = source[i][j]; } } return dest; } public T this[int x, int y] { get { return Get(x, y); } set { Set(x, y, value); } } public void Set(T[][] arr) { if (arr != null) { int rows = arr.Length; int cols = arr[0].Length; __array2d = arr; Width = rows; Height = cols; } else { throw new Exception("array is null"); } } #region IDisposable implementation ~JagMatrix() { this.Dispose(false); } protected bool Disposed { get; private set; } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.Disposed) { if (disposing) { // Perform managed cleanup here. //IDisposable disp = (IDisposable)_2dArray; __array2d = null; } // Perform unmanaged cleanup here. Width = 0; Height = 0; this.Disposed = true; } } #endregion } </code></pre> <h2>2d Dense Matrix</h2> <pre><code>public class DenMatrix&lt;T&gt; : IDisposable where T : struct , IComparable&lt;T&gt; { private T[] __array1d; public int Width { get; set; } public int Height { get; set; } public int Length { get { return Width * Height; } } public bool IsEmpty { get { if (__array1d == null) return true; else return false; } } public DenMatrix() { } public DenMatrix(T[,] data) { this.Set(data); } public DenMatrix(int rows, int cols) { Width = rows; Height = cols; __array1d = new T[Length]; } public T Get(int x, int y) { if (__array1d == null) { throw new Exception("array is empty"); } if (x &lt; Width &amp;&amp; y &lt; Height) { if (__array1d != null) { return __array1d[x + y * Width]; } else { throw new Exception("array is null"); } } else { string message = string.Empty; if (x &gt;= Width) message = "x-value exceeds Width "; if (y &gt;= Height) message += "y-value exceeds Height "; message += "in Array2d.Get(x,y)."; throw new Exception(message); } } public void Set(int x, int y, T val) { int length = Length; if (__array1d == null) { __array1d = new T[length]; } else { if (length != __array1d.Length) { __array1d = null; __array1d = new T[length]; } } if (x &lt; Width &amp;&amp; y &lt; Height) { __array1d[x + y * Width] = val; } else { throw new Exception(x + ", " + Width + "," + y + "," + Height); } } public T[] To1d(T[,] array2d) { T[] array1d = new T[Length]; for (int x = 0; x &lt; Height; x++) { for (int y = 0; y &lt; Width; y++) { T val = array2d[x, y]; int index = x * Width + y; array1d[index] = val; } } return array1d; } public T this[int x, int y] { get { return Get(x, y); } set { Set(x, y, value); } } public void Set(T[,] arr) { if (arr != null) { int rows = arr.GetLength(0); int cols = arr.GetLength(1); Width = cols; Height = rows; __array1d = To1d(arr); } else { throw new Exception("array is null"); } } #region IDisposable implementation ~DenMatrix() { this.Dispose(false); } protected bool Disposed { get; private set; } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.Disposed) { if (disposing) { // Perform managed cleanup here. //IDisposable disp = (IDisposable)_2dArray; __array1d = null; } // Perform unmanaged cleanup here. Width = 0; Height = 0; this.Disposed = true; } } #endregion } </code></pre> <h2>double[][] ToDouble(int[][] image)</h2> <pre><code> public static double[][] ToDouble(int[][] image) { int Width = image.Length; int Height = image[0].Length; double[][] array2d = new double[Width][]; for (int x = 0; x &lt; Width; x++) { array2d[x] = new double[Height]; for (int y = 0; y &lt; Height; y++) { double d = image[x][y] / 255.0; array2d[x][y] = d; } } return array2d; } </code></pre> <h2>DataConverter2d.Todouble(Matrix image)</h2> <pre><code> public static Matrix&lt;double&gt; ToDouble(Matrix&lt;int&gt; image) { int Width = image.Width; int Height = image.Height; Matrix&lt;double&gt; array2d = new Matrix&lt;double&gt;(Width, Height); for (int x = 0; x &lt; Width; x++) { for (int y = 0; y &lt; Height; y++) { double d = image[x, y] / 255.0; array2d[x, y] = d; } } return array2d; } </code></pre>
[]
[ { "body": "<p>I'm not able to add anything to what t3chb0t wrote in his comment about performance, but below find some comments and improvements of the code. I just wonder what you actually want to measure performance-wise: Is it that important with a fast conversion between <code>int</code> and <code>double</c...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T22:40:40.177", "Id": "204889", "Score": "2", "Tags": [ "c#", "performance", "comparative-review", "matrix" ], "Title": "2D Matrix with jagged array isn't faster than one with a multidimensional array" }
204889
<p>I have a need to do some conversions in a loop to display the results using C++98 on Linux, which doesn't have any <code>itoa()</code> to complement <code>atoi()</code>. I opted for this instead of <code>snprintf()</code>. This is for an embedded device and the conversions will be done in a few loops, so speed is important.</p> <p>It's based on some code I found <a href="https://gist.github.com/madex/c5cd5c6a23965a845d6e" rel="nofollow noreferrer">on GitHub</a>. I modified it to write to a user-supplied buffer, so that it's reentrant.</p> <p>Please let me know if anyone has a better method for small numeric conversions to ascii using base-10 only, or any recommended changes. Thanks. </p> <pre><code>/* Modified from: https://gist.github.com/madex/c5cd5c6a23965a845d6e This only works for up to 9 digits and only converts to base 10 ascii, but no division is used and this method is very fast. */ void itoaBase10(int32_t num, char *string, int lengthOfString) { if (!string || num &gt; 9999999999) return; memset(string, 0, lengthOfString); static uint32_t subtractors[10] = { 1000000000, 100000000, 10000000, 1000000, 100000, 10000, 1000, 100, 10, 1 }; char n, *str = string, sign = num &lt; 0 ? '-' : ' '; uint32_t *sub = subtractors; uint32_t u = num &lt; 0 ? (uint32_t)-num : (uint32_t)num; uint8_t i = 10; while (i &gt; 1 &amp;&amp; u &lt; *sub) { i--; sub++; } str++; *(str - 1) = sign; while (i--) { n = '0'; while (u &gt;= *sub) { u -= *sub; n++; } *str++ = n; sub++; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T08:52:33.233", "Id": "395235", "Score": "1", "body": "Why not `snprintf()`? If it's speed, then are you sure that decimal formatting is actually the bottleneck? (In other words, have you profiled your code, and determined that thi...
[ { "body": "<ul>\n<li><p>Since the function may bail out without computing the result, it <em>must</em> signal the caller that something got wrong. Consider returning an error code.</p></li>\n<li><p>Since you are dealing with negative numbers, testing for <code>num &gt; 9999999999</code> is not sufficient.</p></...
{ "AcceptedAnswerId": "204909", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T23:17:12.090", "Id": "204891", "Score": "2", "Tags": [ "c++", "c", "formatting", "linux" ], "Title": "Convert integer to decimal string" }
204891
<p>I know I can do all this via SSMA quite quickly, but I wanted to see if I could do it efficiently in PowerShell myself as a little project.</p> <p>Basically, the entire script takes tables from an Access database and creates a database in SQL Server with the same data. Everything from creating the table structure to cleansing the data is running quick. The slow part is inserting the data, which was inevitable but I want to see if I can make it a bit faster.</p> <p>Here is the code:</p> <pre><code>&lt;# Insert data into tables #&gt; function Insert_Data { param ( $data, $tableName ) $columns = ($data.PSObject.Properties | where {$_.name -eq "Columns"}).value.columnName | Sort-Object $Insert = "INSERT INTO $tableName VALUES " $i = 0 $x = 0 foreach ($item in $data) { $Insert += " (" foreach ($item in $columns) { $Insert += "'" + $data.rows[$x].$item + "'," } $Insert = $Insert.Substring(0,$Insert.Length-1) $Insert += ")," if ($i -eq 900) { $Insert = $Insert.Substring(0,$Insert.Length-1) $Insert += ";" Invoke-SQLCMD -Query $Insert -ServerInstance "." -database tmpAccessData -erroraction "Stop" $Insert = "INSERT INTO $tableName VALUES " $i = 0 } $i++ $x++ } $Insert = $Insert.Substring(0,$Insert.Length-1) $Insert += ";" Invoke-SQLCMD -Query $Insert -ServerInstance "." -database tmpAccessData -erroraction "Stop" Remove-Variable -Name data } </code></pre> <p>It generates a large SQL query and inserts that into the specified table once it hits 900 values or the end of the Access table.</p> <p>The <strong>data</strong> variable is the full Access table pulled into an Object:</p> <pre><code>$data_Clients = Get-AccessData -Query "SELECT * FROM Client" -Source $($settings.FastrackFiles.access_Fastrack); </code></pre> <p>And <strong>tablename</strong> is just the name of the table in the destination SQL database.</p>
[]
[ { "body": "<p>The main problem with this code is that it's not screening column values, unfortuantely buit in mechanisms in <code>Invoke-SQLCMD</code> aren't viable. It allows to use <code>-Variable</code> but it also accepst stings, like <code>-Variable \"p0='var_value'\"</code> which don't help at all with es...
{ "AcceptedAnswerId": "205186", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T23:36:52.140", "Id": "204892", "Score": "3", "Tags": [ "performance", "sql", "sql-server", "t-sql", "powershell" ], "Title": "Inserting data into SQL-Server table dynamically" }
204892
<p>Trying to find the median of two sorted arrays in O(log(m+n)) or better. I believe this is O(log(m+n) or O(log(m)) or O(n). </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var findMedianSortedArrays = function(nums1, nums2) { let ar = [] let len = nums1.length + nums2.length let half; if (len % 2 === 0) { half = len / 2 } else { half = Math.ceil(len / 2) } for (let i = 0, r1 = 0, r2 = 0; i &lt;= len; i++) { if (r1 &gt;= nums1.length || nums1[r1] &gt; nums2[r2]) ar[i] = nums2[r2++] else ar[i] = nums1[r1++] if (!nums1[i] &amp;&amp; nums1.length === r1) { ar = ar.concat(nums2.slice(r2)) return median(ar, len) } if (!nums2[i] &amp;&amp; nums2.length === r2) { ar = ar.concat(nums1.slice(r1)) return median(ar, len) } if (half === i) { return median(ar, len) } } function median(arr, len) { if (len % 2 === 0) { let half = len / 2 return median = (arr[half - 1] + arr[half]) / 2 } else { let half = Math.ceil(len / 2) return median = arr[half - 1] } } } console.log(findMedianSortedArrays([1, 4], [2, 3, 5, 6]))</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T23:54:31.443", "Id": "395168", "Score": "0", "body": "You are using `concat()`, so your implementation is at \\$O(m)\\$, or perhaps \\$O(n)\\$." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T23:59:49...
[ { "body": "<h3>Unnecessary storage</h3>\n\n<p>The current implementation basically processes the two input arrays in parallel, taking the next smaller element from the appropriate array, and appending to <code>ar</code>,\nuntil either the end of an input array is reached,\nor the counter <code>i</code> reaches ...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-03T23:38:08.957", "Id": "204893", "Score": "1", "Tags": [ "javascript", "performance", "programming-challenge", "complexity" ], "Title": "Median of two sorted arrays JavaScript" }
204893
<p>The following is some code for a Battleship game I'm working on. The plan is to create a multiplayer game using Xamarin Forms. This is just the model code, i.e. what the GUI will be interacting with when playing the game. I'd like some advice on conventions and any other code optimizations that can be found. Any help is greatly appreciated!</p> <p><strong>ISerializable.cs</strong></p> <pre><code>namespace Battleship { public interface ISerializable { string Serialize(); } } </code></pre> <p><strong>GridSquare.cs</strong></p> <pre><code>using System; namespace Battleship { public enum SquareType { Foggy, Water, Undamaged, Damaged, Sunk } public class GridSquare : ISerializable { public int Row { get; private set; } public int Column { get; private set; } public SquareType Type { get; set; } public int ShipIndex { get; set; } private readonly bool _charted; public GridSquare(int row, int column, bool charted) { _charted = charted; Row = row; Column = column; Type = charted ? SquareType.Water : SquareType.Foggy; ShipIndex = -1; } public string Serialize() { return GetEncodedNumber(Row) + ":" + GetEncodedNumber(Column) + ":" + _charted.ToString() + ":" + GetEncodedNumber(ShipIndex) + ":" + Type.ToString(); } private string GetEncodedNumber(int n) { return n % 10 == 0 || n &lt; 0 ? n.ToString() : n.ToString().PadLeft('0'); } public static GridSquare Deserialize(string data) { string[] msg = data.Split(':'); return new GridSquare(Convert.ToInt32(msg[0]), Convert.ToInt32(msg[1]), Convert.ToBoolean(msg[2])) { ShipIndex = Convert.ToInt32(msg[3]), Type = (SquareType)Enum.Parse(typeof(SquareType), msg[5]) }; } } } </code></pre> <p><strong>Grid.cs</strong></p> <pre><code>using System; using System.Collections.Generic; using System.Linq; namespace Battleship { public class Grid : ISerializable { public List&lt;List&lt;GridSquare&gt;&gt; Squares { get; private set; } private readonly int _gridSize; public Grid(int gridSize) { _gridSize = gridSize; Squares = new List&lt;List&lt;GridSquare&gt;&gt;(gridSize); } public int GetSize() { return _gridSize; } public string Serialize() { string data = _gridSize + ":"; List&lt;string&gt; info = new List&lt;string&gt;(_gridSize); for (int i = 0; i &lt; _gridSize; ++i) { for (int j = 0; j &lt; _gridSize; ++j) { info.Add(Squares[i][j].Serialize()); } } return data + string.Join(",", info.ToArray()); } public static Grid Deserialize(string data) { string[] msg = data.Split(':'); Grid grid = new Grid(Convert.ToInt32(msg[0])); foreach (string squareData in msg[1].Split(',').ToList()) { // technically this is order insensitive as well GridSquare square = GridSquare.Deserialize(squareData); grid.Squares[square.Row][square.Column] = square; } return grid; } } } </code></pre> <p><strong>Ship.cs</strong></p> <pre><code>using System; namespace Battleship { // the classic rules (patrol boats aren't fit for warfare) public enum ShipType { Carrier = 5, Battleship = 4, Cruiser = 3, Submarine = 3, Destroyer = 2 } public enum Orientation { South = 0, East = 1, North = 2, West = 3 } static class OrientationMethods { public static Orientation FromIndex(this int n) { switch (n) { case 1: return Orientation.East; case 2: return Orientation.North; case 3: return Orientation.West; default: return Orientation.South; } } } public class Ship : ISerializable { public int Health { get; set; } public Orientation Orientation { get; set; } private readonly ShipType _type; public Ship(ShipType type) { _type = type; Repair(); } public int Length() { return (int)_type; } public void Repair() { Health = Length(); } public bool Sunk() { return Health == 0; } public void Hit() { if (Health &gt; 0) { --Health; } } public string Serialize() { return _type.ToString() + ":" + Health; } public static Ship Deserialize(string data) { string[] msg = data.Split(':'); return new Ship((ShipType)Enum.Parse(typeof(ShipType), msg[0])) { Health = Convert.ToInt32(msg[1]) }; } } } </code></pre> <p><strong>Player.cs</strong></p> <pre><code>using System; using System.Collections.Generic; using System.Linq; namespace Battleship { public class Player : ISerializable { public Grid Grid { get; set; } public List&lt;Ship&gt; Ships { get; set; } protected static Random rand = new Random(); public Player(int gridSize) { Grid = new Grid(gridSize); Ships = new List&lt;Ship&gt;(); foreach (ShipType type in Enum.GetValues(typeof(ShipType))) { Ships.Add(new Ship(type)); } PlaceShips(); } private void PlaceShips() { for (int shipIndex = 0; shipIndex &lt; Ships.Count; ++shipIndex) { int x = rand.Next(Grid.GetSize()); int y = rand.Next(Grid.GetSize()); GridSquare sea = Grid.Squares[x][y]; Ship ship = Ships[shipIndex]; List&lt;Orientation&gt; validOrientations = new List&lt;Orientation&gt;(); // calculate valid orientations for (int i = 0; i &lt; 4; ++i) { bool done = false; try { for (int j = 1; j &lt; ship.Length() &amp;&amp; !done; ++j) { Orientation o = OrientationMethods.FromIndex(i); switch (o) { case Orientation.South: if (Grid.Squares[x][y - j].ShipIndex != -1) { done = true; } break; case Orientation.East: if (Grid.Squares[x - j][y].ShipIndex != -1) { done = true; } break; case Orientation.North: if (Grid.Squares[x][y + j].ShipIndex != -1) { done = true; } break; case Orientation.West: if (Grid.Squares[x + j][y].ShipIndex != -1) { done = true; } break; } if (j == Grid.GetSize() - 1) { validOrientations.Add(o); } } } catch (Exception) { } } if (!validOrientations.Any()) { throw new Exception("The current grid cannot fit all of the ships!"); } // set the origin metadata sea.Type = SquareType.Undamaged; sea.ShipIndex = shipIndex; ship.Orientation = validOrientations[rand.Next(validOrientations.Count)]; // pick an orientation at random and layout the ship for (int i = 1; i &lt; ship.Length(); ++i) { switch (ship.Orientation) { case Orientation.South: Grid.Squares[x][y - i].ShipIndex = shipIndex; break; case Orientation.East: Grid.Squares[x - i][y].ShipIndex = shipIndex; break; case Orientation.North: Grid.Squares[x][y + i].ShipIndex = shipIndex; break; case Orientation.West: Grid.Squares[x + i][y].ShipIndex = shipIndex; break; } } } } public void Attack(int x, int y) { GridSquare sea = Grid.Squares[x][y]; switch (sea.Type) { case SquareType.Foggy: // miss sea.Type = SquareType.Water; break; case SquareType.Undamaged: Ship ship = Ships[sea.ShipIndex]; ship.Hit(); if (ship.Sunk()) { sea.Type = SquareType.Sunk; for (int i = 1; i &lt; ship.Length(); ++i) { switch (ship.Orientation) { case Orientation.South: Grid.Squares[x][y - i].Type = SquareType.Sunk; break; case Orientation.East: Grid.Squares[x - i][y].Type = SquareType.Sunk; break; case Orientation.North: Grid.Squares[x][y + i].Type = SquareType.Sunk; break; case Orientation.West: Grid.Squares[x + i][y].Type = SquareType.Sunk; break; } } } else { sea.Type = SquareType.Damaged; } break; default: // unallowed operation that should be handled client-side break; } } public bool GameOver() { return Ships.All(ship =&gt; ship.Sunk()); } public string Serialize() { return Grid.Serialize() + "|" + SerializeShips(); } private string SerializeShips() { List&lt;string&gt; info = new List&lt;string&gt;(); foreach (Ship ship in Ships) { info.Add(ship.Serialize()); } return string.Join(",", info.ToArray()); } public static Player Deserialize(string data) { string[] info = data.Split('|'); Grid grid = Grid.Deserialize(info[0]); return new Player(grid.GetSize()) { Grid = grid, Ships = DeserializeShips(info[1]) }; } private static List&lt;Ship&gt; DeserializeShips(string data) { string[] info = data.Split(','); List&lt;Ship&gt; ships = new List&lt;Ship&gt;(); foreach (string s in info) { ships.Add(Ship.Deserialize(s)); } return ships; } } } </code></pre>
[]
[ { "body": "<p><strong>Global</strong></p>\n\n<p>Why don't you use the usual serialization stuff instead of creating you Interface (which by the way has the same name than <code>System.Runtime.Serialization.ISerializable</code>) and doing some kind of weird tinkering to serialize and deserialize?</p>\n\n<p><stro...
{ "AcceptedAnswerId": "204967", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T00:19:47.850", "Id": "204895", "Score": "4", "Tags": [ "c#", "beginner", "game", "xamarin", "battleship" ], "Title": "Battleship Model" }
204895
<p>I'm just learning Assembly. This program is a simple attempt to determine if a given number is prime or not.</p> <p>Compiled as follows using VS2019 x64 Native Tools Command Prompt:</p> <blockquote> <pre><code>&gt; nasm -g -fwin64 isprime.asm &gt; cl /Zi isprime.obj msvcrt.lib legacy_stdio_definitions.lib </code></pre> </blockquote> <p><strong>isprime.asm</strong></p> <pre><code>bits 64 default rel extern printf extern scanf section .data number: dq 0 isPrime: dq 1 counter: dq 0 question: db "Which number would you like to check? ", 0 fmt: db "%d", 0 numberIsPrime: db "%d is prime", 10, 0 numberIsNotPrime: db "%d is not prime", 10, 0 section .text global main main: push rbp mov rbp, rsp sub rsp, 32 mov rcx, question call printf add rsp, 32 sub rsp, 32 mov rdx, number mov rcx, fmt call scanf add rsp, 32 mov rcx, [number] mov [counter], rcx continue_prime_check: dec qword [counter] cmp qword [counter], 2 jge not_reached_1_yet jmp prime_check_ended not_reached_1_yet: mov rax, [number] cdq mov rbx, [counter] idiv rbx cmp edx, 0 je evenly_divisible jmp not_evenly_divisible evenly_divisible: mov qword [isPrime], 0 not_evenly_divisible: jmp continue_prime_check prime_check_ended: cmp qword [isPrime], 1 je number_was_prime jmp number_wasnt_prime number_was_prime: sub rsp, 32 mov rdx, [number] mov rcx, numberIsPrime call printf add rsp, 32 jmp end_if number_wasnt_prime: sub rsp, 32 mov rdx, [number] mov rcx, numberIsNotPrime call printf add rsp, 32 end_if: mov rbp, rsp pop rbp ret </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T02:23:38.177", "Id": "395185", "Score": "1", "body": "Which assembler are you using?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T02:24:36.400", "Id": "395186", "Score": "1", "body": "T...
[ { "body": "<p>There are numerous small things.</p>\n\n<ol>\n<li>You don't have to keep subtracting and adding 32 from <code>rsp</code>. Allocate the space once at the start of the function (<code>main</code>), reuse it for the duration, and add it back at the end (but see below).</li>\n<li>My personal preferen...
{ "AcceptedAnswerId": "204965", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T01:36:50.910", "Id": "204902", "Score": "24", "Tags": [ "primes", "windows", "assembly", "nasm" ], "Title": "Checking if a number is prime in NASM Win64 Assembly" }
204902
<p>I have this simple loop that prints numbers from 0 to 29 (30 in total). I want to "split" the results in threes and remove the middle number. So the first set is 0,1,2 and I only want 0,2. The second set is 3,4,5 and I only want 3,5. This works as it supposed too, but is there a way to make it more simpler?</p> <pre><code>z = 1 for i in range(0,30): if z == 1: print(i, end=' ') z+=1 elif z == 3: print(i, end=' ') z=1 else: z+=1 </code></pre> <p>This is the result:</p> <pre><code>0 2 3 5 6 8 9 11 12 14 15 17 18 20 21 23 24 26 27 29 </code></pre>
[]
[ { "body": "<p>You want to skip every number of the form 3<i>k</i>+1? Then say that, using a <a href=\"https://docs.python.org/3/tutorial/classes.html#generator-expressions\" rel=\"nofollow noreferrer\">generator expression</a>.</p>\n\n<pre><code>print(' '.join(str(i) for i in range(30) if i % 3 != 1))\n</code><...
{ "AcceptedAnswerId": "204908", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T03:14:02.617", "Id": "204907", "Score": "0", "Tags": [ "python", "python-3.x" ], "Title": "Remove the second number from every group of three numbers" }
204907
<p>I am working on a problem in which given a 7 digit telephone number, we need to print out all possible combinations of letters that each number could represent.</p> <p>I came up with below code and I was wondering if there is any way to optimize it or if there is any better way? As of now complexity is O(n<sup>3</sup>).</p> <pre><code>public class LetterCombinationsOfPhoneNumber { private static final HashMap&lt;Character, String&gt; map = new HashMap&lt;&gt;(8); static { map.put('2', "abc"); map.put('3', "def"); map.put('4', "ghi"); map.put('5', "jkl"); map.put('6', "mno"); map.put('7', "pqrs"); map.put('8', "tuv"); map.put('9', "wxyz"); }; public static List&lt;String&gt; letterCombinations(String digits) { LinkedList&lt;String&gt; results = new LinkedList&lt;&gt;(); results.add(""); for (int i = 0; i &lt; digits.length(); i++) { String letters = map.get(digits.charAt(i)); for (int j = results.size(); j &gt; 0; j--) { String intermediateResult = results.poll(); for (int k = 0; k &lt; letters.length(); k++) { results.add(intermediateResult + letters.charAt(k)); } } } return results; } public static void main(String[] args) { System.out.println(letterCombinations("23")); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T07:43:10.063", "Id": "395218", "Score": "0", "body": "The number of outputs will be 3^n or more (not n^3), so that's obviously a lower bound on the complexity. You won't be able to get lower than that without omitting some of the r...
[ { "body": "<p>This can certainly be optimized.\nYour algorithm works in loops that iterate over all permutations, placing one letter each time.\nLet us take a different approach: </p>\n\n<p>The number of output combinations can be calculated in advanced: multiply the number of letters for all input numbers. in ...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T04:38:56.720", "Id": "204910", "Score": "3", "Tags": [ "java", "algorithm", "combinatorics" ], "Title": "Print out all possible letter combinations a given phone number can represent" }
204910
<p>Thank you for your patience. The game is fully functional again! </p> <p>I have tried to incorporate all the advice I have received so far. Thank you for taking the time to review and comment.</p> <p>I have now decoupled the Model / Presenter from the View as much as VBA allows (please correct me if wrong). There are two functions from inside the view which the presenter calls. One of these functions ends the game, the other takes in a collection which the view promptly displays to the player.</p> <p>When your ship collides with a space object you get a game over message box and then the userform unloads, an upgrade over the previous version which lead to crashes when you tried to run game twice. </p> <p>Rather than throwing all of the spaceobjects into a single collection I have kept the separate collections for each "type" of spaceobject; incoming, missile and ship. Separate Collections for these objects makes handling collisions and object removal more manageable.</p> <p>In the immediate term I want to re introduce scoring and a missile count limit. Also I need to fix the scaling of the objects. I have them in a ratio with gameboard height / width. Somehow it was not working for me? Then I am thinking about heat seeking missiles (give me a chance to work on algorithim stuff a bit, should be fun)</p> <p>You can find the workbook here:</p> <p><a href="https://github.com/Evanml2030/Excel-SpaceInvader" rel="nofollow noreferrer">https://github.com/Evanml2030/Excel-SpaceInvader</a></p> <p>Note that you cannot import and run Gameboard.frm without the corresponding Gameboard.frx file. Frx is a proprietary Microsoft file type that degenerates into alien symbols inside notepad, not sure how to link here.</p> <p>Also note that StopWatch, BoardDimensions and each of the Collections have </p> <pre><code>Attribute VB_PredeclaredId = True </code></pre> <p>Big ups to:</p> <p>StopWatch was put together by the fellow who runs bytecomb, a great site for vba tips. Link: <a href="https://bytecomb.com/accurate-performance-timers-in-vba/" rel="nofollow noreferrer">https://bytecomb.com/accurate-performance-timers-in-vba/</a></p> <p><strong>GameBoard.frm:</strong></p> <pre><code>VERSION 5.00 Begin {C62A69F0-16DC-11CE-9E98-00AA00574A4F} GameBoard Caption = "UserForm1" ClientHeight = 9495 ClientLeft = 120 ClientTop = 465 ClientWidth = 10095 OleObjectBlob = "GameBoard.frx":0000 StartUpPosition = 1 'CenterOwner End Attribute VB_Name = "GameBoard" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Private Sub UserForm_Activate() GameLogic.RunGame Me.InsideHeight, Me.InsideWidth End Sub Private Sub UserForm_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer) Dim passVal As Long Select Case KeyCode.Value Case 37, 39, 32 passVal = CInt(KeyCode) GameLogic.HandleSendKeys passVal End Select End Sub Public Sub RefreshGameBoard(ByVal ControlsToAdd As Collection) Dim Ctrl As Image Dim SpaceObjectIndex As Variant For Each Ctrl In Me.Controls Me.Controls.Remove Ctrl.Name Next Ctrl For SpaceObjectIndex = 1 To ControlsToAdd.Count Set Ctrl = Me.Controls.Add("Forms.Image.1", ControlsToAdd.Item(SpaceObjectIndex).Name, True) Ctrl.Left = ControlsToAdd.Item(SpaceObjectIndex).Left Ctrl.Top = ControlsToAdd.Item(SpaceObjectIndex).Top Ctrl.Height = ControlsToAdd.Item(SpaceObjectIndex).Height Ctrl.Width = ControlsToAdd.Item(SpaceObjectIndex).Width Ctrl.Picture = LoadPicture(LinkToImage(ControlsToAdd.Item(SpaceObjectIndex).SpaceObjectType)) Ctrl.PictureSizeMode = fmPictureSizeModeStretch Next SpaceObjectIndex End Sub Public Sub CloseGame() MsgBox "GAMEOVER" Unload Me End Sub Private Function LinkToImage(ByVal SpaceObjectType As SpaceObjectType) As String Select Case SpaceObjectType Case Alien LinkToImage = "C:\Users\evanm\OneDrive\Desktop\Excel\SpaceInvader\AlienShip.jpg" Case Comet LinkToImage = "C:\Users\evanm\OneDrive\Desktop\Excel\SpaceInvader\Comet.jpg" Case Star LinkToImage = "C:\Users\evanm\OneDrive\Desktop\Excel\SpaceInvader\Star.jpg" Case Missile LinkToImage = "C:\Users\evanm\OneDrive\Desktop\Excel\SpaceInvader\Missile.jpg" Case Ship LinkToImage = "C:\Users\evanm\OneDrive\Desktop\Excel\SpaceInvader\SpaceShip.jpg" End Select End Function </code></pre> <p><strong>GameLogic.bas:</strong></p> <pre><code>Attribute VB_Name = "GameLogic" Option Explicit Public Enum SpaceObjectType Alien = 1 Comet = 2 Star = 3 Missile = 4 Ship = 5 End Enum Public Enum PlayerShipHit Hit = 1 NotHit = 0 End Enum Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal Milliseconds As LongPtr) Const Interval = 3 Sub RunGame(ByVal BoardWith As Long, ByVal BoardHeight As Long) Dim SleepWatch As StopWatch Dim GenerateIncSpaceObjectsRound1 As StopWatch BoardDimensions.Width = BoardWith BoardDimensions.Height = BoardHeight Set SleepWatch = New StopWatch SleepWatch.Start Set GenerateIncSpaceObjectsRound1 = New StopWatch GenerateIncSpaceObjectsRound1.Start InitializePlayerShip Do GameBoard.RefreshGameBoard CombineCollections MoveSpaceObjects.MoveIncomingMissiles MoveSpaceObjects.MoveIncomingSpaceObjects Collisions.HandleMissileCollisions If Collisions.HandleShipCollisions Then Exit Do If Format(GenerateIncSpaceObjectsRound1.Elapsed, "0.000000") &gt; 3.25 Then ReleaseIncomingSpaceObject ReleaseIncomingSpaceObject ReleaseIncomingSpaceObject GenerateIncSpaceObjectsRound1.Restart End If If Format(SleepWatch.Elapsed, "0.000000") &lt; Interval Then Sleep Interval - Format(SleepWatch.Elapsed, "0.000000") SleepWatch.Restart End If DoEvents Loop GameBoard.CloseGame End Sub Public Sub HandleSendKeys(ByVal KeyCode As Long) Select Case KeyCode Case 37 MoveSpaceObjects.MoveShip Left Case 39 MoveSpaceObjects.MoveShip Right Case 32 LaunchMissile End Select End Sub Private Function InitializePlayerShip() Dim PlayerShip As ISpaceObject Set PlayerShip = SpaceObjectFactory.NewSpaceObject(Ship) CollectionShips.Add PlayerShip End Function Private Function LaunchMissile() Dim LaunchedMissile As ISpaceObject Set LaunchedMissile = SpaceObjectFactory.NewSpaceObject(Missile) CollectionMissiles.Add LaunchedMissile End Function Private Function ReleaseIncomingSpaceObject() Dim IncomingSpaceObject As ISpaceObject Set IncomingSpaceObject = SpaceObjectFactory.NewSpaceObject(Application.WorksheetFunction.RandBetween(1, 3)) CollectionIncomingSpaceObjects.Add IncomingSpaceObject End Function Private Function CombineCollections() As Collection Dim ISpaceObjectIndex As Long Set CombineCollections = New Collection For ISpaceObjectIndex = 1 To CollectionIncomingSpaceObjects.Count CombineCollections.Add CollectionIncomingSpaceObjects.Item(ISpaceObjectIndex) Next ISpaceObjectIndex For ISpaceObjectIndex = 1 To CollectionMissiles.Count CombineCollections.Add CollectionMissiles.Item(ISpaceObjectIndex) Next ISpaceObjectIndex For ISpaceObjectIndex = 1 To CollectionShips.Count CombineCollections.Add CollectionShips.Item(ISpaceObjectIndex) Next ISpaceObjectIndex End Function </code></pre> <p><strong>MoveSpaceObjects.bas:</strong></p> <pre><code>Attribute VB_Name = "MoveSpaceObjects" Option Explicit Public Enum Direction Left = 0 Right = 1 End Enum Sub MoveIncomingMissiles() Dim SpaceObjectIndex As Variant For SpaceObjectIndex = CollectionMissiles.Count To 1 Step -1 If CollectionMissiles.Item(SpaceObjectIndex).Top - 3 &lt;= 0 Then CollectionMissiles.Remove SpaceObjectIndex Else CollectionMissiles.Item(SpaceObjectIndex).Top = CollectionMissiles.Item(SpaceObjectIndex).Top - 3 End If Next SpaceObjectIndex End Sub Sub MoveIncomingSpaceObjects() Dim SpaceObjectIndex As Variant For SpaceObjectIndex = CollectionIncomingSpaceObjects.Count To 1 Step -1 If CollectionIncomingSpaceObjects.Item(SpaceObjectIndex).Top + 3 &gt;= BoardDimensions.Height Then CollectionIncomingSpaceObjects.Remove SpaceObjectIndex Else CollectionIncomingSpaceObjects.Item(SpaceObjectIndex).Top = CollectionIncomingSpaceObjects.Item(SpaceObjectIndex).Top + 3 End If Next SpaceObjectIndex End Sub Sub MoveShip(ByVal MoveShipDirection As Direction) Select Case MoveShipDirection Case Direction.Left If CollectionShips.Item(1).Left - 4 &gt;= 0 Then CollectionShips.Item(1).Left = CollectionShips.Item(1).Left - 5 Else CollectionShips.Item(1).Left = 0 End If Case Direction.Right If (CollectionShips.Item(1).Left + CollectionShips.Item(1).Width) &lt; BoardDimensions.Width Then CollectionShips.Item(1).Left = CollectionShips.Item(1).Left + 4 Else CollectionShips.Item(1).Left = BoardDimensions.Width - CollectionShips.Item(1).Width End If End Select End Sub </code></pre> <p><strong>SpaceObjectFactory.bas</strong></p> <pre><code>Attribute VB_Name = "SpaceObjectFactory" Option Explicit Public Function NewSpaceObject(ByVal SpaceObjectType As SpaceObjectType) As Spaceobject Select Case SpaceObjectType Case Alien Set NewSpaceObject = NewSpaceObjectAlien Case Comet Set NewSpaceObject = NewSpaceObjectComet Case Missile Set NewSpaceObject = NewSpaceObjectMissile Case Ship Set NewSpaceObject = NewSpaceObjectShip Case Star Set NewSpaceObject = NewSpaceObjectStar End Select End Function Private Function NewSpaceObjectAlien() As Spaceobject With New Spaceobject .SetInitialLeft Application.WorksheetFunction.RandBetween(1, BoardDimensions.Width) .SetInitialTop 1 .Height = BoardDimensions.Width / 10 .Width = BoardDimensions.Width / 10 .SpaceObjectType = Alien .Name = "INCSPACEOBJECT" &amp; CollectionIncomingSpaceObjects.Count Set NewSpaceObjectAlien = .Self End With End Function Private Function NewSpaceObjectComet() As Spaceobject With New Spaceobject .SetInitialLeft Application.WorksheetFunction.RandBetween(1, BoardDimensions.Width) .SetInitialTop 1 .Height = BoardDimensions.Height / 7 .Width = BoardDimensions.Height / 7 .SpaceObjectType = Comet .Name = "INCSPACEOBJECT" &amp; CollectionIncomingSpaceObjects.Count Set NewSpaceObjectComet = .Self End With End Function Private Function NewSpaceObjectMissile() As Spaceobject With New Spaceobject .SetInitialLeft ((CollectionShips.Item(1).Width - (BoardDimensions.Width / 20)) / 2) + CollectionShips.Item(1).Left .SetInitialTop CollectionShips.Item(1).Top - BoardDimensions.Height / 15 .Height = BoardDimensions.Height / 15 .Width = BoardDimensions.Height / 20 .SpaceObjectType = Missile .Name = "MISSILE" &amp; CollectionMissiles.Count Set NewSpaceObjectMissile = .Self End With End Function Private Function NewSpaceObjectShip() As Spaceobject With New Spaceobject .SetInitialLeft BoardDimensions.Width / 2 - ((BoardDimensions.Height / 7) / 2) .SetInitialTop Round(BoardDimensions.Height - ((BoardDimensions.Height / 7) * 1.25), 0) .Height = BoardDimensions.Height / 7 .Width = BoardDimensions.Width / 7 .SpaceObjectType = Ship .Name = "SHIP" Set NewSpaceObjectShip = .Self End With End Function Private Function NewSpaceObjectStar() As Spaceobject With New Spaceobject .SetInitialLeft Application.WorksheetFunction.RandBetween(1, BoardDimensions.Width) .SetInitialTop 1 .Height = BoardDimensions.Height / 5 .Width = BoardDimensions.Height / 5 .SpaceObjectType = Star .Name = "INCSPACEOBJECT" &amp; CollectionIncomingSpaceObjects.Count Set NewSpaceObjectStar = .Self End With End Function </code></pre> <p><strong>Collisions.bas:</strong></p> <pre><code>Attribute VB_Name = "Collisions" Option Explicit Sub HandleMissileCollisions() Dim MissileObject As ISpaceObject Dim IncomingSpaceObject As ISpaceObject Dim MissileObjectsIndex As Long Dim IncomingSpaceObjectIndex As Long For MissileObjectsIndex = CollectionMissiles.Count To 1 Step -1 Set MissileObject = CollectionMissiles.Item(MissileObjectsIndex) For IncomingSpaceObjectIndex = CollectionIncomingSpaceObjects.Count To 1 Step -1 Set IncomingSpaceObject = CollectionIncomingSpaceObjects.Item(IncomingSpaceObjectIndex) If CheckIfCollided(MissileObject, IncomingSpaceObject) Then CollectionMissiles.Remove MissileObjectsIndex CollectionIncomingSpaceObjects.Remove IncomingSpaceObjectIndex Exit For End If Next IncomingSpaceObjectIndex Next MissileObjectsIndex End Sub Function HandleShipCollisions() As Boolean Dim ShipObject As ISpaceObject Dim IncomingSpaceObject As ISpaceObject Dim ShipObjectIndex As Long Dim IncomingSpaceObjectIndex As Long For ShipObjectIndex = CollectionShips.Count To 1 Step -1 Set ShipObject = CollectionShips.Item(ShipObjectIndex) For IncomingSpaceObjectIndex = CollectionIncomingSpaceObjects.Count To 1 Step -1 Set IncomingSpaceObject = CollectionIncomingSpaceObjects.Item(IncomingSpaceObjectIndex) If CheckIfCollided(ShipObject, IncomingSpaceObject) Then HandleShipCollisions = True Exit For End If Next IncomingSpaceObjectIndex Next ShipObjectIndex End Function Private Function CheckIfCollided(ByVal First As ISpaceObject, ByVal Second As ISpaceObject) As Boolean Dim HorizontalOverlap As Boolean Dim VerticalOverlap As Boolean HorizontalOverlap = (First.Left - Second.Width &lt; Second.Left) And (Second.Left &lt; First.Left + First.Width) VerticalOverlap = (First.Top - Second.Height &lt; Second.Top) And (Second.Top &lt; First.Top + First.Height) CheckIfCollided = HorizontalOverlap And VerticalOverlap End Function </code></pre> <p><strong>CollectionMissiles.cls:</strong></p> <pre><code>VERSION 1.0 CLASS BEGIN MultiUse = -1 'True END Attribute VB_Name = "CollectionMissiles" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Option Explicit Private CollectionMissiles As Collection Private pCount As Long Private Sub Class_Initialize() Set CollectionMissiles = New Collection End Sub Private Sub Class_Terminate() Set CollectionMissiles = Nothing End Sub Public Sub Add(obj As ISpaceObject) CollectionMissiles.Add obj End Sub Public Sub Remove(index As Variant) CollectionMissiles.Remove index End Sub Public Property Get Item(index As Variant) As ISpaceObject Set Item = CollectionMissiles.Item(index) End Property Property Get Count() As Long Count = CollectionMissiles.Count End Property Public Sub Clear() Set CollectionMissiles = New Collection End Sub </code></pre> <p><strong>CollectionIncomingSpaceObjects.cls:</strong></p> <pre><code>VERSION 1.0 CLASS BEGIN MultiUse = -1 'True END Attribute VB_Name = "CollectionIncomingSpaceObjects" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Option Explicit Private CollectionIncomingSpaceObjects As Collection Private Sub Class_Initialize() Set CollectionIncomingSpaceObjects = New Collection End Sub Private Sub Class_Terminate() Set CollectionIncomingSpaceObjects = Nothing End Sub Public Sub Add(obj As ISpaceObject) CollectionIncomingSpaceObjects.Add obj End Sub Public Sub Remove(index As Variant) CollectionIncomingSpaceObjects.Remove index End Sub Public Property Get Item(index As Variant) As ISpaceObject Set Item = CollectionIncomingSpaceObjects.Item(index) End Property Property Get Count() As Long Count = CollectionIncomingSpaceObjects.Count End Property Public Sub Clear() Set CollectionIncomingSpaceObjects = New Collection End Sub </code></pre> <p><strong>CollectionShips.cls:</strong></p> <pre><code>VERSION 1.0 CLASS BEGIN MultiUse = -1 'True END Attribute VB_Name = "CollectionShips" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Option Explicit Private CollectionShips As Collection Private pCount As Long Private Sub Class_Initialize() Set CollectionShips = New Collection End Sub Private Sub Class_Terminate() Set CollectionShips = Nothing End Sub Public Sub Add(obj As ISpaceObject) CollectionShips.Add obj End Sub Public Sub Remove(index As Variant) CollectionShips.Remove index End Sub Public Property Get Item(index As Variant) As ISpaceObject Set Item = CollectionShips.Item(index) End Property Property Get Count() As Long Count = CollectionShips.Count End Property Public Sub Clear() Set CollectionShips = New Collection End Sub </code></pre> <p><strong>ISpaceObject.cls</strong></p> <pre><code>VERSION 1.0 CLASS BEGIN MultiUse = -1 'True END Attribute VB_Name = "ISpaceObject" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = False Attribute VB_Exposed = False Option Explicit Public Property Let Left(ByVal changeLeft As Long) End Property Public Property Get Left() As Long End Property Public Property Let Top(ByVal changeTop As Long) End Property Public Property Get Top() As Long End Property Public Property Get Width() As Long End Property Public Property Get Height() As Long End Property Public Property Get Name() As String End Property Public Property Get SpaceObjectType() As SpaceObjectType End Property Private Function IsMissile() As Boolean End Function Private Function IsIncomingSpaceObject() As Boolean End Function </code></pre> <p><strong>BoardDimensions.cls:</strong></p> <pre><code>VERSION 1.0 CLASS BEGIN MultiUse = -1 'True END Attribute VB_Name = "BoardDimensions" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Option Explicit Private Type BoardDimensionsData Width As Long Height As Long End Type Private this As BoardDimensionsData Public Property Let Width(ByVal Width As Long) this.Width = Width End Property Public Property Get Width() As Long Width = this.Width End Property Public Property Let Height(ByVal Height As Long) this.Height = Height End Property Public Property Get Height() As Long Height = this.Height End Property </code></pre> <p><strong>StopWatch.cls</strong></p> <pre><code>VERSION 1.0 CLASS BEGIN MultiUse = -1 'True END Attribute VB_Name = "StopWatch" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = False Attribute VB_Exposed = False Option Explicit Private Declare PtrSafe Function QueryPerformanceCounter Lib "kernel32" ( _ lpPerformanceCount As UINT64) As Long Private Declare PtrSafe Function QueryPerformanceFrequency Lib "kernel32" ( _ lpFrequency As UINT64) As Long Private pFrequency As Double Private pStartTS As UINT64 Private pEndTS As UINT64 Private pElapsed As Double Private pRunning As Boolean Private Type UINT64 LowPart As Long HighPart As Long End Type Private Const BSHIFT_32 = 4294967296# ' 2 ^ 32 Private Function U64Dbl(U64 As UINT64) As Double Dim lDbl As Double Dim hDbl As Double lDbl = U64.LowPart hDbl = U64.HighPart If lDbl &lt; 0 Then lDbl = lDbl + BSHIFT_32 If hDbl &lt; 0 Then hDbl = hDbl + BSHIFT_32 U64Dbl = lDbl + BSHIFT_32 * hDbl End Function Private Sub Class_Initialize() Dim PerfFrequency As UINT64 QueryPerformanceFrequency PerfFrequency pFrequency = U64Dbl(PerfFrequency) End Sub Public Property Get Elapsed() As Double If pRunning Then Dim pNow As UINT64 QueryPerformanceCounter pNow Elapsed = pElapsed + (U64Dbl(pNow) - U64Dbl(pStartTS)) / pFrequency Else Elapsed = pElapsed End If End Property Public Sub Start() If Not pRunning Then QueryPerformanceCounter pStartTS pRunning = True End If End Sub Public Sub Pause() If pRunning Then QueryPerformanceCounter pEndTS pRunning = False pElapsed = pElapsed + (U64Dbl(pEndTS) - U64Dbl(pStartTS)) / pFrequency End If End Sub Public Sub Reset() pElapsed = 0 pRunning = False End Sub Public Sub Restart() pElapsed = 0 QueryPerformanceCounter pStartTS pRunning = True End Sub Public Property Get Running() As Boolean Running = pRunning End Property </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T07:18:45.120", "Id": "395214", "Score": "0", "body": "The current question title, which states your concerns about the code, is confusing. The site standard is for the title to simply state the task accomplished by the code. Please ...
[ { "body": "<blockquote>\n<pre><code>Private Function InitializePlayerShip()\n Dim PlayerShip As ISpaceObject\n Set PlayerShip = SpaceObjectFactory.NewSpaceObject(Ship)\n CollectionShips.Add PlayerShip\nEnd Function\n</code></pre>\n</blockquote>\n...
{ "AcceptedAnswerId": "204951", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T05:47:55.863", "Id": "204913", "Score": "5", "Tags": [ "beginner", "object-oriented", "game", "vba", "excel" ], "Title": "Space Invader Style Game - Model / Presenter Decoupled From View - Functional Again Too" }
204913
<p>I am new to react (and javascript in general) but am enjoying learning it. I have decided to make a little multiselect component which should work as follows:</p> <p>I start with my data in one list, when I select an item from the list it goes into a second list (I can 'unselect' as well).</p> <p>I also can filter the first list with a text input. </p> <p>Before you review, I realize that there are likely existing solutions for this functionality that I could use, but I am just doing this to learn.</p> <p>codepen here <a href="https://codepen.io/str8wavedave/pen/ZqWXQp" rel="nofollow noreferrer">https://codepen.io/str8wavedave/pen/ZqWXQp</a></p> <pre><code>class MultiSelect extends React.Component { render(){ return( &lt;ul&gt; {this.props.objects.map((object, index) =&gt; &lt;li onClick = {() =&gt; this.props.onClickFunction(index)}&gt;{object.name}&lt;/li&gt;)} &lt;/ul&gt; ); } } class DoubleMultiselect extends React.Component { state = { value: '', filteredUnselectedObjects: this.props.objects, unselectedObjects: this.props.objects, selectedObjects: [], } filterList = (event) =&gt; { var updatedList = this.state.unselectedObjects; updatedList = updatedList.filter(function(item){ return item.name.toLowerCase().search( event.target.value.toLowerCase()) !== -1; }); this.setState({ filteredUnselectedObjects: updatedList, value: event.target.value }) } handleSelect = (index) =&gt; { var obj = this.state.filteredUnselectedObjects[index] var newSelected = this.state.selectedObjects.slice() newSelected.push(obj) var newUnselected = this.state.unselectedObjects.slice() var originalIndex = newUnselected.indexOf(obj); newUnselected.splice(originalIndex, 1) var newFilteredUnselected = this.state.filteredUnselectedObjects.slice() newFilteredUnselected.splice(index, 1) this.setState({ selectedObjects: newSelected, unselectedObjects: newUnselected, filteredUnselectedObjects: newFilteredUnselected }); } handleUnselect = (index) =&gt; { var obj = this.state.selectedObjects[index] var newUnselected = this.state.unselectedObjects.slice() newUnselected.push(obj) var newFilteredUnselected = this.state.filteredUnselectedObjects.slice() if(obj.name.toLowerCase().search(this.state.value.toLowerCase()) !== -1) { newFilteredUnselected.push(obj) } var newSelected = this.state.selectedObjects.slice() newSelected.splice(index, 1) this.setState({ unselectedObjects: newUnselected, selectedObjects: newSelected, filteredUnselectedObjects: newFilteredUnselected }); } render() { return( &lt;div&gt; &lt;input type="text" onChange={this.filterList}/&gt; &lt;MultiSelect objects={this.state.filteredUnselectedObjects} onClickFunction={this.handleSelect}/&gt; &lt;MultiSelect objects={this.state.selectedObjects} onClickFunction={this.handleUnselect}/&gt; &lt;/div&gt; ); } } const PLAYERS =[ {name: 'Charlie', id: 1}, {name: 'David', id: 2}, {name: 'Eric', id: 3}, {name: 'Emily', id: 4}, {name: 'Peter', id: 5}, {name: 'Sam', id: 6}, {name: 'Doug', id: 7} ] React.render(&lt;DoubleMultiselect objects={PLAYERS}/&gt;, document.getElementById('app')); </code></pre>
[]
[ { "body": "<p>Overall this is good, but there are few things we can do improve this and make it more \"modular\".</p>\n\n<p>Lets say someone wants to use your component and instead of an array of player objects, they have just an array of player names, this introduces a couple of problems.</p>\n\n<ol>\n<li>The ...
{ "AcceptedAnswerId": "208717", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T07:15:25.410", "Id": "204915", "Score": "1", "Tags": [ "beginner", "form", "react.js", "jsx" ], "Title": "React multi-select-like component with filter" }
204915
<p>I have been studying C#, and I have made a simple math quiz program.</p> <p>Is my program reasonable or is there anything I need to improve?</p> <pre><code>class Program { static void Main(string[] args) { Console.WriteLine("============== Math Game ==================="); double num1, num2; double userInput; int randomIndex; double sum = 0; string operation; // [2] //int lives = 0; // Console.Write("How many lives do you want?\t"); // lives = Convert.ToInt32(Console.ReadLine()); // Console.WriteLine("You have {0} Lives", lives); bool isPlaying = true; do { // 1 generate randon# Random rnd = new Random(); randomIndex = rnd.Next(1, 4); num1 = rnd.Next(1, 11); num2 = rnd.Next(1, 11); // 2 cal sum &amp;&amp; operation &amp;&amp; Display sum = Cal(num1, num2, randomIndex); operation = Operation(randomIndex); // DisplayProblem(num1, num2, operation); // 3 request input userInput = RequestInput(num1,num2,operation); // 4 check answer CheckAnswer(userInput, sum); } while (isPlaying); } private static double Cal(double num1, double num2, int randomIndex) { double sum = 0; switch (randomIndex) { case 1: sum = num1 + num2; break; case 2: sum = num1 - num2; break; case 3: sum = num1 * num2; break; case 4: sum = num1 / num2; break; default: Console.WriteLine("Error"); break; } return sum; } private static string Operation(int randomIndex) { string operation = ""; switch (randomIndex) { case 1: operation = "+"; break; case 2: operation = "-"; break; case 3: operation = "*"; break; case 4: operation = "/"; break; default: Console.WriteLine("error"); break; } return operation; } private static void DisplayProblem(double num1, double num2, string operation) { Console.Write($"{num1} {operation} {num2} = "); } private static double RequestInput(double num1, double num2, string operation) { DisplayProblem(num1, num2, operation); double userInput; while (!Double.TryParse(Console.ReadLine(),out userInput)) { Console.WriteLine("Invalid input. Please type a whole num"); DisplayProblem(num1, num2, operation); } return userInput; } private static void CheckAnswer(double userInput, double sum) { if (userInput == sum) { Console.WriteLine("Correct Answer."); } else if(userInput != sum) { Console.WriteLine("Wrong Answer."); } } } </code></pre>
[]
[ { "body": "<p>In the <code>Operation</code> method</p>\n\n<pre><code>private static string Operation(int randomIndex)\n{\n string operation = \"\";\n switch (randomIndex)\n {\n case 1:\n operation = \"+\";\n break;\n case 2:\n operation = \"-\";\n ...
{ "AcceptedAnswerId": "204963", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T08:31:35.330", "Id": "204921", "Score": "1", "Tags": [ "c#", "quiz" ], "Title": "Mathematical quiz game" }
204921
<p>In the following code, I implement a class that starts a process and returns its return code, <code>stdout</code> and <code>stderr</code>. It also has a concept of timeout after which the child process is killed. This class will be used as a part of a multi-threaded application.</p> <pre><code>#ifndef PROCESS_H_ #define PROCESS_H_ //Header #include &lt;chrono&gt; #include &lt;thread&gt; #include &lt;iostream&gt; #include &lt;boost/process.hpp&gt; #include &lt;boost/asio.hpp namespace bp = boost::process; class Proces { public: Process(const std::string&amp; cmd, const int timeout); void run(); int getReturnStatus(); //Must be only called after run() exits std::string getStdOut(); //Must be only called after run() exits std::string getStdErr(); //Must be only called after run() exits bool wasKilled(); //Must be only called after run() exits private: void initLog(); void timeoutHandler(const boost::system::error_code&amp; ec); void kill(); const std::string command; const int timeout; int returnStatus; std::string stdOut; std::string stdErr; bool killed; bool stopped; boost::process::group group; boost::asio::io_context ioc; boost::asio::deadline_timer deadline_timer; }; #endif //Source #include &quot;Process.h&quot; Process::Process(const std::string&amp; cmd, const int timeout): command(cmd), timeout(timeout), returnStatus(0), stdOut(&quot;&quot;), stdErr(&quot;&quot;), killed(false), stopped(false), ioc(), deadline_timer(ioc) { } void Process::timeoutHandler(const boost::system::error_code&amp; ec) { if (stopped || ec == boost::asio::error::operation_aborted) { return; } std::cout &lt;&lt; &quot;Time Up!&quot;&lt;&lt; std::endl; kill(); deadline_timer.expires_at(boost::posix_time::pos_infin); } void Process::run() { std::future&lt;std::string&gt; dataOut; std::future&lt;std::string&gt; dataErr; std::cout &lt;&lt; &quot;Running command: &quot; &lt;&lt; command &lt;&lt; std::endl; bp::child c(command, bp::std_in.close(), bp::std_out &gt; dataOut, bp::std_err &gt; dataErr, ioc, group, bp::on_exit([=](int e, const std::error_code&amp; ec) { std::cout &lt;&lt; &quot;on_exit: &quot; &lt;&lt; ec.message() &lt;&lt; &quot; -&gt; &quot; &lt;&lt; e &lt;&lt; std::endl; deadline_timer.cancel(); returnStatus = e; })); deadline_timer.expires_from_now(boost::posix_time::seconds(timeout)); deadline_timer.async_wait(std::bind(&amp;Process::timeoutHandler, this, std::placeholders::_1)); ioc.run(); c.wait(); stdOut = dataOut.get(); stdErr = dataErr.get(); } //Must be only called after run() exits int Process::getReturnStatus() { return returnStatus; } //Must be only called after run() exits std::string Process::getStdOut() { return stdOut; } //Must be only called after run() exits std::string Process::getStdErr() { return stdErr; } void Process::kill() { std::error_code ec; group.terminate(ec); if(ec) { std::cout &lt;&lt; &quot;Error occurred while trying to kill the process: &quot; &lt;&lt; ec.message(); throw std::runtime_error(ec.message()); } std::cout &lt;&lt; &quot;Killed the process and all its descendants&quot; &lt;&lt; std::endl; killed = true; stopped = true; } //Must be only called after run() exits bool Process::wasKilled() { return killed; } </code></pre> <p>Below is the code I am using to test it</p> <pre><code>#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE ProcessTest #include &lt;boost/test/unit_test.hpp&gt; #include &quot;../src/Process.h&quot; BOOST_AUTO_TEST_CASE( ProcessTest ) { const std::vector&lt;std::string&gt; commands = { &quot;ls&quot; , &quot;pwd&quot; , &quot;uname -a&quot; , &quot;cat /proc/cpuinfo&quot; , &quot;wget https://dl.google.com/dl/earth/client/current/google-earth-pro-stable-current.x86_64.rpm&quot;}; for(const auto&amp; cmd: commands) { Process p(cmd, 3600); p.run(); BOOST_CHECK( p.getReturnStatus() == 0); // #1 continues on error } const std::vector&lt;std::string&gt; commandsThatShouldFail = { &quot;ls doesnotexit&quot; , &quot;cat /proc/doesnotexist&quot; , &quot;wget https://dl.google.com/dl/earth/client/current/doesnotxist.rpm&quot;}; for(const auto&amp; cmd: commandsThatShouldFail) { Process p(cmd, 3600); p.run(); BOOST_CHECK( p.getReturnStatus() != 0); // #1 continues on error } } </code></pre> <p>Please provide your valuable comments and suggestions.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T08:46:06.477", "Id": "395234", "Score": "0", "body": "Welcome to Code Review! You say you're trying to implement the program. Does it work so far? Do you have any concerns about your code? It's ok if you don't, as long as the code w...
[ { "body": "<h1>Missing tests</h1>\n\n<p>I don't see any tests for commands that should time out. An obvious example could be <code>sleep 2</code>, if we run it with a timeout of <code>1</code>. A more rigorous test would be a command that ignores all signals (of the ones that can be ignored) - we should ensur...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T08:36:48.670", "Id": "204922", "Score": "3", "Tags": [ "c++", "c++11", "boost", "child-process" ], "Title": "Run an asynchronous child process with timeout" }
204922
<p>I am implementing the factory method approach. My intention is to know if my approach is correct for factory method. Any modifications to be done to align with the approach?</p> <p>First I am creating an interface IAuto.</p> <pre><code> //IAuto.cs namespace TestDesignPatterns.Auto { public interface IAuto { void start(); void stop(); } } </code></pre> <p>Create a class that implements the IAuto.</p> <pre><code> //clsBMW.cs namespace TestDesignPatterns.Auto { public class clsBMW : IAuto { public void start() { Console.WriteLine("BMW started"); } public void stop() { Console.WriteLine("BMW stopped"); } } } </code></pre> <p>Create another concrete class for Audi implementing IAuto.</p> <pre><code>namespace TestDesignPatterns.Auto { public class clsAudi : IAuto { public void start() { Console.WriteLine("Audi started"); } public void stop() { Console.WriteLine("Audi stopped"); } } } </code></pre> <p>Create an Interface of factory which creates the model.</p> <pre><code>//IautoFactory.cs public interface IAutoFactory { IAuto createModel(ModelType m); } </code></pre> <p>concrete factory class.</p> <pre><code>//clsAutofactory.cs public class clsAutoFactory : IAutoFactory { public IAuto createModel(ModelType m) { IAuto instance = null; switch (Convert.ToInt32(m)) { case 0: instance = new clsBMW(); break; case 1: instance = new clsAudi(); break; default: break; } return instance; } } </code></pre> <p>Main Program</p> <pre><code> public enum ModelType { BMW=0, Audi=1 } //program.cs IAutoFactory factory = new clsAutoFactory(); IAuto model = factory.createModel(ModelType.Audi); model.start(); model.stop(); Console.ReadKey(); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T10:42:00.197", "Id": "395249", "Score": "0", "body": "Does it work as intended? In that case, put forth the effort and post a real question. Please take a look at the [help/on-topic] and [How to get the best value out of Code Review...
[ { "body": "<p><code>switch (Convert.ToInt32(m))</code> this is counterproductive and hurts readability. You can use <code>enums</code> in <code>switch</code> statements, so instead do this:</p>\n\n<pre><code>switch (m)\n{\n case ModelType.BMW:\n bla\n case ModelType.Audi:\n bla\n}\n</code></...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T10:23:45.690", "Id": "204928", "Score": "0", "Tags": [ "c#", "enum", "factory-method" ], "Title": "Factory method to create two kinds of cars based on an enum" }
204928
<p>This is a fairly short code snippet, but it made me a little headache, because it is hard to understand, isn't it?</p> <pre><code>// You have to be in both 'group' and 'board' to get access (or be a superuser) if ( ( !$is_in_group || !$is_in_board ) &amp;&amp; !$is_superuser) { die('No access'); } </code></pre> <p>This code is from a download page, where registered users can download files. Only users within a certain board and group are allowed to download files. The three variables are just for this demo. The values are coming from a CMS function.</p> <p>Do you have a more readable or better way to verifying access here?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T11:05:09.957", "Id": "395252", "Score": "0", "body": "It's lacking context, but simplified like that I don't see anything wrong with it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T11:07:07.443", ...
[ { "body": "<p>You can rewrite it like this:</p>\n\n<pre><code>// you have to be in both 'group' and 'board' to get access\n$has_access = $is_in_group &amp;&amp; $is_in_board;\n// you must have access or be a superuser\nif (!($has_access || $is_superuser)) die('No access');\n</code></pre>\n\n<p>I don't think an ...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T11:00:46.100", "Id": "204929", "Score": "0", "Tags": [ "php" ], "Title": "More readable approach?" }
204929
<p>Made some adjustments to my original program. Here's a link to it: <a href="https://codereview.stackexchange.com/questions/204855/find-the-cheapest-order-placed-out-of-all-of-the-stores-visited/204924#204924">original</a>. Also, here's a link to the problem statement: <a href="https://drive.google.com/file/d/1RnhUCxKIYUZRoN9WpQ0V8esduiJgF78S/view?usp=sharing" rel="nofollow noreferrer">problem statement</a>.</p> <p>The assignment is past due; The code I turned in is stupid simple. Which is great, but I didn't learn anything, so I am testing the many different ways to do things in C, and hoping some will have some hints, tips, tricks, advice, suggestions, etc.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdbool.h&gt; int read_positive_int(const char* prompt) { printf("%s\n\nInput Specifications: Please type a positive integer and press the 'Enter' or the 'return' key when finished.\n", prompt); int n; while (true) { char line[1024]; /* the input line */ fgets(line, sizeof(line), stdin); int sscanf_result = sscanf(line, "%d", &amp;n); if (sscanf_result == 1 &amp;&amp; n &gt; 0) { return n; } puts("\nInput Error: Please carefully read the input specifications that are provided after each question prompt and then try again.\n"); } } float read_real_positive_float(const char* prompt) { printf("%s\n\nInput Specifications: Please type a real number in currency format, i.e., XXX.XX, and press the 'Enter' or the 'return' key when finished.\n", prompt); float n; while (true) { char line[1024]; fgets(line, sizeof(line), stdin); int sscanf_result = sscanf(line, "%f", &amp;n); if (sscanf_result == 1 &amp;&amp; n &gt; 0 ) { return n; } puts("\nInput Error: Please carefully read the input specifications that are provided after each question prompt and then try again.\n"); } } int main(void) { int total_shops = read_positive_int("How many shops will be visited?"); float **cost_ingredients_ptr = malloc(total_shops * sizeof(float*)); /* allocate an array of pointers */ if (!cost_ingredients_ptr) { fprintf(stderr, "Memory allocation failure!\n"); exit(1); } float **total_cost_ingredients_ptr = malloc(total_shops * sizeof(float*)); memset(total_cost_ingredients_ptr, 0, total_shops * sizeof(float)); if (!total_cost_ingredients_ptr) { fprintf(stderr, "Memory allocation failure!\n"); exit(1); } for (int i = 0; i &lt; total_shops; i++) { printf("\nYou are at shop #%d.\n\n", i+1); int quantity_ingredients = read_positive_int("How many ingredients are needed?"); cost_ingredients_ptr[i] = malloc(quantity_ingredients * sizeof(float)); if (!cost_ingredients_ptr[i]) { fprintf(stderr, "Memory allocation failure!\n"); exit(1); } total_cost_ingredients_ptr[i] = malloc(sizeof(float)); if (!total_cost_ingredients_ptr) { fprintf(stderr, "Memory allocation failure!\n"); exit(1); } for (int j = 0; j &lt; quantity_ingredients; j++) { printf("\nWhat is the cost of ingredient #%d", j+1); cost_ingredients_ptr[i][j] = read_real_positive_float("?"); *total_cost_ingredients_ptr[i] += cost_ingredients_ptr[i][j]; } printf("\nThe total cost at shop #%d is $%0.2f.\n", i+1, *total_cost_ingredients_ptr[i]); if (i == total_shops-1) { float cheapest_order = *total_cost_ingredients_ptr[0]; int location_cheapest_order = 1; for (int k = 1; k &lt; total_shops; k++) { if (*total_cost_ingredients_ptr[k] &lt; cheapest_order) { cheapest_order = *total_cost_ingredients_ptr[k]; location_cheapest_order = k + 1; } printf("\nThe cheapest order placed was at shop #%d, and the total cost of the order placed was $%0.2f.\n", location_cheapest_order, cheapest_order); } } } free(cost_ingredients_ptr); free(total_cost_ingredients_ptr); cost_ingredients_ptr = NULL; total_cost_ingredients_ptr = NULL; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T17:43:26.977", "Id": "395335", "Score": "2", "body": "Please copy the problem statement into your question instead of linking to an external site." } ]
[ { "body": "<h2>Don't be overly verbose</h2>\n\n<p>Your prompts are very verbose, and you use a lot of newlines. Keep it simple. If you ask \"how many\", then people naturally expect to enter a natural number. If you ask for \"cost\", then people will naturally assume they can enter some value with two digits af...
{ "AcceptedAnswerId": "204962", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T11:48:47.777", "Id": "204932", "Score": "1", "Tags": [ "c" ], "Title": "Find the cheapest order placed out of all of the stores visited - follow-up #1" }
204932
<p>This is the code I built to implement a simple linear regression to check the impact of variable A on B. I am not interested in predicting that's why the statistical approach is important for me to focus on the descriptive analytics such as the statsmodels summary and comparing RMSE of training set and test set to see if the model did a good job or not (I'm not looking to compare Dependent variable and RMSE to check prediction quality for example). Is there anything fundamentally wrong with this approach to a simple Linear Regression? </p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt import statsmodels.api as sm from scipy import stats # Import Excel File data = pd.read_excel("C:\\Users\\AchourAh\\Desktop\\Simple_Linear_Regression\\SP Level Simple Linear Regression\\PL32_PMM_03_09_2018_SP_Level.xlsx",'Sheet1') #Import Excel file # Replace null values of the whole dataset with 0 data1 = data.fillna(0) print(data1) # Extraction of the independent and dependent variable X = data1.iloc[0:len(data1),1].values.reshape(-1, 1) #Extract the column of the COPCOR SP we are going to check its impact Y = data1.iloc[0:len(data1),2].values.reshape(-1, 1) #Extract the column of the PAUS SP # Data Splitting to train and test set from sklearn.model_selection import train_test_split X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size =0.25,random_state=42) # Training the model and Evaluation of the Model from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error import math from sklearn import model_selection from sklearn.model_selection import KFold lm = LinearRegression() #create an lm object of LinearRegression Class lm.fit(X_train, Y_train) #train our LinearRegression model using the training set of data - dependent and independent variables as parameters. Teaching lm that Y_train values are all corresponding to X_train. kf = KFold(n_splits=6, random_state=None) for train_index, test_index in kf.split(X_train): print("Train:", train_index, "Validation:",test_index) X_train1, X_test1 = X[train_index], X[test_index] Y_train1, Y_test1 = Y[train_index], Y[test_index] results = -1 * model_selection.cross_val_score(lm, X_train1, Y_train1,scoring='neg_mean_squared_error', cv=kf) print(results) print(results.mean()) mse_test = mean_squared_error(X_test, Y_test) print(mse_test) #RMSE values interpretation test and train are similar no overfitting or underfitting the model performed well print(math.sqrt(mse_test)) print(math.sqrt(results.mean())) # Graph of the Training model plt.scatter(X_train, Y_train, color = 'red')#plots scatter graph of COP COR against PAUS for values in X_train and y_train plt.plot(X_train, lm.predict(X_train), color = 'blue')#plots the graph of predicted PAUS against COP COR. plt.title('SP000905974') plt.xlabel('COP COR Quantity') plt.ylabel('PAUS Quantity') plt.show()#Show the graph # Statistical Analysis of the training set with Statsmodels X2 = sm.add_constant(X_train) # add a constant to the model est = sm.OLS(Y_train, X2).fit() print(est.summary()) # print the results </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T11:52:58.930", "Id": "204933", "Score": "2", "Tags": [ "python", "statistics", "machine-learning" ], "Title": "Simple linear regression of two variables" }
204933
<p>I am in the need to cache <code>Bitmap</code>'s in a memory-optimized way because the API I am building will need to process many colored <code>Bitmap</code>'s in parallel and can be used in x86 or x64 compiled applications. </p> <p>If the API is being used in x86 I can't just store the <code>Bitmap</code>'s as they are but need to store them as compressed <code>MemoryStream</code>'s otherwise the API would throw an <code>OutOfMemoryException</code> pretty fast. </p> <p>After storing the "<code>Bitmap</code>'s" they will be processed by multiple threads hence thread-safety is a major point. </p> <p>Any feedback is welcome. </p> <pre><code>public static class ImageCache { private static int currentId = 0; private static readonly object addImageLock = new object(); private static readonly object releaseImageLock = new object(); private static readonly ConcurrentDictionary&lt;int, MemoryStream&gt; images = new ConcurrentDictionary&lt;int, MemoryStream&gt;(); /// &lt;summary&gt; /// Release an image based on its id. /// &lt;/summary&gt; /// &lt;param name="id"&gt;&lt;/param&gt; public static void ReleaseIamge(int id) { lock (releaseImageLock) { ReleaseMemoryStream(id); } } private static void ReleaseMemoryStream(int id) { MemoryStream ms = null; if (images.TryGetValue(id, out ms) &amp;&amp; ms != null) { images[id].Dispose(); images[id] = null; } } /// &lt;summary&gt; /// Releases all Images /// &lt;/summary&gt; public static void ReleaseAllImages() { lock (releaseImageLock) { lock (addImageLock) { foreach (var id in images.Keys) { ReleaseMemoryStream(id); } images.Clear(); } } } /// &lt;summary&gt; /// Returns a Bitmap from the cache which is identified by an id /// &lt;/summary&gt; /// &lt;param name="id"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public static Bitmap GetBitmap(int id) { lock (releaseImageLock) { MemoryStream ms = null; if (images.TryGetValue(id, out ms)) { if (ms != null) { return (Bitmap)Image.FromStream(ms); } } } return null; } /// &lt;summary&gt; /// Adds an Bitmap to the cache /// &lt;/summary&gt; /// &lt;param name="bitmap"&gt;&lt;/param&gt; /// &lt;returns&gt;0 if the Bitmap is null, otherwise a uique id&lt;/returns&gt; public static int Add(Bitmap bitmap) { if (bitmap == null) { return 0; } var ms = new MemoryStream(); bitmap.Save(ms, ImageFormat.Tiff); var id = 0; lock (addImageLock) { // If the dictionary is empty we can reset the currentId if (images.Count == 0) { currentId = 0; id = Interlocked.Increment(ref currentId); images.TryAdd(id, ms); return id; } // We don't know how long an application using this is running and how many // images having been stored but we don't want to reach int.MaxValue here // hence we recycle the Value of a KeyValuePair of the dictionary if the Value // will be null. id = images.Where(item =&gt; item.Value == null).FirstOrDefault().Key; if (id == 0) { id = Interlocked.Increment(ref currentId); } images[id] = ms; } return id; } } </code></pre> <p>Clarifying comments:</p> <blockquote> <p>Why don't you use a Guid as id and key in the dictionary? </p> </blockquote> <p>Well the problem with this is that I need to "mimic" an API we use for our main application in such a way that I can interchange this API and the other API. The other api is a comercial imaging sdk whichs licence doesn't permits the use of it for a sdk/api.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T16:35:18.310", "Id": "395316", "Score": "0", "body": "Why don't you use a `Guid` as id and key in the dictionary?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T16:46:34.950", "Id": "395318", ...
[ { "body": "<p>Spell-check: <code>ReleaseIamge</code> should presumably be <code>ReleaseImage</code>; <code>uique</code> should be <code>unique</code>.</p>\n\n<hr>\n\n<pre><code> private static void ReleaseMemoryStream(int id)\n {\n MemoryStream ms = null;\n if (images.TryGetValue(id, out ms)...
{ "AcceptedAnswerId": "204953", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T12:07:58.477", "Id": "204934", "Score": "7", "Tags": [ "c#", "image", "thread-safety", "concurrency" ], "Title": "Caching Color-Bitmaps as MemoryStreams" }
204934
<p>So I am working on a project that should take .txt file as an input and analyze words in it (assuming all words are English). Program must run asynchronously. Final output should be multiple .txt files, each with words and their count, arranged alphabetically. And there should be four files for words starting AG, HN, OU, VZ.</p> <p>I wrote the program, but to be honest I am not happy with it, the structure looks messy. But I can not come up with how to improve it. Also I will add test later. I am a bit more confident about writing them, so won't bother you with that part of the code.</p> <p>I've also added some comments and links on which I based some my solutions.</p> <p>I would really appreciate all suggestions and criticism.</p> <p>I have one controller method:</p> <pre><code>@RequestMapping("/file-reader") @RestController public class FileReaderController { @Autowired InputFileService service; @RequestMapping(value = "/zip", method = RequestMethod.POST) public void readFile(MultipartFile file) throws IOException { Map&lt;FileType, byte[]&gt; result = service.readFile(file); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zipFile = new ZipOutputStream(baos); result.forEach((ft, content) -&gt; { try { zipFile.putNextEntry(new ZipEntry(ft + ".txt")); zipFile.write(content); zipFile.closeEntry(); } catch (IOException e) { e.printStackTrace(); } }); } } </code></pre> <p>And Services implementations (with their interfaces accordingly).</p> <p>This service is responsible for returning final result. What I am not proud of in here is creation of multiple lists, maps... But could't get my head around more sophisticated method. Also I am not sure if it is fine to create ExecutorService twice. But I've done it trying to make program as fast as possible.</p> <pre><code>@Service public class InputFileServiceImpl implements InputFileService { // create output lists private List&lt;String&gt; wordsAG = new ArrayList&lt;&gt;(); private List&lt;String&gt; wordsHN = new ArrayList&lt;&gt;(); private List&lt;String&gt; wordsOU = new ArrayList&lt;&gt;(); private List&lt;String&gt; wordsVZ = new ArrayList&lt;&gt;(); private Map&lt;FileType, List&lt;String&gt;&gt; allocatedWordsMap = new HashMap&lt;&gt;(); @Inject private WordsCountingService wordsCountingService; @Inject private TextAnalyzerService textAnalyzerService; @Override public Map&lt;FileType, byte[]&gt; readFile(@NotNull MultipartFile file) throws IOException { byte[] fileContent = file.getBytes(); // create map for storing counted words (in bytes) with letter indicator Map&lt;FileType, byte[]&gt; resultContent = new HashMap&lt;&gt;(); if (fileContent.length &gt; 0) { String fileData = new String(fileContent).toLowerCase(); List&lt;String&gt; wordsList = textAnalyzerService.splitTextIntoWords(fileData); // put list in map to pass to another method allocatedWordsMap.put(FileType.AG, wordsAG); allocatedWordsMap.put(FileType.HN, wordsHN); allocatedWordsMap.put(FileType.OU, wordsOU); allocatedWordsMap.put(FileType.VZ, wordsVZ); // in case list is big partition it to make sorting async if (wordsList.size() &gt; 4000) { List&lt;List&lt;String&gt;&gt; smallerLists = Lists.partition(wordsList, 4); // https://stackoverflow.com/questions/949355/executors-newcachedthreadpool-versus-executors-newfixedthreadpool ExecutorService es1 = Executors.newCachedThreadPool(); smallerLists.forEach(smallerList -&gt; { es1.execute(() -&gt; textAnalyzerService.allocateWords(smallerList, allocatedWordsMap)); }); // ensure that all thread are over. https://stackoverflow.com/questions/7939257/wait-until-all-threads-finish-their-work-in-java# es1.shutdown(); try { es1.awaitTermination(1, TimeUnit.MINUTES); } catch (InterruptedException e) { // TODO: add normal error e.printStackTrace(); } } else { textAnalyzerService.allocateWords(wordsList, allocatedWordsMap); } // when all words from file are analyzed sort them, count and put into map ExecutorService es2 = Executors.newCachedThreadPool(); allocatedWordsMap.forEach((tp, w) -&gt; { if (w.size() &gt; 0) { es2.execute(() -&gt; { resultContent.put(tp, wordsCountingService.countWords(w)); }); } }); } else { // TODO: if file empty return error? } return resultContent; } </code></pre> <p>Service for analyzing text. Not sure if that huge switch is good practice and smart solution or stupid one.</p> <pre><code>@Service public class TextAnalyzerServiceImpl implements TextAnalyzerService { @Override public List&lt;String&gt; splitTextIntoWords(String text) { List&lt;String&gt; words = new ArrayList&lt;&gt;(); BreakIterator breakIterator = BreakIterator.getWordInstance(); breakIterator.setText(text); int lastIndex = breakIterator.first(); while (BreakIterator.DONE != lastIndex) { int firstIndex = lastIndex; lastIndex = breakIterator.next(); if (lastIndex != BreakIterator.DONE &amp;&amp; Character.isLetterOrDigit(text.charAt(firstIndex))) { words.add(text.substring(firstIndex, lastIndex)); } } return words; } @Override public void allocateWords(List&lt;String&gt; wordsList, Map&lt;FileType, List&lt;String&gt;&gt; allocatedWordsMap) { wordsList.forEach(word -&gt; { char firstLetter = word.charAt(0); switch (firstLetter) { case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': addWordToList(word, allocatedWordsMap.get(FileType.AG)); break; case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': addWordToList(word, allocatedWordsMap.get(FileType.HN)); break; case 'o': case 'p': case 'r': case 's': case 't': case 'u': addWordToList(word, allocatedWordsMap.get(FileType.OU)); break; case 'v': case 'z': addWordToList(word, allocatedWordsMap.get(FileType.VZ)); break; } }); } private void addWordToList(String word, List&lt;String&gt; wordsList) { wordsList.add(word); } } </code></pre> <p>Service for counting words:</p> <pre><code>@Component public class WordsCountingServiceImpl implements WordsCountingService { @Override public byte[] countWords(@NotEmpty List&lt;String&gt; words) { Map&lt;String, Integer&gt; countedWords = new HashMap&lt;&gt;(); words.forEach(word -&gt; { if (countedWords.containsKey(word)) { countedWords.put(word, countedWords.get(word) + 1); } else { countedWords.put(word, 0); } }); return countedWords.toString().getBytes(); } </code></pre> <p>Also for handling error and making them more informative. I am not very familiar with custom errors, so maybe there are better practices than @ControllerAdvice.</p> <pre><code>@ControllerAdvice public class GlobalControllerExceptionHandler { private Logger log = LoggerFactory.getLogger(this.getClass()); @ExceptionHandler(IOException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ErrorDTO handle(IOException e) { log.error(String.format("Invoked exception handler for %s", e.getClass()), e); return new ErrorDTO("INPUT FILE NOT FOUND", "Input file not found"); } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T12:18:49.030", "Id": "204935", "Score": "1", "Tags": [ "java", "file-system", "spring" ], "Title": "Java Multipart text file analysis to zip" }
204935
<p>The full question is... "Please, how can this code base or project (for client-side routing using Knockout and HTML5 History API) be further enhanced as regards security, production-readiness, ES6, etc.?".</p> <p>I intend that this eventually stays on somewhere like GitHub where anyone who has been faced with the challenge of creating an SPA app can easily use this to start off.</p> <p>The idea is to do page-to-page navigation using partial views as Knockout components (and get something similar to that of Angular, React, etc.). This project uses ASP.NET MVC 5, but can be used with any web development framework.</p> <p>The project works just like if Angular/React/etc. were used. No hash bang is needed. Full page loading from any URL based on the site domain works. Navigation works, etc. The full project folder (ASP.NET MVC 5), for anyone who is interested in running it in full is <a href="https://drive.google.com/open?id=169h20jCY2T0CNudrrVoCuI0gJnF36Chv" rel="nofollow noreferrer">on Google Drive</a>.</p> <p>On page load, an controller's action returns an empty view but with a full featured layout view. And as soon as the page loads on the client-side, a call is made to the server (via the same page URL, but with a query string, say <code>template=1</code>) to supply the partial view for the current page as the template of a custom component (say "partial-page-custom-component") that represents the main page content. The same URL, using another query string (say <code>viewModel=1</code>), is used to fetch the view model for the said component. Then, HTML5 History API is used to handle URL changes, back and forward browser navigation, clicking of elements that reference the same domain, etc.</p> <p>RequireJS and the likes are not used to load the JS needed for the view model. Instead, eval() is used to run the code from the server directly in order to construct the view model for the page. There is another global view model that handles global data-binding affairs.</p> <p>The following paragraphs detail the basics of the workings of the project/code.</p> <p>The JS code for doing the main client-side routing and data-binding using Knockout and HTML5 History API...</p> <pre><code>var globalData = { lastNavigatedUrl: null }; function GlobalViewModel() { var self = this; self.pageTitle = ko.observable(""); self.partialPageComponentUrl = ko.observable(""); self.partialPageComponentTemplateUrl = ko.pureComputed(function () { if (self.partialPageComponentUrl() !== "") { var ppcu = self.partialPageComponentUrl(); var templatePartInQueryString = "template=1"; var templatePartAttachmentInQueryString = (ppcu.indexOf("?") &gt;= 0) ? ("&amp;" + templatePartInQueryString) : ("?" + templatePartInQueryString); if (ppcu.indexOf("#") &gt;= 0) { var indexOfHashInPpcu = ppcu.indexOf("#"); var hashPartAttachmentInPpcu = ppcu.substring(indexOfHashInPpcu); var ppcuPartWithoutHashPart = ppcu.substring(0, indexOfHashInPpcu); return ppcuPartWithoutHashPart + templatePartAttachmentInQueryString + hashPartAttachmentInPpcu; } else { return ppcu + templatePartAttachmentInQueryString; } } else { return ""; } }); self.partialPageComponentViewModelUrl = ko.pureComputed(function () { if (self.partialPageComponentUrl() !== "") { var ppcu = self.partialPageComponentUrl(); var viewModelPartInQueryString = "viewModel=1"; var viewModelPartAttachmentInQueryString = (ppcu.indexOf("?") &gt;= 0) ? ("&amp;" + viewModelPartInQueryString) : ("?" + viewModelPartInQueryString); if (ppcu.indexOf("#") &gt;= 0) { var indexOfHashInPpcu = ppcu.indexOf("#"); var hashPartAttachmentInPpcu = ppcu.substring(indexOfHashInPpcu); var ppcuPartWithoutHashPart = ppcu.substring(0, indexOfHashInPpcu); return ppcuPartWithoutHashPart + viewModelPartAttachmentInQueryString + hashPartAttachmentInPpcu; } else { return ppcu + viewModelPartAttachmentInQueryString; } } else { return ""; } }); self.partialPageComponentName = ko.observable("partial-page-custom-component-placeholder"); } var globalViewModel = new GlobalViewModel(); function indicateScrollTargetElement() { $(window.location.hash).addClass("scroll-target-element"); setTimeout(function () { $(window.location.hash).removeClass("scroll-target-element"); }, 2000); } function setUpComponents() { ko.components.register("partial-page-custom-component-placeholder", { template: "&lt;span&gt;It's the partial page custom component placeholder.&lt;/span&gt;", viewModel: null }); var customComponentTemplateLoader = { loadTemplate: function (name, templateConfig, callback) { // This line can be used to run the writable computed observable (of globalViewModel) (for fixing placeholder UI that indicates the page is loading) to enable the placeholder UI. if (name === "partial-page-custom-component") { $.ajax({ asyn: false, type: "GET", url: globalViewModel.partialPageComponentTemplateUrl(), success: function (customComponentTemplate) { ko.components.defaultLoader.loadTemplate(name, customComponentTemplate, callback); // This line can be used to run the writable computed observable (of globalViewModel) (for fixing placeholder UI that indicates the page is loading) to disable the placeholder UI. if (window.location.href.indexOf("#") &gt;= 0) { $(window.location.hash).get(0).scrollIntoView(); indicateScrollTargetElement(); } else { $(window).scrollTop(0); } } }); } else { callback(null); } } }; ko.components.loaders.unshift(customComponentTemplateLoader); var customComponentViewModelLoader = { loadViewModel: function (name, viewModelConfig, callback) { if (name === "partial-page-custom-component") { var customComponentViewModel = function (params) { var self = this; $.ajax({ async: false, type: "GET", url: params.partialPageComponentViewModelUrl_params(), success: function (customComponentViewModelJsCode) { eval(customComponentViewModelJsCode.replace("&lt;script&gt;", "").replace("&lt;/script&gt;", "")); } }); }; ko.components.defaultLoader.loadViewModel(name, customComponentViewModel, callback); } else { callback(null); } } }; ko.components.loaders.unshift(customComponentViewModelLoader); ko.components.register("partial-page-custom-component", { template: { dummy: "" }, viewModel: { dummy: null } }); ko.applyBindings(globalViewModel, $("html").get(0)); } function navigateToPartialPageComponent(shouldReplaceStateBefore, stateWrtReplaceStateBefore, shouldPushStateBefore, stateWrtPushStateBefore, swapOrderWrtStateBefore, partialPageComponentUrlToNavigateTo, shouldReplaceStateAfter, stateWrtReplaceStateAfter, shouldPushStateAfter, stateWrtPushStateAfter, swapOrderWrtStateAfter) { // Somewhere in this code can be used to run the writable computed observable (of globalViewModel) (for fixing placeholder UI that indicates the page is loading) to enable or disable the placeholder UI. if (swapOrderWrtStateBefore === false) { if (shouldReplaceStateBefore === true) { window.history.replaceState(stateWrtReplaceStateBefore, "", partialPageComponentUrlToNavigateTo); } if (shouldPushStateBefore === true) { window.history.pushState(stateWrtPushStateBefore, "", partialPageComponentUrlToNavigateTo); } } else if (swapOrderWrtStateBefore === true) { if (shouldPushStateBefore === true) { window.history.pushState(stateWrtPushStateBefore, "", partialPageComponentUrlToNavigateTo); } if (shouldReplaceStateBefore === true) { window.history.replaceState(stateWrtReplaceStateBefore, "", partialPageComponentUrlToNavigateTo); } } globalViewModel.partialPageComponentName("partial-page-custom-component-placeholder");// This helps to do mediation work to make sure that the new component, if has the same name as the old active component, still gets rendered. globalViewModel.partialPageComponentUrl(""); ko.components.clearCachedDefinition("partial-page-custom-component"); globalViewModel.partialPageComponentUrl(partialPageComponentUrlToNavigateTo); globalViewModel.partialPageComponentName("partial-page-custom-component"); if (swapOrderWrtStateAfter === false) { if (shouldReplaceStateAfter === true) { window.history.replaceState(stateWrtReplaceStateAfter, "", partialPageComponentUrlToNavigateTo); } if (shouldPushStateAfter === true) { window.history.pushState(stateWrtPushStateAfter, "", partialPageComponentUrlToNavigateTo); } } else if (swapOrderWrtStateAfter === true) { if (shouldPushStateAfter === true) { window.history.pushState(stateWrtPushStateAfter, "", partialPageComponentUrlToNavigateTo); } if (shouldReplaceStateAfter === true) { window.history.replaceState(stateWrtReplaceStateAfter, "", partialPageComponentUrlToNavigateTo); } } globalData.lastNavigatedUrl = partialPageComponentUrlToNavigateTo; } function isNextUrlHashIfAnyForLastNavigatedUrl(nextUrl, previousUrl) { if (previousUrl === null) { return false; } if (nextUrl.indexOf("#") &gt;= 0 &amp;&amp; (nextUrl.substring(0, nextUrl.indexOf("#")) === ((previousUrl.indexOf("#") &gt;= 0) ? previousUrl.substring(0, previousUrl.indexOf("#")) : previousUrl))) { return true; } else { return false; } } function setUpNavigation() { $(window).on("popstate", function (evnt) { if (isNextUrlHashIfAnyForLastNavigatedUrl(window.location.href, globalData.lastNavigatedUrl) === false) { navigateToPartialPageComponent(false, {}, false, {}, false, window.location.href, false, {}, false, {}, false); } else { indicateScrollTargetElement(); } }); $(document).on("click", "a[href^='/'], area[href^='/']", null, function (evnt) { if (isNextUrlHashIfAnyForLastNavigatedUrl(this.href, globalData.lastNavigatedUrl) === false) { navigateToPartialPageComponent(false, {}, false, {}, false, this.href, false, {}, true, {}, false); evnt.preventDefault(); } }); } function processNavigationOnPageLoad() { navigateToPartialPageComponent(true, {}, false, {}, false, window.location.href, false, {}, false, {}, false); } $(function () { setUpComponents(); setUpNavigation(); processNavigationOnPageLoad(); }); </code></pre> <p>The HomeController (or any other controller code) looks like thus...</p> <pre><code>public class HomeController : Controller { public ActionResult Index(string extraData = "") { Response.AppendHeader("Cache-Control", "no-store");// I included this because of some client-side caching issues that happened. if (extraData == "blablo") { ViewBag.ExtraIndexData = "The extra data to Index."; } if (Request.QueryString["template"] == "1") { ViewBag.Mode = "template"; return PartialView("IndexPartial"); } if (Request.QueryString["viewModel"] == "1") { ViewBag.Mode = "viewModel"; return PartialView("IndexPartial");// This can be replaced by actual JS code, but I decided to put the partial view's JS code into &lt;script&gt; elements inside the partial view. } return View("Empty");// This is an actual empty view that uses the layout view. If the request is not for retrieving the template or view model, this is returned but does not display any page content but just the header and footer aspects of the web page as specified in the layout view. } public ActionResult About() { Response.AppendHeader("Cache-Control", "no-store"); ViewBag.Message = "Your application description page."; if (Request.QueryString["template"] == "1") { ViewBag.Mode = "template"; return PartialView("AboutPartial"); } if (Request.QueryString["viewModel"] == "1") { ViewBag.Mode = "viewModel"; return PartialView("AboutPartial"); } return View("Empty"); } } </code></pre> <p>A typical partial view code is as follows...</p> <pre><code> @{ string randomString = Guid.NewGuid().ToString(); ViewBag.Title = "Home Page"; } @if (ViewBag.Mode == "template") { &lt;div&gt;@randomString&lt;/div&gt; &lt;div&gt;&lt;span&gt;Page title: &lt;/span&gt;&lt;span data-bind="text: $parent.pageTitle"&gt;&lt;/span&gt;&lt;/div&gt; &lt;span data-bind="text: someDataaa"&gt;&lt;/span&gt; } @if (ViewBag.Mode == "viewModel") { &lt;script&gt; globalViewModel.pageTitle("Home"); self.someDataaa = ko.observable("This is a content for the index page."); &lt;/script&gt; } </code></pre> <p>And a typical layout view can be like thus...</p> <pre><code> &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;title data-bind="text: pageTitle"&gt;&lt;/title&gt; @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") &lt;/head&gt; &lt;body&gt; &lt;input type="hidden" id="is-full-page" /&gt; &lt;div class="navbar navbar-inverse navbar-fixed-top"&gt; &lt;div class="container"&gt; &lt;div class="navbar-header"&gt; &lt;button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;/button&gt; @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" }) &lt;/div&gt; &lt;div class="navbar-collapse collapse"&gt; &lt;ul class="nav navbar-nav"&gt; &lt;li&gt;&lt;a href="/"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/Home/About"&gt;About&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/Home/Contact"&gt;Contact&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="container body-content"&gt; &lt;div id="partial-page-component-container" data-bind="component: { name: partialPageComponentName, params: { partialPageComponentViewModelUrl_params: partialPageComponentViewModelUrl } }"&gt; &lt;/div&gt; @RenderBody() &lt;hr /&gt; &lt;footer&gt; &lt;p&gt;&amp;copy; @DateTime.Now.Year - My ASP.NET Application&lt;/p&gt; &lt;/footer&gt; &lt;/div&gt; &lt;style&gt; .scroll-target-element { background-color: green !important; } &lt;/style&gt; @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) &lt;script src="~/Scripts/knockout-3.4.2.js"&gt;&lt;/script&gt; &lt;script src="~/Scripts/mine/my-knockout-routing.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T12:41:14.947", "Id": "395267", "Score": "0", "body": "This is the intended goal when I asked [a more niche question](https://stackoverflow.com/questions/52351941/can-knockout-components-be-registered-by-a-dynamically-generated-scrip...
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T12:30:25.853", "Id": "204936", "Score": "4", "Tags": [ "javascript", "jquery", "url-routing", "knockout.js" ], "Title": "Client-side routing using Knockout and HTML5 History API for a single-page web application" }
204936
<p>I have a static homepage with some routes and thought about creating this with VueJs. I am totally new to this and just know NodeJs with Handlebars. So normally I would have something like this</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#page { margin: 30px 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="header"&gt; &lt;a href="#"&gt;Page 1&lt;/a&gt; &lt;a href="#"&gt;Page 2&lt;/a&gt; &lt;a href="#"&gt;Page 3&lt;/a&gt; &lt;/div&gt; &lt;div id="page"&gt; Current Page (depends on URL) &lt;/div&gt; &lt;div id="footer"&gt; Footer &lt;/div&gt;</code></pre> </div> </div> </p> <p>And I tried to create this by using VueJs</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const header = new Vue({ el: "#header", methods: { loadPage(pageToLoad) { page.$data.currentPage = "Current Page: " + pageToLoad; } } }); const page = new Vue({ el: "#page", data: { currentPage: "Current Page: 1" } });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#page { margin: 30px 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://unpkg.com/vue@2.5.17/dist/vue.js"&gt;&lt;/script&gt; &lt;div id="header"&gt; &lt;a v-on:click="loadPage(1)"&gt;Page 1&lt;/a&gt; &lt;a v-on:click="loadPage(2)"&gt;Page 2&lt;/a&gt; &lt;a v-on:click="loadPage(3)"&gt;Page 3&lt;/a&gt; &lt;/div&gt; &lt;div id="page"&gt; &lt;span v-html="currentPage"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div id="footer"&gt; Footer &lt;/div&gt;</code></pre> </div> </div> </p> <p>As you can see this example works fine. Instead of rendering the whole page I just change the "main content" of the page without reloading the header and footer.</p> <p>Is this the correct way to go or how would you create a page with multiple routes?</p>
[]
[ { "body": "<p>This may be an incorrect assumption, but it seems like with your proposed approach, you would need to either keep the HTML for each page within the HTML for the main page in the <em>onclick</em> attributes for each link or else have the links contain a key that corresponds to a mapping of keys to ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T13:44:21.510", "Id": "204939", "Score": "2", "Tags": [ "javascript", "html", "ecmascript-6", "url-routing", "vue.js" ], "Title": "create static page with vuejs" }
204939
<p>In a ray tracing project that I'm trying to make compile-time (constexpr) for fun and challenge, I've run into a bit of an issue: I have an object (intersection) that needs to refer to one of a group of other objects (shapes).</p> <p>Now, my understanding is that you cannot use polymorphism / virtual methods with constexpr because of the vtable lookups, so as far as I know, I cannot have a superclass, <code>Shape</code>, from which the other classes derive. Thus, I need to make <code>Intersection</code> a template class that holds one of its shapes.</p> <p>Unfortunately, I need to store these <code>Intersection</code> classes in an array or some other container, and I want to be able to call a common function on them and their shape, i.e. where the pseudopolymorphism comes in.</p> <p>I implemented something that solves the problem, where I take an <code>std::array</code> of <code>std::variant</code> and whenever I add to the array, if the type isn't represented by anything in the <code>std::variant</code>, then I expand it. I can also achieve pseudopolymorphism by using <code>std::visit</code>, invoking a commonly named function on each element to result in an <code>std::array</code> of final elements.</p> <pre><code>/** * variant_ops.h * * This file comprises operations that allow processing of variants and arrays of variants. * This includes: * 1. Making std::variant a monoid. * 2. Allowing addition of a value of type T to an array of variant, and having the variant types, if necessary, grow to * include T. This can be either a prepend or append operation. * 3. Invoking an operation across an array of variant. This assumes that the types in the array all have a method in * common, and is used to simulate compile-time polymorphism. */ #pragma once #include &lt;array&gt; #include &lt;type_traits&gt; #include &lt;variant&gt; namespace meta { /** * Determine if type T occurs in the types in List. */ template&lt;typename T, typename... List&gt; struct contains: std::true_type {}; template&lt;typename T, typename Head, typename... Tail&gt; struct contains&lt;T, Head, Tail...&gt; : std::conditional&lt;std::is_same&lt;T, Head&gt;::value, std::true_type, contains&lt;T, Tail...&gt; &gt;::type {}; template &lt;typename T&gt; struct contains&lt;T&gt;: std::false_type {}; } namespace variant_ops { /** * Variant forms a monoid with zero element std::monostate. * The operation is concatenate and we treat types not wrapped in a variant as if they were for convenience. */ struct Variant_Monoid { using zero = std::monostate; template &lt;typename T, typename... Args&gt; struct concatenate; template &lt;typename... Args0, typename... Args1&gt; struct concatenate&lt;std::variant&lt;Args0...&gt;, std::variant&lt;Args1...&gt;&gt; { using type = std::variant&lt;Args0..., Args1...&gt;; }; // Convenience method to concatenate types without having to wrap them into a variant first. template&lt;typename... Args0, typename... Args1&gt; struct concatenate&lt;std::variant&lt;Args0...&gt;, Args1...&gt; { using type = std::variant&lt;Args0..., Args1...&gt;; }; }; namespace details { /** * Concatenate-prepend one argument to a variant, provided it isn't already in the variant types. */ template&lt;typename T, typename... Args0&gt; struct concat1_prepend; template&lt;typename ArgNew, typename... Args&gt; struct concat1_prepend&lt;ArgNew, std::variant&lt;Args...&gt;&gt; { using type = std::conditional_t&lt; meta::contains&lt;ArgNew, Args...&gt;::value, std::variant&lt;Args...&gt;, std::variant&lt;ArgNew, Args...&gt;&gt;; }; /** * Concatenate-append one argument to a variant, provided it isn't already in the variant types. */ template&lt;typename T, typename... Args0&gt; struct concat1_append; template&lt;typename ArgNew, typename... Args&gt; struct concat1_append&lt;ArgNew, std::variant&lt;Args...&gt;&gt; { using type = std::conditional_t&lt; meta::contains&lt;ArgNew, Args...&gt;::value, std::variant&lt;Args...&gt;, std::variant&lt;Args..., ArgNew&gt;&gt;; }; template&lt;typename R, typename V, size_t N, typename Function, size_t... Indices&gt; constexpr std::array&lt;R, N&gt; va_map_aux(const std::array&lt;V, N&gt; &amp;v, Function f, std::index_sequence&lt;Indices...&gt;) noexcept { return {{std::visit(f, v[Indices])...}}; } template&lt;size_t N, typename T, typename S, size_t... Indices&gt; constexpr std::array&lt;T, N+1&gt; va_prepend_existing_type_element_aux(const S &amp;s, const std::array&lt;T, N&gt; &amp;a, std::index_sequence&lt;Indices...&gt;) noexcept { return {{T{s}, a[Indices]...}}; } template&lt;size_t N, typename T, typename S, size_t... Indices&gt; constexpr std::array&lt;T, N + 1&gt; va_append_existing_type_element_aux(const std::array&lt;T, N&gt; &amp;a, const S &amp;s, std::index_sequence&lt;Indices...&gt;) noexcept { return {{a[Indices]..., T{s}}}; } template&lt;size_t N, typename T, typename S, size_t... Indices&gt; constexpr std::array&lt;typename Variant_Monoid::concatenate&lt;T, S&gt;::type, N + 1&gt; va_prepend_element_with_type_aux(const S &amp;s, const std::array&lt;T, N&gt; &amp;a, std::index_sequence&lt;Indices...&gt;) noexcept { return {{s, std::visit([](auto &amp;&amp;t) -&gt; typename Variant_Monoid::concatenate&lt;T, S&gt;::type { return t; }, a[Indices])...}}; } template&lt;size_t N, typename T, typename S, size_t... Indices&gt; constexpr std::array&lt;typename Variant_Monoid::concatenate&lt;T, S&gt;::type, N + 1&gt; va_append_element_with_type_aux(const std::array&lt;T, N&gt; &amp;a, const S &amp;s, std::index_sequence&lt;Indices...&gt;) noexcept { return {{std::visit([](auto &amp;&amp;t) -&gt; typename Variant_Monoid::concatenate&lt;T, S&gt;::type { return t; }, a[Indices])..., s}}; } template&lt;size_t N, typename T, typename S, size_t... Indices&gt; constexpr std::array&lt;typename details::concat1_prepend&lt;S, T&gt;::type, N + 1&gt; va_prepend_element_aux(const S &amp;s, const std::array&lt;T, N&gt; &amp;a, std::index_sequence&lt;Indices...&gt;) noexcept { return {{s, std::visit([](auto &amp;&amp;t) -&gt; typename details::concat1_prepend&lt;S, T&gt;::type { return t; }, a[Indices])...}}; } template&lt;size_t N, typename T, typename S, size_t... Indices&gt; constexpr std::array&lt;typename details::concat1_append&lt;S, T&gt;::type, N + 1&gt; va_append_element_aux(const std::array&lt;T, N&gt; &amp;a, const S &amp;s, std::index_sequence&lt;Indices...&gt;) noexcept { return {{std::visit([](auto &amp;&amp;t) -&gt; typename details::concat1_append&lt;S, T&gt;::type { return t; }, a[Indices])..., s}}; } } /** * Map a pseudopolymorphic function across an array of variant. * For example, say we have three structs unrelated by any concept of inheritance: * struct S1 { constexpr int val() const { return 1; }}; * struct S2 { constexpr int val() const { return 2; }}; * struct S3 { constexpr int val() const { return 3; }}; * And: * constexpr std::array&lt;std::variant&lt;S1, S2, S3&gt;, 4&gt; va = {{S1{}, S2{}, S3{}, S2{}}}; * Then the result of calling: * constexpr auto result = va_map(va, [](auto &amp;&amp;a){return a.val();}); * would be: * constexpr std::array&lt;int, 4&gt;{{1, 2, 3, 2}}; */ template&lt;typename R, typename V, size_t N, typename Function&gt; constexpr std::array&lt;R, N&gt; va_map(const std::array&lt;V, N&gt; &amp;v, Function f) noexcept { return details::va_map_aux&lt;R, V, N, Function&gt;(v, f, std::make_index_sequence&lt;N&gt;{}); } /** * Allow prepending an element to an array of variant, provided the element type is already in the variant. * For example: * If T = std::variant&lt;int, std::string&gt; * and my_array is an std::array&lt;T, 2&gt; with contents {T{3}, T{"hello"}} * then va_prepend_existing_type_element("world", my_array) * would return an std::array&lt;T, 3&gt; with contents {T{"world"}, T{3}, T{"hello"}}. */ template&lt;size_t N, typename T, typename S&gt; constexpr std::array&lt;T, N + 1&gt; va_prepend_existing_type_element(const S &amp;s, const std::array&lt;T, N&gt; &amp;a) noexcept { return details::va_prepend_existing_type_element_aux(s, a, std::make_index_sequence&lt;N&gt;{}); } /** * Allow appending an element to an array of variant, provided the element type is in the variant. * For example: * If T = std::variant&lt;int, std::string_view&gt; * and my_array is an std::array&lt;T, 2&gt; with contents {T{3}, T{"hello"}} * then va_append_existing_type_element(my_array, "world") * would return an std::array&lt;T, 3&gt; with contents {T{3}, T{"hello"}, T{"world"}}. */ template&lt;size_t N, typename T, typename S&gt; constexpr std::array&lt;T, N + 1&gt; va_append_existing_type_element(const std::array&lt;T, N&gt; &amp;a, const S &amp;s) noexcept { return details::va_append_existing_type_element_aux(a, s, std::make_index_sequence&lt;N&gt;{}); } /** * Allow prepending an element to an array of variant, provided the element type is not in the variant. * For example: * If T = std::variant&lt;int&gt; * and my_array is an std::array&lt;T, 2&gt; with contents {T{3}, T{4}} * then va_prepend_element_with_type(3.114159, my_array) * would result in a T' = std::variant&lt;double, int&gt; * and would return an std::array&lt;T', 2&gt; with contents {T'{3.14159}, T'{3}, T'{4}}. */ template&lt;size_t N, typename T, typename S&gt; constexpr std::array&lt;typename Variant_Monoid::concatenate&lt;T, S&gt;::type, N + 1&gt; va_prepend_element_with_type(const S &amp;s, const std::array&lt;T, N&gt; &amp;a) noexcept { return details::va_prepend_element_with_type_aux(s, a, std::make_index_sequence&lt;N&gt;{}); } /** * Allow appending an element to an array of variant, provided the element type is not in the variant. * For example: * If T = std::variant&lt;int&gt; * and my_array is an std::array&lt;T, 2&gt; with contents {T{3}, T{4}} * then va_prepend_element_with_type(my_array, 3.114159) * would result in a T' = std::variant&lt;int, double&gt; * and would return an std::array&lt;T', 2&gt; with contents {T'{3}, T'{4}, T'{3.14159}}. */ template&lt;size_t N, typename T, typename S&gt; constexpr std::array&lt;typename Variant_Monoid::concatenate&lt;T, S&gt;::type, N + 1&gt; va_append_element_with_type(const std::array&lt;T, N&gt; &amp;a, const S &amp;s) noexcept { return details::va_append_element_with_type_aux(a, s, std::make_index_sequence&lt;N&gt;{}); } /** * This is the most flexible means of appending an element to an array of variant. * It behaves like the previous two va_append_element methods, but widens the variant type if and only if the * type of the element to be appended is not already part of that type. */ template&lt;size_t N, typename T, typename S&gt; constexpr std::array&lt;typename details::concat1_prepend&lt;S, T&gt;::type, N + 1&gt; va_prepend_element(const S &amp;s, const std::array&lt;T, N&gt; &amp;a) noexcept { return details::va_prepend_element_aux(s, a, std::make_index_sequence&lt;N&gt;{}); } /** * This is the most flexible means of prepending an element to an array of variant. * It behaves like the previous two va_prepend_element methods, but widens the variant type if and only if the * type of the element to be prepended is not already part of that type. */ template&lt;size_t N, typename T, typename S&gt; constexpr std::array&lt;typename details::concat1_append&lt;S, T&gt;::type, N + 1&gt; va_append_element(const std::array&lt;T, N&gt; &amp;a, const S &amp;s) noexcept { return details::va_append_element_aux(a, s, std::make_index_sequence&lt;N&gt;{}); } /// Need this to print; nothing will be printed no matter what is defined here. std::ostream &amp;operator&lt;&lt;(std::ostream &amp;out, const std::monostate &amp;m) noexcept { return out; } } </code></pre> <p>Now, I've been known to solve problems with much more difficulty than is necessary, so I was wondering if any of you know of a simpler way to achieve this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T14:47:37.657", "Id": "395286", "Score": "0", "body": "Please copy your implementation into your post. The code to be reviewed needs to be in the post, not linked from elsewhere." }, { "ContentLicense": "CC BY-SA 4.0", "C...
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T14:46:19.213", "Id": "204944", "Score": "2", "Tags": [ "c++", "template-meta-programming", "c++17", "polymorphism", "variant-type" ], "Title": "Creating an array of distinct objects with an identical method that can be evaluated (mapped) at compile-time (constexpr)" }
204944
<p>I have this working code tested over lots of np.arrays. It is a for-loop that walks through all the values of a np.array (x,y).</p> <p>For each y-row, it finds the first x-column for which the value is different to zero. Afterward, it finds the last x-column for which value is different to 0.</p> <p>Then all the columns between first x-column and last x-column are centred.</p> <p>This is then repeated for all y-rows. Example:</p> <pre><code>#Input : array([[ 0.0, 0.149, 0.064, 0.736, 0.0], [ 0.0, 0.0, 0.258, 0.979, 0.618 ], [ 0.0, 0.0, 0.0, 0.786, 0.666], [ 0.0, 0.0, 0.0, 0.782, 0.954], #Output : array([[ 0.0, 0.149, 0.064, 0.736, 0.0], [ 0.0, 0.258, 0.979, 0.618, 0.0], [ 0.0, 0.786, 0.666, 0.0, 0.0], [ 0.0, 0.782, 0.954, 0.0, 0.0], </code></pre> <p>Also:</p> <ul> <li><p>Not all the values between first and last columns are different than zero.</p> <pre><code>for y in range(len(array)): begin = False inside = False end = False for x in range(len(array[0])): if (array[y][x] == 0) &amp; (begin == True) &amp; (end == False): boundary_two = ( x - 1 ) inside = False end = True elif (array[y][x] != 0) &amp; (inside == False): boundary_one = x begin = True inside = True y_position.append(y) m = np.split(array[y],[boundary_one,boundary_two]) zeros = len(array[0])-len(m[1]) array[y] = np.concatenate((np.zeros(zeros//2),m[1],np.zeros(int(np.ceil(zeros/2))))) </code></pre></li> </ul> <p>Furthermore, I added a variable(count) inside the function (which I erase for the upper code example, to simplify lecture) which count how many empty rows since last non empty rows. When count ==10, we break out of the loop. This is to save time. Once we have +/- 10 empty rows after the non-empty ones, it is sure all other y-rows will be empty as well.</p> <p>Finally, I must save the value for the last y-row non-empty.</p> <p>This is my script most time demanding calculation, so I was wondering if there is a way of to improve it, either by making it clearer and/or faster.</p> <p>Thanks a lot, hope it is clear!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T15:03:13.543", "Id": "395290", "Score": "0", "body": "Welcome to Code Review! Does the code function correctly? If not, it isn't ready for review (see [help/on-topic]) and the question may be deleted. If you've tested it, I recomm...
[ { "body": "<h1>review</h1>\n\n<h2>comparison</h2>\n\n<p>no need to compare against True or False. <code>(begin == True)</code> can be easier expressed as <code>begin</code> and <code>(end == False)</code> as <code>not end</code>. and comparison chaining is done with <code>and</code>, not <code>&amp;</code>(bitw...
{ "AcceptedAnswerId": "204991", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T14:57:39.460", "Id": "204948", "Score": "1", "Tags": [ "python", "array", "numpy" ], "Title": "Centre all columns of an array" }
204948
<p>This is my first asp.net core web api and i did followed the Repository pattern but i don't know whether this approach is good practice.</p> <pre><code>public class TrainerRepo : IRepoTrainer { private readonly IConfiguration _config; public TrainerRepo(IConfiguration config) { _config = config; } public IDbConnection dbConnection { get { return new SqlConnection(_config.GetConnectionString("MyConnString")); } } public List&lt;Trainer&gt; GetTrainers() { string sql = "select trainer_id,trainer_name from trainer"; using(IDbConnection conn = dbConnection) { conn.Open(); var res = conn.Query&lt;Trainer&gt;(sql).ToList&lt;Trainer&gt;(); conn.Close(); return res; } } public int NewTrainer(Trainer trainer) { string sql = "insert into trainer ( trainer_name) values ( @name)"; using(IDbConnection conn = dbConnection) { conn.Open(); var res = conn.Execute(sql, param: new { //id = trainer.trainer_id, name = trainer.trainer_name }); conn.Close(); return res; } } public async Task&lt;int&gt; updateTrainer(Trainer trainer) { string sql = "update trainer set trainer_name = @tname where trainer_id = @tid"; using(IDbConnection conn = dbConnection) { conn.Open(); var res = await conn.ExecuteAsync(sql, param: new { tname = trainer.trainer_name, tid = trainer.trainer_id }); conn.Close(); return res; } } public int deleteTrainer(int id) { string sql = "delete from trainer where trainer_id=@trainerId"; using(IDbConnection conn = dbConnection) { conn.Open(); var res = conn.Execute(sql, param: new { trainerId = id }); conn.Close(); return res; } } } </code></pre> <p>IRepoTrainer interface</p> <pre><code>public interface IRepoTrainer { List&lt;Trainer&gt; GetTrainers(); int NewTrainer(Trainer trainer); Task&lt;int&gt; updateTrainer(Trainer trainer); int deleteTrainer(int id); } </code></pre> <p>my problem is that reuse of following code block, is it good practice ?</p> <pre><code> using(IDbConnection conn = dbConnection) { conn.Open(); // conn.Close(); return res; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T17:01:59.200", "Id": "395322", "Score": "0", "body": "You could make the repo disposable. Open the connection only if it is closed, and close it when the repo is disposed." }, { "ContentLicense": "CC BY-SA 4.0", "Creatio...
[ { "body": "<p>It has been suggested in docs to not pass <code>IConfiguration</code> around for injection. Try creating a <code>IConnectionFactory</code> or just have a connection injected directly into the repo</p>\n\n<p>Something like</p>\n\n<pre><code>public interface IDbConnectionFactory {\n IDbConnection ...
{ "AcceptedAnswerId": "204960", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T15:59:01.237", "Id": "204955", "Score": "2", "Tags": [ "c#", "sql", "repository", "asp.net-core" ], "Title": "Repository of trainers" }
204955
<p>I made a simple authentication system with php for an elm webapp that will have a small number (1 - 5) of users able to log in. </p> <p>I am planning to send the users their php session-id at login, and keep this in memory while the app is running in order to anthenticate all the requests sent by the app to the server. </p> <p>Elm allows for single page applications, keeping state between all pages transitions.</p> <p>All client/server communications will be sent as Json.</p> <p>I have a few questions:</p> <ul> <li>I think it should work even with cookies disabled, since the information needed to start the session in Php will be the stored session id in the POST request sent by Elm. Is this right? And if so how can I make sure php does not set session cookies?</li> <li>Is there any obvious security mistake in my login, signup and logout?</li> </ul> <p>login.php</p> <pre><code>&lt;?php include 'utils.php'; session_start(); $id = session_id(); if((getenv('REQUEST_METHOD') == 'POST')) { $json_data = file_get_contents("php://input"); $php_data = json_decode($json_data); if (is_null($php_data)){ logError("json data could not be decoded"); exit(); } if(!isset($php_data-&gt;username) || !isset($php_data-&gt;password)){ logError("wrong input"); exit(); } $db = mysqli_connect($mysql_server, $mysql_user, $mysql_password, $mysql_db); if (mysqli_connect_errno()){ logError('Could not connect to database'); exit(); } $stmt = mysqli_stmt_init($db); $getLogInfoQuery = "SELECT password, salt FROM users WHERE name = ?"; mysqli_stmt_prepare($stmt, $getLogInfoQuery); mysqli_stmt_bind_param($stmt,'s', $php_data-&gt;username); mysqli_stmt_execute($stmt); mysqli_stmt_bind_result($stmt, $hashedPass, $salt); if (!mysqli_stmt_fetch($stmt)){ logError("Wrong username/password"); mysqli_close($db); exit(); } if (hash('sha256', $php_data-&gt;username.$php_data-&gt;password.$salt) !== $hashedPass){ sleep (2); logError("Wrong username/password"); mysqli_close($db); exit(); } mysqli_close($db); $_SESSION['logInfo']['username'] = $php_data-&gt;username; $result = array('username' =&gt; $php_data-&gt;username ,'sessionId' =&gt; $id ); $toJson = json_encode($result); echo $toJson; exit(); } elseif((getenv('REQUEST_METHOD') == 'GET') &amp;&amp; isset($_SESSION['logInfo']['username'])){ //check if already logged in $result = array('username' =&gt; $_SESSION['logInfo']['username'] ,'sessionId' =&gt; session_id() ); $toJson = json_encode($result); echo $toJson; exit(); } else { $result = array('notLoggedIn' =&gt; 'true'); echo (json_encode($result)); exit(); } ?&gt; </code></pre> <p>signup.php</p> <pre><code>&lt;?php include 'utils.php'; session_start(); $id = session_id(); if(getenv('REQUEST_METHOD') == 'POST') { if (isset($_SESSION['logInfo']['username'])){ logError("You are already logged in!"); exit(); } $json_data = file_get_contents("php://input"); $php_data = json_decode($json_data); if (is_null($php_data)){ logError("json data could not be decoded"); exit(); } if(!isset($php_data-&gt;username) || !isset($php_data-&gt;password)){ logError("wrong input"); exit(); } $db = mysqli_connect($mysql_server, $mysql_user, $mysql_password, $mysql_db); if (mysqli_connect_errno()){ logError('Could not connect to database'); exit(); } $username = $php_data-&gt;username; $password = $php_data-&gt;password; $salt = md5(uniqid(mt_rand(), true)); $hash = hash('sha256', $username.$password.$salt); $ip = $_SERVER['REMOTE_ADDR']; $stmt = mysqli_stmt_init($db); $query = "SELECT name FROM users WHERE name = ?"; mysqli_stmt_prepare($stmt, $query); mysqli_stmt_bind_param($stmt,'s', $username); mysqli_stmt_execute($stmt); if (mysqli_stmt_fetch($stmt)){ logError("This username is already in use"); mysqli_close($db); exit(); } $query = "INSERT INTO users(name, password, salt, ip) VALUES (?, ?, ?, ?)"; mysqli_stmt_prepare($stmt, $query); mysqli_stmt_bind_param($stmt,'ssss',$username, $hash, $salt, $ip); mysqli_stmt_execute($stmt); if (mysqli_stmt_affected_rows($stmt) == 0){ logError("Data was not inserted into database"); mysqli_close($db); exit(); } $result = array('signUpComplete' =&gt; true); echo (json_encode($result)); mysqli_close($db); exit(); } </code></pre> <p>logout.php</p> <pre><code>&lt;?php include 'utils.php'; session_start(); session_unset(); session_destroy(); $result = array('notLoggedIn' =&gt; 'true'); echo (json_encode($result)); exit(); ?&gt; </code></pre> <p>And here is an example of the way I plan to use it:</p> <pre><code>&lt;?php include 'utils.php'; if(getenv('REQUEST_METHOD') == 'POST') { $json_data = file_get_contents("php://input"); $php_data = json_decode($json_data); if (is_null($php_data)){ logError("json data could not be decoded"); exit(); } if(!isset($php_data-&gt;sessionId)){ logError("wrong input"); exit(); } session_id($php_data-&gt;sessionId); session_start(); if (!isset($_SESSION['logInfo']['username'])){ logError("wrong credentials"); exit(); } # Do some stuff requiring valid credentials... exit(); } else { logError("invalid request"); } ?&gt; </code></pre> <p>Here is a quick draft of the elm side. I removed the view code for conciseness. I also didn't do any of the error handling yet.</p> <pre><code>module Auth exposing (..) import Http exposing (..) import Json.Decode as Decode exposing (..) import Json.Encode as Encode exposing (..) type LogInfo = LoggedIn { username : String , sessionId : String } | LoggedOut type alias Model = { username : String , password : String , logInfo : LogInfo , signUpComplete : Bool , displayMode : DisplayMode , files : List String } type DisplayMode = DisplaySignUp | DisplayLogin type Msg = SetUsername String | SetPassword String | Login | SignUp | Logout | ChangeDisplayMode DisplayMode | GetFiles | SetFiles (Result Http.Error (List String)) | ConfirmSignUp (Result Http.Error Bool) | ProcessAuthMsg (Result Http.Error LogInfo) update msg model = case msg of SetUsername s -&gt; ( { model | username = s } , Cmd.none ) SetPassword s -&gt; ( { model | password = s } , Cmd.none ) Login -&gt; ( model , login model ) SignUp -&gt; ( model , signUp model ) Logout -&gt; ( model , logout ) ChangeDisplayMode mode -&gt; ( { model | displayMode = mode } , Cmd.none ) GetFiles -&gt; ( model , case model.logInfo of LoggedOut -&gt; Cmd.none LoggedIn { sessionId } -&gt; getFiles sessionId ) SetFiles res -&gt; case res of Err _ -&gt; ( model, Cmd.none ) Ok files -&gt; ( { model | files = files }, Cmd.none ) ConfirmSignUp res -&gt; case res of Err _ -&gt; ( model, Cmd.none ) Ok _ -&gt; ( { model | signUpComplete = True } , Cmd.none ) ProcessAuthMsg res -&gt; case res of Err _ -&gt; ( model, Cmd.none ) Ok logInfo -&gt; ( { model | logInfo = logInfo } , Cmd.none ) login : Model -&gt; Cmd Msg login model = let body = Encode.object [ ( "username" , Encode.string (.username model) ) , ( "password" , Encode.string (.password model) ) ] |&gt; Http.jsonBody request = Http.post "login.php" body decodeLoginResult in Http.send ProcessAuthMsg request decodeLoginResult : Decoder LogInfo decodeLoginResult = Decode.map2 (\a b -&gt; LoggedIn { username = a, sessionId = b }) (Decode.field "username" Decode.string) (Decode.field "sessionId" Decode.string) signUp : Model -&gt; Cmd Msg signUp model = let body = Encode.object [ ( "username" , Encode.string (.username model) ) , ( "password" , Encode.string (.password model) ) ] |&gt; Http.jsonBody request = Http.post "signup.php" body decodeSignupResult in Http.send ConfirmSignUp request logout : Cmd Msg logout = --let -- request = -- Http.get (domainAdr "logout.php") decodeRes --in --Http.send ProcessHttpResult request Debug.todo "" decodeSignupResult = Decode.field "signUpComplete" Decode.bool getFiles : String -&gt; Cmd Msg getFiles sessionId = let body = Encode.object [ ( "sessionId" , Encode.string sessionId ) ] |&gt; Http.jsonBody request = Http.post "getFiles.php" body decodeFiles in Http.send SetFiles request decodeFiles = Decode.list Decode.string </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T19:37:50.880", "Id": "395351", "Score": "0", "body": "I added some code for the elm side. This is an early draft though. My main concern is more about security holes in my approach server side." }, { "ContentLicense": "CC BY...
[ { "body": "<p>I know little to nothing about Elm, but speaking of PHP your code is awfully duplicated. Sometimes it duplicates itself, either across different files or in the same file and also it duplicates the functionality already exists in PHP. For example, PHP can log errors for you, and not a single line ...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T17:42:21.743", "Id": "204956", "Score": "2", "Tags": [ "php", "authentication", "session", "elm" ], "Title": "Basic PHP user authentication system for an Elm app" }
204956
<p>Problem statement: Given an integer list from 0 to 100 find the missing Element.</p> <p>I saw this problem on reddit on a compilation of interview questions, tried it out for fun. Mainly tried to generalize the code for any boundry(not just 100) and multiple missing arguments. Focused on readability and writing docstrings based on Google's recommendations. Did I hit my targets? How can and should my code be improved. Thanks!</p> <pre><code>""" Problem: Given a list from 0 to 100, find the missing element """ def makeIntArray(excludedValues, boundry): return [i for i in range(boundry + 1) if i not in excludedValues] def compareToComplete(partial): """ Compares a possibly partial list to its complete version Args: partial: List containing integer type, all duplicates will be ignored Returns: Set of unique missing elements or empty set if partial is complete example: partial = [1,2,3,4,6,8,10], complete = [0,1,2,3,4,5,6,7,8,9,10] returns: {0,5,7,9} """ partial.sort() return {i for i in range(partial[-1] + 1)}.difference(set(partial)) </code></pre>
[]
[ { "body": "<p>Well, firstly your code doesn't \"run\" as you have no entry point (ala <code>if __name__</code>...), secondly, you have no test code to even prove your code works as you believe it to, and thirdly - you have a function <code>makeIntArray</code> which is not used in your code.</p>\n\n<p>Regarding ...
{ "AcceptedAnswerId": "205005", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T18:49:09.973", "Id": "204961", "Score": "1", "Tags": [ "python" ], "Title": "Find Missing Element in integer List" }
204961
<p>I'm working on an Android app, and at one point I need to retrieve a request code in a callback method and perform some database operations depending on the request code. It started out ok when there were just 2 request codes, but then I had a need to add two more, and I can't really find a good way to avoid a messy looking method.</p> <p>This is the method right now</p> <pre><code>@Override public void onActivityResult(final int requestCode, int resultCode, Intent data) { final Context applicationContext = getContext(); DevLog.v(TAG, "onActivityResult() requestCode="+requestCode+" resultCode="+resultCode+" data="+data); if( (requestCode == ACTIVITY_REQUEST_ADD_SENDER || requestCode == ACTIVITY_REQUEST_EDIT_SENDER || requestCode == ACTIVITY_REQUEST_ADD_SOS_RECEIVER || requestCode == ACTIVITY_REQUEST_EDIT_SOS_RECEIVER) &amp;&amp; resultCode == RESULT_OK &amp;&amp; data != null &amp;&amp; applicationContext != null ){ final String number = getNumberFromContactResultIntent(data); if (number != null) { AsyncTask.execute(new Runnable() { @Override public void run() { switch (requestCode) { case ACTIVITY_REQUEST_ADD_SENDER: AppDatabase.db(applicationContext).getSenderDao().insert(new Sender(number)); break; case ACTIVITY_REQUEST_EDIT_SENDER: if (mEditSender != null) { mEditSender.number = number; AppDatabase.db(applicationContext).getSenderDao().update(mEditSender); } break; case ACTIVITY_REQUEST_ADD_SOS_RECEIVER: AppDatabase.db(applicationContext).getSosReceiverDao().insert(new SosReceiver(number)); break; case ACTIVITY_REQUEST_EDIT_SOS_RECEIVER: if (mEditSosReceiver != null ) { mEditSosReceiver.number = number; AppDatabase.db(applicationContext).getSosReceiverDao().update( mEditSosReceiver ); } break; } } }); } } else super.onActivityResult(requestCode, resultCode, data); } </code></pre> <p>What bugs me the most is the repeated check of the <code>requestCode</code> parameter. First I need to check if it's <strong>any</strong> of four values (the <code>if</code>), and then I have to perform different operations depending on <strong>exactly</strong> which of those four values it is (the <code>switch</code>).</p> <p>If I remove the <code>if( (requestCode ...</code> part and move the <code>switch</code> statement out from the <code>AsyncTask</code>, I would still need to perform the other checks (<code>resultCode == RESULT_OK &amp;&amp; data != null ...</code> etc), <strong>AND</strong> I would have to create one <code>AsyncTask</code> in each <code>case</code>, so I'd basically end up with even more redundant code than there already is.</p> <p>I would also need to move the </p> <pre><code>getNumberFromContactResultIntent(data) </code></pre> <p>call, since it only makes sense for these four request codes and shouldn't be called on any other request codes.</p> <p>I considered putting the four request codes into an array (they are <code>static final int</code>) and call it something like <code>REQUEST_CODE_GROUP_ADD_OR_EDIT</code> and perform </p> <pre><code>Arrays.binarySearch(REQUEST_CODE_GROUP_ADD_OR_EDIT, requestCode) </code></pre> <p>on it, which would at least reduce the <code>if</code> statement slightly. But it seems a bit silly to turn four simple and efficient <code>==</code> checks into a much more complex operation. It's highly unlikely I'll need to add more similar request codes in the future, and if I do it will most certainly only be a limited number of them (2-4).</p> <p>Is there a neat way to simplify something like this, where one needs to combine first checking for <strong>any</strong> of a limited set of values, perform some operations that is common to all of them, and then perform some operations that are <strong>specific for each</strong> value?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-05T14:22:16.603", "Id": "395477", "Score": "0", "body": "It would be probably too little for a full feature answer in this site but I hope that this could help: https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern (It helped m...
[ { "body": "<p>You could define an abstract class that holds a request code and a command.\nThen for each code, create a concrete subclass that hold that code and command associated with that code. Then you pass an instance of that concrete subclass, do your null checks, and call the command.</p>\n", "commen...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T19:39:11.110", "Id": "204966", "Score": "1", "Tags": [ "java", "android", "database" ], "Title": "Handler for several kinds of requests to modify a database in an Android app" }
204966
<p>Recently I've started learning ReactJS and I do not look forward to making one Page website so I learned about <code>react-router</code> and this is my way of doing to it.</p> <p>App.js</p> <pre><code>import React, { Component } from "react"; import "babel-polyfill"; import Navbar from "./Components/MenuNavbar"; import Footer from "./Components/Bottom"; import Home from "./Components/Home"; import About from "./Components/About"; import Contact from "./Components/Contact"; import { BrowserRouter as Router, Route, Switch } from "react-router-dom"; import Products from "./Components/Products"; import { CircleArrow as ScrollUpButton } from "react-scroll-up-button"; // import Topbar from "./Components/Topbar"; class App extends Component { render() { return ( &lt;div className="App"&gt; &lt;Router&gt; &lt;React.Fragment&gt; &lt;Navbar /&gt; &lt;Switch&gt; &lt;Route exact path="/" component={Home} /&gt; &lt;Route exact path="/products" component={Products} /&gt; &lt;Route exact path="/about" component={About} /&gt; &lt;Route exact path="/contact" component={Contact} /&gt; &lt;/Switch&gt; &lt;ScrollUpButton /&gt; &lt;Footer /&gt; &lt;/React.Fragment&gt; &lt;/Router&gt; &lt;/div&gt; ); } } export default App; </code></pre> <p>In my other Components, I wrap parent in a <code>div</code> as learned in some tutorials, like this:</p> <pre><code>render() { return ( &lt;div id="products"&gt; &lt;ProductsHero /&gt; &lt;ProductsCashew /&gt; &lt;ProductsAlmonds /&gt; &lt;/div&gt; ); } </code></pre> <p>Is this the best practice? If not how can I improve? Shall I wrap every child in <code>React.Fragment</code> instead of <code>div</code>? If so why?</p>
[]
[ { "body": "<p>Whether to use <code>React.Fragment</code> or not depends on how you want the resulting DOM structured. Using <code>React.Fragment</code> avoids introducing additional elements in the DOM when they are not needed.</p>\n\n<p>Fragments were introduced because only one React element can be returned f...
{ "AcceptedAnswerId": "205471", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T21:30:01.497", "Id": "204970", "Score": "3", "Tags": [ "react.js", "jsx" ], "Title": "Basic ReactJS Components routing" }
204970
<p>The following is some code that is used to provide the frontend with certain parameters when rendering a form. The parameters are conditional based around what data is being changed, <code>getNewSaleFormOptions</code> provides a way of quering these options using a <code>GET</code> request and url params (ie <code>/sales/new?dealership=11&amp;vehicle=2</code>), and another <code>getEditSaleFormOptions</code> when returning to edit, but through the entity id, ie <code>/sales/1</code> (this will pull necessary data, dealership, vehicle, from <code>Sale 1</code>).</p> <p>I've tried to use <code>MaybeT</code> here to simplify a lot of the calls that return <code>m (Maybe a)</code>, though its possible i'm not using it in the most efficient way. There are lots of <code>MaybeT</code> and <code>runMaybeT</code> calls (though this might be okay), and a few spots where there is duplicated code... I'm just not sure of the best way to eliminate them.</p> <pre><code>{-# LANGUAGE GADTs #-} {-# LANGUAGE FlexibleContexts #-} module Forms.SaleForm ( SaleFormOptions(..) , getNewSaleFormOptions , getEditSaleFormOptions ) where import Control.Monad (join) import Control.Monad.Trans.Maybe (MaybeT(..), runMaybeT) import qualified Data.Aeson as Aeson import Data.Aeson ((.=), ToJSON) import qualified Data.Maybe as M import Data.Text (Text) import Database.Esqueleto (SqlPersistT, get) import Yesod.Core (MonadHandler(..), PathPiece(..)) data SaleFormOptions = SaleFormOptions { saleFormOptionsCampaigns :: Maybe MarketingCampaigns , saleFormOptionsDiscountElegible :: Bool } instance ToJSON SaleFormOptions where toJSON SaleFormOptions{..} = Aeson.object [ "campaigns" .= saleFormOptionsCampaigns , "discount_elegible" .= saleFormOptionsDiscountElegible ] getNewSaleFormOptions :: MonadHandler m =&gt; Key User -&gt; SqlPersistT m SaleFormOptions getNewSaleFormOptions userKey = NewTenancyFormFields &lt;$&gt; campaigns &lt;*&gt; discountElegible where campaigns = runMaybeT (MaybeT . fetchCampaigns userKey =&lt;&lt; lookupIdGetParamM "dealership") discountElegible = M.fromMaybe False &lt;$&gt; runMaybeT (MaybeT . fmap Just . isDiscountElegible =&lt;&lt; lookupIdGetParamM "vehicle") getEditSaleFormOptions :: MonadHandler m =&gt; Key User -&gt; Key Sale -&gt; SqlPersistT m SaleFormOptions getEditSaleFormOptions userKey saleKey = do sale &lt;- get saleKey EditTenancyTenantFormFields &lt;$&gt; fmap join (mapM (fetchCampaigns userKey) (saleDealership &lt;$&gt; sale)) &lt;*&gt; (M.fromMaybe False &lt;$&gt; mapM isDiscountElegible (saleVehicle &lt;$&gt; sale)) fetchCampaigns :: MonadHandler m =&gt; Key User -&gt; Key Dealership -&gt; SqlPersistT m (Maybe MarketingCampaigns) fetchCampaigns userKey dealershipKey = do enabled &lt;- campaignsEnabled userKey dealershipKey if enabled then Just &lt;$&gt; getCampaigns dealershipKey else return Nothing isDiscountElegible :: MonadHandler m =&gt; Key Vehicle -&gt; SqlPersistT m Bool isDiscountElegible vehicleKey = M.fromMaybe False &lt;$&gt; runMaybeT checkElegible where checkElegible = do vehicle &lt;- MaybeT (get vehicleKey) vehicleHasDiscount &lt;$&gt; (MaybeT . get $ vehicleManufacturer vehicle) &lt;*&gt; pure vehicle lookupIdGetParamM :: (PathPiece (Key a), MonadHandler m) =&gt; Text -&gt; MaybeT m (Key a) lookupIdGetParamM = MaybeT . lookupIdGetParam </code></pre> <p>And this is the code for <code>lookupIdGetParam</code>:</p> <pre><code>lookupIdGetParam :: (PathPiece (Key a), MonadHandler m) =&gt; Text -&gt; m (Maybe (Key a)) lookupIdGetParam name = do mraw &lt;- lookupGetParam name case mraw of Nothing -&gt; return Nothing Just raw -&gt; return (fromPathPiece raw) </code></pre>
[]
[ { "body": "<p>I'd suggest these points to simplify your code:</p>\n\n<ul>\n<li><p>Make everything that returns <code>Maybe something</code> into <code>MaybeT</code>, and as close to the origin as possible. This will make composition of your functions much easier. For example:</p>\n\n<pre><code>lookupIdGetParam ...
{ "AcceptedAnswerId": "205510", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T21:56:06.610", "Id": "204971", "Score": "2", "Tags": [ "haskell", "monads", "optional" ], "Title": "Haskell/Yesod - Butchering use of MaybeT" }
204971
<p>This is the revised code from my <a href="https://codereview.stackexchange.com/questions/204895/battleship-model">prior question</a>. Same requests as before! Something I'm doing new here is using the <code>XmlEncoder</code> extension methods to handle serialization and de-serialization.</p> <p><strong>XmlEncoder.cs</strong></p> <pre><code>using System; using System.IO; using System.Text; using System.Xml.Serialization; namespace Battleship { //https://stackoverflow.com/questions/2347642/deserialize-from-string-instead-textreader#2347661 public static class XmlEncoder { public static string XmlSerializeToString(this object objectInstance) { var serializer = new XmlSerializer(objectInstance.GetType()); StringBuilder sb = new StringBuilder(); using (TextWriter writer = new StringWriter(sb)) { serializer.Serialize(writer, objectInstance); } return sb.ToString(); } public static T XmlDeserializeFromString&lt;T&gt;(this string objectData) { return (T)XmlDeserializeFromString(objectData, typeof(T)); } public static object XmlDeserializeFromString(this string objectData, Type type) { var serializer = new XmlSerializer(type); object result; using (TextReader reader = new StringReader(objectData)) { result = serializer.Deserialize(reader); } return result; } } } </code></pre> <p><strong>GridSquare.cs</strong></p> <pre><code>namespace Battleship { public enum SquareType { Foggy, Water, Undamaged, Damaged, Sunk } public class GridSquare { public SquareType Type { get; set; } public int ShipIndex { get; set; } public GridSquare() { Type = SquareType.Foggy; ShipIndex = -1; } } } </code></pre> <p><strong>Grid.cs</strong></p> <pre><code>namespace Battleship { public class Grid { public GridSquare[,] Squares { get; private set; } public int Size { get; private set; } public Grid(int gridSize) { Size = gridSize; Squares = new GridSquare[gridSize, gridSize]; for (int x = 0; x &lt; gridSize; ++x) { for (int y = 0; y &lt; gridSize; ++y) { Squares[x, y] = new GridSquare(); } } } } } </code></pre> <p><strong>Ship.cs</strong></p> <pre><code>namespace Battleship { // the classic rules (patrol boats aren't fit for warfare) public enum ShipType { Carrier = 5, Battleship = 4, Cruiser = 3, Submarine = 3, Destroyer = 2 } public enum Orientation { South = 0, East = 1, North = 2, West = 3 } internal static class OrientationExtension { public static Orientation GetOrientation(this int n) { switch (n) { case 1: return Orientation.East; case 2: return Orientation.North; case 3: return Orientation.West; default: return Orientation.South; } } } public class Ship { public ShipType ShipType { get; set; } public Orientation Orientation { get; set; } public int Health { get; set; } public Ship() { ShipType = ShipType.Destroyer; Repair(); } public int GetLength() { return (int)ShipType; } public void Repair() { Health = GetLength(); } public bool Sunk() { return Health == 0; } public void Hit() { if (Health &gt; 0) { --Health; } } } } </code></pre> <p><strong>Player.cs</strong></p> <pre><code>using System; using System.Collections.Generic; using System.Linq; namespace Battleship { public class Player { public Grid Grid { get; set; } public List&lt;Ship&gt; Ships { get; set; } protected static Random rand = new Random(); public Player(int gridSize) { Grid = new Grid(gridSize); Ships = new List&lt;Ship&gt;(); foreach (ShipType type in Enum.GetValues(typeof(ShipType))) { Ships.Add(new Ship { ShipType = type }); } PlaceShips(); } private void PlaceShips() { for (int shipIndex = 0; shipIndex &lt; Ships.Count; ++shipIndex) { int x = rand.Next(Grid.Size); int y = rand.Next(Grid.Size); GridSquare sea = Grid.Squares[x, y]; Ship ship = Ships[shipIndex]; List&lt;Orientation&gt; validOrientations = new List&lt;Orientation&gt;(); // calculate valid orientations for (int i = 0; i &lt; 4; ++i) { Orientation o = i.GetOrientation(); bool done = false; try { for (int j = 1; j &lt; ship.GetLength() &amp;&amp; !done; ++j) { switch (o) { case Orientation.South: if (Grid.Squares[x, y - j].ShipIndex != -1) { done = true; } break; case Orientation.East: if (Grid.Squares[x - j, y].ShipIndex != -1) { done = true; } break; case Orientation.North: if (Grid.Squares[x, y + j].ShipIndex != -1) { done = true; } break; case Orientation.West: if (Grid.Squares[x + j, y].ShipIndex != -1) { done = true; } break; } if (j == Grid.Size - 1) { validOrientations.Add(o); } } } catch (Exception err) { if (err is IndexOutOfRangeException) { Console.WriteLine(ship.ShipType + " fell off the edge of the world while heading " + o + "!"); } } } if (!validOrientations.Any()) { throw new Exception("The current grid cannot fit all of the ships!"); } // set the origin metadata sea.Type = SquareType.Undamaged; sea.ShipIndex = shipIndex; ship.Orientation = validOrientations[rand.Next(validOrientations.Count)]; // pick an orientation at random and layout the ship for (int i = 1; i &lt; ship.GetLength(); ++i) { switch (ship.Orientation) { case Orientation.South: Grid.Squares[x, y - i].ShipIndex = shipIndex; break; case Orientation.East: Grid.Squares[x - i, y].ShipIndex = shipIndex; break; case Orientation.North: Grid.Squares[x, y + i].ShipIndex = shipIndex; break; case Orientation.West: Grid.Squares[x + i, y].ShipIndex = shipIndex; break; } } } } public void Attack(int x, int y) { GridSquare sea = Grid.Squares[x, y]; switch (sea.Type) { case SquareType.Foggy: // miss sea.Type = SquareType.Water; break; case SquareType.Undamaged: Ship ship = Ships[sea.ShipIndex]; ship.Hit(); if (ship.Sunk()) { sea.Type = SquareType.Sunk; for (int i = 1; i &lt; ship.GetLength(); ++i) { switch (ship.Orientation) { case Orientation.South: Grid.Squares[x, y - i].Type = SquareType.Sunk; break; case Orientation.East: Grid.Squares[x - i, y].Type = SquareType.Sunk; break; case Orientation.North: Grid.Squares[x, y + i].Type = SquareType.Sunk; break; case Orientation.West: Grid.Squares[x + i, y].Type = SquareType.Sunk; break; } } } else { sea.Type = SquareType.Damaged; } break; default: throw new InvalidOperationException("You cannot change that square type!"); } } public bool GameOver() { return Ships.All(ship =&gt; ship.Sunk()); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T23:16:28.187", "Id": "395389", "Score": "0", "body": "You might want to study [this implementation](https://github.com/rubberduck-vba/Battleship). It's VBA, but it's full-blown OOP (MVC) and you'll find that the model classes' (`AIP...
[ { "body": "<h3>Inconsistent use of <code>var</code></h3>\n\n<p>I love <code>var</code>, I use it pretty much everywhere. IMO <em>not</em> using it makes C# read like Java, and that can't be good. But that's just my opinion, and given a code base that doesn't use it, I'll conform to the style in place and keep i...
{ "AcceptedAnswerId": "204985", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T21:58:06.127", "Id": "204972", "Score": "3", "Tags": [ "c#", "beginner", "game", "battleship" ], "Title": "Battleship Model - follow-up" }
204972
<p>I'm looking for the fastest way to determine if a long value is a perfect square (i.e. its square root is another integer). I was asked this in an interview recently.</p> <p>Here is the very simple and straightforward way I'm doing it now:</p> <pre><code> private static boolean isSquare(long n) { int i = 1; for (;;) { if (n &lt; 0) return false; if (n == 0) return true; n -= i; i += 2; } } </code></pre> <p>Is there any better way by which we can do this or optimize this more?</p>
[]
[ { "body": "<p>It is indeed very simple and straightforward. The time complexity is however <span class=\"math-container\">\\$(O(\\sqrt n)\\$</span>. A binary search variation will do it in <span class=\"math-container\">\\$O(\\log n)\\$</span> time. Along the lines of the pseudocode:</p>\n\n<pre><code> while...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-04T22:47:37.737", "Id": "204974", "Score": "2", "Tags": [ "java", "algorithm" ], "Title": "Fastest way to determine if a number is perfect square" }
204974
<p>I've written my own UI for Mathieu Guindon's VBA Battleship (<a href="https://codereview.stackexchange.com/q/202911/171419">Battleship UI: GameSheet</a>) which uses a webpage in a WebBrowser control for the View.</p> <p><a href="https://i.stack.imgur.com/5NXmH.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5NXmH.gif" alt="Battleship-Unofficial UI: Demo Gif" /></a></p> <h2>Webform: <code>Userform</code></h2> <p>Displays the webpage in a Webbrower control.</p> <pre><code>Private controller As GameController Private Sub UserForm_Initialize() Dim View As WebView Set View = New WebView View.Init Me.WebBrowser1 Dim randomizer As IRandomizer Set randomizer = New GameRandomizer Set controller = New GameController controller.NewGame GridViewAdapter.Create(View), randomizer End Sub Private Sub UserForm_Terminate() Set controller = Nothing End Sub </code></pre> <h2><code>WebElementListener</code>: Class</h2> <p>Monitors the Click, Right Click, and Double Click events of a <code>HMTLElement</code>. It raises its own corresponding event when a <code>HMTLElement</code> event fires and relays to to a WebGroupListener, if applicable.</p> <pre><code>Attribute VB_Name = &quot;WebElementListener&quot; Attribute VB_PredeclaredId = True Option Explicit '@Folder(&quot;Battleship.WebUI.Listeners&quot;) Private WithEvents GenericElement As HTMLGenericElement Attribute GenericElement.VB_VarHelpID = -1 Private WithEvents TableCell As HTMLTableCell Attribute TableCell.VB_VarHelpID = -1 Private Type Members ID As String listener As WebGroupListener End Type Private this As Members Public Event onClick(Element As HTMLGenericElement) Public Event onDoubleClick(Element As HTMLGenericElement) Public Event onRightClick(Element As HTMLGenericElement) Public Function Create(newElement As Variant, Optional newListener As WebGroupListener) As WebElementListener With New WebElementListener .Object = newElement .listener = newListener Set Create = .Self End With End Function Public Property Get Self() As WebElementListener Set Self = Me End Property Public Sub Rotate(degrees As Long) Object.Style.cssText = &quot;-ms-transform:rotate(&quot; &amp; degrees &amp; &quot;deg)&quot; End Sub Public Property Get Object() As HTMLGenericElement Select Case True Case Not GenericElement Is Nothing Set Object = GenericElement Case Not TableCell Is Nothing Set Object = TableCell End Select End Property Public Property Let Object(ByVal Value As HTMLGenericElement) Select Case TypeName(Value) Case &quot;HTMLTableCell&quot; Set TableCell = Value Case Else Set GenericElement = Value End Select End Property Private Function GenericElement_onclick() As Boolean RaiseEvent onClick(Object) If Not listener Is Nothing Then listener.onClick Object GenericElement_onclick = True End Function Private Function GenericElement_oncontextmenu() As Boolean RaiseEvent onRightClick(Object) If Not listener Is Nothing Then listener.onRightClick Object GenericElement_oncontextmenu = False End Function Private Function GenericElement_ondblclick() As Boolean RaiseEvent onDoubleClick(Object) If Not listener Is Nothing Then listener.onDoubleClick Object GenericElement_ondblclick = True End Function Public Property Get listener() As WebGroupListener Set listener = this.listener End Property Private Function TableCell_onclick() As Boolean RaiseEvent onClick(Object) If Not listener Is Nothing Then listener.onClick Object TableCell_onclick = True End Function Private Function TableCell_oncontextmenu() As Boolean RaiseEvent onRightClick(Object) If Not listener Is Nothing Then listener.onRightClick Object TableCell_oncontextmenu = False End Function Private Function TableCell_ondblclick() As Boolean RaiseEvent onDoubleClick(Object) If Not listener Is Nothing Then listener.onDoubleClick Object TableCell_ondblclick = True End Function Public Property Let listener(ByVal Value As WebGroupListener) Set this.listener = Value End Property Public Property Get Visible() As Boolean Visible = Object.Style.display = &quot;block&quot; End Property Public Property Let Visible(ByVal Value As Boolean) Object.Style.display = IIf(Value, &quot;block&quot;, &quot;none&quot;) End Property </code></pre> <h2><code>WebGroupListener</code>: Class</h2> <p>Monitors the Click, Right Click, and Double Click events of a <code>WebElementListener</code>. It raises its own corresponding event when a <code>WebElementListener</code> event fires and relays to to a <code>WebGridGroup</code>, if applicable.</p> <pre><code>Option Explicit '@Folder(&quot;Battleship.WebUI.Listeners&quot;) Public Elements As New Dictionary Public Event onClick(Element As HTMLGenericElement) Public Event onDoubleClick(Element As HTMLGenericElement) Public Event onRightClick(Element As HTMLGenericElement) Public EnableEvents As Boolean Public Sub AddElement(key As Variant, ElementItem As Variant) Elements.Add key, WebElementListener.Create(ElementItem, Self) End Sub Public Sub onClick(Element As HTMLGenericElement) If EnableEvents Then RaiseEvent onClick(Element) End Sub Public Sub onDoubleClick(Element As HTMLGenericElement) If EnableEvents Then RaiseEvent onDoubleClick(Element) End Sub Public Sub onRightClick(Element As HTMLGenericElement) If EnableEvents Then RaiseEvent onRightClick(Element) End Sub Public Property Get Self() As WebGroupListener Set Self = Me End Property Private Sub Class_Initialize() EnableEvents = True End Sub </code></pre> <h2><code>WebGroupListener</code>: Class</h2> <p>Relays the Click, Right Click, and Double Click events of a <code>WebGroupListener</code>.</p> <pre><code>'@Folder(&quot;Battleship.WebUI.Listeners&quot;) Public WithEvents TableGrid1 As WebGroupListener Attribute TableGrid1.VB_VarHelpID = -1 Public WithEvents TableGrid2 As WebGroupListener Attribute TableGrid2.VB_VarHelpID = -1 Public Event onClick(Element As HTMLGenericElement) Public Event onDoubleClick(Element As HTMLGenericElement) Public Event onRightClick(Element As HTMLGenericElement) Public EnableEvents As Boolean Private Sub Class_Initialize() Set TableGrid1 = New WebGroupListener Set TableGrid2 = New WebGroupListener EnableEvents = True End Sub Public Sub onClick(Element As HTMLGenericElement) If EnableEvents Then RaiseEvent onClick(Element) End Sub Public Sub onDoubleClick(Element As HTMLGenericElement) If EnableEvents Then RaiseEvent onDoubleClick(Element) End Sub Public Sub onRightClick(Element As HTMLGenericElement) If EnableEvents Then RaiseEvent onRightClick(Element) End Sub Public Property Get Self() As WebGroupListener Set Self = Me End Property Private Sub TableGrid1_onClick(Element As MSHTML.HTMLGenericElement) If EnableEvents Then RaiseEvent onClick(Element) End Sub Private Sub TableGrid1_onDoubleClick(Element As MSHTML.HTMLGenericElement) If EnableEvents Then RaiseEvent onDoubleClick(Element) End Sub Private Sub TableGrid1_onRightClick(Element As MSHTML.HTMLGenericElement) If EnableEvents Then RaiseEvent onRightClick(Element) End Sub Private Sub TableGrid2_onClick(Element As MSHTML.HTMLGenericElement) If EnableEvents Then RaiseEvent onClick(Element) End Sub Private Sub TableGrid2_onDoubleClick(Element As MSHTML.HTMLGenericElement) If EnableEvents Then RaiseEvent onDoubleClick(Element) End Sub Private Sub TableGrid2_onRightClick(Element As MSHTML.HTMLGenericElement) If EnableEvents Then RaiseEvent onRightClick(Element) End Sub </code></pre> <h2><code>WebFlashElement</code>: Class</h2> <p>Flashes an <code>HTMLDivElement</code> element</p> <pre><code>Option Explicit '@Folder(&quot;Battleship.WebUI.Shapes&quot;) Private WithEvents TargetElement As HTMLDivElement Attribute TargetElement.VB_VarHelpID = -1 Private mREADYSTATE As tagREADYSTATE Public Function Create(newElement As HTMLDivElement) As WebFlashElement With New WebFlashElement .Element = newElement Set Create = .Self End With End Function Public Property Get Self() As WebFlashElement Set Self = Me End Property Public Property Get Element() As HTMLDivElement Set Element = TargetElement End Property Public Property Let Element(ByVal Value As HTMLDivElement) Set TargetElement = Value End Property Sub FlashShape(td As HTMLTableCell, ByVal flashes As Long, Optional ByVal Delay As Long = 50) If mREADYSTATE &lt;&gt; READYSTATE_COMPLETE Then Exit Sub mREADYSTATE = READYSTATE_LOADING Dim Left As Double, Top As Double Dim rect As IHTMLRect Set rect = td.getBoundingClientRect Left = rect.Left - TargetElement.offsetWidth / 2 - rect.Width Top = rect.Top - TargetElement.offsetHeight / 2 - rect.Height If Left &lt; 0 Then Left = rect.Left If Top &lt; 0 Then Top = rect.Top Dim i As Long, n As Long For i = 0 To flashes - 1 With GameRandomizer n = CInt(GameRandomizer.NextSingle * 30) - 15 End With TargetElement.Style.cssText = &quot;-ms-transform:rotate(&quot; &amp; n &amp; &quot;deg)&quot; TargetElement.Style.Left = Left &amp; &quot;px&quot; TargetElement.Style.Top = Top &amp; &quot;px&quot; TargetElement.Style.display = &quot;block&quot; DoEvents Sleep Delay * 1.5 TargetElement.Style.display = &quot;none&quot; DoEvents Sleep Delay * 0.75 Next TargetElement.Style.display = &quot;block&quot; DoEvents Sleep Delay * 2 TargetElement.Style.display = &quot;none&quot; DoEvents mREADYSTATE = READYSTATE_COMPLETE End Sub Public Property Get READYSTATE() As tagREADYSTATE READYSTATE = mREADYSTATE End Property Private Sub Class_Initialize() mREADYSTATE = READYSTATE_COMPLETE End Sub </code></pre> <h2><code>WebView</code>: Class</h2> <p>Interacts with the <code>Gamecontroller</code> to control the webpage.</p> <pre><code>Option Explicit '@Folder(&quot;Battleship.WebUI&quot;) Implements IGridViewCommands Private Const InfoBoxMessage As String = _ &quot;ENEMY FLEET DETECTED&quot; &amp; vbNewLine &amp; _ &quot;ALL SYSTEMS READY&quot; &amp; vbNewLine &amp; vbNewLine &amp; _ &quot;DOUBLE CLICK IN THE ENEMY Grid TO FIRE A MISSILE.&quot; &amp; vbNewLine &amp; vbNewLine &amp; _ &quot;FIND AND DESTROY ALL ENEMY SHIPS BEFORE THEY DESTROY YOUR OWN FLEET!&quot; Private Const InfoBoxPlaceSHIPs As String = _ &quot;FLEET DEPLOYMENT&quot; &amp; &quot;&lt;BR&gt;&quot; &amp; _ &quot;ACTION REQUIRED:&quot; &amp; &quot;&lt;BR&gt;&quot; &amp; _ &quot;DEPLOY %SHIP%&quot; &amp; &quot;&lt;BR&gt;&quot; &amp; _ &quot; -CLICK TO PREVIEW&quot; &amp; &quot;&lt;BR&gt;&quot; &amp; _ &quot; -RIGHT CLICK TO ROTATE&quot; &amp; &quot;&lt;BR&gt;&quot; &amp; _ &quot; -DOUBLE CLICK TO CONFIRM&quot; Private Const ErrorBoxInvalidPosition As String = _ &quot;FLEET DEPLOYMENT&quot; &amp; vbNewLine &amp; _ &quot;SYSTEM ERROR&quot; &amp; vbNewLine &amp; vbNewLine &amp; _ &quot; -SHIPS CANNOT OVERLAP.&quot; &amp; vbNewLine &amp; _ &quot; -SHIPS MUST BE ENTIRELY WITHIN THE Grid.&quot; &amp; vbNewLine &amp; vbNewLine &amp; _ &quot;DEPLOY SHIP TO ANOTHER POSITION.&quot; Private Const ErrorBoxInvalidKnownAttackPosition As String = _ &quot;TARGETING SYSTEM&quot; &amp; vbNewLine &amp; vbNewLine &amp; _ &quot;SPECIFIED Grid LOCATION IS ALREADY IN A KNOWN STATE.&quot; &amp; vbNewLine &amp; vbNewLine &amp; _ &quot;NEW VALID COORDINATES REQUIRED.&quot; Private Const DebugMode As Boolean = True Private Type Members ActiveGridID As Byte Adapter As IWeakReference currentPosition As GridCoord GridCells As New Dictionary Fleets(1 To 2) As New Dictionary HumanID As Byte IE As SHDocVw.InternetExplorerMedium PrimaryID As Byte HumanFleet As Collection PreviousMode As ViewMode Mode As ViewMode ShipHitAreas(1 To 2) As New Dictionary End Type Private this As Members Private Type TFlashBoxes HitGrid As WebFlashElement MissLabelGrid As WebFlashElement SunkGrid As WebFlashElement End Type Private flashBoxes As TFlashBoxes Private WithEvents Document As HTMLDocument Attribute Document.VB_VarHelpID = -1 Private WithEvents WebGrid As WebGridGroup Attribute WebGrid.VB_VarHelpID = -1 Private WithEvents StrategyButtonGroup1 As WebGroupListener Attribute StrategyButtonGroup1.VB_VarHelpID = -1 Private WithEvents StrategyButtonGroup2 As WebGroupListener Attribute StrategyButtonGroup2.VB_VarHelpID = -1 Private WithEvents ErrorBox As HTMLDivElement Attribute ErrorBox.VB_VarHelpID = -1 Private WithEvents Informationbox As HTMLDivElement Attribute Informationbox.VB_VarHelpID = -1 Private WithEvents GameOverLoseGrid As HTMLDivElement Attribute GameOverLoseGrid.VB_VarHelpID = -1 Private WithEvents GameOverWinGrid As HTMLDivElement Attribute GameOverWinGrid.VB_VarHelpID = -1 Private PlayerNameDiv As HTMLDivElement Private WithEvents btnPlayerNameOK As HTMLInputElement Attribute btnPlayerNameOK.VB_VarHelpID = -1 Private txtPlayerName As HTMLInputElement Public Sub Init(IE As SHDocVw.InternetExplorerMedium) Set this.IE = IE End Sub Public Sub ClearGrid(ByVal GridID As Byte) Dim TableGrid As WebGroupListener Set TableGrid = IIf(GridID = 1, WebGrid.TableGrid1, WebGrid.TableGrid2) Dim n As Long, listener As WebElementListener For n = 0 To TableGrid.Elements.Count - 1 Set listener = TableGrid.Elements.Items(n) listener.Object.className = &quot;&quot; Next End Sub Private Function btnPlayerNameOK_onclick() As Boolean PlayerNameDiv.Style.display = &quot;none&quot; ViewEvents.CreatePlayer this.HumanID, HumanControlled, AIDifficulty.Unspecified btnPlayerNameOK_onclick = True End Function Private Function ErrorBox_onclick() As Boolean setErrorBox &quot;&quot;, False End Function Private Sub FlashBoxFlash(FlashBox As WebFlashElement, ByVal GridID As Byte) Dim td As HTMLTableCell, TableGrid As WebGroupListener Set TableGrid = IIf(GridID = 1, WebGrid.TableGrid1, WebGrid.TableGrid2) Set td = TableGrid.Elements.item(this.currentPosition.ToString).Object With GameRandomizer FlashBox.FlashShape td, IIf(.NextSingle &lt; 0.75, 1, IIf(.NextSingle &lt; 0.75, 3, 4)) End With While FlashBox.READYSTATE &lt;&gt; READYSTATE_COMPLETE: DoEvents: Wend End Sub Private Function getBattleShipURL() As String Dim Path As String Path = Split(ThisWorkbook.Path, &quot;:&quot;)(1) Path = Replace(Path, &quot;\&quot;, &quot;/&quot;) getBattleShipURL = &quot;file://127.0.0.1/c$&quot; &amp; Path &amp; &quot;/index.html&quot; End Function Private Function getCaption(GridID As Byte) As HTMLTableCaption Set getCaption = Document.getElementById(&quot;Grid&quot; &amp; GridID).getElementsByTagName(&quot;caption&quot;).item(0) End Function Private Function getCurrentHumanPlayerGrid() As WebGroupListener If this.Mode = ViewMode.FleetPosition Then Set getCurrentHumanPlayerGrid = IIf(this.PrimaryID = 1, WebGrid.TableGrid1, WebGrid.TableGrid2) Else Set getCurrentHumanPlayerGrid = IIf(this.PrimaryID = 2, WebGrid.TableGrid1, WebGrid.TableGrid2) End If End Function Private Function getShipDiv(ShipName As String, GridID As Byte) As HTMLDivElement ShipName = Replace(ShipName, &quot; &quot;, &quot;&quot;) &amp; GridID Set getShipDiv = Document.getElementById(ShipName) End Function Private Function getTargetShipDiv(ShipName As String, GridID As Byte, Optional isSunken As Boolean) As HTMLDivElement ShipName = &quot;Target-&quot; &amp; Replace(ShipName, &quot; &quot;, &quot;&quot;) &amp; GridID Set getTargetShipDiv = Document.getElementById(ShipName) If isSunken Then getTargetShipDiv.getElementsByTagName(&quot;div&quot;).item(0).Style.display = &quot;block&quot; End Function Private Function Informationbox_onclick() As Boolean this.Mode = this.PreviousMode ViewEvents.HumanPlayerReady Informationbox.Style.display = &quot;none&quot; End Function Private Sub InitGrid(GridID As Byte) Dim group As New WebGroupListener Dim tbody As HTMLTableSection, td As HTMLTableCell, tr As HTMLTableRow Set tbody = Document.getElementById(&quot;Grid&quot; &amp; GridID).getElementsByTagName(&quot;tbody&quot;).item(0) Dim X As Long Dim Y As Long Dim key As Variant For Y = 1 To tbody.Rows.Length - 1 Set tr = tbody.Rows(Y) For X = 1 To tr.Cells.Length - 1 Set td = tr.Cells.item(X) key = GridCoord.Create(X, Y).ToString group.AddElement key, td Next Next If GridID = 1 Then Set WebGrid.TableGrid1 = group Else Set WebGrid.TableGrid2 = group End Sub Private Sub InitPrimaryID(GridID As Byte) Const EnemyShip As String = &quot; bg-Enemy-&quot;, PrimaryShip As String = &quot; bg-&quot; this.PrimaryID = GridID 'Display Acquired Target and Fleet Position Boxes With Document.getElementsByClassName(&quot;TargetsBox&quot;) .item(IIf(this.PrimaryID = 1, 1, 0)).className = &quot;TargetsBox acquired-targets&quot; .item(0).Style.display = &quot;block&quot; .item(1).Style.display = &quot;block&quot; End With 'Add Ship Classes to Fleet Position Box Divs Dim n As Long For n = 0 To UBound(Ship.Names) With getTargetShipDiv(CStr(Ship.Names(n)), this.PrimaryID) .className = .className &amp; PrimaryShip &amp; Replace(Ship.Names(n), &quot; &quot;, &quot;&quot;) End With With getTargetShipDiv(CStr(Ship.Names(n)), IIf(this.PrimaryID = 1, 2, 1)) .className = .className &amp; EnemyShip &amp; Replace(Ship.Names(n), &quot; &quot;, &quot;&quot;) End With Next End Sub Private Sub InitPrimaryShips(GridID As Byte, ShipSuffix As Byte, Fleet As Collection) 'Show Table Ships Dim currentShip As IShip, ShipName As String Dim td As HTMLTableCell, ShipDiv As HTMLDivElement Dim TableGrid As WebGroupListener Set TableGrid = IIf(GridID = 1, WebGrid.TableGrid1, WebGrid.TableGrid2) For Each currentShip In Fleet ShipName = Replace(currentShip.name, &quot; &quot;, &quot;&quot;) &amp; ShipSuffix Set ShipDiv = Document.getElementById(ShipName) Set td = TableGrid.Elements.item(GridCoord.Create(currentShip.GridPosition.X, currentShip.GridPosition.Y).ToString).Object Dim PaddingLeft As Double, PaddingTop As Double SnapToTableCell ShipDiv, td, currentShip.Orientation this.Fleets(GridID).Add currentShip.name, ShipDiv Dim n As Long, X As Long, Y As Long Dim hitArea As HTMLDivElement, hitCood As GridCoord With currentShip X = .GridPosition.X Y = .GridPosition.Y For n = 0 To .Size - 1 Set hitArea = ShipDiv.getElementsByTagName(&quot;div&quot;).item(n) Set hitCood = GridCoord.Create(IIf(.Orientation = Horizontal, X + n, X), IIf(.Orientation = Vertical, Y + n, Y)) this.ShipHitAreas(GridID).Add hitCood.ToString, hitArea Next End With Next End Sub Private Sub InitStrategyButtonGroup(GridID As Byte) Dim group As New WebGroupListener Dim div As HTMLDivElement Dim n As Long Set div = Document.getElementsByClassName(&quot;strategy&quot;).item(GridID - 1) For n = 0 To 3 group.AddElement n, div.getElementsByTagName(&quot;div&quot;).item(n) Next If GridID = 1 Then Set StrategyButtonGroup1 = group Else Set StrategyButtonGroup2 = group End Sub Public Sub RefreshGrid(ByVal Grid As PlayerGrid) Dim state As Variant, X As Long, Y As Long Dim td As HTMLTableCell, listener As WebElementListener, key As Variant, className As String, group As WebGroupListener Set group = IIf(Grid.GridID = 1, WebGrid.TableGrid1, WebGrid.TableGrid2) For X = 1 To Grid.Size For Y = 1 To Grid.Size key = GridCoord.Create(X, Y).ToString state = Grid.StateArray(X, Y) className = Switch(IsEmpty(state), &quot;&quot;, _ state = GridState.Unknown, &quot;&quot;, _ state = GridState.InvalidPosition, &quot;InvalidPosition&quot;, _ state = GridState.PreviewShipPosition, &quot;PreviewShipPosition&quot;, _ state = GridState.ShipPosition, &quot;ShipPosition&quot;, _ state = GridState.PreviousMiss, &quot;PreviousMiss&quot;, _ state = GridState.InvalidPosition, &quot;InvalidPosition&quot;, _ state = GridState.PreviousHit, &quot;PreviousHit&quot;) If this.PrimaryID = Grid.GridID And this.ShipHitAreas(Grid.GridID).Exists(key) And className = &quot;PreviousHit&quot; Then this.ShipHitAreas(Grid.GridID).item(key).Style.display = &quot;block&quot; className = &quot;&quot; End If Set listener = group.Elements.item(key) Set td = listener.Object td.className = className Next Next DoEvents End Sub Private Sub setErrorBox(Message As String, Show As Boolean) If Show Then this.PreviousMode = this.Mode this.Mode = MessageShown ErrorBox.innerText = Message ErrorBox.Style.display = &quot;block&quot; Else this.Mode = this.PreviousMode ErrorBox.Style.display = &quot;none&quot; End If End Sub Private Sub SnapToTableCell(target As HTMLDivElement, td As HTMLTableCell, Orientation As ShipOrientation) Dim Left As Double, Top As Double Dim rect As IHTMLRect Set rect = td.getBoundingClientRect target.Style.cssText = &quot;&quot; target.Style.display = &quot;block&quot; If Orientation = Horizontal Then Left = rect.Left Top = rect.Top Else target.Style.cssText = &quot;-ms-transform:rotate(90deg)&quot; target.Style.display = &quot;block&quot; Left = rect.Left - target.offsetWidth / 2 + rect.Width / 2 Top = rect.Top + target.offsetWidth / 2 - rect.Width / 2 + 3 End If DoEvents target.Style.Left = Left &amp; &quot;px&quot; target.Style.Top = Top &amp; &quot;px&quot; End Sub Private Sub StrategyButtonGroup1_onClick(Element As MSHTML.HTMLGenericElement) StrategyButtonGroupClicked Element, 1, StrategyButtonGroup1 End Sub Private Sub StrategyButtonGroup2_onClick(Element As MSHTML.HTMLGenericElement) StrategyButtonGroupClicked Element, 2, StrategyButtonGroup2 End Sub Private Sub StrategyButtonGroupClicked(Element As MSHTML.HTMLGenericElement, GridID As Byte, group As WebGroupListener) Dim item As Variant For Each item In group.Elements.Items item.Visible = False Next Select Case Element.getAttribute(&quot;type&quot;) Case &quot;Human&quot; IIf(GridID = 1, StrategyButtonGroup2.Elements.Items(0), StrategyButtonGroup1.Elements.Items(0)).Visible = False this.HumanID = GridID PlayerNameDiv.Style.display = &quot;block&quot; txtPlayerName.Focus Case &quot;FairplayAI&quot; getCaption(GridID).innerHTML = &quot;FairplayAI&quot; ViewEvents.CreatePlayer GridID, ComputerControlled, AIDifficulty.FairplayAI Case &quot;RandomAI&quot; getCaption(GridID).innerHTML = &quot;RandomAI&quot; ViewEvents.CreatePlayer GridID, ComputerControlled, AIDifficulty.RandomAI Case &quot;MercilessAI&quot; getCaption(GridID).innerHTML = &quot;MercilessAI&quot; ViewEvents.CreatePlayer GridID, ComputerControlled, AIDifficulty.MercilessAI End Select DoEvents End Sub Private Sub WebGrid_onClick(Element As MSHTML.HTMLGenericElement) Dim position As GridCoord Set position = GridCoord.Create(Element.cellIndex, Element.parentElement.RowIndex) If this.Mode = ViewMode.FleetPosition Then ViewEvents.PreviewShipPosition this.PrimaryID, position End If End Sub Private Sub WebGrid_onDoubleClick(Element As MSHTML.HTMLGenericElement) Dim position As GridCoord Set position = GridCoord.Create(Element.cellIndex, Element.parentElement.RowIndex) If this.Mode = ViewMode.FleetPosition Then ViewEvents.ConfirmShipPosition this.PrimaryID, position ElseIf this.Mode = IIf(this.PrimaryID = 1, ViewMode.player1, ViewMode.player2) Then ViewEvents.AttackPosition IIf(this.PrimaryID = 1, 2, 1), position End If End Sub Private Sub WebGrid_onRightClick(Element As MSHTML.HTMLGenericElement) Dim position As GridCoord Set position = GridCoord.Create(Element.cellIndex, Element.parentElement.RowIndex) If this.Mode = ViewMode.FleetPosition Then ViewEvents.PreviewRotateShip this.PrimaryID, position End If End Sub Private Property Get ViewEvents() As IGridViewEvents Set ViewEvents = this.Adapter.Object End Property ':IGridViewCommands ':Messages sent from the controller ':********************************* Private Property Set IGridViewCommands_Events(ByVal Value As IGridViewEvents) Set this.Adapter = WeakReference.Create(Value) End Property Private Property Get IGridViewCommands_Events() As IGridViewEvents Set IGridViewCommands_Events = this.Adapter.Object End Property Private Sub IGridViewCommands_OnBeginAttack(ByVal currentPlayerGridId As Byte) ClearGrid this.PrimaryID InitPrimaryShips this.PrimaryID, 1, this.HumanFleet End Sub 'Automatically Confirm Ship Position Private Sub IGridViewCommands_OnBeginShipPosition(ByVal currentShip As IShip, ByVal player As IPlayer) If this.PrimaryID = 0 Then InitPrimaryID player.PlayGrid.GridID this.Mode = FleetPosition End If 'Display Deployment Message in Table Caption Marquee getCaption(this.PrimaryID).innerHTML = &quot;&lt;marquee behavior=scroll direction='up' scrollamount='3' style='font-size:14px;'&gt;&quot; &amp; Replace(InfoBoxPlaceSHIPs, &quot;%SHIP%&quot;, &quot;&lt;span style='color:white;'&gt;&quot; &amp; UCase$(currentShip.name) &amp; &quot;&lt;/span&gt;&quot;) &amp; &quot;&lt;marquee&gt;&quot; 'Show Deployed Ship getTargetShipDiv(currentShip.name, this.PrimaryID).Style.display = &quot;block&quot; End Sub Private Sub IGridViewCommands_OnBeginWaitForComputerPlayer() If Not DebugMode Then Application.Cursor = xlWait Application.StatusBar = &quot;Please wait...&quot; End If End Sub Private Sub IGridViewCommands_OnEndWaitForComputerPlayer() Application.Cursor = xlDefault Application.StatusBar = False End Sub Private Sub IGridViewCommands_OnConfirmShipPosition(ByVal player As IPlayer, ByVal newShip As IShip) If player.PlayGrid.Fleet.Count = Ship.Fleet.Count Then getCaption(this.PrimaryID).innerText = txtPlayerName.Value Set this.HumanFleet = player.PlayGrid.Fleet this.PreviousMode = ViewMode.player1 this.Mode = MessageShown Informationbox.innerText = InfoBoxMessage Informationbox.Style.display = &quot;block&quot; End If End Sub Private Sub IGridViewCommands_OnGameOver(ByVal winningGridId As Byte) this.Mode = ViewMode.GameOver Dim td As HTMLTableCell Dim TableGrid As WebGroupListener Set TableGrid = IIf(winningGridId = 1, WebGrid.TableGrid1, WebGrid.TableGrid2) SnapToTableCell GameOverWinGrid, TableGrid.Elements.item(&quot;(4,3)&quot;).Object, Horizontal Set TableGrid = IIf(winningGridId = 2, WebGrid.TableGrid1, WebGrid.TableGrid2) SnapToTableCell GameOverLoseGrid, TableGrid.Elements.item(&quot;(4,3)&quot;).Object, Horizontal End Sub Private Sub IGridViewCommands_OnHit(ByVal GridID As Byte) FlashBoxFlash flashBoxes.HitGrid, GridID End Sub Private Sub IGridViewCommands_OnInvalidShipPosition() setErrorBox ErrorBoxInvalidPosition, True End Sub Private Sub IGridViewCommands_OnKnownPositionAttack(): End Sub Private Sub IGridViewCommands_OnLockGrid(ByVal GridID As Byte): End Sub Private Sub IGridViewCommands_OnMiss(ByVal GridID As Byte) FlashBoxFlash flashBoxes.MissLabelGrid, GridID End Sub Private Sub IGridViewCommands_OnNewGame() this.Mode = ViewMode.NewGame With this.IE .Silent = True If Len(.LocationURL) = 0 Then .Navigate getBattleShipURL Else .Refresh End If While .Busy Or .READYSTATE &lt;&gt; READYSTATE_COMPLETE: DoEvents: Wend Set Document = .Document End With 'Initiate StrategyButtonGroups InitStrategyButtonGroup 1 InitStrategyButtonGroup 2 'Initiate WebGridGroup Set WebGrid = New WebGridGroup InitGrid 1 InitGrid 2 'Initiate Message Boxes Set ErrorBox = Document.getElementById(&quot;ErrorBox&quot;) Set Informationbox = Document.getElementById(&quot;informationbox&quot;) Set GameOverLoseGrid = Document.getElementById(&quot;GameOverLoseGrid&quot;) Set GameOverWinGrid = Document.getElementById(&quot;GameOverWinGrid&quot;) Set PlayerNameDiv = Document.getElementById(&quot;PlayerName&quot;) Set btnPlayerNameOK = Document.getElementById(&quot;btnPlayerNameOK&quot;) Set txtPlayerName = Document.getElementById(&quot;txtPlayerName&quot;) 'Initiate Flash Boxes Set flashBoxes.HitGrid = WebFlashElement.Create(Document.getElementById(&quot;HitGrid&quot;)) Set flashBoxes.MissLabelGrid = WebFlashElement.Create(Document.getElementById(&quot;MissLabelGrid&quot;)) Set flashBoxes.SunkGrid = WebFlashElement.Create(Document.getElementById(&quot;SunkGrid&quot;)) End Sub Private Sub IGridViewCommands_OnPreviewShipPosition(ByVal player As IPlayer, ByVal newShip As IShip) RefreshGrid player.PlayGrid Debug.Assert Not newShip Is Nothing Dim n As Long, X As Long, Y As Long Dim td As HTMLTableCell, listener As WebElementListener, key As Variant, className As String, group As WebGroupListener Set group = IIf(player.PlayGrid.GridID = 1, WebGrid.TableGrid1, WebGrid.TableGrid2) With newShip X = .GridPosition.X Y = .GridPosition.Y For n = 0 To .Size - 1 key = GridCoord.Create(X + IIf(.Orientation = Horizontal, n, 0), Y + IIf(.Orientation = Vertical, n, 0)).ToString Set listener = group.Elements.item(key) Set td = listener.Object className = IIf(Len(td.className) &gt; 0, &quot;InvalidPosition&quot;, &quot;PreviewShipPosition&quot;) td.className = className Next End With DoEvents End Sub Private Sub IGridViewCommands_OnRefreshGrid(ByVal Grid As PlayerGrid) If this.PrimaryID = 0 Then InitPrimaryID 1 RefreshGrid Grid End Sub Private Sub IGridViewCommands_OnSelectPosition(ByVal GridID As Byte, ByVal position As IGridCoord) Set this.currentPosition = position this.Mode = IIf(this.Mode = ViewMode.player1, ViewMode.player2, ViewMode.player1) End Sub Private Sub IGridViewCommands_OnSink(ByVal GridID As Byte) FlashBoxFlash flashBoxes.SunkGrid, GridID End Sub Private Sub IGridViewCommands_OnUpdateFleetStatus(ByVal player As IPlayer, ByVal hitShip As IShip, Optional ByVal showAIStatus As Boolean = False) If (player.PlayerType = ComputerControlled And showAIStatus) Or hitShip.isSunken Then getTargetShipDiv(hitShip.name, player.PlayGrid.GridID, hitShip.isSunken).Style.display = &quot;block&quot; End If End Sub </code></pre> <p>Overall, I am pretty happy with the project but there are still a few issues to iron out:</p> <ul> <li><p>The game keeps running after the Webform is closed. I will probably have to add a Close event to the Webform to trigger the actual Webform variable to be destroyed.</p> </li> <li><p>Create a <strong>New Game</strong> button to restart the game</p> </li> <li><p>Display the attack position coordinates.</p> </li> <li><p>Run the UI in an actual IE Browser. Currently, the code will run but IE will not repaint the page after the second player is created. The page is updated when the game is over. DoEvents is used to allow the Webbrowser control to update but has no effect on IE. I have tried a myriad of jank solutions from my research to no avail.</p> </li> </ul> <p>I got a little sloppy towards the end. There are a few methods in my classes are no longer being used. I'm going to leave them for now.</p> <p><a href="https://drive.google.com/open?id=1uMWPQzVg3Js4APtz3_6_JGX0jqGIHQc5" rel="nofollow noreferrer">Download Web Battleship -The Unofficial Battleship UI</a></p> <p><a href="https://github.com/rubberduck-vba/Battleship" rel="nofollow noreferrer">Mathieu Guindon's original VBA Battleship file on GitHub</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-05T04:03:59.107", "Id": "395402", "Score": "1", "body": "wah that's bloody impressive!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-05T04:31:02.487", "Id": "395405", "Score": "0", "body": "I...
[]
{ "AcceptedAnswerId": null, "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-05T03:43:58.477", "Id": "204982", "Score": "7", "Tags": [ "object-oriented", "vba", "excel", "battleship" ], "Title": "Web Battleship -The Unofficial Battleship UI" }
204982
<p>I've write a gomoku terminal game with socket client and server.</p> <p>The main suggestions I am looking for:</p> <ul> <li><p>Am I using the multithread in right way? As when I tried to migrate the terminal game to GUI(pygame), the main thread is blocking, pygame can't render. </p></li> <li><p>I am new in socket in python, so any suggestions about socket all appreciate.</p></li> <li><p>Also not sure for my <code>singleton</code>, I have checked the <code>id</code>, they keep the same, but I am just new in singleton in python, is it pythonic?</p></li> <li><p>My server just accept two connection, so I tried to close the server while client close the connection, I doubt my implement</p> <pre><code>if connection_0_data == b'': print("connection 0 is GONE") return None, None connection_1_data = connection[1].recv(1024) if connection_1_data == b'': print("connection 1 is GONE") return None, None </code></pre></li> </ul> <p>Any other suggestions all welcome.</p> <p>(The code is bit long)</p> <hr> <h2>Client part</h2> <pre><code>import socket import json import sys import argparse import re import threading import queue </code></pre> <h3>socket part, using singleton</h3> <pre><code>def singleton(cls): instances = {} def _singleton(*args, **kwags): if cls not in instances: instances[cls] = cls(*args, **kwags) return instances[cls] return _singleton @singleton class GomokuClient(): def __init__(self): self._client = None @property def client(self): return self._client def connect(self, host, port): self._client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._client.connect((host, port)) def send(self, data): self._client.send(json.dumps(data).encode("utf-8")) def receive(self): response = self._client.recv(4096) return json.loads(response.decode("utf-8")) def close(self): self._client.close() self._client = None </code></pre> <h3>Client multithread part</h3> <p>this part I get from <a href="https://github.com/eliben/code-for-blog/blob/master/2011/socket_client_thread_sample/socketclientthread.py" rel="nofollow noreferrer">here</a></p> <pre><code>class ClientCommand(): CONNECT, SEND, RECEIVE, CLOSE = range(4) def __init__(self, type_, data=None): self.type_ = type_ self.data = data class GomokuClientThread(threading.Thread): def __init__(self, send_q=queue.Queue(), reply_q=queue.Queue()): super(GomokuClientThread, self).__init__() self.cmd_q = send_q self.reply_q = reply_q self.clientsocket = GomokuClient() self.handlers = { ClientCommand.CONNECT: self.connect, ClientCommand.CLOSE: self.close, ClientCommand.SEND: self.send, ClientCommand.RECEIVE: self.recieve, } def run(self): while True: try: cmd = self.cmd_q.get(True, 0.1) self.handlers[cmd.type_](cmd.data) except queue.Empty as e: continue def connect(self, data): host, port = data self.clientsocket.connect(host, port) self.cmd_q.put(ClientCommand(ClientCommand.RECEIVE)) def send(self, data): if data.get("grid"): data["grid"] = self.grid_matrix_2_str(data["grid"]) self.clientsocket.send(data) self.cmd_q.put(ClientCommand(ClientCommand.RECEIVE)) def recieve(self, data=None): data = self.clientsocket.receive() if data: self.reply_q.put(data) def close(self, data=None): self.clientsocket.close() def grid_matrix_2_str(self, grid): n = len(grid) m = len(grid[0]) return "".join("".join(str(grid[i][j]) for j in range(m)) for i in range(n)) </code></pre> <h3>Game part</h3> <pre><code>class GomokuGame(): def __init__(self, player, board_row=5, board_column=5, host="localhost", port=50003): self.board_row = board_row self.board_column = board_column self.player = player self.host = host self.port = port def display(self): client_thread = GomokuClientThread() client_thread.start() client_thread.cmd_q.put(ClientCommand(ClientCommand.CONNECT, (self.host, self.port))) while True: data = client_thread.reply_q.get(True) grid = self.grid_str_2_matrix(data["grid"]) if data["gameover"] == -1: if data["next_player"] != self.player: client_thread.cmd_q.put(ClientCommand(ClientCommand.SEND, {"wait": True})) else: self.print_grid(grid) grid, x, y = self.next_move(grid) self.print_grid(grid) print("Waiting...") data = {"grid":grid, "x":x, "y":y, "player":self.player} client_thread.cmd_q.put(ClientCommand(ClientCommand.SEND, data)) else: if data["gameover"] == 0: print("Draw") else: if data["player"] == self.player: print("You Win") else: print("You Lost") client_thread.cmd_q.put(ClientCommand(ClientCommand.CLOSE)) break def grid_str_2_matrix(self, grid): return [list(map(int, grid[i:i+self.board_column])) for i in range(0, len(grid), self.board_column)] def print_grid(self, grid): print("\n".join([" | ".join(list(map(str, grid[i]))) for i in range(self.board_row)])) def next_move(self, grid): while True: position = input(f"What's your next move, separate by ',', only integer between 0-{self.board_row} allowed:") x, y = position.split(",") try: x = int(x) y = int(y) if grid[x][y] == 0: grid[x][y] = self.player break print(f"Already has piece on {x}/{y}") except: pass return grid, x, y def __call__(self): return self.display() </code></pre> <h3>Run the game</h3> <pre><code>def parse_options(): parser = argparse.ArgumentParser(usage='%(prog)s [options]', description='Gomoku socket client @Qin', formatter_class=argparse.RawDescriptionHelpFormatter, epilog= ''' Examples: python server.py -i '0.0.0.0' -p 9999 ''' ) parser.add_argument('-i','--ip', type=str, default="localhost", help='server host') parser.add_argument('-p','--port', type=int, default=9999, help='server port') parser.add_argument('-e','--player', type=int, default=1, help='player') args = parser.parse_args() ip_pattern = "((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:(?&lt;!\.)|\.)){4}" ip = re.match(ip_pattern, args.ip) valid_ip = (ip and ip.group(0) == args.ip) if not (args.ip == "localhost" or valid_ip): print("[-] IPV4 host is not valid") sys.exit(1) return args if __name__ == "__main__": args = parse_options() game = GomokuGame(args.player, host=args.ip, port=args.port) game() </code></pre> <hr> <h2>Server Part</h2> <pre><code>import socket import json import random import threading import argparse import re class GomokuServer(): ''' Package: Server -&gt; Client: grid =&gt; grid(str, with 0 1 and 2) x =&gt; last move x position(int) y =&gt; last move y position(int) player =&gt; Last Player(int) next_player =&gt; who's next player(int) gameover =&gt; is gameover(int), -1=No, 0=Draw, 1=Player Win Client -&gt; Server: (case 1: with move) grid =&gt; grid(str, with 0 1 and 2) x =&gt; last move x position(int) y =&gt; last move y position(int) player =&gt; Last Player(int) (case 2: without move) wait =&gt; (always be True) ''' def __init__(self, host, port, board_row, board_column): self.board_row = board_row self.board_column = board_column self.host = host self.port = port self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind((self.host, self.port)) def listen(self): self.sock.listen(2) print(f"Listing {self.host}:{self.port}") connection = [] while True: self.waiting_for_connections(connection) self.listen_2_clients(connection) def close(self): self.sock.close() def listen_2_clients(self, connection): self.response = {"grid":"0"*(self.board_row*self.board_column), "x": -1, "y": -1, "player": -1, "next_player": 1, "gameover": -1} while True: data_arr = json.dumps(self.response).encode("utf-8") connection[0].send(data_arr) connection[1].send(data_arr) player1, player2 = self.recieve_information(connection) if player1 is None: self.sock.close() break self.response = self.process_positions(player1, player2) def waiting_for_connections(self, connection): while len(connection)&lt;2: conn, addr = self.sock.accept() conn.settimeout(60) connection.append(conn) print(conn) print(connection) def recieve_information(self, connection): connection_0_data = connection[0].recv(1024) if connection_0_data == b'': print("connection 0 is GONE") return None, None connection_1_data = connection[1].recv(1024) if connection_1_data == b'': print("connection 1 is GONE") return None, None player_1_info = json.loads(connection_0_data.decode("utf-8")) player_2_info = json.loads(connection_1_data.decode("utf-8")) return player_1_info, player_2_info def process_positions(self, player1, player2): if not player1.get("wait"): grid = player1["grid"] player = player1["player"] x = player1["x"] y = player1["y"] else: grid = player2["grid"] player = player2["player"] x = player2["x"] y = player2["y"] grid = self.grid_str_2_matrix(grid) if self._check_win(grid, [x, y], player): gameover = 1 elif self._check_draw(grid): gameover = 0 else: gameover = -1 grid = self.grid_matrix_2_str(grid) return {"grid":grid, "x":x, "y":y, "player":player, "next_player":3-player, "gameover":gameover} def grid_str_2_matrix(self, grid): return [list(map(int, grid[i:i+self.board_column])) for i in range(0, len(grid), self.board_column)] def grid_matrix_2_str(self, grid): return "".join("".join(str(grid[i][j]) for j in range(self.board_column)) for i in range(self.board_row)) def _check_draw(self, grid): return all([grid[i][j] != 0 for i in range(self.board_row) for j in range(self.board_column)]) def _check_win(self, grid, position, player): target = player if grid[position[0]][position[1]] != target: return False directions = [([0, 1], [0, -1]), ([1, 0], [-1, 0]), ([-1, 1], [1, -1]), ([1, 1], [-1, -1])] for direction in directions: continue_chess = 0 for i in range(2): p = position[:] while 0 &lt;= p[0] &lt; self.board_row and 0 &lt;= p[1] &lt; self.board_column: if grid[p[0]][p[1]] == target: continue_chess += 1 else: break p[0] += direction[i][0] p[1] += direction[i][1] if continue_chess &gt;= 6: return True return False def __call__(self): return self.listen() def parse_options(): parser = argparse.ArgumentParser(usage='%(prog)s [options]', description='Gomoku socket server @Qin', formatter_class=argparse.RawDescriptionHelpFormatter, epilog= ''' Examples: python server.py -i '0.0.0.0' -p 9999 ''' ) parser.add_argument('-i','--ip', type=str, default="localhost", help='server host') parser.add_argument('-p','--port', type=int, default=9999, help='server port') parser.add_argument('-r','--row', type=int, default=15, help='board row length') parser.add_argument('-c','--column', type=int, default=15, help='board column length') args = parser.parse_args() ip_pattern = "((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:(?&lt;!\.)|\.)){4}" ip = re.match(ip_pattern, args.ip) valid_ip = (ip and ip.group(0) == args.ip) if not (args.ip == "localhost" or valid_ip): print("[-] IPV4 host is not valid") sys.exit(1) return args if __name__ == "__main__": args = parse_options() server = GomokuServer(args.ip, args.port, args.row, args.column) try: server() except KeyboardInterrupt: server.close() </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-05T05:36:39.690", "Id": "204986", "Score": "2", "Tags": [ "python", "python-3.x", "socket" ], "Title": "Gomoku game with socket client(multithread) and server" }
204986
<p>I have been studying C#, and I am trying to model the "Rock / Paper / Scissors" game.</p> <p>Is my program reasonable or is there anything I need to improve?</p> <ol> <li>user input a round.</li> <li>user input RockPaper or Scissor.</li> <li>After the game is finished , user can choose to play again or quit.</li> </ol> <p></p> <pre><code>namespace Project_RockPaperSci_Revised { public class RockPaperScissor { public Random rnd = new Random(); public string userInput; public int userScore = 0; public int comScore = 0; public bool isPlaying = true; public int around; public void PlayGame() { Console.WriteLine("Welcome Let's play Rock Paper Scissors"); SetRound(ref around); while (isPlaying) { userScore = 0; comScore = 0; while (userScore &lt; around &amp;&amp; comScore &lt; around) { PlayerInput(ref userInput); Console.WriteLine("\nPlayer chose {0}", userInput); Match(userInput, ref userScore, ref comScore); Console.WriteLine($"User's Score&lt;{userScore}&gt;\tCom's Score&lt;{comScore}&gt;\n"); } string again = string.Empty; Console.WriteLine("Do you want to play again? y/n "); again = Console.ReadLine(); again = again.ToUpper(); if (again == "Y") { Console.Clear(); } else if (again == "N") { Console.WriteLine("Good Bye"); isPlaying = false; } } } public string PlayerInput(ref string userInput) { Console.Write("Choose btw RockPaperScissor \n"); userInput = Console.ReadLine(); userInput = userInput.ToUpper(); return userInput; } public int ShowResult(int flagNum) { int flagScore =0 ; switch (flagNum) { case 1: Console.WriteLine("User Win !!"); break; case 2: Console.WriteLine("Computer Win !!"); break; case 3: Console.WriteLine("Draw !!"); break; default: break; } return flagScore; } public void Match(string userInput,ref int userScore, ref int comScore) { int comChoice; comChoice = rnd.Next(1, 4); // flagNum 1 = userWin 2 = ComWin 3 = Draw int flagNum = 0; switch (comChoice) { case 1: Console.WriteLine("Computer chose ROCK"); if (userInput == "ROCK") { flagNum = 3; }else if (userInput == "PAPER") { flagNum = 1; comScore++; } else if (userInput == "SCISSOR") { flagNum = 2; userScore++; } break; case 2: Console.WriteLine("Computer chose PAPER"); if (userInput == "ROCK") { flagNum = 2; comScore++; } else if (userInput == "PAPER") { flagNum = 3; } else if (userInput == "SCISSOR") { flagNum = 1; userScore++; } break; case 3: Console.WriteLine("Com Chose SCISSOR"); if (userInput == "ROCK") { flagNum = 1; userScore++; } else if (userInput == "PAPER") { flagNum = 2; comScore++; } else if (userInput == "SCISSOR") { flagNum = 3; } break; default: Console.WriteLine("Error"); break; } ShowResult(flagNum); } public void SetRound(ref int around) { Console.Write("How many round would you like to play?\t"); around = Convert.ToInt32(Console.ReadLine()); } } class Program { static void Main(string[] args) { RockPaperScissor rps1 = new RockPaperScissor(); rps1.PlayGame(); } } } </code></pre>
[]
[ { "body": "<p>I gave this a very quick review while still on my first cup of coffee. The answer is not very detailed, but then there were a lot of things I caught even with a quick scan.</p>\n\n<p>The public fields at the top of the <code>RockPaperScissor</code> class should either be <code>private fields</cod...
{ "AcceptedAnswerId": "205017", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-05T09:42:29.297", "Id": "205002", "Score": "7", "Tags": [ "c#", "beginner", "console", "rock-paper-scissors" ], "Title": "RockPaperScissor Game" }
205002
<p>I wrote a simple Dependency Resolver in PHP that I'm hoping to get some input on.</p> <p>The main problem that gave me some trouble was when it had to resolve typed arguments ( like type hinting a constructor argument with an interface, I don't remember exactly what they call it ). The only work around was to let the <code>DependencyResolver</code> know about such dependencies that are not directly resolvable (instantiable).</p> <p>Note: The class name of this <code>Dependency Resolver</code> is <code>ObjectManager</code></p> <pre><code>// dependencies.php // this is where I define all my dependencies in case if they are not directly instantiable $deps = array( 'DependentClass' =&gt; array( 'depclass' =&gt; 'DependencyClass' ) ); ObjectManager::getInstance()-&gt;setDependencies($deps); </code></pre> <p><code>ObjectManager</code> uses singleton pattern so I can use the same object throughout the flow</p> <pre><code>// mainfile.php use DependencyClassInterface; use AnotherClass; Class DependentClass { protected $depClass; public function __construct(DependencyClassInterface $depclass, AnotherClass $another) { $this-&gt;depClass = $depClass; } public function doSomething() { echo "Something"; } } ObjectManager::getInstance() -&gt;get('DependentClass') -&gt;doSomething(); </code></pre> <p>And finally the implementation of Dependency Resolver.</p> <pre><code>&lt;?php class ObjectManager { protected $dependencies; protected static $omInstance; public static function getInstance() { if (!self::$omInstance) { self::$omInstance = new ObjectManager(); } return self::$omInstance; } public function setDependencies(array $dependencies) { $this-&gt;dependencies = $dependencies; } public function getDependencies() { return $this-&gt;dependencies; } public function get($class) { $finalizedParams = array(); $deps = array(); // check if deps are defined if (array_key_exists($class, $this-&gt;dependencies)) { $deps = $this-&gt;dependencies[$class]; } $reflector = new ReflectionClass($class); if (!$reflector-&gt;isInstantiable()) { throw new Exception("Class {$class} is not instantiable"); } $constructor = $reflector-&gt;getConstructor(); if ($constructor == null) { return $reflector-&gt;newInstance(); } $parameters = $constructor-&gt;getParameters(); foreach ($parameters as $key =&gt; $parameter) { $parameterType = $this-&gt;getParameterType($parameter); $parameterName = $parameter-&gt;getName(); if ($parameterType == null) { if ($parameter-&gt;isDefaultValueAvailable()) { $finalizedParams[$key] = $parameter-&gt;getDefaultValue(); } else { throw new Exception(" Failed resolving argument (dependency) \"$parameterName\" for class $class. Not directly instantiatable. No default value specified."); } continue; } $classReflection = new ReflectionClass($parameterType); // if dep is directly instantiable; save and continue if ($classReflection-&gt;isInstantiable()) { $finalizedParams[$key] = $classReflection-&gt;newInstance(); continue; } // if defined in di.php if (array_key_exists($parameterName, $deps)) { $argName = $deps[$parameterName]; $finalizedParams[$key] = ObjectManager::getInstance()-&gt;get($argName); continue; } } return $reflector-&gt;newInstanceArgs($finalizedParams); } protected function getParameterType(ReflectionParameter $parameter) { $export = ReflectionParameter::export( array( $parameter-&gt;getDeclaringClass()-&gt;name, $parameter-&gt;getDeclaringFunction()-&gt;name, ), $parameter-&gt;name, true ); return preg_match('/[&gt;] ([A-z]+) /', $export, $matches) ? $matches[1] : null; } } </code></pre> <p>Hopefully, you got the idea. It might be an overkill to resolve dependencies this way, but I like the option of an Object Manager being able to do that.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-05T11:24:39.503", "Id": "205008", "Score": "1", "Tags": [ "php", "dependency-injection", "reflection" ], "Title": "Dependency resolver in PHP" }
205008
<p>I am using VS 2017 with C++ 17 standard set on Windows OS. What I'm missing in couple of heavily threaded projects is synchronizing mechanism that can be atomically upgraded from shared to exclusive access, without releasing the shared lock. Using <a href="https://www.boost.org/doc/libs/1_58_0/doc/html/thread/synchronization.html#thread.synchronization.mutex_concepts.upgrade_lockable" rel="nofollow noreferrer" title="boost">boost</a> is not an option for me (another topic is why), so I decided to develop a very light solution by myself. Below implementation works fine in my tests, but I thought I should post it here, cause someone may see or realize something I haven't, or use it in their own projects.</p> <pre><code>#include &lt;Windows.h&gt; #include &lt;exception&gt; #include &lt;atomic&gt; namespace rip_parallel { // Class upgrade_mutex. // Used as a synchronization mutex for upgrade_lock class upgrade_mutex { public: // Constructs upgrade_mutex object. upgrade_mutex(void) noexcept : m_readers(0), m_upgraders(0) { InitializeSRWLock(&amp;m_sharedlock); m_mutex = CreateMutex(nullptr, FALSE, nullptr); // We need synchronization event as a barrier that will be set by the owner of shared lock once it needs upgrade. m_readevent = CreateEvent(nullptr, TRUE, TRUE, nullptr); } // Destroys upgrade_mutex object. ~upgrade_mutex(void) { // Once the object is marked for destruction - set the event and close the handle. SetEvent(m_readevent); CloseHandle(m_readevent); } // Acquires shared access over the lock. Suspends the calling thread until lock is obtained. void lock_shared(void) { // Request READ access. AcquireSRWLockShared(&amp;m_sharedlock); // Once acquired, increment readers count. m_readers++; } // Releases shared access over the lock. void unlock_shared(void) { // Release READ access. ReleaseSRWLockShared(&amp;m_sharedlock); // Once released, decrement readers count. m_readers--; } // Acquires exclusive access over the lock. Suspends the calling thread until lock is obtained. void lock(void) { // Request WRITE access. AcquireSRWLockExclusive(&amp;m_sharedlock); } // Releases exclusive access over the lock. void unlock(void) { // Release WRITE access. ReleaseSRWLockExclusive(&amp;m_sharedlock); } // Waits until shared access over the lock is disabled. void wait_read(void) { // Each thread that wants READ access, has to wait for read to be enabled first. // This will enable the thread that wants to acquire upgraded lock to disable further readers while upgrade is active. // Writers are not involved in this wait mechanism, cause once at least one thread has shared access, writers are suspended. // Wait infinite. WaitForSingleObject(m_readevent, INFINITE); } // Enables shared access over the lock. void enable_read(void) { // Since current thread has upgraded access type, we have to update readers count, since it'll be decremented in unlock_shared. m_readers++; // We have to keep track of upgraders count, in order to enable read ONLY once all upgarders have completed. m_upgraders--; if (m_upgraders == 0) { // Once all upgraders have completed W operation, enable readers. SetEvent(m_readevent); } } // Disables shared access over the lock. void disable_read(void) { // The thread that wants to upgrade access, has to disable further read access. // It has to reset the event and disable other threads to reach acquiring mutex - otherwise we would deadlock. if (m_upgraders == 0) { // If there are no other upgraders at the moment - reset the event. Otherwise, it's already in non-signaled state. ResetEvent(m_readevent); } // Since current thread is upgrading access type, we have to reduce readers count. m_readers--; // We have to keep track of upgraders count, in order to enable read ONLY once all upgarders have completed. m_upgraders++; } // Returns active readers count. int readers_count(void) { // Getactual readers count. return m_readers; } // Synchronizes all threads that are requesting upgrade in between, by allowing one writer at a time. void upgrade(void) { // Once we have upgraded our state, we need to acquire exclusive access. WaitForSingleObject(m_mutex, INFINITE); } // Synchronizes all threads that are requesting upgrade in between, by allowing one writer at a time. void downgrade(void) { // Once we have completed exclusive operation we have to release exclusive access. ReleaseMutex(m_mutex); } private: SRWLOCK m_sharedlock; HANDLE m_mutex; HANDLE m_readevent; volatile std::atomic&lt;int&gt; m_readers; volatile std::atomic&lt;int&gt; m_upgraders; }; enum upgrade_lock_state { defer_state = 0, shared_state = 1, exclusive_state = 2, upgrade_state = 3 }; class upgrade_lock { public: upgrade_lock(upgrade_mutex&amp; ref_mutex, upgrade_lock_state initial_state = defer_state) : m_mutex(ref_mutex), m_state(defer_state) { switch (initial_state) { case rip_parallel::shared_state: lock_shared(); break; case rip_parallel::exclusive_state: case rip_parallel::upgrade_state: lock_unique(); break; } } ~upgrade_lock(void) { unlock(); } public: upgrade_lock(const upgrade_lock&amp;) = delete; upgrade_lock(upgrade_lock&amp;&amp;) = delete; public: upgrade_lock&amp; operator=(const upgrade_lock&amp;) = delete; upgrade_lock&amp; operator=(upgrade_lock&amp;&amp;) = delete; public: void unlock(void) { switch (m_state) { case rip_parallel::shared_state: m_mutex.unlock_shared(); m_state = defer_state; break; case rip_parallel::exclusive_state: m_mutex.unlock(); m_state = defer_state; break; case rip_parallel::upgrade_state: m_mutex.downgrade(); m_mutex.enable_read(); m_mutex.unlock_shared(); m_state = defer_state; break; } } void lock_unique(void) { if (m_state == rip_parallel::exclusive_state) { return; } if (m_state != rip_parallel::defer_state) { throw std::exception("While trying to acquire unique lock, invalid state of upgrade_lock found. State was: " + m_state); } m_mutex.lock(); m_state = rip_parallel::exclusive_state; } void lock_shared(void) { if (m_state == rip_parallel::shared_state) { return; } if (m_state != rip_parallel::defer_state) { throw std::exception("While trying to acquire shared lock, invalid state of upgrade_lock found. State was: " + m_state); } m_mutex.wait_read(); m_mutex.lock_shared(); m_state = rip_parallel::shared_state; } void lock_upgrade(void) { if (m_state == upgrade_state) { return; } else if (m_state == exclusive_state) { throw std::exception("While trying to upgrade shared lock, invalid state of upgrade_lock found. State was: " + m_state); } else if (m_state == defer_state) { m_mutex.lock_shared(); } m_state = rip_parallel::upgrade_state; m_mutex.disable_read(); while (m_mutex.readers_count()) { Sleep(10); } m_mutex.upgrade(); // DO THE JOB } private: upgrade_mutex&amp; m_mutex; upgrade_lock_state m_state; }; }; // one use case.. using namespace rip_parallel; upgrade_mutex g_mutex; #include &lt;chrono&gt; #include &lt;thread&gt; void Read(void) { upgrade_lock lock(g_mutex, upgrade_lock_state::shared_state); // DO WORK std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } void Write(void) { upgrade_lock lock(g_mutex); lock.lock_unique(); // DO WORK std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } void ReadWrite(void) { upgrade_lock lock(g_mutex, upgrade_lock_state::shared_state); // DO SHARED WORK std::this_thread::sleep_for(std::chrono::milliseconds(500)); lock.lock_upgrade(); // DO EXCLUSIVE WORK std::this_thread::sleep_for(std::chrono::milliseconds(500)); } int main() { std::thread t1(Read); std::thread t2(Write); std::thread t3(ReadWrite); std::thread t4(Read); std::thread t5(Read); std::thread t6(ReadWrite); std::thread t7(Read); std::thread t8(ReadWrite); std::thread t9(Write); std::thread t10(Read); t1.join(); t2.join(); t3.join(); t4.join(); t5.join(); t6.join(); t7.join(); t8.join(); t9.join(); t10.join(); return 0; } </code></pre> <p>Once a thread that already owns shared lock wants to upgrade, it needs to reset event (set a barrier) to prevent any future shared lock acquisition. Then it needs to spin/sleep while all current readers release the shared lock. All readers that currently holds the shared lock upon releasing it will decrement readers count and once count reaches zero, that's the moment when all upgraders can proceed. We'll use another mutex to synchronize exclusive access between upgraders - and basically that's it.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-26T11:32:53.117", "Id": "398057", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where y...
[ { "body": "<h2>The constructor of <code>upgrade_lock</code> never locks the mutex</h2>\n\n<p>When constructing an <code>upgrade_lock</code> variable, the constructor sets <code>m_state = initial_state</code> before calling either <code>lock_shared()</code> or <code>lock_unique()</code>. In the latter two functi...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-05T11:27:09.973", "Id": "205009", "Score": "4", "Tags": [ "c++", "multithreading", "thread-safety", "locking", "winapi" ], "Title": "C++ upgradable RW lock implementation" }
205009
<p>We are using Keycloak v4.4.0 as SSO for multiple microservices and SPAs. The main goal is to prevent user entering his credentials when landing to another SPA UI. </p> <p>I've not worked with such authentication mechanism before, so I'm trying to use all its features. </p> <p>This js module is compiled via webpack. <code>decodeToken</code> function taken from keycloak-js sources.</p> <pre><code>import Axios from "axios"; import * as Keycloak from '../../node_modules/keycloak-js'; export const apiClient = Axios.create({}); const tokenStoreName = 'keycloak.token', refreshTokenStoreName = 'keycloak.refreshToken', timeSkewStoreName = 'keycloak.timeSkew '; var _keycloakInstance: Keycloak.KeycloakInstance; function decodeToken(str) { str = str.split('.')[1]; str = str.replace('/-/g', '+'); str = str.replace('/_/g', '/'); switch (str.length % 4) { case 0: break; case 2: str += '=='; break; case 3: str += '='; break; default: throw 'Invalid token'; } str = (str + '===').slice(0, str.length + (str.length % 4)); str = str.replace(/-/g, '+').replace(/_/g, '/'); str = decodeURIComponent(escape(atob(str))); str = JSON.parse(str); return str; } function checkRefreshTokenExpired(refreshTokenParsed){ let nowInSeconds = new Date().getTime()/1000; return nowInSeconds &gt;= refreshTokenParsed.exp // refresh token expired } function automaticTokenRefresh(){ let refreshAfter = Math.round((_keycloakInstance.tokenParsed.exp - new Date().getTime()/1000) - 25); if(refreshAfter &lt; 0) refreshAfter = 1; setTimeout(async () =&gt; { _tokenResolver.state = 0; await _tokenResolver.getToken(); automaticTokenRefresh(); }, refreshAfter*1000) } export function init(state){ return new Promise(function(resolve, reject){ let globalSettings = state.globalSettings; _keycloakInstance = Keycloak({ url: globalSettings.idp.baseUrl, realm: globalSettings.idp.realm, clientId: globalSettings.serviceName, }); let isIe = document['documentMode'] || /Edge/.test(navigator.userAgent); let token = localStorage.getItem(tokenStoreName); if(token === null || token === 'undefined') token = undefined; let refreshToken = localStorage.getItem(refreshTokenStoreName); if(refreshToken === null || refreshToken === 'undefined') refreshToken = undefined; let timeSkewString = localStorage.getItem(timeSkewStoreName); let timeSkew = undefined; if(timeSkewString === null || timeSkewString === 'NaN') timeSkew = undefined; else timeSkew = Number.parseInt(timeSkewString); if(Number.isNaN(timeSkew)) timeSkew = undefined; if(refreshToken){ let refreshTokenParsed = decodeToken(refreshToken); if(!refreshTokenParsed || !refreshTokenParsed.exp || checkRefreshTokenExpired(refreshTokenParsed)){ token = undefined; refreshToken = undefined; timeSkew = undefined; clearTokenData(); } } _keycloakInstance['onAuthLogout'] = function(){ clearTokenData(); } _keycloakInstance.init({onLoad: 'login-required', token, refreshToken, timeSkew, checkLoginIframe: !isIe}).success(function(authenticated){ storeTokenData(); if(!authenticated || !_keycloakInstance.token || _keycloakInstance.token == 'undefined') { logout(); return; } automaticTokenRefresh(); apiClient.interceptors.request.use(async function(config){ // before request let tokenData; try{ tokenData = await _tokenResolver.getToken(); // get current token } catch(error) { logout(); return Promise.reject(error); } if(!tokenData) { logout(); return Promise.reject(); } config.headers['Authorization'] = 'Bearer ' + tokenData; // set request auth token return config; }, (error) =&gt; { logout(); return Promise.reject(error); }); apiClient.interceptors.response.use(function(response) { return response; },async (error) =&gt; { if(error === undefined) return Promise.reject({message: 'error is undefined'}); const originalRequest = error.config; if(error.response &amp;&amp; error.response.status === 401 &amp;&amp; !originalRequest._retry){ // if response is unathorized, and first attempt originalRequest._retry = true; _tokenResolver.state = 0; let tokenData = await _tokenResolver.getToken(); // get current token if(!tokenData) return Promise.reject(error) originalRequest.headers['Authorization'] = 'Bearer ' + tokenData.access_token; return apiClient(originalRequest); // retry } return Promise.reject(error); } ); resolve(); }).error(function(){ reject(); }); }); } function storeTokenData(){ localStorage.setItem(tokenStoreName, _keycloakInstance.token); localStorage.setItem(refreshTokenStoreName, _keycloakInstance.refreshToken); localStorage.setItem(timeSkewStoreName, _keycloakInstance.timeSkew.toString()); } function clearTokenData(){ localStorage.removeItem(tokenStoreName); localStorage.removeItem(refreshTokenStoreName); localStorage.removeItem(timeSkewStoreName); } export function logout(){ clearTokenData(); _keycloakInstance.logout(); } const _tokenResolver = { state: 2, promise: undefined, result: undefined, getToken: async function(){ if(!this.result) // init data this.result = _keycloakInstance.token; if(!this.result) return Promise.reject('keycloakInstance.token is empty'); if(_keycloakInstance.isTokenExpired(0)) // token expired. Need to refresh this.state = 0; if(this.state === 0){ this.state = 1; let that = this; this.promise = new Promise(function(resolve, reject){ return _keycloakInstance.updateToken(-1) // refresh token .success(function(refreshed){ storeTokenData(); that.result = _keycloakInstance.token; that.state = 2; // set state to resolved resolve(that.result) }).error(function(){ reject('Failed to refresh the token, or the session has expired'); }); }) return this.promise; } else if(this.state === 1) return this.promise; else if(this.state === 2) return Promise.resolve(this.result); } } </code></pre> <p>Function <code>init</code> is called once at application start. <code>state</code> object is passed outside and retrieved from API. <code>isIe</code> variable is created to prevent keycloak to use LoginIframe when browser is Internet Explorer or Edge, because bug with infinite refresh is reproducing and not fixed.</p> <p>I'm saving values of token, <code>refreshtoken</code> and <code>timeskew</code> in local storage to prevent resetting session and need to login again if browser was closed. But also I'm checking if refresh token isn't expired. </p> <p>On success keycloak init I'm triggering automatic forced token refresh and setting up my axios instance interceptors. Adding <code>Bearer</code> value to <code>Authorization</code> header and handling 401 error code on each response. </p> <p>I'm wrapped all work with token in single place - <code>tokenResolver</code>. It helps prevent simultaneous requests to refresh token if it is expired and multiple clients try to make requests to API.</p> <p>The code works as expected. How this code can be improved in terms of authentication? And in terms of keycloak js adapter best usage? </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-05T11:53:46.973", "Id": "205012", "Score": "2", "Tags": [ "javascript", "authentication" ], "Title": "Keycloak js adapter" }
205012
<p>Made some adjustments to the previous code thanks to the helpful and thoughtful review by @G.Sliepen.</p> <p>Problem statement: This program should ask for the total number of shops that will be visited. At each shop, ask for the number of ingredients that need to be purchases. For each ingredient, ask for the price. Keep track of the total for the order so that you can write it down before leaving the shop. This program should also track with order was the cheapest and which shop the cheapest order was at.</p> <p>Original code: <a href="https://codereview.stackexchange.com/questions/204855/find-the-cheapest-order-placed-out-of-all-of-the-stores-visited/204868?noredirect=1#comment395217_204868">Find the cheapest order placed out of all of the stores visited</a></p> <p>1st adjustments to the original code: <a href="https://codereview.stackexchange.com/questions/204932/adjustments-based-on-reviews-1-find-the-cheapest-order-placed-out-of-all-of-th/204977#204977">Adjustments based on reviews #1; Find the cheapest order placed out of all of the stores visited</a></p> <p>Any and all hints, tips, tricks, advice, suggestions are greatly appreciated!</p> <p><a href="https://i.stack.imgur.com/PSWvv.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PSWvv.jpg" alt="enter image description here"></a></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdbool.h&gt; int read_positive_int(const char* prompt) { printf("%s", prompt); int n; while (true) { if (scanf("%d", &amp;n) != 1) { fprintf(stderr, "Invalid input!\n"); return 1; } return n; } } float read_real_positive(const char* prompt) { printf("%s", prompt); float m; while (true) { if (scanf("%f", &amp;m) != 1) { fprintf(stderr, "Invalid input!\n"); return 1; } return m; } } int main(void) { int num_shops = read_positive_int("How many shops will be visited? "); float total_cost[num_shops]; float cheapest_order; int cheapest_shop = 1; for (int i = 0; i &lt; num_shops; i++) { printf("You are at shop #%d.\n", i+1); int num_ingredients = read_positive_int("How many ingredients are needed? "); float cost_ingredient[num_ingredients]; total_cost[i] = 0; for (int j = 0; j &lt; num_ingredients; j++) { printf("What is the cost of ingredient #%d", j+1); cost_ingredient[j]= read_real_positive("? "); total_cost[i] += cost_ingredient[j]; } printf("The total cost at shop #%d is $%.2f.\n", i+1, total_cost[i]); if (i == num_shops - 1) { cheapest_order = total_cost[0]; for (int k = 1; k &lt; num_shops; k++) { if (total_cost[k] &lt; cheapest_order) { cheapest_order = total_cost[k]; cheapest_shop = k + 1; } } } } printf("The cheapest order was at shop #%d, and the total cost of the order was $%0.2f\n", cheapest_shop, cheapest_order); return 0; }![enter image description here](https://i.stack.imgur.com/GcAtS.jpg) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-05T14:19:47.127", "Id": "395475", "Score": "0", "body": "Have you tested this? It doesn't seem correct to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-05T14:28:33.010", "Id": "395481", "Scor...
[ { "body": "<p>I see some things that may help you further improve your program.</p>\n\n<h2>Eliminate arrays by carefully rethinking the problem</h2>\n\n<p>At the end of the program, all that is needed is the <code>cheapest_order</code> and the <code>cheapest_shop</code>. All of the arrays could be eliminated b...
{ "AcceptedAnswerId": "205022", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-05T12:53:03.640", "Id": "205015", "Score": "1", "Tags": [ "c" ], "Title": "Find the cheapest order placed out of all of the stores visited - follow-up #2" }
205015
<p>I was wondering if someone could help critique this code I put together. It is supposed to delete all temp files and folders and then empty the recycle bin. I had to make some adjustments because using <code>Pyinstaller</code>, I wanted the console to stay open and have the user proceed after reading.</p> <pre><code>import os file_size = os.path.getsize('C:\Windows\Temp') print(str(file_size) + "kb of data will be removed") import os, subprocess del_dir = r'c:\windows\temp' pObj = subprocess.Popen('rmdir /S /Q %s' % del_dir, shell=True, stdout = subprocess.PIPE, stderr= subprocess.PIPE) rTup = pObj.communicate() rCod = pObj.returncode if rCod == 0: print('Success: Cleaned Windows Temp Folder') else: print('Fail: Unable to Clean Windows Temp Folder') import winshell winshell.recycle_bin().empty(confirm=False, show_progress=False, sound=False) from random import randint from time import sleep sleep(randint(4,6)) input("Press any key to continue") </code></pre>
[]
[ { "body": "<p>I'm not sure this answer will be sufficient, but some quick things that jump out:</p>\n\n<ul>\n<li>Keep your code organized:\n\n<ul>\n<li>Put imports at the top</li>\n<li><a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">Guard any serious code execution in a <code>__...
{ "AcceptedAnswerId": "205019", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-05T13:16:55.970", "Id": "205016", "Score": "0", "Tags": [ "python", "python-3.x", "file-system", "windows" ], "Title": "Delete temp files and empty recycle bin" }
205016
<p>I have a file of <code>SQL</code> (actually <code>HiveQL</code>) queries terminated by semicolon (<code>;</code>). I need to obtain a list of formatted queries from this file. Formatting includes replacing multiple spaces with single one and removing extra spaces in cases like <code>'( ', ' )', ' ,'</code>. So, the following is my approach and it looks monstrous:</p> <pre><code>fdHql = open(args.hql, 'r') hql_file = fdHql.read() fdHql.close() queries = [re.sub('\s+', ' ', each.replace('\n', ' ').strip()).replace('( ', '(').replace(' )', ')').replace(' ,', ',') for each in hql_file.split(';')] </code></pre> <p>Is there a better way to implement same behavior?</p>
[]
[ { "body": "<p>You can eliminate the <code>.close()</code> using a <code>with ... as ...:</code> statement.</p>\n\n<p>Since newlines are white-space characters, <code>re.sub('\\s+', ' ', ...)</code> will already convert any <code>'\\n'</code> characters to a space, so the <code>.replace('\\n', ' ')</code> is unn...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-05T15:03:07.993", "Id": "205020", "Score": "0", "Tags": [ "python", "python-3.x", "strings" ], "Title": "Formatting list of queries in python" }
205020
<p>Today I have written my first implementation of a SkipList (on top of a <code>std::vector</code>), because I was tired in using <code>std::lower_bound</code> and the other functions manually. I tried to create it as generic as possible to provide the user as much freedom as healthy. During the implementation I always had an eye on the <code>std::set</code> and <code>std::multiset</code> documentations, to keep the interface similar to those.</p> <p>At first I decided to hide the non-const iterators from the public interface to prevent the <code>SkipList</code> from getting manipulated on accident, but after the first iteration the usage it was very inelegant. At latest when you tried to use just one property of the <code>value_type</code> Objects as key it revealed its weaknesses.To change any of the other variables of that element I had to remove it first and insert it again afterwards. That was neither good, clean or elegant; that's the reason why I decided to expose the non-const-iterators, too. Btw, <code>std::set</code> and <code>std::multiset</code> expose them, too, thus it shouldn't be a huge surprise for the user of that classes.</p> <p>Here is the code for both, the <code>SkipList</code> (unique elements) and the <code>MultiSkipList</code>.</p> <pre><code>#include &lt;vector&gt; #include &lt;algorithm&gt; #include &lt;iterator&gt; namespace detail { template &lt;class T, bool UniqueElements, class Compare = std::less&lt;&gt;, class Container = std::vector&lt;T&gt;&gt; class BaseSkipList { public: using container_type = Container; using value_type = typename Container::value_type; using size_type = typename Container::size_type; using iterator = typename Container::iterator; using reverse_iterator = typename Container::reverse_iterator; using const_iterator = typename Container::const_iterator; using const_reverse_iterator = typename Container::const_reverse_iterator; BaseSkipList() = default; explicit BaseSkipList(Compare&amp;&amp; _compare) : m_Compare(std::move(_compare)) {} explicit BaseSkipList(Container _container, Compare&amp;&amp; _compare = Compare()) : m_Container(std::move(_container)), m_Compare(std::move(_compare)) { std::sort(std::begin(m_Container), std::end(m_Container), m_Compare); } BaseSkipList(const BaseSkipList&amp;) = default; BaseSkipList(BaseSkipList&amp;&amp;) = default; BaseSkipList&amp; operator =(const BaseSkipList&amp;) = default; BaseSkipList&amp; operator =(BaseSkipList&amp;&amp;) = default; bool empty() const { return std::empty(m_Container); } size_type size() const { return std::size(m_Container); } void clear() { m_Container.clear(); } void reserve(size_type _new_cap) { m_Container.reserve(_new_cap); } size_type capacity() const noexcept { return m_Container.capacity(); } void shrink_to_fit() { return m_Container.shrink_to_fit(); } template &lt;class TValueType&gt; std::pair&lt;iterator, bool&gt; insert(TValueType&amp;&amp; _value) { return _insert(begin(), std::forward&lt;TValueType&gt;(_value)); } template &lt;class TIterator&gt; void insert(TIterator _itr, const TIterator&amp; _end) { for (; _itr != _end; ++_itr) _insert(*_itr); } void insert(std::initializer_list&lt;value_type&gt; _ilist) { insert(std::begin(_ilist), std::end(_ilist)); } iterator erase(const_iterator _itr) { return m_Container.erase(_itr); } iterator erase(const_iterator _first, const_iterator _last) { return m_Container.erase(_first, _last); } template &lt;class TComparable&gt; iterator erase(const TComparable&amp; _value) { auto itr = std::lower_bound(std::begin(m_Container), std::end(m_Container), _value, m_Compare); if (itr != end()) return m_Container.erase(itr); return end(); } template &lt;class TComparable&gt; iterator find(const TComparable&amp; _value) { return _find(m_Container, m_Compare, _value); } template &lt;class TComparable&gt; const_iterator find(const TComparable&amp; _value) const { return _find(m_Container, m_Compare, _value); } template &lt;class TComparable&gt; iterator lower_bound(const TComparable&amp; _value) { return _lower_bound(m_Container, m_Compare, _value); } template &lt;class TComparable&gt; const_iterator lower_bound(const TComparable&amp; _value) const { return _lower_bound(m_Container, m_Compare, _value); } template &lt;class TComparable&gt; iterator upper_bound(const TComparable&amp; _value) { return _upper_bound(m_Container, m_Compare, _value); } template &lt;class TComparable&gt; const_iterator upper_bound(const TComparable&amp; _value) const { return _upper_bound(m_Container, m_Compare, _value); } template &lt;class TComparable&gt; bool contains(const TComparable&amp; _value) const { return find(_value) != end(); } /*##### # multi element stuff #####*/ template &lt;class TComparable, typename = std::enable_if_t&lt;!UniqueElements&gt;&gt; std::pair&lt;iterator, iterator&gt; equal_range(const TComparable&amp; _value) { return _equal_range(m_Container, m_Compare, _value); } template &lt;class TComparable, typename = std::enable_if_t&lt;!UniqueElements&gt;&gt; std::pair&lt;const_iterator, const_iterator&gt; equal_range(const TComparable&amp; _value) const { return _equal_range(m_Container, m_Compare, _value); } template &lt;class TComparable, typename = std::enable_if_t&lt;!UniqueElements&gt;&gt; iterator find_last(const TComparable&amp; _value) { return _find_last(m_Container, m_Compare, _value); } template &lt;class TComparable, typename = std::enable_if_t&lt;!UniqueElements&gt;&gt; const_iterator find_last(const TComparable&amp; _value) const { return _find_last(m_Container, m_Compare, _value); } template &lt;class TComparable, typename = std::enable_if_t&lt;!UniqueElements&gt;&gt; iterator erase_all_of(const TComparable&amp; _value) { auto range = _equal_range(m_Container, m_Compare, _value); return m_Container.erase(range.first, range.second); } template &lt;class TComparable, typename = std::enable_if_t&lt;!UniqueElements&gt;&gt; size_type count(const TComparable&amp; _value) const { auto range = _equal_range(m_Container, m_Compare, _value); return std::distance(range.first, range.second); } template &lt;class TValueType = value_type, typename = std::enable_if_t&lt;!UniqueElements&gt;&gt; void unique() { m_Container.erase(std::unique(std::begin(m_Container), std::end(m_Container), [&amp;compare = m_Compare](const auto&amp; _lhs, const auto&amp; _rhs) { return !compare(_lhs, _rhs) &amp;&amp; !compare(_rhs, _lhs); } ), end()); } /*##### # comparison stuff #####*/ bool operator ==(const BaseSkipList&amp; _other) const { return std::equal(begin(), end(), std::begin(_other), std::end(_other), [&amp;compare = m_Compare](const auto&amp; _elLhs, const auto&amp; _elRhs) { return !compare(_elLhs, _elRhs) &amp;&amp; !compare(_elRhs, _elLhs); } ); } friend bool operator !=(const BaseSkipList&amp; _lhs, const BaseSkipList&amp; _rhs) { return !(_lhs == _rhs); } bool operator &lt;(const BaseSkipList&amp; _other) const { return std::lexicographical_compare(begin(), end(), std::begin(_other), std::end(_other), m_Compare); } friend bool operator &gt;=(const BaseSkipList&amp; _lhs, const BaseSkipList&amp; _rhs) { return !(_lhs &lt; _rhs); } friend bool operator &gt;(const BaseSkipList&amp; _lhs, const BaseSkipList&amp; _rhs) { return _rhs &lt; _lhs; } friend bool operator &lt;=(const BaseSkipList&amp; _lhs, const BaseSkipList&amp; _rhs) { return !(_lhs &gt; _rhs); } /*##### # Iterator stuff #####*/ iterator begin() noexcept { return std::begin(m_Container); } const_iterator begin() const noexcept { return std::begin(m_Container); } const_iterator cbegin() const noexcept { return std::cbegin(m_Container); } iterator end() noexcept { return std::end(m_Container); } const_iterator end() const noexcept { return std::end(m_Container); } const_iterator cend() const noexcept { return std::cend(m_Container); } iterator rbegin() noexcept { return std::rbegin(m_Container); } const_reverse_iterator rbegin() const noexcept { return std::rbegin(m_Container); } const_reverse_iterator crbegin() const noexcept { return std::crbegin(m_Container); } iterator rend() noexcept { return std::rend(m_Container); } const_reverse_iterator rend() const noexcept { return std::rend(m_Container); } const_reverse_iterator crend() const noexcept { return std::crend(m_Container); } private: Container m_Container; Compare m_Compare; template &lt;class TValueType&gt; std::pair&lt;iterator, bool&gt; _insert(TValueType&amp;&amp; _value) { auto itr = _lower_bound(m_Container, m_Compare, _value); if constexpr (UniqueElements) { if (itr == end() || m_Compare(_value, *itr)) { m_Container.insert(itr, std::forward&lt;TValueType&gt;(_value)); return { itr, true }; } } else { m_Container.insert(itr, std::forward&lt;TValueType&gt;(_value)); return { itr, true }; } return { itr, false }; } template &lt;class TContainer, class TCompare, class TComparable&gt; static auto _find(TContainer&amp;&amp; _container, TCompare&amp;&amp; _compare, const TComparable&amp; _value) { auto itr = _lower_bound(_container, _compare, _value); if (itr != std::end(_container) &amp;&amp; !_compare(_value, *itr)) return itr; return std::end(_container); } template &lt;class TContainer, class TCompare, class TComparable&gt; static auto _find_last(TContainer&amp;&amp; _container, TCompare&amp;&amp; _compare, const TComparable&amp; _value) { auto range = _equal_range(_container, _compare, _value); auto dist = std::distance(range.first, range.second); if (0 &lt; dist) { std::advance(range.first, dist - 1); return range.first; } return std::end(_container); } template &lt;class TContainer, class TCompare, class TComparable&gt; static auto _lower_bound(TContainer&amp;&amp; _container, TCompare&amp;&amp; _compare, const TComparable&amp; _value) { return std::lower_bound(std::begin(_container), std::end(_container), _value, _compare); } template &lt;class TContainer, class TCompare, class TComparable&gt; static auto _upper_bound(TContainer&amp;&amp; _container, TCompare&amp;&amp; _compare, const TComparable&amp; _value) { return std::upper_bound(std::begin(_container), std::end(_container), _value, _compare); } template &lt;class TContainer, class TCompare, class TComparable&gt; static auto _equal_range(TContainer&amp;&amp; _container, TCompare&amp;&amp; _compare, const TComparable&amp; _value) { return std::equal_range(std::begin(_container), std::end(_container), _value, _compare); } }; } // namespace detail template &lt;class T, class Compare = std::less&lt;&gt;, class Container = std::vector&lt;T&gt;&gt; using SkipList = detail::BaseSkipList&lt;T, true, Compare, Container&gt;; template &lt;class T, class Compare = std::less&lt;&gt;, class Container = std::vector&lt;T&gt;&gt; using MultiSkipList = detail::BaseSkipList&lt;T, false, Compare, Container&gt;; </code></pre> <p>Here is a simple example program; please be aware, that in the second example the member <code>x</code> of the <code>Test</code> objects is used as key. We can search for concrete objects or simply key values.</p> <pre><code>int main() { SkipList&lt;int&gt; ints({ 3, 4, 1, 2 }); auto intItr = ints.find(1); // intItr = ints.find_last(5); // not available for SkipLists ints.insert({ 5, 2, 3, 10, 0 }); ints.erase(4); struct TestCompare { bool operator ()(const Test&amp; _lhs, const Test&amp; _rhs) const { return _lhs.x &lt; _rhs.x; } bool operator ()(const Test&amp; _lhs, int _rhs) const { return _lhs.x &lt; _rhs; } bool operator ()(int _lhs, const Test&amp; _rhs) const { return _lhs &lt; _rhs.x; } }; MultiSkipList&lt;Test, TestCompare&gt; tests({ { 3 }, { 4 }, { 1 }, { 2 }, { 2 } }); auto testItr = tests.find(2); testItr = tests.find_last(2); if (testItr == tests.find_last(Test{ 2 })) tests.unique(); // that line removes the second Test object with x == 2 auto count = tests.count(2); // there is only one element with x == 2 left tests.insert({ { 5}, { 2}, {3}, {10}, {0} }); // again 2 of x == 2 tests &lt;= tests; tests == tests; tests.erase_all_of(2); // all twos are gone } </code></pre>
[]
[ { "body": "<p>After a few days in use, I discovered a few mistakes and would like to share them to you. I also fixed a compile error in clang, because the MultiSkipList functions weren't disabled in a correct way.</p>\n\n<p>I still would like to receive some opinions about style, usability and correctness.</p>\...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-05T18:32:29.127", "Id": "205029", "Score": "1", "Tags": [ "c++", "template-meta-programming", "c++17", "skip-list" ], "Title": "Generic (Multi)SkipList adapter class" }
205029
<p>I was able to find all kinds of examples that demonstrate how to validate a Luhn Checksum but very few that actually generated the check digit. Here is my attempt in base 10, based on the validation examples found at <a href="https://en.wikipedia.org/wiki/Luhn_algorithm" rel="nofollow noreferrer">Wikipedia</a> and <a href="https://www.rosettacode.org/wiki/Luhn_test_of_credit_card_numbers" rel="nofollow noreferrer">Rosetta Code</a>:</p> <pre><code>/// &lt;summary&gt; /// Constructs the check digit for a given numeric string using the Luhn algorithm; also known as the "mod 10" algorithm. /// &lt;/summary&gt; /// &lt;param name="value"&gt;The string that a check digit will be calculated from.&lt;/param&gt; public static int Mod10(string value) { const int validCodePointCount = 10; const int validCodePointOffset = 48; var index = value.Length; var parity = true; var sum = 0; while (0 &lt; index--) { var digit = (value[index] - validCodePointOffset); if (parity) { if ((validCodePointCount - 1) &lt; (digit &lt;&lt;= 1)) { digit -= (validCodePointCount - 1); } } parity = !parity; sum += digit; } return ((validCodePointCount - (sum %= validCodePointCount)) % validCodePointCount); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-05T21:21:51.180", "Id": "395511", "Score": "0", "body": "The site you linked has c# code for the check digit (`Luhn.GetCheckValue`) : https://www.rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#C.23" }, { "ContentLicense"...
[ { "body": "<blockquote>\n<pre><code>const int validCodePointCount = 10;\nconst int validCodePointOffset = 48;\n</code></pre>\n</blockquote>\n\n<p>Constants should be written in PascalCase, whether it is <code>private</code> or local.</p>\n\n<blockquote>\n<pre><code>while (0 &lt; index--) {\nvar digit = (value[i...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-05T19:00:13.303", "Id": "205031", "Score": "4", "Tags": [ "c#", "algorithm", "checksum" ], "Title": "Calculating a Luhn Check Digit" }
205031
<p>I have a method, which outputs multiplication table sized by given maximum number. Also, it visually separates first row and column from the rest table. How my code could be improved or optimized? </p> <pre><code>public class Example { public static void main(String args[]) { printMultiplicationTable(15); } private static void printMultiplicationTable(int max) { for (var row = 1; row &lt;= max; row += 1) { if (row == 2) { for (var column = 2; column &lt;= max; column += 1) { System.out.print("----"); } System.out.println(); continue; } for (var column = 1; column &lt;= max; column += 1) { int result = row * column; if (column == 1) { if (row &lt; 10) { System.out.print(result + " |\t"); } else { System.out.print(result + "|\t"); } } else { System.out.print(result + "\t"); } } System.out.println(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-05T20:00:57.530", "Id": "395507", "Score": "0", "body": "You don't care about the 2x row? Maybe you don't want to `continue` if row == 2." } ]
[ { "body": "<p>When I run your code I see:</p>\n\n<pre><code>1 | 2 3 4 5 6 7 8 9 10 11 12 13 14 15\n--------------------------------------------------------\n3 | 6 9 12 15 18 21 24 27 30 ...
{ "AcceptedAnswerId": "205037", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-05T19:17:13.260", "Id": "205032", "Score": "0", "Tags": [ "java", "console" ], "Title": "Console output of multiplication table" }
205032
<p>This is my first bigger than a few lines bash script.</p> <p>It automates kernel updating and removing on Ubuntu through <code>ukuu</code> (Ubuntu kernel update utility).</p> <p>I'm not yet familiar with all the bells and whistles of GNU utilities and want to strive for clarity. The only thing I know now is <code>grep -P</code> and everything seems like a nail if you have a hammer. Also this is mostly stitched from examples on StackExchange.</p> <p>What would you change to make the code more readable or perhaps better in some other ways?</p> <pre><code>#!/bin/bash updateInstalledKernels () { # TODO (low priority) modify to not double-count kernels which have two "Installed" records in ukuu --list while read I do INSTALLED_KERNELS=( "${INSTALLED_KERNELS[@]}" "$I" ) done &lt; &lt;(printf "$AVAILABLE_KERNELS" | grep -oP 'v\d+\.\d+((\.\d+)|(-\w+))*(?=\s+[0-9.]*\s+(Installed|Running)\s*?\z)') } containsElement () { # usage: containsElement string element1 element2 ... local e match="$1" shift for e; do [[ "$e" == "$match" ]] &amp;&amp; return 0; done return 1 } FALLBACK_KERNELS=( 'v4.15.0-33.36' 'v4.15.0-30.32' ) # array of kernels for fallback echo "fallback kernels: ${FALLBACK_KERNELS[@]}" # TODO variable which chooses the number of latest kernels to keep AVAILABLE_KERNELS=$(ukuu --list) if ! echo "$AVAILABLE_KERNELS" | grep -oPzq 'Available Kernels.*?\n=+\n\K.*?(Installed|Running).*?\n'; then ukuu --install-latest else LATEST_KERNEL=$(echo "$AVAILABLE_KERNELS" | grep -oPz 'Available Kernels.*?\n=+\n\Kv.+?(?=\s.*?\n)') echo "Latest kernel ${LATEST_KERNEL} installed. Removing old kernels apart from ${FALLBACK_KERNELS[@]}." declare -a INSTALLED_KERNELS updateInstalledKernels echo "Installed kernels: ${INSTALLED_KERNELS[@]}." for INSTALLED_KERNEL in "${INSTALLED_KERNELS[@]}" do echo "$INSTALLED_KERNEL" if ! containsElement "$INSTALLED_KERNEL" "${FALLBACK_KERNELS[@]}" then if ! echo "$INSTALLED_KERNEL" | grep -q "$LATEST_KERNEL" then echo "${INSTALLED_KERNEL} is not fallback, nor latest. Removing it..." ukuu --remove "$INSTALLED_KERNEL" fi fi done &lt;&lt;&lt; "$INSTALLED_KERNELS" fi </code></pre>
[]
[ { "body": "<blockquote>\n <p>The only thing I know now is <code>grep -P</code> and everything seems like a nail if you have a hammer.</p>\n</blockquote>\n\n<p>I hope that's an exaggeration. Otherwise, I don't know how you will understand a review ;-)</p>\n\n<h3>Use more here-strings</h3>\n\n<p>The script uses ...
{ "AcceptedAnswerId": "205815", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-05T19:31:59.627", "Id": "205033", "Score": "2", "Tags": [ "bash", "linux", "installer" ], "Title": "Ubuntu kernel update and removal automation script" }
205033
<p>I've implemented the search/insert part of a hashtable in JavaScript. This is in linear probing style. It resizes when the array is out of space.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var share = { bucketSize: 10 }; function hash(key){ return key % share.bucketSize; } function expandArr(arr){ share.bucketSize = share.bucketSize * 2; let newArr = []; for(let i=0; i&lt;arr.length; i++){ let item = arr[i]; let key = item.key; hashInsert(key, item, newArr); } arr = newArr; } function hashInsert(key, data, arr){ let bucketKey = hash(key); let hasReset = false; let pointer = bucketKey; while(true){ if(pointer &gt;= share.bucketSize){ // bound check pointer = 0; hasReset = true; } if(pointer === bucketKey &amp;&amp; hasReset){ // all full expandArr(arr); bucketKey = hash(key); pointer = bucketKey; hasReset = false; } if(arr[pointer] === undefined){ // found space arr[pointer] = { key: key, data: data }; break; } pointer++; } } function hashSearch(key, arr){ let bucketKey = hash(key); let hasReset = false; let pointer = bucketKey; while(true){ if(pointer === bucketKey &amp;&amp; hasReset){ // complete cycle return undefined; } if(pointer &gt;= share.bucketSize){ // bound check pointer = 0; hasReset = true; } let curr = arr[pointer]; if(curr === undefined){ // not found return undefined; } if(curr.key === key){ // found it return curr; } pointer++; } } var arr = []; for(var i=0; i&lt;100; i++){ hashInsert(i, 'data ' + i, arr); console.log( hashSearch(i, arr) ); }</code></pre> </div> </div> </p>
[]
[ { "body": "<p>Looks good. I'm not sure what feedback you are looking for, but here's a little:</p>\n\n<ul>\n<li>use <code>const</code> where you can, instead of <code>let</code></li>\n<li>the naming is a little confusing at times, hash vs. key. Maybe if you call the <code>hash</code> function <code>calcHash</co...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-05T19:49:39.473", "Id": "205035", "Score": "1", "Tags": [ "javascript", "hash-map" ], "Title": "hashtable search in JavaScript" }
205035
<p>The task is to make a program that prints out how many possible paths a driver can use to visit three cities so that he visits each city exactly n times. The program must be executed within 1 minute and print the solution for n = 10. The program works correctly but for n above 7 it doesn't execute in time. Is there a way to get it to execute n=10 in time? These are some of the solutions: n = 1, the solution is 6, n = 2, the solution is 30, n = 3, the solution is 174 and n = 4, the solution is 1092.</p> <pre><code>#include&lt;iostream&gt; #include &lt;algorithm&gt; using namespace std; double paths (long long unsigned int path[],int n,double s,int e){ int r=0; do{ for(int i=0;i&lt;e-1;i++){ if(path[i]!=path[i+1]){ r++; } } if(r==e-1){ s++; } r=0; }while(next_permutation(path, (path+e))); return s; } int main(){ double s=0; int y=0; int buff=0; int n; cin&gt;&gt;n; int e=(n*3); long long unsigned int path[e]; while(y!=e){ for(int t=1;t&lt;=3;t++){ path[y]=t; y++; } }; bool test=false; for(int z=0;z&lt;e;z++){ for (int j =0; j&lt;e; j++){ if (path[j+1] &lt; path[j]){ buff=path[j]; path[j]=path[j+1]; path[j+1]=buff; test=true; } } if(!test){ break; }else{ test=false; } } cout&lt;&lt;"Number of posibilities: "&lt;&lt;paths(path,n,s,e)&lt;&lt;endl; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-05T21:35:58.197", "Id": "395512", "Score": "0", "body": "Why do you generate an array with '1,2,3' repeating in that order and then immediately bubble-sort it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-1...
[ { "body": "<p>Ignoring a potential mathematical solution to your problem (the requirement that two adjacent entries in the combination adds a wrinkle), the biggest problem here is when you are scanning <code>path</code> for identical adjacent members. You scan the entire array every time, counting the number o...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-05T20:49:43.787", "Id": "205036", "Score": "2", "Tags": [ "c++", "algorithm", "time-limit-exceeded", "combinatorics" ], "Title": "Counting paths between 3 cities in C++" }
205036
<p>I am creating an Idle game right now (tycoon style) which has 9 trains, (8 of them needed to be purchased), and 1 is always active, no matter if you just started the game.</p> <p>I was trying to create a simple code, but it got really really messy, so there's 8 buttons, that each one, should "instantiate" the train and the trail of it, and after you press the first button (the most left one) the one next to it (in the right side) should be interactable, and when they press that button the train&amp;mine on it should appear (right now I'm just using <code>gameobject.active = true</code>), after they "purchased" the trail&amp;train it should be always active (Using right now the playerprefs).</p> <pre><code>public class GameManager : MonoBehaviour { public Button[] Buttons; public GameObject TrainB, TrainC, TrainD, TrainE, TrainF, TrainG, TrainH, TrainI; public GameObject MineB, MineC, MineD, MineE, MineF, MineG, MineH, MineI; public Text text; public int CurrentTrainToSpawn = 0; private void Start() { } private void Update() { UpdateTrainPreFab(); } public void ButtonA() { int ButtonAChoosed = PlayerPrefs.GetInt("PressedButtonA", 0); if (ButtonAChoosed == 0) { Buttons[0].gameObject.active = false; TrainB.gameObject.active = true; MineB.gameObject.active = true; PlayerPrefs.SetInt("PressedButtonA", 1); } } public void ButtonB() { int ButtonBChoosed = PlayerPrefs.GetInt("PressedButtonB", 0); if (ButtonBChoosed == 0 &amp;&amp; PlayerPrefs.GetInt("PressedButtonA", 0) == 1) { Buttons[1].gameObject.active = false; TrainC.gameObject.active = true; MineC.gameObject.active = true; PlayerPrefs.SetInt("PressedButtonB", 1); } } public void ButtonC() { int ButtonCChoosed = PlayerPrefs.GetInt("PressedButtonC", 0); if (ButtonCChoosed == 0 &amp;&amp; PlayerPrefs.GetInt("PressedButtonB", 0) == 1) { Buttons[2].gameObject.active = false; TrainD.gameObject.active = true; MineD.gameObject.active = true; PlayerPrefs.SetInt("PressedButtonC", 1); } } public void ButtonD() { int ButtonDChoosed = PlayerPrefs.GetInt("PressedButtonD", 0); if (ButtonDChoosed == 0 &amp;&amp; PlayerPrefs.GetInt("PressedButtonC", 0) == 1) { Buttons[3].gameObject.active = false; TrainE.gameObject.active = true; MineE.gameObject.active = true; PlayerPrefs.SetInt("PressedButtonD", 1); } } public void ButtonE() { int ButtonEChoosed = PlayerPrefs.GetInt("PressedButtonE", 0); if (ButtonEChoosed == 0 &amp;&amp; PlayerPrefs.GetInt("PressedButtonD", 0) == 1) { Buttons[4].gameObject.active = false; TrainF.gameObject.active = true; MineF.gameObject.active = true; PlayerPrefs.SetInt("PressedButtonE", 1); } } public void ButtonF() { int ButtonFChoosed = PlayerPrefs.GetInt("PressedButtonF", 0); if (ButtonFChoosed == 0 &amp;&amp; PlayerPrefs.GetInt("PressedButtonE", 0) == 1) { Buttons[5].gameObject.active = false; TrainG.gameObject.active = true; MineG.gameObject.active = true; PlayerPrefs.SetInt("PressedButtonF", 1); } } public void ButtonG() { int ButtonGChoosed = PlayerPrefs.GetInt("PressedButtonG", 0); if (ButtonGChoosed == 0 &amp;&amp; PlayerPrefs.GetInt("PressedButtonF", 0) == 1) { Buttons[6].gameObject.active = false; TrainH.gameObject.active = true; MineH.gameObject.active = true; PlayerPrefs.SetInt("PressedButtonG", 1); } } public void ButtonH() { int ButtonHChoosed = PlayerPrefs.GetInt("PressedButtonH", 0); if (ButtonHChoosed == 0 &amp;&amp; PlayerPrefs.GetInt("PressedButtonG", 0) == 1) { Buttons[7].gameObject.active = false; TrainI.gameObject.active = true; MineI.gameObject.active = true; PlayerPrefs.SetInt("PressedButtonH", 1); } } public void UpdateTrainPreFab() { int ButtonAChoosed = PlayerPrefs.GetInt("PressedButtonA", 0); if (ButtonAChoosed == 1) { Buttons[0].gameObject.active = false; TrainB.gameObject.active = true; MineB.gameObject.active = true; PlayerPrefs.SetInt("PressedButtonA", 1); } int ButtonBChoosed = PlayerPrefs.GetInt("PressedButtonB", 0); if (ButtonBChoosed == 1 &amp;&amp; PlayerPrefs.GetInt("PressedButtonA", 0) == 1) { Buttons[1].gameObject.active = false; TrainC.gameObject.active = true; MineC.gameObject.active = true; PlayerPrefs.SetInt("PressedButtonB", 1); } int ButtonCChoosed = PlayerPrefs.GetInt("PressedButtonC", 0); if (ButtonCChoosed == 1 &amp;&amp; PlayerPrefs.GetInt("PressedButtonB", 0) == 1) { Buttons[2].gameObject.active = false; TrainD.gameObject.active = true; MineD.gameObject.active = true; PlayerPrefs.SetInt("PressedButtonC", 1); } int ButtonDChoosed = PlayerPrefs.GetInt("PressedButtonD", 0); if (ButtonDChoosed == 1 &amp;&amp; PlayerPrefs.GetInt("PressedButtonC", 0) == 1) { Buttons[3].gameObject.active = false; TrainE.gameObject.active = true; MineE.gameObject.active = true; PlayerPrefs.SetInt("PressedButtonD", 1); } int ButtonEChoosed = PlayerPrefs.GetInt("PressedButtonE", 0); if (ButtonEChoosed ==1 &amp;&amp; PlayerPrefs.GetInt("PressedButtonD", 0) == 1) { Buttons[4].gameObject.active = false; TrainF.gameObject.active = true; MineF.gameObject.active = true; PlayerPrefs.SetInt("PressedButtonE", 1); } int ButtonFChoosed = PlayerPrefs.GetInt("PressedButtonF", 0); if (ButtonFChoosed == 1 &amp;&amp; PlayerPrefs.GetInt("PressedButtonE", 0) == 1) { Buttons[5].gameObject.active = false; TrainG.gameObject.active = true; MineG.gameObject.active = true; PlayerPrefs.SetInt("PressedButtonF", 1); } int ButtonGChoosed = PlayerPrefs.GetInt("PressedButtonG", 0); if (ButtonGChoosed == 1 &amp;&amp; PlayerPrefs.GetInt("PressedButtonF", 0) == 1) { Buttons[6].gameObject.active = false; TrainH.gameObject.active = true; MineH.gameObject.active = true; PlayerPrefs.SetInt("PressedButtonG", 1); } int ButtonHChoosed = PlayerPrefs.GetInt("PressedButtonH", 0); if (ButtonHChoosed == 1 &amp;&amp; PlayerPrefs.GetInt("PressedButtonG", 0) == 1) { Buttons[7].gameObject.active = false; TrainI.gameObject.active = true; MineI.gameObject.active = true; PlayerPrefs.SetInt("PressedButtonH", 1); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-06T04:24:44.603", "Id": "395527", "Score": "1", "body": "If you need to have that many named objects of the same type, used in repetitive code like that, you should rethink how you're doing things. Perhaps arrays would be helpful?" ...
[ { "body": "<p>I had take a look on your source code, and my comments are bellow:</p>\n\n<h2>Readable:</h2>\n\n<ol>\n<li>You should follow coding conventions. Such as: add an empty line between brackets( <strong>{}</strong> ). Ex:</li>\n</ol>\n\n<blockquote>\n<pre><code>int ButtonAChoosed = PlayerPrefs.GetInt(\"...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-05T21:58:19.820", "Id": "205041", "Score": "0", "Tags": [ "c#", "unity3d" ], "Title": "Tycoon-style Idle game" }
205041
<p>I have some code that draws sprites and and allows new ones to be added. To do this, I use 2 lists: 1 for the sprites that need to be drawn, and one for the new sprites that need to be added to the main list. I have done it this way so that new sprites can still be added in even if the main list is being drawn at that time. </p> <p>I have the <code>addSprite</code> method synchronized with <code>newSprites</code>. The section for updating the main list with new sprites is also synchronized. These locks are there so that new sprites are not removed from the <code>newSprites</code> list before they are added to the main list. </p> <p>I also thought of another option: Remove the <code>newSprites</code> list completely. Instead, just synchronize the main <code>sprites</code> list. This would work, but I am worried it could slow down the program because new sprites could not be added until drawing had completed. </p> <p>Here is my current code:</p> <pre><code>List&lt;Sprite&gt; sprites=new ArrayList&lt;Sprite&gt;(); List&lt;Sprite&gt; newSprites=new ArrayList&lt;Sprite&gt;(); public void doDrawing() { for(Sprite s:sprites) { if(s.isVisible()) { s.draw(); } } synchronized (newSprites) { if(newSprites.size()&gt;0) { sprites.addAll(newSprites); newSprites.clear(); } } } public void addSprite(Sprite s) { synchronized (newSprites) { newSprites.add(s); } } </code></pre> <p><strong>Is the <code>newSprites</code> a good idea? Should I replace this with something else?</strong> Any other advice or review is welcome as well, of course.</p> <p>Note: I am not drawing an insane number of sprites, almost always (much) less than 100.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-06T10:53:15.643", "Id": "395534", "Score": "1", "body": "A thread safe collection can solve these problems: https://stackoverflow.com/questions/38845778/thread-safety-when-iterating-through-an-arraylist-using-foreach" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-05T22:15:34.830", "Id": "205044", "Score": "1", "Tags": [ "java", "array", "thread-safety", "graphics" ], "Title": "Drawing sprites and adding new ones" }
205044
<p>I am learning about monadic structures and have created a sort of monad list that implements the map and binding "operators" (or technically methods) in C#.</p> <p>I understand that Linq already exists and would solve many of the problems that my solution solves (I am in fact already using linq to help in parts of my code) and that lists are technically already monads. However this is still a learning experience for me and so I want to make sure I have the right idea.</p> <pre><code>class ListMonad&lt;T&gt; : IEnumerable&lt;T&gt; { private readonly List&lt;T&gt; items; private List&lt;T&gt; Items =&gt; items; public ListMonad(List&lt;T&gt; value) { this.items = new List&lt;T&gt;(value); } public ListMonad() { items = new List&lt;T&gt; { }; } public ListMonad&lt;TO&gt; Bind&lt;TO&gt;(Func&lt;T, ListMonad&lt;TO&gt;&gt; func) { var lists = new List&lt;ListMonad&lt;TO&gt;&gt;(); foreach(var el in Items) lists.Add(func(el)); return new ListMonad&lt;TO&gt;(lists.SelectMany(x =&gt; x.Items).ToList()); } public ListMonad&lt;TO&gt; Map&lt;TO&gt;(Func&lt;T, TO&gt; func) { var result = new ListMonad&lt;TO&gt;(); foreach(var item in Items) result.Items.Add(func(item)); return result; } IEnumerator&lt;T&gt; IEnumerable&lt;T&gt;.GetEnumerator() { foreach(var item in Items) yield return item; } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable&lt;T&gt;)this).GetEnumerator(); } public T this[int index] =&gt; Items[index]; } </code></pre> <p>Use:</p> <pre><code>class Program { static void Main(string[] args) { var listMonad = new ListMonad&lt;int&gt;(new List&lt;int&gt; { 1, 2, 3, 4, 5, 6, 7 }); var doubledAndSquared = Compose((int x) =&gt; x * x, (int x) =&gt; x * 2); Func&lt;int, ListMonad&lt;int&gt;&gt; zeroSeparated = x =&gt; new ListMonad&lt;int&gt;(new List&lt;int&gt; { x, 0 }); listMonad = listMonad .Bind(zeroSeparated) .Map(doubledAndSquared); foreach(var item in listMonad) Console.Write(item + ", "); } static Func&lt;V, U&gt; Compose&lt;T, U, V&gt;(Func&lt;T, U&gt; func1, Func&lt;V, T&gt; func2) =&gt; (V x) =&gt; func1(func2(x)); } </code></pre>
[]
[ { "body": "<p>Just a few points that I've noticed:</p>\n\n<ul>\n<li><p>Readonly property can be declared directly like this:</p>\n\n<pre><code>private List&lt;T&gt; Items { get; }\n</code></pre></li>\n<li><p>It is not clear if this class is intended to be immutable. The <code>Items</code> is not exposed directl...
{ "AcceptedAnswerId": "205051", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-05T23:41:56.470", "Id": "205048", "Score": "7", "Tags": [ "c#", "functional-programming", "monads" ], "Title": "Monadic list for a more functional approach to C#" }
205048
<h3>The Story</h3> <p>While flying a plane over the forests of Wisconsin a couple years ago, I thought to myself &quot;If I lost an engine, I would be awfully long way from an emergency landing airport. I wonder where the worst place to lose an engine in Wisconsin would be, if we define worst as &quot;furthest from any airport&quot;?</p> <p>To scratch my itch, I mapped out Wisconsin's borders, downloaded a data file of airport coordinates, and wrote a program that brute-forces the answer. It took a while to run, naturally, and I've always wondered how I could have done better.</p> <h3>The Goal</h3> <p><strong>I'm mostly interested in improvements to (or replacements for) the list comprehension that determines the furthest point from an airport.</strong> This is simply for my own information/education.</p> <h3>The Changes</h3> <p>I've made the following changes to make the code more compact for posting:</p> <ul> <li>To simplify the problem of determining borders I've changed the state from Wisconsin to Colorado</li> <li>I've pruned the number of airports in Colorado down to 4</li> <li>I'm only considering coordinates located at 1 degree intervals</li> <li>This same code is also <a href="https://github.com/Steve-V/wi-desolate/blob/75d4642e82171948cd089df1bbb6716f98b13937/desolate.py" rel="noreferrer">posted on GitHub</a>.</li> </ul> <h3>The Code</h3> <pre><code>from geopy.distance import great_circle from shapely.geometry import Polygon, Point import numpy, itertools def buildGrid(): '''Return a grid of all latitude and longitude coordinates in the state, at whatever resolution. One of these will be our solution point. ''' # Use shapely to build a polygon representing the land area of the state # For states like Colorado this is trivial but for non-square states we # would import the coordinate list from a separate file stateBorders = [ (-109.0448,37.0004), (-102.0424,36.9949), (-102.0534,41.0006), (-109.0489, 40.9996), (-109.0448, 37.0004)] borders = Polygon( stateBorders ) # This represents the bounding latitude and longitude of the state. With # a state like Colorado this approximates the actual borders, but with # a state such as Florida this would also contain much ocean. # Step by a full degree for a coarse grid or less (such as a tenth of # a degree) for a finer solution latstep = 1.0 lonstep = -1.0 latitudeBox = numpy.arange(35,43,latstep) longitudeBox = numpy.arange(-101,-110,lonstep) # Return all points that meet the criteria for being within the # actual state borders. For example, remove all ocean from # Florida, leaving only land area. return (i for i in itertools.product(latitudeBox,longitudeBox) if Point(i[1],i[0]).within(borders) ) def distanceToNearestAirport(point, allAirports): '''Given a point, determine the distance to the nearest airport Point is a tuple of the following format: (latitude, longitude) allAirports is an OrderedDict containing at least value['lat'] and value['long'] great_circle is provided by geopy, nautical is to make the answer easy to verify using standard aeronautical charts''' return min( [great_circle(point, (eachAirport['lat'],eachAirport['long'])).nautical for eachAirport in allAirports] ) def main(): '''Figure out the place in a state that is furthest from the nearest airport''' # Airport data would be stored on disk as a pickled OrderedDict # in the working directory. This is a small subset. allAirports = [ {'long': -104.8493156, 'lat': 39.57013424, 'code': 'APA'}, {'long': -104.6731767, 'lat': 39.86167312, 'code': 'DEN'}, {'long': -104.5376322, 'lat': 39.78420646, 'code': 'FTG'}, {'long': -105.1172046, 'lat': 39.90881199, 'code': 'BJC'} ] # this list comprehension walks through the grid of points and creates a # list of tuples: (the distance from a provided point to the nearest # airport, and the point itself) # the max function takes the highest-distance value from the list # of tuples, which is our answer howfar, furthestpoint = (max( ((distanceToNearestAirport(eachpoint, allAirports), eachpoint ) for eachpoint in buildGrid() ) ) ) # Since i also want to know which airport is nearest to the point, we run # our known furthest point back through the distance algorithm again. # It outputs a tuple of the following format: (distance, airportname) result = min( [ (great_circle(furthestpoint, (eachAirport['lat'], eachAirport['long']) ).nautical, eachAirport['code']) for eachAirport in allAirports] ) # Output! print(&quot;Latitude of most desolate point: {} \n&quot; &quot;Longitude of furthest point: {} \n&quot; &quot;Nearest airport to point: {}\n&quot; &quot;Distance from point to airport: {}\n&quot; .format( furthestpoint[0] , furthestpoint[1] , result[1] , result[0]) ) main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-06T14:41:37.993", "Id": "395540", "Score": "0", "body": "What do you use as your data source?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-06T16:40:10.617", "Id": "395546", "Score": "0", "bod...
[ { "body": "<blockquote>\n<pre><code> # Step by a full degree for a coarse grid or less (such as a tenth of \n # a degree) for a finer solution\n latstep = 1.0\n lonstep = -1.0\n</code></pre>\n</blockquote>\n\n<p>If you want to do it by sampling, there's no need to stick to a single resolution. Given...
{ "AcceptedAnswerId": "205272", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-06T06:53:03.103", "Id": "205055", "Score": "10", "Tags": [ "python", "performance", "algorithm", "computational-geometry", "geospatial" ], "Title": "Where is the most desolate place in Colorado?" }
205055
<p>In my project I send messages, so there are items that should be sent and that were already sent. I want to have container to manage these two entities.</p> <p>The container I wrote seems to work ok. It supposed to be thread unsafe, data racing issues should be managed by class users.</p> <p>What might be done better? All ideas are welcome, I will be happy to know your opinions and objections. </p> <p><strong>WaitSentMap.h</strong></p> <pre><code>#pragma once #include &lt;deque&gt; #include "MessageException.h" template &lt;typename T&gt; class WaitSentMap { public: WaitSentMap() {}; ~WaitSentMap() {}; template &lt;typename U&gt; void addItem( U &amp;&amp; item ); T&amp; getNextItem(); template &lt;typename U&gt; void rescheduleItem( U &amp;&amp; item ); template &lt;typename U&gt; void removeItem( U &amp;&amp; item ); private: std::deque&lt; std::unique_ptr&lt;T&gt; &gt; m_waitingRequests; std::deque&lt; std::unique_ptr&lt;T&gt; &gt; m_sentRequests; }; template &lt;typename T&gt; template &lt;typename U&gt; void WaitSentMap&lt;T&gt;::addItem( U &amp;&amp; item ) { m_waitingRequests.push_back( std::make_unique&lt;T&gt;( std::forward&lt;T&gt;( item ) ) ); } template &lt;typename T&gt; T&amp; WaitSentMap&lt;T&gt;::getNextItem() { std::unique_ptr&lt;T&gt; item; if ( m_waitingRequests.empty() ) { THROW_MESSAGE &lt;&lt; "Waiting queue is empty"; } try { item = std::move( m_waitingRequests.front() ); m_waitingRequests.pop_front(); T * pReturn = item.get(); m_sentRequests.push_back( std::move( item ) ); return *pReturn; } catch ( ... ) { // In case of exception raised and item might be lost between two queues // let's check and restore the starting state auto itWait = std::find( m_waitingRequests.begin(), m_waitingRequests.end(), item ); auto itSent = std::find( m_sentRequests.begin(), m_sentRequests.end(), item ); if( ( itSent == m_sentRequests.end() ) &amp;&amp; ( itWait == m_waitingRequests.end() ) ) { m_waitingRequests.push_front( std::move( item ) ); } throw; } } template &lt;typename T&gt; template &lt;typename U&gt; void WaitSentMap&lt;T&gt;::rescheduleItem( U &amp;&amp; item ) { auto it = std::find_if( m_sentRequests.begin(), m_sentRequests.end(), [&amp;] ( std::unique_ptr&lt;T&gt; &amp; p ) { return *(p.get()) == item; } ); if ( it == m_sentRequests.end() ) { THROW_MESSAGE &lt;&lt; "Item " &lt;&lt; item &lt;&lt; " was not scheduled"; } std::unique_ptr&lt;T&gt; pItem; try { pItem = std::move( *it ); m_sentRequests.erase( it ); m_waitingRequests.push_back( std::move( pItem ) ); } catch ( ... ) { // In case of exception raised and item might be lost between two queues // let's check and restore the starting state auto itWait = std::find_if( m_waitingRequests.begin(), m_waitingRequests.end(), [&amp;] ( std::unique_ptr&lt;T&gt; &amp; p ) { return *(p.get()) == item; } ); auto itSent = std::find_if( m_sentRequests.begin(), m_sentRequests.end(), [&amp;] ( std::unique_ptr&lt;T&gt; &amp; p ) { return *(p.get()) == item; } ); if ( ( itWait == m_waitingRequests.end() ) &amp;&amp; ( itSent == m_sentRequests.end() ) &amp;&amp; ( *pItem ) ) { m_sentRequests.push_back( std::move( pItem ) ); } throw; } } template &lt;typename T&gt; template &lt;typename U&gt; void WaitSentMap&lt;T&gt;::removeItem( U &amp;&amp; item ) { auto itWait = std::find_if( m_waitingRequests.begin(), m_waitingRequests.end(), [&amp;] ( std::unique_ptr&lt;T&gt; &amp; p ) { return *(p.get()) == item; } ); if ( itWait != m_waitingRequests.end() ) { m_waitingRequests.erase( itWait ); } auto itSent = std::find_if( m_sentRequests.begin(), m_sentRequests.end(), [&amp;] ( std::unique_ptr&lt;T&gt; &amp; p ) { return *(p.get()) == item; } ); if ( itSent != m_sentRequests.end() ) { m_sentRequests.erase( itSent ); } } </code></pre>
[]
[ { "body": "<h2>Code</h2>\n\n<ul>\n<li>Missing a <code>#include &lt;memory&gt;</code> for <code>std::unique_ptr</code>, <code>#include &lt;algorithm&gt;</code> for <code>std::find_if</code>.</li>\n<li><p>Use <code>= default;</code> or <code>= delete;</code> for constructors, rather than declaring an empty functi...
{ "AcceptedAnswerId": "205076", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-06T11:57:04.293", "Id": "205063", "Score": "0", "Tags": [ "c++", "queue" ], "Title": "C++ container to manage waiting/sent messages" }
205063
<p>This is my first <a href="https://programmingpraxis.com/2009/08/11/uncle-bobs-bowling-game-kata/" rel="nofollow noreferrer">bowling kata</a> solution in java. I would be very grateful if you say something about that. I want to learn from you to become a better programmer. I think the score method is quite small, but is it clear enough as well? How can I improve it more?</p> <pre><code>public class BowlingGame { int[] rolls = new int[21]; int currentRollIndex = 0; public void roll(int roll) { if (currentRollIndex &lt; 21) { rolls[currentRollIndex++] = roll; } } public int score() { int score = 0; int index = 0; for (int i = 0; i &lt; 10; i++) { score += rollIndex(index++); if (isStrike(index - 1)) score += rollIndex(index, index + 1); else { score += rollIndex(index++); if (isSpare(index - 2)) score += rollIndex(index); } } return score; } private boolean isStrike(int index) { return rolls[index] == 10; } private boolean isSpare(int index) { return rolls[index] + rolls[index + 1] == 10; } private int rollIndex(int... indexes) { int sum = 0; for (int i = 0; i &lt; indexes.length; i++) sum += rolls[indexes[i]]; return sum; } } </code></pre> <h2>JUnit test:</h2> <pre><code>public class BowlingKataTest { public BowlingKataTest() { } Bowling bowling; @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { bowling = new Bowling(); } @After public void tearDown() { } @Test public void NullTest() { bowling.roll(0); assertEquals(0, bowling.score()); } void setRolls(int n, int pin) { for (int i = 0; i &lt; n; i++) { bowling.roll(pin); } } void set2Rolls(int n, int pin1, int pin2) { for (int i = 0; i &lt; n; i++) { bowling.roll(pin1); bowling.roll(pin2); } } void setArrayRolls(int[] n) { for (int i = 0; i &lt; n.length; i++) { bowling.roll(n[i]); } } @Test public void OnesTest() { setRolls(20, 1); assertEquals(20, bowling.score()); } @Test public void OnesBonusTest() { setRolls(10, 1); bowling.roll(10); setRolls(8, 1); assertEquals(30, bowling.score()); } @Test public void FullBonusTest() { setRolls(12, 10); assertEquals(300, bowling.score()); } @Test public void FullHalfBonusTest1() { set2Rolls(10, 3, 7); bowling.roll(10); assertEquals(137, bowling.score()); } @Test public void FullHalfBonusTest2() { setRolls(21, 5); assertEquals(150, bowling.score()); } @Test public void RealTest() { int[] rolls = {0,10,5,5,3,2,10,10,3,7,7,1,4,2,9,1,8,2,5}; setArrayRolls(rolls); assertEquals(140, bowling.score()); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-06T14:22:52.073", "Id": "395539", "Score": "0", "body": "Can you provide a link to the kata instructions?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-06T14:54:59.947", "Id": "395542", "Score": "...
[ { "body": "<p>Overall, looks good design. good breakdown into methods.\nHere are my comments:</p>\n\n<ol>\n<li><p>Avoid <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic numbers</a><br>\nMagic numbers are literals (String or Numeric values). They should be r...
{ "AcceptedAnswerId": "205094", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-06T12:17:39.080", "Id": "205064", "Score": "1", "Tags": [ "java", "junit" ], "Title": "Bowling kata solution in java" }
205064
<p>I've been trying to pick up some Rust experience and decided to try and make a text adventure game. I'd like some feedback on potential bad practice and non-Rust-style code I may have used. I'm moving towards Rust from a Python perspective.</p> <pre><code>use std::io::stdin; struct Game { room: usize, inventory: Vec&lt;Item&gt;, rooms: Vec&lt;Room&gt; } impl Game { fn room(&amp;self) -&gt; &amp;Room { &amp;self.rooms[self.room] } fn room_mut(&amp;mut self) -&gt; &amp;mut Room { &amp;mut self.rooms[self.room] } fn exits(&amp;self) { let mut index = 0; let mut s = String::from( format!("{} has {} exits:", &amp;self.room().name, &amp;self.room().exits.len()) ); for exit in &amp;self.room().exits { s = format!("{}\n({}) {}", s, index, self.rooms[*exit].name); index += 1; } println!("{}", s); } fn view_inventory(&amp;self) { let mut index = 0; let mut s = String::from( format!("You have {} items:", self.inventory.len()) ); for item in &amp;self.inventory { s = format!("{}\n({}) {}", s, index, item.name); index += 1; } println!("{}", s); } fn move_room(&amp;mut self, room: usize) { self.room = self.room().exits[room]; } fn take(&amp;mut self, item: usize) -&gt; &amp;Item { let item = self.room_mut().items.remove(item); self.inventory.push(item); &amp;self.inventory[self.inventory.len() - 1] } } struct Item { name: String, description: String } struct Room { name: String, description: String, exits: Vec&lt;usize&gt;, items: Vec&lt;Item&gt; } impl Room { fn look(&amp;self) { println!("{}", self.description) } fn inspect(&amp;self) { let mut index = 0; let mut s = String::from( format!("{} has {} items:", &amp;self.name, &amp;self.items.len()) ); for item in &amp;self.items { s = format!("{}\n({}) {}", s, index, item.name); index += 1; } println!("{}", s); } } fn main() { let mut rooms = vec![ Room { name: String::from("Bedroom"), description: String::from("A tidy, clean bedroom with 1 door and a balcony"), exits: vec![1, 2], items: vec![ Item { name: String::from("Key"), description: String::from("A golden key") }] }, Room { name: String::from("Balcony"), description: String::from("An outdoor balcony that overlooks a gray garden"), exits: vec![0], items: vec![] }, Room { name: String::from("Landing"), description: String::from("A carpetted landing with doors leading off it. It overlooks a large living space. A set of stairs leads down"), exits: vec![0], items: vec![] }, ]; let mut player = Game { room: 0, rooms: rooms, inventory: vec![] }; println!("Type `look' to look around. Type `move &lt;room no&gt;' to switch room"); loop { let mut input = String::new(); match stdin().read_line(&amp;mut input) { Ok(_) =&gt; { let mut commands = input.trim().split_whitespace(); match commands.next() { Some("look") =&gt; { player.room().look(); player.exits(); } Some("move") =&gt; { let args: Vec&lt;&amp;str&gt; = commands.collect(); if args.len() != 1 { println!("Incorrect args."); continue; } let room_no: usize = match args[0].parse() { Ok(a) =&gt; {a}, Err(e) =&gt; { println!("{}", e); continue } }; player.move_room(room_no); println!("You moved to {}", player.room().name); } Some("inventory") =&gt; { player.view_inventory(); } Some("inspect") =&gt; { player.room().inspect(); } Some("take") =&gt; { let args: Vec&lt;&amp;str&gt; = commands.collect(); if args.len() != 1 { println!("Incorrect args."); continue; } let item_no: usize = match args[0].parse() { Ok(a) =&gt; {a}, Err(e) =&gt; { println!("{}", e); continue } }; let item = player.take(item_no); println!("You collected {}", item.name); } None =&gt; {}, _ =&gt; {}, } } Err(error) =&gt; panic!("Error occured reading stdin: {}", error), } } } </code></pre> <p>The source is also <a href="https://github.com/JellyWX/adventure-rs/tree/85903392d74b58889ede2a84b6dc5308f02594d6" rel="nofollow noreferrer">available on GitHub</a>.</p>
[]
[ { "body": "<pre><code>struct Game {\n room: usize,\n inventory: Vec&lt;Item&gt;,\n rooms: Vec&lt;Room&gt;\n}\n</code></pre>\n\n<p>I would recommend <code>current_room</code> instead of <code>room</code>. The meaning is slightly clearer.</p>\n\n<p>You have several functions like the following, the comme...
{ "AcceptedAnswerId": "205068", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-06T14:26:07.380", "Id": "205066", "Score": "5", "Tags": [ "beginner", "rust", "adventure-game" ], "Title": "Beginner Rust text adventure" }
205066
<p>This is a relatively simple implementation of the Sieve of Eratosthenes in Rust. The main objective is to find the <span class="math-container">\$n\$</span>th prime quickly when <span class="math-container">\$n\$</span> might grow to huge numbers.</p> <pre><code>pub fn nth(n: u32) -&gt; u32 { // A convenient variable that will help in simplifying a complicated expression let x = if n &lt;= 10 { 10.0 } else { n as f64 }; // The prime counting function is pi(x) which is approximately x/ln(x) // We need the inverse of that. A good estimate is ceil(x * ln(x * ln(x))) let limit: usize = (x * (x * (x).ln()).ln()).ceil() as usize; let mut sieve = vec![true; limit]; let mut count = 0; // Exceptional case for 0 and 1 sieve[0] = false; sieve[1] = false; for prime in 2..limit { if !sieve[prime] { continue; } if count == n { return prime as u32; } count += 1; for multiple in ((2 * prime)..limit).step_by(prime) { sieve[multiple] = false; } } return &lt;u32&gt;::max_value(); } </code></pre> <p>This entire function would be present in <code>main.rs</code> or <code>lib.rs</code>, as necessary.</p> <p>Please feel free to nitpick on any aspect of the code. Suggestions to make the code cleaner or more efficient are welcome.</p>
[]
[ { "body": "<p>Nice use of the Prime Number Theorem there. However, there are some issues with your code as is:</p>\n\n<ul>\n<li>The name <code>nth</code> does not convey the meaning of the function.</li>\n<li>A <code>return</code> statement is used instead of an expression at the end of the function.</li>\n<li>...
{ "AcceptedAnswerId": "205098", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-06T17:07:35.067", "Id": "205069", "Score": "3", "Tags": [ "performance", "primes", "rust", "sieve-of-eratosthenes" ], "Title": "Sieve of Eratosthenes in Rust" }
205069
<p>I solved this <a href="https://codingbat.com/prob/p191914" rel="nofollow noreferrer">CodingBat problem</a>:</p> <blockquote> <p>Given a string, return a new string where "not " has been added to the front. However, if the string already begins with "not", return the string unchanged. Note: use .equals() to compare 2 strings.</p> </blockquote> <pre><code>notString("candy") → "not candy" notString("x") → "not x" notString("not bad") → "not bad" </code></pre> <p>Here is the solution I came up with:</p> <pre><code>public String notString(String str) { if(str.indexOf("not") == 0){ return str; } return "not " + str; } </code></pre> <p>I was wondering how it compared to their solution:</p> <blockquote> <pre><code>public String notString(String str) { if (str.length() &gt;= 3 &amp;&amp; str.substring(0, 3).equals("not")) { return str; } return "not " + str; } </code></pre> </blockquote> <p>Obviously neither is "wrong" but I was just wondering (in the long run) which has better syntax / more efficient code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-06T18:04:14.663", "Id": "395555", "Score": "0", "body": "I am also using multiple resources to learn Java including edx.org, Head First Java, CodingBat, and more. I have learned how to approach problems in a variety of different ways,...
[ { "body": "<p>It should be obvious which strategy is better. Suppose you are given a very long string. Do you really want to search the entire string for \"not\", then realize that the match is irrelevant because it doesn't occur at the beginning? Or would you rather just examine the first three characters of ...
{ "AcceptedAnswerId": "205075", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-06T17:27:42.700", "Id": "205070", "Score": "0", "Tags": [ "java", "strings", "programming-challenge", "comparative-review" ], "Title": "CodingBat warm up: conditionally prepending \"not\" to a string" }
205070
<p>Here is my code of project <a href="https://projecteuler.net/problem=7" rel="nofollow noreferrer">Euler #7</a>:</p> <pre><code>from math import * import time start = time.time() def isPrime(n): prime_fst = [2,3,5,7] num = round(sqrt(n)) j=0 while num&gt;7: if num%2!=0 and num%3!=0 and num%5!=0 and num%7!=0: prime_fst.append(num) num-=1 prime_fst.sort() while j &lt; len(prime_fst): for i in prime_fst: if i!=prime_fst[j]: if i%prime_fst[j]==0: prime_fst.remove(i) j+=1 for t in prime_fst: if n%t==0: k=n%t return False return True x=int(input()) l=1 res = [2,3,5,7] while len(res)!=x: if l!=1: if isPrime(l): res.append(l) l+=2 print(res[-1]) end = time.time() print(end-start) </code></pre> <p>Can you recommend what I should do with algorithm skills? How can I think effectively? Will skills develop with time? All your recommendations and help to speed up this code by explaining?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-06T21:26:47.453", "Id": "395560", "Score": "1", "body": "To respond to the \"too broad\" close vote you could try removing the tangential questions like \"How to think effectively?\" - those questions don't belong on this site. I'm not...
[ { "body": "<p>Some recommendations:</p>\n\n<ul>\n<li>Running your code through a linter like <a href=\"https://pypi.org/project/pycodestyle/\" rel=\"nofollow noreferrer\"><code>pycodestyle</code></a>, then learning what the messages mean and applying them to your code is going to make your code more idiomatic, ...
{ "AcceptedAnswerId": "205079", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-06T18:51:43.863", "Id": "205074", "Score": "0", "Tags": [ "python", "beginner", "programming-challenge" ], "Title": "Euler #7 - 10001st prime" }
205074
<p>I don't like my current code, because of duplications. What's the best way to leverage Kotlin to make it more concise. I have simple registration form</p> <pre><code>data class RegisterForm @JvmOverloads constructor( val email: String = "", val emailError: String = "", val lastName: String = "", val lastNameError: String = "", ... ) </code></pre> <p>In my ViewModel I'm reacting to my <code>TextWatcher</code>. I set my state by updating my <code>RegisterForm</code> data class</p> <pre><code>fun onEmailChanged(email: String) { setState { copy(registerForm = registerForm .copy(email = email, emailError = validateEmail(email)) ) } } fun onFirstNameChanged(text: String) { setState { copy(registerForm = registerForm .copy(firstName = text, firstNameError = validateFirstName(text)) ) } } </code></pre> <p>As you can see, I need to copy paste the code in my <code>ViewModel</code> every time I'm adding the new input field. How can I leverage <code>Kotlin</code> to get rid of these duplications?</p>
[]
[ { "body": "<p>In functional programming terms, using <a href=\"https://www.schoolofhaskell.com/school/to-infinity-and-beyond/pick-of-the-week/basic-lensing\" rel=\"nofollow noreferrer\">Lenses</a> could help you modify nested object elegantly. There are no native supported lenses in kotlin language but some lib...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-06T19:18:12.953", "Id": "205077", "Score": "0", "Tags": [ "android", "kotlin" ], "Title": "Simple Registration Form. I would like to get rid of code duplications" }
205077
<blockquote> <p>You are given an array sorted in ascending order which is rotated at some pivot unknown to you beforehand. Find your target in <span class="math-container">\$O(log n)\$</span> which means it should be a binary search. If the value does not exist return <code>-1</code>.</p> </blockquote> <p>The approach I took was to narrow the subset of solutions by using an upper bound <code>infinity</code> and a lower bound <code>infinity</code>. I would cut the array in half. If the <code>mid</code> was less than the <code>target</code>, the right of the <code>mid</code> would become the new lower bound and if the <code>high</code> was less than the current <code>target</code> the <code>mid</code> would be the new upper bound. </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 findTarget(array, target) { let lo = 0, hi = array.length, limit; while (lo &lt; hi) { let mid=Math.floor((hi+lo)/2); if ((array[mid] &lt; array[0]) === (target &lt; array[0])) { limit = array[mid] } else if (target &lt; array[0]) { limit = Number.NEGATIVE_INFINITY } else { limit = Number.POSITIVE_INFINITY } if (limit &lt; target) { lo = mid + 1 } else if (limit &gt; target) { hi = mid } else { return mid } } return -1 } console.log(findTarget([4, 5, 6, 7, 0, 1, 2], 3))</code></pre> </div> </div> </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-06T20:24:09.913", "Id": "205078", "Score": "2", "Tags": [ "javascript", "array", "complexity", "binary-search", "namespaces" ], "Title": "Find target in sorted array pivoted at some unknown point in O(log n)" }
205078
<p>This Java class (aka application component) role is to handle a series of XML files stored in the file system. It must convert those XML files to the corresponding application domain model, and it needs to maintain them always synchronized with the XML representation. It must handle changes, deletion and (re)creation. And everything must be thread-safe.</p> <p>A note: I didn't use a ConcurrentHashMap because the <code>DomainChange</code> event which I fire is synchronous and I need to wait for all the observers to finish.</p> <p>I would like to have an opinion for my code, to understand if I got thread safety right, or where it is not needed / needed more. Unfortunately I have noone to ask face-to-face ;)</p> <p>The code is pretty documented and self-explanatory but I had to translate JavaDoc and inline comments from Italian, so pardon errors, if any.</p> <p>This component is pretty much CDI managed.<br> At costruction time I inject a <code>Configuration</code> (<a href="https://commons.apache.org/proper/commons-configuration/javadocs/v1.10/apidocs/org/apache/commons/configuration/PropertiesConfiguration.html" rel="nofollow noreferrer">JavaDoc</a>) object for later usage.</p> <p>The core field is the <code>managedDomains</code> map. This map uses the unique domain name as key and the objects related to that domain (inside an instance of the holder class <code>ManagedDomain</code>) as value.</p> <p>I removed a couple of "secret" constants in the code (you'll read <code>REMOVED</code> or <code>...</code>).</p> <p>I'm running this on a <code>Java 7</code> environment.</p> <pre><code>/** * XML-file persisted domains controller. * &lt;p&gt; * This component publishes a {@link DomainChange} event every time a persisted * domain is changed, removed or (re)created. It is possible to listen for this * event, also by qualifier: see {@link Change}, {@link Creation} and {@link Removal}. * * @author Edoardo */ @Singleton @ThreadSafe class XmlFileDomainsPersistenceController extends FileAlterationListenerAdaptor implements DomainsPersistenceController { private static final Logger logger = LoggerFactory.getLogger(XmlFileDomainsPersistenceController.class); private static final String PREFIX_FOR_PERSISTENCE_KEYS = "REMOVED"; private static final String SCHEMA_NAME = "schema.xsd"; private final ReadWriteLock managedDomainsReadWriteLock = new ReentrantReadWriteLock(true); private final Lock writeLock = managedDomainsReadWriteLock.writeLock(); private final Lock readLock = managedDomainsReadWriteLock.readLock(); @GuardedBy("managedDomainsReadWriteLock") private final Map&lt;String, ManagedDomain&gt; managedDomains = new HashMap&lt;&gt;(16); @Nonnull private final Configuration configuration; @Nonnull private final JAXBContext jaxbContext; @Nonnull private final Schema schema; @Inject private Event&lt;ApplicationError&gt; applicationErrorEvent; @Inject private Event&lt;DomainChange&gt; domainChangeEvent; @Inject XmlFileDomainsPersistenceController(@Nonnull final Configuration configuration) throws Exception { this.configuration = configuration; jaxbContext = JAXBContext.newInstance(Domain.class); try (final InputStream schemaInputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(SCHEMA_NAME)) { final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); schema = schemaFactory.newSchema(new StreamSource(schemaInputStream)); } } @Nonnull @Override public Optional&lt;Domain&gt; getDomain(@Nonnull final String domainName) { final ManagedDomain managedDomain; readLock.lock(); try { managedDomain = managedDomains.get(domainName); } finally { readLock.unlock(); } return managedDomain == null ? Optional.&lt;Domain&gt; absent() : Optional.of(managedDomain.domain); } /** * Tell this component to read and translate to the domain model {@link Domain} the * XML file containing the information for the domain which name is equal to the input one. * * @param domainName * The unique name of the domain * @throws DomainPersistenceException * In case the configured domain's file's path is invalid */ @Nonnull @Contract("_ -&gt; new") @Override public Domain addDomain(@Nonnull final String domainName) throws DomainPersistenceException { final ManagedDomain managedDomain; readLock.lock(); try { managedDomain = managedDomains.get(domainName); } finally { readLock.unlock(); } // If the domain is already managed by this component, it is an application error. if (managedDomain != null) { throw new IllegalArgumentException( "The domain " + domainName + " is already being managed"); } // Build the prefix to access the domain configuration keys. final String configurationKeysPrefix = String.format(PREFIX_FOR_PERSISTENCE_KEYS, domainName); final String filePathConfigurationKey = configurationKeysPrefix + "REMOVED"; final String filePath = configuration.getString(filePathConfigurationKey); // Verify the file's path. if (StringUtils.isEmpty(filePath)) { final String message = "Invalid path for XML file: '" + filePath + "'. Check configuration key " + filePathConfigurationKey; throw buildAndPublishDomainPersistenceException(message); } final File file = getFilePathConsideringEnvironment(filePathConfigurationKey, filePath); final FileAlterationObserver fileAlterationObserver; final FileAlterationMonitor fileMonitor; try { // Build the objects which will listen for XML file's modifications. fileAlterationObserver = new FileAlterationObserver( file.getParentFile(), FileFilterUtils.nameFileFilter(file.getName())); fileAlterationObserver.addListener(this); final int frequency = configuration.getInt(configurationKeysPrefix + "REMOVED", 5); // Convert seconds to milliseconds. fileMonitor = new FileAlterationMonitor(frequency * 1000L); fileMonitor.addObserver(fileAlterationObserver); } catch (final Exception ignored) { final String message = "Invalid path for XML file: '" + filePath + "'. Check configuration key '" + filePathConfigurationKey + "'"; throw buildAndPublishDomainPersistenceException(message); } // Convert the XML file to the domain model. final Domain domain = unmarshalXmlToDomainModel(domainName, file); writeLock.lock(); try { // Store everything in a map which uses the unique domain name as key. // I will need these objects for other operations. managedDomains.put( domainName, ManagedDomain.of(domain, fileAlterationObserver, fileMonitor)); return domain; } finally { writeLock.unlock(); } } /** * Remove and return the domain under our control. * If the domain is not managed a {@link com.google.common.base.Absent} is returned. * * @param domainName * The unique name of the domain */ @Nonnull @Override public Optional&lt;Domain&gt; removeDomain(@Nonnull final String domainName) { final ManagedDomain managedDomain; writeLock.lock(); try { managedDomain = managedDomains.remove(domainName); if (managedDomain == null) { return Optional.absent(); } final FileAlterationObserver fileAlterationObserver = managedDomain.fileAlterationObserver; fileAlterationObserver.removeListener(this); try { final FileAlterationMonitor fileAlterationMonitor = managedDomain.fileAlterationMonitor; fileAlterationMonitor.removeObserver(fileAlterationObserver); fileAlterationMonitor.stop(1); } catch (final Exception ignored) { // No-op. } domainChangeEvent.select(RemovalAnnotationLiteral.INSTANCE) .fire(DomainChange.of(managedDomain.domain)); } finally { writeLock.unlock(); } // After returning managedDomains should be elegible for garbage collection. return Optional.of(managedDomain.domain); } /** * Update the domain under our control and persist changes to the XML file. * * @param domain * The domain model to use for persisting changes * @throws DomainPersistenceException * In case of errors during persistence operations */ @Override public void updateDomain(@Nonnull final Domain domain) throws DomainPersistenceException { final String domainName = domain.getName(); final ManagedDomain managedDomain; readLock.lock(); try { managedDomain = managedDomains.get(domainName); } finally { readLock.unlock(); } if (managedDomain == null) { throw new IllegalArgumentException("Cannot update the non-managed domain " + domainName); } // Having a listener for the XML file's state, doing a marshal operation would produce // an unneeded callback to onFileChange(). // To avoid this, before marshalling I have to remove myself from the observer's listeners // and stop the scheduled monitor. // After marshalling is completed I need to create a new XML file's observer for having // "clean" file attributes, and to add myself as listener again. // In the end I have to start the scheduled monitor. // Remove myself from the listeners. final FileAlterationObserver observer = managedDomain.fileAlterationObserver; observer.removeListener(this); final FileAlterationMonitor fileAlterationMonitor = managedDomain.fileAlterationMonitor; // Save the monitor status prior to marshalling. final boolean wasMonitorRunning = getMonitorRunningStatus(fileAlterationMonitor); // Signal to the monitor to no more call the observer. fileAlterationMonitor.removeObserver(observer); final File file = observer.getDirectory(); try { // Stop the scheduled monitor. fileAlterationMonitor.stop(1); final Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setSchema(schema); marshaller.marshal(domain, file); writeLock.lock(); try { managedDomain.domain = domain; domainChangeEvent.select(ChangeAnnotationLiteral.INSTANCE) .fire(DomainChange.of(domain)); // Create the new observer with clean file's attributes. final FileAlterationObserver newFileAlterationObserver = new FileAlterationObserver( file.getParentFile(), FileFilterUtils.nameFileFilter(file.getName())); // Add myself as a listener again. newFileAlterationObserver.addListener(this); // Signal to the monitor to call the observer again. fileAlterationMonitor.addObserver(newFileAlterationObserver); // Restore the monitor status. if (wasMonitorRunning) { fileAlterationMonitor.start(); } // Update the reference of the stored observer with the new one. managedDomain.fileAlterationObserver = newFileAlterationObserver; } finally { writeLock.unlock(); } } catch (final Exception e) { final String message = "Error writing domain " + domainName + " to '" + file + "' using schema " + SCHEMA_NAME; throw buildAndPublishDomainPersistenceException(e, message); } } /** * Return the running/stopped status of a FileAlterationMonitor via reflection, as * it is not exposed. * * @param monitor * The monitor from which to extract the status */ private boolean getMonitorRunningStatus(@Nonnull final FileAlterationMonitor monitor) { try { // noinspection JavaReflectionMemberAccess final Field running = monitor.getClass().getField("running"); running.setAccessible(true); return running.getBoolean(monitor); } catch (final NoSuchFieldException | IllegalAccessException e) { throw new RuntimeException("Couldn't extract the monitor running status", e); } } @Override public void startObserving() { for (final ManagedDomain managedDomain : managedDomains.values()) { try { // noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (managedDomain) { managedDomain.fileAlterationMonitor.start(); } } catch (final Exception ignored) { // No-op. } } } @Override public void startObserving(@Nonnull final String domainName) { final ManagedDomain managedDomain = managedDomains.get(domainName); if (managedDomain == null) { throw new IllegalArgumentException( "Cannot start observing the non-managed domain " + domainName); } try { // noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (managedDomain) { managedDomain.fileAlterationMonitor.start(); } } catch (final Exception ignored) { // No-op. } } @Override public void stopObserving() { for (final ManagedDomain managedDomain : managedDomains.values()) { try { // noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (managedDomain) { managedDomain.fileAlterationMonitor.stop(1); } } catch (final Exception ignored) { // No-op. } } } @Override public void stopObserving(@Nonnull final String domainName) { final ManagedDomain managedDomain = managedDomains.get(domainName); if (managedDomain == null) { throw new IllegalArgumentException( "Cannot stop observing the non-managed domain " + domainName); } try { // noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (managedDomain) { managedDomain.fileAlterationMonitor.stop(); } } catch (final Exception ignored) { // No-op. } } @Override public void onFileChange(final File file) { updateDomainModel(file, ChangeAnnotationLiteral.INSTANCE); } @Override public void onFileCreate(final File file) { updateDomainModel(file, CreationAnnotationLiteral.INSTANCE); } private &lt;T extends Annotation&gt; void updateDomainModel( final File file, final AnnotationLiteral&lt;T&gt; eventQualifier) { // At this point I expect the file I'm being notified for correspond to a domain // already contained in the managedDomains map. If not, it is an application error. final Domain domain; try { domain = unmarshalXmlToDomainModel(null, file); } catch (final DomainPersistenceException e) { applicationErrorEvent.fire(ApplicationError.of(e)); return; } writeLock.lock(); try { final ManagedDomain managedDomain = managedDomains.get(domain.getName()); if (managedDomain == null) { throw new RuntimeException("The XML file does not match any of the configured domains"); } // Overwrite the old domain model with the new one. managedDomain.domain = domain; domainChangeEvent.select(eventQualifier).fire(DomainChange.of(domain)); } finally { writeLock.unlock(); } } /** * Ritorna il path del file XML considerando il tipo di ambiente dove e' installato il prodotto. * * @param filePathConfigurationKey * La chiave di configurazione per accedere al path del file XML * @param filePath * Il path del file XML * @throws DomainPersistenceException * In caso ci si trovi in ambiente ... ed il path del file XML non sia valido */ @Nonnull @ParametersAreNonnullByDefault @Contract("_, _ -&gt; new") private File getFilePathConsideringEnvironment( final String filePathConfigurationKey, final String filePath) throws DomainPersistenceException { // ... REMOVED return new File(filePath); } /** * Trasforma il file XML in domain model. * * @param domainName * Il nome univoco del dominio da caricare in memoria. * Passare {@code null} nel caso in cui non si voglia effettuare il confronto con il nome * trovato nel file XML * @param file * Il path del file XML * @throws DomainPersistenceException * Se {@code domainName} e' diverso da {@code null} e non e' uguale al nome del dominio trovato * nel file XML */ @Nonnull @Contract("_, _ -&gt; new") private Domain unmarshalXmlToDomainModel( @Nullable final String domainName, @Nonnull final File file) throws DomainPersistenceException { try { final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); // Set the XSD schema for unmarshalling validation. unmarshaller.setSchema(schema); final Domain domain = (Domain) unmarshaller.unmarshal(file); // Check that the configured domain name is equal to the domain name // stored in the XML file. If not, it is an application error. if (domainName != null &amp;&amp; !domainName.equals(domain.getName())) { final String message = "Domain name '" + domain.getName() + "' in file " + file + " does not match domain name '" + domainName + "' declared in the configuration."; throw buildAndPublishDomainPersistenceException(message); } return domain; } catch (final UnmarshalException e) { final String message = "Error parsing XML content from '" + file + "' using schema " + SCHEMA_NAME; throw buildAndPublishDomainPersistenceException(e, message); } catch (final JAXBException e) { throw buildAndPublishDomainPersistenceException(e, "Error loading domain from " + file); } } @Contract("_ -&gt; new") private DomainPersistenceException buildAndPublishDomainPersistenceException( @Nonnull final String message) { return buildAndPublishDomainPersistenceException(null, message); } @Contract("_, _-&gt; new") private DomainPersistenceException buildAndPublishDomainPersistenceException( @Nullable final Throwable cause, @Nonnull final String message) { // noinspection ConstantConditions final DomainPersistenceException e = new DomainPersistenceException(message, cause); applicationErrorEvent.fire(ApplicationError.of(e)); return e; } /** * Contenitore degli oggetti necessari alla gestione di un dominio. * Non utilizzare per altri scopi. */ private static class ManagedDomain { @Nonnull Domain domain; @Nonnull FileAlterationObserver fileAlterationObserver; @Nonnull final FileAlterationMonitor fileAlterationMonitor; @ParametersAreNonnullByDefault private ManagedDomain( final Domain domain, final FileAlterationObserver fileAlterationObserver, final FileAlterationMonitor fileAlterationMonitor) { this.domain = domain; this.fileAlterationObserver = fileAlterationObserver; this.fileAlterationMonitor = fileAlterationMonitor; } @ParametersAreNonnullByDefault static ManagedDomain of( final Domain domain, final FileAlterationObserver fileAlterationObserver, final FileAlterationMonitor fileAlterationMonitor) { return new ManagedDomain(domain, fileAlterationObserver, fileAlterationMonitor); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-07T15:01:02.083", "Id": "395573", "Score": "0", "body": "Maybe using tryLock() is better. That's the one I can see doable." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-06T21:27:38.657", "Id": "205083", "Score": "1", "Tags": [ "java", "thread-safety", "concurrency" ], "Title": "Thread-safe Java class for managing XML files <> domain models" }
205083
<p>I'm creating a Tic Tac Toe solver algorithm. The idea is to iterate through each row, column and both diagonals and put them into a map in JavaScript. With that map I can run other logic to check for a winner and where that winner's position is.</p> <p>I'm not building an actual TTT game nor am I writing any AI for now. My question is if there's a better way of achieving the same results without having to use two for loops to get the columns and second diagonals.</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>let board = [ ['x','o','x'], ['o','o','o'], ['o','o','x'] ]; const mapper = board =&gt; { let map = {}, d1 = [], d2 = []; for (let i = 0; i &lt; board.length; i++) { let tmp = []; // get all rows map[`ROW${i}`] = board[i]; // get second diagonals d2.push(board[i][board.length-1-i]); for (let j = 0; j &lt; board.length; j++) { // get all columns tmp.push(board[j][i]); // get first diagonals if (i === j) { d1.push(board[i][j]) } } map[`COL${i}`] = tmp; } map[`DIA1`] = d1; map[`DIA2`] = d2; return map; } const checkForWinner = board =&gt; { return mapper(board); } checkForWinner(board);</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-07T06:19:56.383", "Id": "395566", "Score": "0", "body": "hard code it (i.e. unroll the loops) and cross your fingers that the TTT board never changes. You know, like zip codes never changed and 2 digit years was good enough." } ]
[ { "body": "<h2>Not the board, store the moves</h2>\n\n<p>A TicTacToe board can be mapped to two 9bit numbers that represent each player's moves then the test for winning moves is just a simple bitwise test against the 8 possible combinations of move that are a win.</p>\n\n<blockquote>\n <p>My question is if th...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-07T00:37:15.323", "Id": "205088", "Score": "1", "Tags": [ "javascript", "tic-tac-toe" ], "Title": "mapping a tictactoe board in javascript" }
205088
<p>In the code below, I implemented the SpaceSaving frequency estimation algorithm described in <a href="http://www.cse.ust.hk/~raywong/comp5331/References/EfficientComputationOfFrequentAndTop-kElementsInDataStreams.pdf" rel="nofollow noreferrer">this paper</a>. Given a parameter <code>eps</code>, the algorithm finds all elements of a data stream of length <code>n</code> that occur more than <code>n/eps</code> times (with high probability). Here's a screenshot from the paper with the pseudocode:</p> <p><a href="https://i.stack.imgur.com/626HP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/626HP.png" alt="SpaceSaving algorithm pseudocode"></a></p> <p>I would appreciate any feedback on my implementation: style, performance, etc.</p> <pre><code>import math, heapq class SpaceSavingCounter: def __init__(self, eps): self.k = math.ceil(1/eps) self.n = 0 self.counts = dict() self.queue = [] def inc(self, x): # increment total elements seen self.n += 1 # x is being watched if x in self.counts: self.counts[x] += 1 # x is not being watched else: # make room for x if self.n &gt; self.k: while True: count, tstamp, key = self.pop() assert self.counts[key] &gt;= count if self.counts[key] == count: del self.counts[key] break else: self.push(self.counts[key], tstamp, key) else: count = 0 # watch x self.counts[x] = count + 1 self.push(count, self.n, x) def push(self, count, tstamp, key): heapq.heappush( self.queue, (count, tstamp, key) ) def pop(self): return heapq.heappop(self.queue) def test_SpaceSavingCounter(): seq = [1,5,3,4,2,7,7,1,3,1,3,1,3,1,3] counter = SpaceSavingCounter(1 / 1.9) for x in seq: counter.inc(x) assert counter.counts.keys() == {1,3} </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-08T15:17:24.997", "Id": "395662", "Score": "1", "body": "It's fine if you're just implementing this for fun/school/practice, but if you're in Python 3+ (based on your tag), why not just use `functools.lru_cache`? It's not identical (an...
[ { "body": "<p>Thanks for putting this code online! Two updates for people who may want to use it:</p>\n\n<ol>\n<li><p>Correctness: The \"<em>if self.n > self.k:</em>\" is probably mistaken: for instance, when the sequence starts with k times the same element, we are later stuck with a data structure that contai...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-07T03:44:41.600", "Id": "205090", "Score": "3", "Tags": [ "python", "algorithm", "python-3.x" ], "Title": "SpaceSaving frequent item counter in Python" }
205090
<p>I've implemented a simple ListView in MVVM that displays a few <code>PrepStep</code>s (short form of PreparationSteps). While implementing I wasn't sure about if my approach is "the way to go" so I decided to get the code reviewed.</p> <p>First I want to share the image of the application so you get a better idea of what I have accomplished.</p> <p><a href="https://i.stack.imgur.com/1IAxB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1IAxB.png" alt="preparation list view"></a></p> <hr> <p><strong>Model:</strong></p> <p><em>prep_step.dart:</em></p> <pre><code>class PrepStep { static int id = 1; String name; String shortDescription; String longDescription; int number; bool isFinished; PrepStep() { this.shortDescription = 'This is a very short description of the Step'; this.longDescription = 'This is a slightly longer description of the Step. Detailed instructions go here.'; this.number = id++; this.isFinished = false; this.name = 'Step ${this.number}'; } String getDueDays() { if (this.number == 1) { return '1 Day'; } else { return '${this.number} Days'; } } } </code></pre> <p><em>prep_step_list.dart:</em></p> <pre><code>import 'package:itinerary/model/prep_step.dart'; class PrepStepList { List&lt;PrepStep&gt; prepSteps; PrepStepList({this.prepSteps}) { } } </code></pre> <p><strong>ViewModel:</strong></p> <p><em>prep_step_view_model.dart:</em></p> <pre><code>import 'package:itinerary/model/prep_step.dart'; class PrepStepViewModel { PrepStep step; PrepStepViewModel({step}) { this.step = step; } } </code></pre> <p><em>prep_step_list_view_model.dart:</em></p> <pre><code>import 'package:itinerary/model/prep_step_list.dart'; import 'package:itinerary/viewmodel/prep_step_view_model.dart'; class PrepStepListViewModel { PrepStepList prepStepList; List&lt;PrepStepViewModel&gt; prepStepViewModels; PrepStepListViewModel({prepStepList}) { this.prepStepViewModels = new List(); this.prepStepList = prepStepList; if (this.prepStepList != null) { for (int index = 0; index &lt; this.prepStepList.prepSteps.length; index++) { prepStepViewModels.add(new PrepStepViewModel(step: this.prepStepList.prepSteps[index])); } } } } </code></pre> <p><strong>View:</strong></p> <p><em>prep_step_view.dart:</em></p> <pre><code>import 'package:flutter/material.dart'; import 'package:itinerary/viewmodel/prep_step_view_model.dart'; class PrepStepView extends StatefulWidget { PrepStepViewModel stepViewModel; PrepStepView({stepViewModel}) { this.stepViewModel = stepViewModel; } @override _PrepStepViewState createState() =&gt; _PrepStepViewState(); } class _PrepStepViewState extends State&lt;PrepStepView&gt; { @override Widget build(BuildContext context) { return Card( child: Column( children: &lt;Widget&gt;[ ListTile( title: Text(this.widget.stepViewModel.step.name), subtitle: Text( 'Step ${this.widget.stepViewModel.step.number.toString().padLeft(2, '0')} - Due in ${this.widget.stepViewModel.step.getDueDays()}'), trailing: Checkbox( value: this.widget.stepViewModel.step.isFinished, onChanged: onCheckBoxChanged, tristate: true, ), ), Divider( height: 1.0, ), ListTile( leading: Icon(Icons.description), title: Text(this.widget.stepViewModel.step.shortDescription), subtitle: Text('Description'), ) ], ), ); } void onCheckBoxChanged(bool value) { setState(() { this.widget.stepViewModel.step.isFinished = value; }); } } </code></pre> <p><em>prep_step_list_view.dart:</em></p> <pre><code>import 'package:flutter/material.dart'; import 'package:itinerary/view/prep_step_view.dart'; import 'package:itinerary/viewmodel/prep_step_list_view_model.dart'; class PrepStepListView extends StatefulWidget { PrepStepListViewModel prepStepListViewModel; PrepStepListView({prepStepListViewModel}) { this.prepStepListViewModel = prepStepListViewModel; } @override _PrepStepListViewState createState() =&gt; _PrepStepListViewState(); } class _PrepStepListViewState extends State&lt;PrepStepListView&gt; { @override Widget build(BuildContext context) { return ListView.builder(itemBuilder: (context, index) { return PrepStepView(stepViewModel: this.widget.prepStepListViewModel.prepStepViewModels[index]); }, itemCount: this.widget.prepStepListViewModel.prepStepViewModels.length,); } } </code></pre> <p><strong>Main:</strong></p> <pre><code>import 'package:flutter/material.dart'; import 'package:itinerary/model/prep_step_list.dart'; import 'package:itinerary/view/prep_step_list_view.dart'; import 'package:itinerary/view/prep_step_view.dart'; import 'package:itinerary/model/prep_step.dart'; import 'package:itinerary/viewmodel/prep_step_list_view_model.dart'; import 'package:itinerary/viewmodel/prep_step_view_model.dart'; void main() =&gt; runApp(new MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: 'Itinerary', theme: new ThemeData( primarySwatch: Colors.orange, ), home: new ItineraryApp(), ); } } class ItineraryApp extends StatefulWidget { ItineraryApp() {} @override _ItineraryAppState createState() =&gt; _ItineraryAppState(); } class _ItineraryAppState extends State&lt;ItineraryApp&gt; { List&lt;PrepStep&gt; prepSteps; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Itinerary'), ), body: PrepStepListView( prepStepListViewModel: PrepStepListViewModel( prepStepList: PrepStepList(prepSteps: prepSteps)))); } @override void initState() { super.initState(); prepSteps = new List&lt;PrepStep&gt;(); for (int counter = 0; counter &lt; 30; counter++) { PrepStep step = new PrepStep(); this.prepSteps.add(step); } } } </code></pre> <hr> <p>The PrepStepList implementation seem to be a little bit weird because there is so much wrapping going on especially in the ViewModel class, but I don't know how to improve that. Maybe my approach is not the right one? </p>
[]
[ { "body": "<p>I'm not sure if this is helpful, but this is some feedback:</p>\n\n<ol>\n<li><p><code>PrepStep</code> shouldn't have a <code>static int id</code> because that will be a class-wide variable. This means that if you crease another PrepList, the numbers will not start at 1. See the <a href=\"https:/...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-07T06:32:54.453", "Id": "205092", "Score": "1", "Tags": [ "mvvm", "dart", "flutter" ], "Title": "Flutter - Implementing a simple ListView with MVVM" }
205092
<p>I got the below code that is looping through all controls and changing the state in a after update event and enables new row for user to use. Everything works fine but i'm just wondering whether there is a better way to achieve the same result as what i have done is long winded. This will only enable the controls if the combobox has data if blank skip enable. <a href="https://i.stack.imgur.com/7angK.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7angK.jpg" alt="enter image description here"></a></p> <pre><code>Private Sub Item1_AfterUpdate() Call UpdateItemsToClean End Sub Private Sub UpdateItemsToClean() Dim ctl As MSForms.Control Dim lbl As MSForms.Label Dim cmb As MSForms.ComboBox Dim txtbox As MSForms.TextBox Dim optbtn As MSForms.OptionButton Dim i As Integer For i = 2 To ItemsListFrame.Controls.Count For Each ctl In ItemsListFrame.Controls If TypeName(ctl) = "Label" Then If ctl.Tag = "GroupItem" &amp; i - 1 Then Set lbl = ctl If Controls("Item" &amp; i - 1).Value &lt;&gt; vbNullString Then Controls("OrderLbl" &amp; i).Enabled = True End If End If ElseIf TypeName(ctl) = "ComboBox" Then If ctl.Tag = "GroupItem" &amp; i - 1 Then Set cmb = ctl If Controls("Item" &amp; i - 1).Value &lt;&gt; vbNullString Then Controls("Item" &amp; i).Enabled = True End If End If ElseIf TypeName(ctl) = "TextBox" Then If ctl.Tag = "GroupItem" &amp; i - 1 Then Set txtbox = ctl If Controls("Item" &amp; i - 1).Value &lt;&gt; vbNullString Then Controls("Qty" &amp; i).Enabled = True Controls("UnitPrice" &amp; i).Enabled = True Controls("SubTotal" &amp; i).Enabled = True Controls("Comments" &amp; i).Enabled = True End If End If ElseIf TypeName(ctl) = "OptionButton" Then If ctl.Tag = "GroupItem" &amp; i - 1 Or ctl.Tag = "InOut" &amp; i - 1 Then Set optbtn = ctl If Controls("Item" &amp; i - 1).Value &lt;&gt; vbNullString Then Controls("OptionIn" &amp; i).Enabled = True Controls("OptionOut" &amp; i).Enabled = True End If End If End If Next ctl Next i End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-08T13:46:50.770", "Id": "395648", "Score": "1", "body": "I'd suggest to separate the \"control cleaning\" into different `Subs` for each control type, e.g. `UpdateLabelsToClean` and `UpdateTextBoxesToClean`. That way your overall metho...
[ { "body": "<p>I rows are being added dynamically I would write a class to wrap each row of controls and respond to the combobox events.</p>\n\n<p>Since there appears to be is a fixed number of rows, there is no reason to iterate over all the Controls in the userform.</p>\n\n<p>These variables seem legacy code b...
{ "AcceptedAnswerId": "205212", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-07T10:05:22.540", "Id": "205096", "Score": "1", "Tags": [ "vba", "excel", "user-interface" ], "Title": "Loop through different controls and enabled the state of the whole group VBA" }
205096
<p>This is k-means implementation using Python (numpy). I believe there is room for improvement when it comes to computing distances (given I'm using a list comprehension, maybe I could also pack it in a numpy operation) and to compute the centroids using label-wise means (which I think also may be packed in a numpy operation).</p> <pre><code>import numpy as np def k_means(data, k=2, max_iter=100): """Assigns data points into clusters using the k-means algorithm. Parameters ---------- data : ndarray A 2D array containing data points to be clustered. k : int, optional Number of clusters (default = 2). max_iter : int, optional Number of maximum iterations Returns ------- labels : ndarray A 1D array of labels for their respective input data points. """ # data_max/data_min : array containing column-wise maximum/minimum values data_max = np.max(data, axis=0) data_min = np.min(data, axis=0) n_samples = data.shape[0] n_features = data.shape[1] # labels : array containing labels for data points, randomly initialized labels = np.random.randint(low=0, high=k, size=n_samples) # centroids : 2D containing centroids for the k-means algorithm # randomly initialized s.t. data_min &lt;= centroid &lt; data_max centroids = np.random.uniform(low=0., high=1., size=(k, n_features)) centroids = centroids * (data_max - data_min) + data_min # k-means algorithm for i in range(max_iter): # distances : between datapoints and centroids distances = np.array( [np.linalg.norm(data - c, axis=1) for c in centroids]) # new_labels : computed by finding centroid with minimal distance new_labels = np.argmin(distances, axis=0) if (labels == new_labels).all(): # labels unchanged labels = new_labels print('Labels unchanged ! Terminating k-means.') break else: # labels changed # difference : percentage of changed labels difference = np.mean(labels != new_labels) print('%4f%% labels changed' % (difference * 100)) labels = new_labels for c in range(k): # computing centroids by taking the mean over associated data points centroids[c] = np.mean(data[labels == c], axis=0) return labels </code></pre>
[]
[ { "body": "<p>The code looks good, I wouldn't suggest anything as needing to be changed. In line with your question about possible ways to use Numpy better, I'll offer a few things you could try:</p>\n\n<ul>\n<li><p>You can pass low/high bounding arrays into <code>numpy.randint</code>, like <code>.randint(low=d...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-07T10:05:53.073", "Id": "205097", "Score": "5", "Tags": [ "python", "numpy", "machine-learning", "clustering", "data-mining" ], "Title": "k-means using numpy" }
205097
<p>I'm trying to script a C# game of Draughts/Checkers. I'm at the point of taking user input and validating it. I first check the input of current x and y coords to see they are numbers, then check the coord pair against the board. Then repeat for target coords. I end up with a really long function that has repetition, but can't figure out how to refactor it down.</p> <p>The code for this function is:</p> <pre><code>public static Board MovePiece(Board board, Player player) { bool CanContinue = false; bool validNumber = false; int number = 0; int xCurrent = 0; int yCurrent = 0; int xTarget = 0; int yTarget = 0; int validationStage = 0; while (!CanContinue) { validNumber = false; requestXCoord(validationStage); while (!validNumber) { if (Int32.TryParse(Console.ReadLine(), out number)) { xCurrent = number; validNumber = true; } else { Console.WriteLine(Message.notValidNumber); requestXCoord(validationStage); validNumber = false; } } validNumber = false; requestYCoord(validationStage); while (!validNumber) { if (Int32.TryParse(Console.ReadLine(), out number)) { yCurrent = number; validNumber = true; } else { Console.WriteLine(Message.notValidNumber); requestYCoord(validationStage); validNumber = false; } } if (validatePosition(board, player, xCurrent, yCurrent, validationStage)) { CanContinue = true; } else { CanContinue = false; } } validationStage = 1; CanContinue = false; while (!CanContinue) { validNumber = false; requestXCoord(validationStage); while (!validNumber) { if (Int32.TryParse(Console.ReadLine(), out number)) { xTarget = number; validNumber = true; } else { Console.WriteLine(Message.notValidNumber); requestXCoord(validationStage); validNumber = false; } } validNumber = false; requestYCoord(validationStage); while (!validNumber) { if (Int32.TryParse(Console.ReadLine(), out number)) { yTarget = number; validNumber = true; } else { Console.WriteLine(Message.notValidNumber); requestYCoord(validationStage); validNumber = false; } } if (validatePosition(board, player, xTarget, yTarget, validationStage)) { CanContinue = true; } else { CanContinue = false; } } PerformMove(board, player, xCurrent, yCurrent, xTarget, yTarget); return board; } </code></pre> <p>The other called functions are:</p> <pre><code>private static Board PerformMove(Board board, Player player, int xCurrent, int yCurrent, int xTarget, int yTarget) { if (canMakeMove(board, player, xCurrent, yCurrent, xTarget, yTarget)) { switchOwnership(board, player, xCurrent, yCurrent, xTarget, yTarget); return board; } return null; } private static void switchOwnership(Board board, Player player, int xCurrent, int yCurrent, int xTarget, int yTarget) { board.tiles[xTarget, yTarget].OwnedBy = player; board.tiles[xCurrent, yCurrent].OwnedBy = null; } private static bool canMakeMove(Board board, Player player, int xCurrent, int yCurrent, int xTarget, int yTarget) { return board.tiles[xCurrent, yCurrent].OwnedBy == player &amp;&amp; board.tiles[xTarget, yTarget].OwnedBy == null; } private static void requestXCoord(int step) { var xCoord = step &gt; 0 ? Message.targetX : Message.currentX; Console.Write(xCoord); } private static void requestYCoord(int step) { var yCoord = step &gt; 0 ? Message.targetY : Message.currentY; Console.Write(yCoord); } private static bool validatePosition(Board board, Player player, int x, int y, int step) { if (x &lt; 0 || y &lt; 0 || x &gt; 7 || y &gt; 7) { Console.WriteLine(Message.outOfBounds); return false; } else if (board.tiles[x, y].OwnedBy == null &amp;&amp; step == 0) { Console.WriteLine(Message.emptySpace); return false; } else if (board.tiles[x, y].OwnedBy == null &amp;&amp; step == 1) { return true; } else if (board.tiles[x, y].OwnedBy == player &amp;&amp; step == 1) { Console.WriteLine(Message.youOwnThis); return false; } else if (board.tiles[x, y].OwnedBy != player) { Console.WriteLine(Message.opponentOwns); return false; } return true; } </code></pre>
[]
[ { "body": "<p>This method revolves around one big piece of code repeated four times: Trying to read a number until it succeeds. We can refactor that into a separate method, accepting a string as argument containing the prompt to the user:</p>\n\n<pre><code>private int GetNumber(string message)\n{\n int resul...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-07T11:31:52.963", "Id": "205100", "Score": "7", "Tags": [ "c#", "checkers-draughts" ], "Title": "Validating user input for the game of draughts/checkers" }
205100
<p>I decided to resume my (limited) Python skills after not coding for a long time. </p> <p>Here's a very simple self-contained program to convert the characters of an email address into their HTML entities (the purpose is to make the email invisible to spamrobots). </p> <ul> <li><p>Any comment for improvement? (e.g. args parsing, code style, etc.)</p></li> <li><p>Apart from the <code>-h</code> option in <code>argparse</code>, what is the standard way to add some documentation for it, such as a manpage or some embedded help? </p></li> </ul> <pre><code>#!/usr/bin/python # # mung - Convert a string into its HTML entities # import argparse parser = argparse.ArgumentParser(description = 'Convert a string into its HTML entities.') parser.add_argument('string_to_mung', help = 'String to convert') parser.add_argument('-l', '--link', action = 'store_true', help = 'Embed the munged string into a mailto: link') args = parser.parse_args() def mung(plain): munged = '' for c in plain: munged = munged + '&amp;#' + str(ord(c)) + ';' return munged string_munged = mung(args.string_to_mung) if (args.link): print('&lt;a href="&amp;#109;&amp;#97;&amp;#105;&amp;#108;&amp;#116;&amp;#111;&amp;#58;') print(string_munged + '"&gt;') print(string_munged + '&lt;/a&gt;') else: print(string_munged) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-08T08:53:02.700", "Id": "395613", "Score": "1", "body": "Spam bots deal rather well with X(HT)ML escape sequences since they often use appropriate parser libraries." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2...
[ { "body": "<p>The code is straightforward and reads well, but:</p>\n\n<ol>\n<li>string concatenation is not very efficient, especially in a loop. You'd be better off using <code>str.join</code> on an iterable;</li>\n<li>encoding the <code>mailto:</code> part yourself impairs readability and maintenance, if only...
{ "AcceptedAnswerId": "205109", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-07T13:11:47.953", "Id": "205103", "Score": "6", "Tags": [ "python", "html", "email", "escaping" ], "Title": "Python program that obfuscates an email address" }
205103