body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I came across a problem that needs to reverse each word in a string without affecting space in it. For example, if a string has two spaces between the word, the answer needs to have space between two words. These are example test cases, I have been given<br> <strong>/This is a sentence/</strong><br> <strong>/ This is a Sentence /</strong><br> My approach is: </p> <pre><code>string oreverse(string s){ for(int i=0,n=s.size();i&lt;n/2;++i) swap(s[i],s[n-i-1]); return s; } string reverseWords(string s) { string re; for(auto i=0;i&lt;s.size();){ if(s[i]!=' '||s[i]=='/0'){ int _t = s.find_first_of(' ',i); re+=oreverse(s.substr(i,_t-i)); i=_t; }else{ re+=s[i]; i++; } } return re; } </code></pre> <p>I like to know, is there any further optimisation can be done or any other approaches with increased efficiency.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-28T10:28:41.550", "Id": "380533", "Score": "1", "body": "Welcome to Code Review! Could you please provide an example main and provide all of the includes? Also, did you test this? The compiler should complain about `'/0'`, as it should...
[ { "body": "<h1>Use compiler warnings</h1>\n\n<p>You should always enable compilers warning in c++. For your code, clang &amp; g++ gives the following warnings (<a href=\"https://wandbox.org/permlink/qswjiVNP5oPyGqzq\" rel=\"nofollow noreferrer\">live demo</a>):</p>\n\n<pre><code>prog.cc:14:29: warning: multi-ch...
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-28T07:12:54.010", "Id": "197400", "Score": "1", "Tags": [ "c++", "strings" ], "Title": "Reverse words in a string without affecting space" }
197400
<p>My first (real?) program.</p> <p>The client connects to a Django restframework API by sending user credentials to obtain a token for headers. Then the user can drag and drop an image from a OS folder into the terminal and press enter, then write a title for it to upload.</p> <p>The image(s) URL is obtained from the server and then turned into markdown that are listed in a bytearray. This byte array gets loaded into a tempfile that can be edited with the system's default editor or Vim. When this is saved and closed, it's converted to html and the article is published.</p> <h3>api_client.py</h3> <pre><code>import requests import tempfile import os import pypandoc import json from getpass import getpass from subprocess import call EDITOR = os.environ.get('EDITOR', 'vim') ARTICLE_URL = 'http://127.0.0.1:8000/api/articles/' IMAGE_URL = 'http://127.0.0.1:8000/api/media/images/' TOKEN_URL = 'http://127.0.0.1:8000/api-auth-token/' def obtain_token(username, password): """Authenticate and obtain token""" data = {'username': username, 'password': password} req = requests.post(TOKEN_URL, data=data) res = req.json() token = res['token'] headers = {'Authorization': 'Token {}'.format(token)} return headers """ Ask for user credentials to set header, not sure how to place this code in a functional way """ username = input("Username: ") password = getpass() headers = obtain_token(username=username, password=password) def image_upload(img_file, img_title): """Upload image with title""" files = {'image': img_file} payload = {'title': img_title} upload = requests.post(IMAGE_URL, files=files, data=payload, headers=headers) return upload md_urls = bytearray() def img_docload(): """ Get the latest uploaded image and convert it to a html string so that pypandoc again can make it into markdown, then extend each to the bytearray. """ get_url = requests.get(IMAGE_URL) get_json = json.loads(get_url.content) clean = get_json[-1]['image'] md_html = "&lt;img src='"+clean+"'&gt;" md = pypandoc.convert_text(md_html, 'md', format='html') md_urls.extend(md.encode()) def article(headline, summary): """ Make a tempfile and write the list of markdown inserts, then open it in Vim or any default editor. Save and quit to convert from markdown to html and upload the article. """ with tempfile.NamedTemporaryFile(suffix='.md') as tmp: tmp.write(md_urls) tmp.flush() call([EDITOR, tmp.name]) tmp.seek(0) edited = tmp.read() article = edited.decode('utf-8') content = pypandoc.convert_text(article, 'html', format='md') payload = { 'headline': headline, 'summary': summary, 'content': content, } upload = requests.post(ARTICLE_URL, json=payload, headers=headers) return upload def main(): while True: action = input("Upload image? (k): ") if action == 'k': img_file = open(input("Image - Filename: ").strip('\''), 'rb') img_title = input("Image - Title: ") image_upload(img_file=img_file, img_title=img_title) img_docload() continue else: headline = input("Article - Headline: ") summary = input("Article - Summary: ") article(headline=headline, summary=summary) print("Article is published") break main() </code></pre> <h3>Questions:</h3> <ul> <li>I wrote the program without a single function to begin with. Then I tried to follow the functional design to learn more about functions and how to structure programs. What could be done better? </li> <li>How would you place the <code>obtain_token</code> function and its I/O?</li> <li>My next goal is to learn about classes and OOP; is there a place for classes in this program or is it unnecessary?</li> <li>What do you think about the way it first upload an image and then gets the URL, then puts it into a HTML <code>img</code> element, and then converts it to md (pypandoc needs it to make the markdown, and I wanted the links to be "dynamic")? This can't be the best approach; would you do it server-side? Or is it best to do as much as possible on the client-side?</li> </ul> <p>In general I would like to know about all the mistakes I have made - what could be done better - especially regarding structure, before I move on to learn more.</p>
[]
[ { "body": "<blockquote>\n<pre><code>ARTICLE_URL = 'http://127.0.0.1:8000/api/articles/'\nIMAGE_URL = 'http://127.0.0.1:8000/api/media/images/'\nTOKEN_URL = 'http://127.0.0.1:8000/api-auth-token/'\n</code></pre>\n</blockquote>\n\n<p>The repetition here could be harmful. If you move the server, then there's thre...
{ "AcceptedAnswerId": "226899", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-28T09:37:06.260", "Id": "197406", "Score": "4", "Tags": [ "python", "beginner" ], "Title": "Python API article/image client using requests, pypandoc and os editor" }
197406
<p>Python3's <code>async</code>/<code>await</code> syntax is great, but it does create a divide between libraries which are async-based and those which are not. For example, <a href="https://github.com/boto/boto3" rel="noreferrer">boto3</a> (AWS API library) currently doesn't work with async. There is a separate project, <a href="https://github.com/aio-libs/aiobotocore" rel="noreferrer">aiobotocore</a>, attempts to recreate some of this functionality in an async context.</p> <p>I have been thinking for a while about how to create HTTP API clients which can be run async and sync contexts. I have come up with a strategy that involves creating a separation between the logic (preparation of requests, interpretation of responses), and the sending. The logic is implemented as a generator function, which yields out an object which represents the request, and receives back an object representing the response. This generator is "run" by a runner function, which does the actual sending, and may be sync or async.</p> <p>You can imagine that if, for example, <code>boto3</code> had been written this way, it would be easy to re-use the bulk of the code to make an async version, rather than having to do an async rewrite.</p> <p>I have included a toy example below. I would welcome comments.</p> <pre><code>from typing import Iterable, NamedTuple, Dict, Any, Optional import requests from aiohttp import ClientSession URL_TEMPLATE = "https://api.icndb.com/jokes/{id}/" class Request(NamedTuple): method: str url: str json: Optional[Dict[str, Any]] = None class Response(NamedTuple): status: int json: Optional[Dict[str, Any]] = None def get_joke(id: int) -&gt; Iterable[Request]: response = yield Request("GET", URL_TEMPLATE.format(id=id)) try: if response.status != 200: raise JokeApiError("API request failed") data = response.json if data.get("type") == 'NoSuchQuoteException': raise NoSuchJoke(data.get("value", "")) if data.get("type") != "success": raise JokeApiError("API request failed") raise Return(data["value"]["joke"]) except (JokeApiError, Return, StopIteration): raise except Exception as e: raise JokeApiError() from e def call_api_sync(it): try: for req in it: response = requests.request(req.method, req.url, json=req.json) it.send( Response(status=response.status_code, json=response.json()) ) except Return as e: return e.value async def call_api_async(it): async with ClientSession() as session: try: for req in it: async with session.request( method=req.method, url=req.url, json=req.json) as res: json = await res.json() response = Response(status=res.status, json=json) it.send(response) except Return as e: return e.value class JokeApiError(Exception): pass class NoSuchJoke(JokeApiError): pass class Return(Exception): def __init__(self, value): self.value = value </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-28T17:23:09.423", "Id": "380596", "Score": "0", "body": "I'd suggest adding a`if name...` section as well" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-28T18:13:17.057", "Id": "380602", "Score": "...
[ { "body": "<p>The code is admirably clear.\nNice annotations.\nWith these classes,\nChuck Norris wouldn't need a debugger,\nhe could just stare down the bug until the code confesses.</p>\n\n<pre><code>class Request(NamedTuple):\n method: str\n</code></pre>\n\n<p>Maybe list <code>method</code> 2nd, and allow ...
{ "AcceptedAnswerId": "216602", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-28T11:48:22.063", "Id": "197425", "Score": "8", "Tags": [ "python", "python-3.x", "async-await" ], "Title": "Creating API clients that are \"async agnostic\"" }
197425
<p>I'm writing my own MVC framework for learning purposes. Usually in my projects I like to use <code>AJAX</code> to send requests and retrive data. Now my doubt is if this can be a best approach to make a one page dashboard. </p> <p>I've created an <code>.htaccess</code> who will display only folders that have an index file inside, the dashboard will be loaded only after user login, the login form is on the index file who is inside a folder named user. On the root of the project there is another index file who will be publicy available.</p> <p>Assuming I've this code in the user dashboard file:</p> <p><code>HTML</code></p> <pre><code>&lt;div class="container-fluid" id="app"&gt; &lt;div class="row"&gt; &lt;div class="col-sm-12 col-lg-4"&gt; &lt;a href="#" id="open-settings"&gt; &lt;div class="card"&gt; &lt;div class="card-body"&gt; &lt;div class="card-img-top text-center"&gt; &lt;i class="fas fa-cog fa-3x"&gt;&lt;/i&gt; &lt;/div&gt; &lt;h5 class="card-title text-uppercase text-center"&gt;settings&lt;/h5&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class="col-sm-12 col-lg-4"&gt; &lt;a href="#"&gt; &lt;div class="card"&gt; &lt;div class="card-body"&gt; &lt;div class="card-img-top text-center"&gt; &lt;i class="fas fa-database fa-3x"&gt;&lt;/i&gt; &lt;/div&gt; &lt;h5 class="card-title text-uppercase text-center"&gt;show database entry&lt;/h5&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class="col-sm-12 col-lg-4"&gt; &lt;a href="#"&gt; &lt;div class="card"&gt; &lt;div class="card-body"&gt; &lt;div class="card-img-top text-center"&gt; &lt;i class="fas fa-plus fa-3x"&gt;&lt;/i&gt; &lt;/div&gt; &lt;h5 class="card-title text-uppercase text-center"&gt;new insert&lt;/h5&gt; &lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row" id="display-view"&gt;&lt;/div&gt; &lt;/div&gt; &lt;!-- container end --&gt; </code></pre> <p>What is the best approach to load the requested view for the user selected action? I want to avoid duplication of the jquery code who now is something like this</p> <pre><code>$('#open-settings').on('click',function(e){ e.preventDefault(); preloader.modal('show'); $.ajax({ type: 'GET', url: 'view/settings.php', cache: false, beforeSend: function(){ preloader.modal('show'); }, success: function(response){ $('#display-view').html(response) } }); </code></pre>
[]
[ { "body": "<p>Without really knowing a great deal about how your code is structured and basing it purely on your ajax function you could so somethhing like this; </p>\n\n<pre><code>function loadView(url, beforeSend, callback) {\n $.ajax({\n type: 'GET',\n url: url,\n cache: false,\n ...
{ "AcceptedAnswerId": "197434", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-28T12:10:46.287", "Id": "197427", "Score": "0", "Tags": [ "javascript", "jquery", "ajax" ], "Title": "Simple AJAX view loading approach" }
197427
<p>The story here is about a console application that replays to a test system string clauses already imported in the production system.</p> <p>Looking forward to your comments.</p> <pre><code>namespace MyCompany.Department.ProjectXYZ; { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.ServiceModel; using MyCompany.XYZ; /// &lt;summary&gt; /// Books message clauses to staging Diamant via web service.&lt;para/&gt; /// If no arguments are provided, the program reads from the production database log table (&lt;see cref="ImportJobData"/&gt;) /// all clauses that were imported in the last 24 hours.&lt;para/&gt; /// If a single filename argument is provided, the program reads clauses from that file.&lt;para/&gt; /// The program writes clauses that encounter an error on booking to Diamant in a text file in the FailedClauses directory. /// &lt;/summary&gt; public class Program { /// &lt;summary&gt; /// Client to the staging web service. /// &lt;/summary&gt; private static ImportVSMessageClient _client; /// &lt;summary&gt; /// Error messages for all processed clauses. /// &lt;/summary&gt; private static readonly List&lt;string&gt; _errorMessages = new List&lt;String&gt;(); private static readonly IApplicationLogger _logger = ApplicationMonitoring.GetLogger(typeof(Program)); private static readonly Lazy&lt;ErrorService&gt; _errorService = new Lazy&lt;ErrorService&gt;(() =&gt; new ErrorService()); internal static void Main(string[] args) { WebServiceClientApplication.Initialize(); _client = new ImportVSMessageClient(); try { var clauses = GetClausesToImport(args); DoImport(clauses); } catch (Exception ex) { _errorMessages.Add(ex.Message); } finally { if (_errorMessages.Any()) { _errorService.Value.ProcessError( "WebService.Client - Error", string.Join(Environment.NewLine, _errorMessages)); } _client.Close(); } } #region Private methods private static IEnumerable&lt;string&gt; GetClausesToImport(string[] args) { if (!args.Any()) { return GetImportedClausesOnPreviousDay(); } string filename = args[0]; return File.ReadAllLines(filename); } private static IEnumerable&lt;string&gt; GetImportedClausesOnPreviousDay() { IImportJobsService importJobsService = new ImportJobsService(); return importJobsService.Load(DiamantSystem.Produktion, DateTime.Now.AddDays(-1), DateTime.Now) .Where(IsValid).OrderBy(ijd =&gt; ijd.Erstelldatum) .Select(ijd =&gt; ijd.Eingangswerte); } private static Boolean IsValid(ImportJobData ijd) { return ijd.Status == VerarbeitungsStatus.ImportErfolgreich &amp;&amp; ijd.Satzart != Satzart.LOGOUT; } private static void DoImport(IEnumerable&lt;string&gt; clauses) { var clausesList = clauses.ToList(); if (clausesList.Any()) { _logger.Info("Importing {0} messages.", clausesList.Count); ImportClauses(clausesList); _logger.Info("Closing connection."); ImportClause(Satzart.LOGOUT); _logger.Info("Finished importing."); } else { _logger.Info("Nothing to import."); } } private static void ImportClauses(IEnumerable&lt;string&gt; clauses) { var failedClauses = new List&lt;String&gt;(); foreach (var clause in clauses) { var success = ImportClause(clause); if (!success) { failedClauses.Add(clause); } } if (failedClauses.Any()) { WriteFailedClauses(failedClauses); } } // Returns true when successful. private static bool ImportClause(String clause) { var errorMessage = RunImportAction(() =&gt; _client.ImportMessage(clause)); if (string.IsNullOrEmpty(errorMessage)) { return true; } LogError(string.Format("Clause: {0}", clause)); LogError(string.Format("Error: {0}", errorMessage)); return false; } private static void LogError(string errorMsg) { _errorMessages.Add(errorMsg); _logger.Error(errorMsg); } // Returns empty string when successful, otherwise the error message. private static String RunImportAction(Action action) { try { action(); return string.Empty; } catch (FaultException&lt;DiamantWarningFaultContract&gt; faultException) { return faultException.Detail.ErrorMessage.Aggregate((a, b) =&gt; a + Environment.NewLine + b); } catch (FaultException&lt;DiamantFatalFaultContract&gt; faultException) { return faultException.Detail.ErrorMessage.Aggregate((a, b) =&gt; a + Environment.NewLine + b); } catch (FaultException exception) { return string.Format("Code: {0}, Message: {1}", exception.Code.Name, exception.Message); } catch (Exception exception) { return exception.Message; } } private static void WriteFailedClauses(IEnumerable&lt;string&gt; failedClauses) { string filename = String.Format("FailedClauses_{0}.txt", DateTime.Now.ToString("yyyy-MM-dd-HHmmss")); filename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "FailedClauses", filename); File.WriteAllLines(filename, failedClauses); } #endregion } } </code></pre>
[]
[ { "body": "<p>Few small observaions.</p>\n\n<ol>\n<li><p>Good use of <code>readonly</code> </p></li>\n<li><p>Might want to declare your <code>_errorMessages</code> as a more generic type, e.g.:</p>\n\n<p><code>private static readonly ICollection&lt;string&gt; _errorMessages = new List&lt;String&gt;();</code></p...
{ "AcceptedAnswerId": "197431", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-28T13:19:49.843", "Id": "197430", "Score": "4", "Tags": [ "c#", ".net" ], "Title": "From production to staging" }
197430
<p>I've written a perl script that creates a csv file consolidated of values from multiple files. This file that I've created is then used to update certain rows in a main excel spreadsheet my company uses. I've created a VBA script that scans the main file for values that match up with those from my perl generate file and it all works fine. </p> <p>The problem is that it takes about four minutes to run. The main file is only about 1000 or so rows long, and the file I'm generating only comes out to about 100 rows top. My logic in my script is to scan through every row in the main file for each row in the generated file:</p> <pre><code>Sub TransferDataToForecast() Dim strPath As String 'File path Dim foreb As Workbook 'Workbook that the file path points to Dim copys As Worksheet 'Worksheet that contains the data to be copied Dim dests As Worksheet 'Worksheet that is being copied to Dim copysLastRow As Long 'Last row of data worksheet Dim copysLastCol As Long 'Last column of data worksheet Dim destsLastRow As Long 'Last row of target worksheet Dim counter As Long 'Counter for loop control Application.ScreenUpdating = False Set copys = ActiveWorkbook.ActiveSheet 'Get user to select target workbook strPath = BrowseForFile("Select the DM Forecast file you want to update") If strPath = vbNullString Then Exit Sub 'Debug.Print strPath Set foreb = Workbooks.Open(strPath) Set dests = foreb.Worksheets("Material_Usage_Prim") 'Get last row of each worksheet and last column of data sheet in order to help with loop control copysLastRow = copys.Cells(Rows.Count, 3).End(xlUp).Row copysLastCol = copys.Cells(2, Columns.Count).End(xlToLeft).Column destsLastRow = dests.Cells(Rows.Count, 1).End(xlUp).Row counter = 0 'Loop through each row of the data sheet For i = 2 To copysLastRow Debug.Print "i is "; i 'For each row in the data sheet, loop through every row in the destination sheet in order 'to find matching id's between each sheet For j = 2 To destsLastRow Debug.Print "j is "; j If Trim(copys.Cells(i, 3).Value2) = vbNullString Then Exit For 'This exits the loop if the data sheet has a blank row If dests.Cells(j, 4) &lt;&gt; copys.Cells(i, 4) Then GoTo NextDestLoop 'This skips the rest of the current j if values in col4 of each sheet don't match up 'Have to use replace due to differing naming conventins among people i.e. _ vs - (this row can be changed for specific peoples needs) 'This checks that columns 3 and 4 of each sheet match If Replace(copys.Cells(i, 3).Value2, "_", "") = Replace(dests.Cells(j, 3).Value2, "_", "") And copys.Cells(i, 4).Value2 = dests.Cells(j, 4).Value2 Then counter = 0 For k = 5 To copysLastCol Debug.Print "k is "; k 'Go to 14, because we want to keep the first 14 weeks (columns) If counter &lt; 14 Then counter = counter + 1 GoTo NextIteration End If counter = counter + 1 dests.Cells(j, k).Value2 = copys.Cells(i, k).Value2 NextIteration: Next k End If If counter = copysLastRow Then GoTo NextLoop NextDestLoop: Next j NextLoop: Next i Application.ScreenUpdating = True MsgBox ("Data has been transferred.") End Sub 'This function brings up a window for the user to pick an excel file they want to update Private Function BrowseForFile(Optional strTitle As String) As String Dim fDialog As FileDialog On Error GoTo Err_handler Set fDialog = Application.FileDialog(msoFileDialogFilePicker) With fDialog .Title = strTitle .Filters.Add "Excel Files", "*.xlsx; *.xlsm; *.xls; *.xlsb", 1 .AllowMultiSelect = False .InitialView = msoFileDialogViewList If .Show &lt;&gt; -1 Then GoTo Err_handler: BrowseForFile = fDialog.SelectedItems.Item(1) End With lbl_Exit: Exit Function Err_handler: BrowseForFile = vbNullString Resume lbl_Exit End Function </code></pre> <p>If anyone can help me to make this more efficient I would be grateful! </p>
[]
[ { "body": "<p>I found something a little awkward that I would do differently</p>\n\n<p>your code </p>\n\n<blockquote>\n<pre><code> If Replace(copys.Cells(i, 3).Value2, \"_\", \"\") = Replace(dests.Cells(j, 3).Value2, \"_\", \"\") And copys.Cells(i, 4).Value2 = dests.Cells(j, 4).Value2 Then\n counter = 0\n ...
{ "AcceptedAnswerId": "197445", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-28T15:33:01.883", "Id": "197435", "Score": "5", "Tags": [ "performance", "vba" ], "Title": "VBA script that copies data from one workbook to another" }
197435
<h2>Program purpose</h2> <p>The purpose for the program is to create a file containing the effective inventory for each stocked item stored in a collection of shops. </p> <h2>Input and algorithm details</h2> <p>For clarity, in the descriptions below, variables in the C++ program use this style: <code>nShopID</code>, while fields in CSV files are shown like this: <em>shop_id</em>. </p> <h3>Shops and groups</h3> <p>The problem domain is a collection of <strong>shops</strong> (identified by an <code>int</code> shop ID number) each of which is assigned to a <strong>group</strong> (also identified by an <code>int</code>). The association between <code>nShopID</code> and <code>nGroupID</code> is contained in a text file <code>shopgroups.csv</code>, which is a tab-delimited file with a header with two fields: <em>shop_id</em> and <em>shopgroup_id</em>. </p> <h3>Simple inventory</h3> <p>The <strong>simple inventory</strong> is in a file named <code>shopstock_all.csv</code>. That file is also a tab-delimited file with header containing three fields: <em>item_idx</em>, <em>shop_id</em>, and <em>amount</em>. The <em>item_idx</em> field is a string containing the item identifier, and the <em>shop_id</em> represents the shop that has the item and <em>amount</em> is an integer representing the quantity of the item at that shop. </p> <h3>Effective inventory</h3> <p>The <em>simple inventory</em> is simply the number of items at each shop, as described above, but the desired <strong>effective inventory</strong> takes into account the fact that the inventory of nearby shops could, if needed, be quickly moved to one particular shop. Thus, the <em>effective inventory</em> of a particular shop represents the <em>simple inventory</em> of that shop plus that of nearby stores. Nearby stores and the direction of possible movement of inventory is represented in a third tab-delimited file called <code>sgm.csv</code> which contains a header and two fields: <em>shop_group_from</em> and <em>shop_group_to</em>. For example, a line in the file might say <code>8 15</code> which means that any inventory in group 8 can be counted in the effective inventory of all shops in group 15. These associations are many-to-many (that is group 8 might feed multiple groups and group 15 might be fed from multiple other groups) and not necessarily reciprocal. That is, group 8 inventory may be moved to group 15 shops but not necessarily the other direction unless explicitly stated in the file.</p> <p>Additionally, all shops within the same group also share their effective inventory without needing a special line in the <code>sgm.csv</code> file.</p> <p>Finally, some warehouse shops (those with <code>nShopID &gt; 10000</code>) have extra storage available and goods are only transferred <em>from</em> and never <em>to</em> such shops. To differentiate, the program actually calculates two effective inventory quantities for each store; <code>nTotalAmount</code> which is the effective inventory from all stores including these warehouse shops and <code>nTotalAmount10k</code> which is the effective inventory excluding these warehouse shops.</p> <h2>Output file</h2> <p>The output file is a tab-delimited file with no header with each record (line) containing four fields: <em>itemID</em>, <em>shopID</em>, <em>totalAmount</em>, <em>totalAmount10k</em> each of which has been described above. The order of the records within the file does not matter.</p> <h2>The code</h2> <p>The code and sample files are all on <a href="https://gitlab.com/pk72/shop-stock-total" rel="nofollow noreferrer">on GitLab</a></p> <h2>Questions</h2> <p>Since I rarely write C++ code, I've got a mix of C++ and C code. Could it be fixed without hurting performance?</p> <p>What should be fixed to improve readability, naming of variables and code styling?</p> <p>Could makefile be less "bloated"? (This is the 2nd one I've ever written.)</p> <p>P.S. I'm using vim, so there are</p> <pre><code>// {{{ manual-style folding comments // ... // }}} </code></pre> <p>and I would prefer to leave those as is.</p> <h2>shop_stock_total.h</h2> <pre><code>// {{{ Structures and typedefs // {{{ ShopGroupMove typedef list&lt;int&gt; GroupsFromList; struct ShopGroupMoveStruct { int nGroupTo; GroupsFromList *lstGroupsFrom; }; typedef unordered_map&lt;int, struct ShopGroupMoveStruct&gt; ShopGroupMovesMap; // }}} // {{{ ShopGroup typedef list&lt;int&gt; ShopsList; struct ShopGroupStruct { int nGroupID; ShopsList *lstShops; // all shops with the same group }; typedef unordered_map&lt;int, struct ShopGroupStruct&gt; ShopGroupsMap; // }}} // {{{ Shop struct ShopStruct { int nShopID; int nGroupID; ShopsList *lstFromAll; ShopsList *lstFrom10k; }; typedef unordered_map&lt;int, struct ShopStruct&gt; ShopsMap; // }}} // {{{ Availability struct AvailabilityStruct { int nShopID; int nAmount; int nTotalAmount; int nTotalAmount10k; }; typedef unordered_map&lt;int, struct AvailabilityStruct&gt; AvailabilitiesMap; // }}} // {{{ ShopStock struct ShopStockStruct { char *sItemID; AvailabilitiesMap *mapAv; }; typedef unordered_map&lt;std::string, struct ShopStockStruct&gt; ShopStocksMap; // }}} // }}} // {{{ Functions // {{{ APP specific void ProcessShopGroupMoves(ShopGroupMovesMap *mapSGM); void DebugPrintSGM(ShopGroupMovesMap *mapSGM); void ProcessShopGroups(ShopGroupsMap *mapSG, ShopsMap *mapS); void DebugPrintSG(ShopGroupsMap *mapSG, ShopsMap *mapS); void Fill_FromShopAll(ShopGroupMovesMap *mapSGM, ShopGroupsMap *mapSG, ShopsMap *mapS); void DebugPrintS(ShopsMap *mapS); void ProcessShopStocks(ShopStocksMap *mapSS, ShopsMap *mapS, FILE *out); void PostProcessItem(ShopStockStruct *pstSS, ShopsMap *mapS, FILE *out); void DebugPrintSS(ShopStockStruct *pstSS); void WriteResult(ShopStockStruct *pstSS, FILE *out); // }}} // {{{ generic std::vector&lt;std::string&gt; &amp;split(const std::string &amp;s, char delim, std::vector&lt;std::string&gt; &amp;elems); std::vector&lt;std::string&gt; split(const std::string &amp;s, char delim); // }}} // }}} </code></pre> <hr> <h2>shop_stock_total.cpp</h2> <pre><code>// {{{ standard and other includes #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;iostream&gt; #include &lt;locale&gt; #include &lt;fstream&gt; #include &lt;string&gt; #include &lt;string.h&gt; #include &lt;sstream&gt; #include &lt;assert.h&gt; #include &lt;ctype.h&gt; #include &lt;algorithm&gt; #include &lt;unordered_map&gt; #include &lt;vector&gt; #include &lt;list&gt; // }}} // {{{ filenames const char *SHOP_GROUP_MOVES_FILE = "sgm.csv"; const char *SHOP_GROUPS_FILE = "shopgroups.csv"; const char *SHOP_STOCKS_FILE = "shopstock_all.csv"; const char *SHOP_STOCK_TOTALS_FILE = "shop_stock_total.csv"; // }}} using namespace std; #include "shop-stock-total.h" // {{{ main int main() { // ShopGroupMoves ShopGroupMovesMap *mapSGM; mapSGM = new ShopGroupMovesMap(); ProcessShopGroupMoves(mapSGM); DebugPrintSGM(mapSGM); // ShopGroups and Shops ShopGroupsMap *mapSG; mapSG = new ShopGroupsMap(); ShopsMap *mapS; mapS = new ShopsMap(); ProcessShopGroups(mapSG, mapS); DebugPrintSG(mapSG, mapS); Fill_FromShopAll(mapSGM, mapSG, mapS); DebugPrintS(mapS); // ShopStock ShopStocksMap *mapSS; mapSS = new ShopStocksMap(); FILE* fileSST = fopen (SHOP_STOCK_TOTALS_FILE, "w+"); ProcessShopStocks(mapSS, mapS, fileSST); fclose(fileSST); return 0; } // }}} // {{{ ProcessShopGroupMoves void ProcessShopGroupMoves(ShopGroupMovesMap *mapSGM) { std::ifstream file(SHOP_GROUP_MOVES_FILE); std::string l; ShopGroupMoveStruct *pstSGM; int nKey = -1; int nSGMs = 0; int nGroupFrom; int nGroupTo; std::vector&lt;std::string&gt; vsItems; while (std::getline(file, l)) { // skip first line if (nKey &lt; 0) { nKey = 0; continue; } vsItems = split(l, (char) '\t'); if (vsItems.size() &lt; 2) continue; nGroupFrom = atoi(vsItems[0].c_str()); nGroupTo = atoi(vsItems[1].c_str()); auto sgm = mapSGM-&gt;find(nGroupTo); if (sgm == mapSGM-&gt;end()) { // not found, so we need to create a new one pstSGM = new ShopGroupMoveStruct(); pstSGM-&gt;nGroupTo = nGroupTo; pstSGM-&gt;lstGroupsFrom = new GroupsFromList(); // and store it, we'll add from value a bit later (* mapSGM)[nGroupTo] = *pstSGM; } else { // found group already, get a pointer to it for adding nGroupFrom // value later pstSGM = &amp;(sgm-&gt;second); } // in any case (found or not), we've to add GroupFrom value pstSGM-&gt;lstGroupsFrom-&gt;push_back(nGroupFrom); nSGMs++; } printf("Total %d ShopGroupMoves loaded.\n", nSGMs); } // }}} // {{{ DebugPrintSGM void DebugPrintSGM(ShopGroupMovesMap *mapSGM) { for (auto sgm=mapSGM-&gt;begin(); sgm != mapSGM-&gt;end(); sgm++) { printf("%d:\t", sgm-&gt;second.nGroupTo); for (auto f=sgm-&gt;second.lstGroupsFrom-&gt;begin(); f!=sgm-&gt;second.lstGroupsFrom-&gt;end(); f++) { printf("%d ", *f); } printf("\n"); } } // }}} // {{{ ProcessShopGroups void ProcessShopGroups(ShopGroupsMap *mapSG, ShopsMap *mapS) { std::ifstream file(SHOP_GROUPS_FILE); std::string l; int nSGs = 0; int nKey = -1; int nShopID; int nGroupID; ShopStruct *pstShop; ShopGroupStruct *pstSG; std::vector&lt;std::string&gt; vsItems; while (std::getline(file, l)) { // skip first line if (nKey &lt; 0) { nKey = 0; continue; } vsItems = split(l, (char) '\t'); if (vsItems.size() &lt; 2) continue; nShopID = atoi(vsItems[0].c_str()); nGroupID = atoi(vsItems[1].c_str()); // skip zero ID shop if (nShopID == 0) continue; // create new Shop and save it pstShop = new ShopStruct(); pstShop-&gt;nShopID = nShopID; pstShop-&gt;nGroupID = nGroupID; pstShop-&gt;lstFromAll = new ShopsList(); pstShop-&gt;lstFrom10k = new ShopsList(); (* mapS)[nShopID] = *pstShop; // do we need to save ShopGroup if (nGroupID == 0) continue; auto sg = mapSG-&gt;find(nGroupID); if (sg == mapSG-&gt;end()) { // not found, so we need to create a new one pstSG = new ShopGroupStruct(); pstSG-&gt;nGroupID = nGroupID; pstSG-&gt;lstShops = new ShopsList(); // and store it, we'll add from value a bit later (* mapSG)[nGroupID] = *pstSG; } else { // found group already, get a pointer to it for adding shop // value later pstSG = &amp;(sg-&gt;second); } // in any case (found or not), we've to add GroupFrom value pstSG-&gt;lstShops-&gt;push_back(nShopID); nSGs++; } printf("Total %d ShopGroups loaded.\n", nSGs); } // }}} // {{{ Fill_FromShopAll void Fill_FromShopAll(ShopGroupMovesMap *mapSGM, ShopGroupsMap *mapSG, ShopsMap *mapS) { for (auto s = mapS-&gt;begin(); s != mapS-&gt;end(); s++) { // fill shops from the same group auto sg = mapSG-&gt;find(s-&gt;second.nGroupID); if (sg != mapSG-&gt;end()) { for (auto s_ = sg-&gt;second.lstShops-&gt;begin(); s_ != sg-&gt;second.lstShops-&gt;end(); s_++) { s-&gt;second.lstFromAll-&gt;push_back(*s_); } } // fill shops from movement groups auto sgm = mapSGM-&gt;find(s-&gt;second.nGroupID); if (sgm != mapSGM-&gt;end()) { for (auto sg = sgm-&gt;second.lstGroupsFrom-&gt;begin(); sg != sgm-&gt;second.lstGroupsFrom-&gt;end(); sg++) { auto sg_ = mapSG-&gt;find(*sg); if (sg_ != mapSG-&gt;end()) { for (auto s_ = sg_-&gt;second.lstShops-&gt;begin(); s_ != sg_-&gt;second.lstShops-&gt;end(); s_++) { s-&gt;second.lstFromAll-&gt;push_back(*s_); } } } } // de duping s-&gt;second.lstFromAll-&gt;sort(); s-&gt;second.lstFromAll-&gt;unique(); // remove shop itself s-&gt;second.lstFromAll-&gt;remove(s-&gt;second.nShopID); // copy to 10k /* auto n = std::copy_if( */ /* s-&gt;second.lstFromAll-&gt;begin(), */ /* s-&gt;second.lstFromAll-&gt;end(), */ /* s-&gt;second.lstFrom10k-&gt;begin(), */ /* [](int i){return (i &lt; 10000);}); */ /* s-&gt;second.lstFrom10k-&gt;size( */ /* auto n = std::copy( */ /* s-&gt;second.lstFromAll-&gt;begin(), */ /* s-&gt;second.lstFromAll-&gt;end(), */ /* s-&gt;second.lstFrom10k-&gt;begin() */ /* ); */ /* s-&gt;second.lstFrom10k-&gt;resize( */ /* std::distance(s-&gt;second.lstFrom10k-&gt;begin(), n)); */ for (auto s_ = s-&gt;second.lstFromAll-&gt;begin(); s_ != s-&gt;second.lstFromAll-&gt;end(); s_++) { if (*s_ &lt; 10000) { s-&gt;second.lstFrom10k-&gt;push_back(*s_); } } } } // }}} // {{{ DebugPrintS void DebugPrintS(ShopsMap *mapS) { for (auto s = mapS-&gt;begin(); s != mapS-&gt;end(); s++) { printf("%d:\t", s-&gt;second.nShopID); for (auto s_ = s-&gt;second.lstFrom10k-&gt;begin(); s_ != s-&gt;second.lstFrom10k-&gt;end(); s_++) { printf("%d, ", *s_); } printf("\n"); } } // }}} // {{{ DebugPrintSG void DebugPrintSG(ShopGroupsMap *mapSG, ShopsMap *mapS) { // print shop groups for (auto sg=mapSG-&gt;begin(); sg != mapSG-&gt;end(); sg++) { printf("%d:\t", sg-&gt;second.nGroupID); for (auto s = sg-&gt;second.lstShops-&gt;begin(); s != sg-&gt;second.lstShops-&gt;end(); s++) { printf("%d ", *s); } printf("\n"); } // print shops for ( auto s = mapS-&gt;begin(); s != mapS-&gt;end(); s++) { printf("%d : %d\n", s-&gt;second.nShopID, s-&gt;second.nGroupID); } } // }}} // {{{ PostProcessItem void PostProcessItem(ShopStockStruct *pstSS, ShopsMap *mapS, FILE *out) { AvailabilityStruct *pstAV; for (auto s = mapS-&gt;begin(); s != mapS-&gt;end(); s++) { // if shop is not present in current item Availability // add it with 0 amounts, // coz we could still move goods there from others shops auto s_ = pstSS-&gt;mapAv-&gt;find(s-&gt;second.nShopID); if (s_ == pstSS-&gt;mapAv-&gt;end()) { pstAV = new AvailabilityStruct(); pstAV-&gt;nShopID = s-&gt;second.nShopID; pstAV-&gt;nAmount = 0; pstAV-&gt;nTotalAmount = 0; pstAV-&gt;nTotalAmount10k = 0; (*(pstSS-&gt;mapAv))[s-&gt;second.nShopID] = *pstAV; } } // summing up total availability for (auto av = pstSS-&gt;mapAv-&gt;begin(); av != pstSS-&gt;mapAv-&gt;end(); av++) { // add amounts from shop itself av-&gt;second.nTotalAmount = av-&gt;second.nAmount; av-&gt;second.nTotalAmount10k = av-&gt;second.nAmount; // add amount from other shops which could move goods into this one auto s_ = mapS-&gt;find(av-&gt;second.nShopID); if (s_ == mapS-&gt;end()) continue; for (auto s__ = s_-&gt;second.lstFromAll-&gt;begin(); s__ != s_-&gt;second.lstFromAll-&gt;end(); s__++) { auto av_ = pstSS-&gt;mapAv-&gt;find(*s__); if (av_ == pstSS-&gt;mapAv-&gt;end()) continue; av-&gt;second.nTotalAmount += av_-&gt;second.nAmount; if (*s__ &lt; 10000) { av-&gt;second.nTotalAmount10k += av_-&gt;second.nAmount; } } } //DebugPrintSS(pstSS); WriteResult(pstSS, out); } // }}} // {{{ DebugPrintSS void DebugPrintSS(ShopStockStruct *pstSS) { printf("%s:\t", pstSS-&gt;sItemID); for (auto av = pstSS-&gt;mapAv-&gt;begin(); av != pstSS-&gt;mapAv-&gt;end(); av++) { printf("%d - %d - %d;", av-&gt;second.nShopID, av-&gt;second.nTotalAmount, av-&gt;second.nTotalAmount10k); } printf("\n"); } // }}} // {{{ WriteResult void WriteResult(ShopStockStruct *pstSS, FILE *out) { for (auto av = pstSS-&gt;mapAv-&gt;begin(); av != pstSS-&gt;mapAv-&gt;end(); av++) { if (av-&gt;second.nTotalAmount + av-&gt;second.nTotalAmount10k == 0) { continue; } fprintf(out, "%s\t%d\t%d\t%d\n", pstSS-&gt;sItemID, av-&gt;second.nShopID, av-&gt;second.nTotalAmount, av-&gt;second.nTotalAmount10k ); } } // }}} // {{{ ProcessShopStocks void ProcessShopStocks(ShopStocksMap *mapSS, ShopsMap *mapS, FILE *out) { std::ifstream file(SHOP_STOCKS_FILE); std::string l; ShopStockStruct *pstSS = NULL; AvailabilityStruct *pstAV; int nKey = -1; int nSSs = 0; char *sItemID; char *sItemIDprev = (char *)""; int nShopID; int nAmount; std::vector&lt;std::string&gt; vsItems; while (std::getline(file, l)) { // skip first line if (nKey &lt; 0) { nKey = 0; continue; } vsItems = split(l, (char) '\t'); if (vsItems.size() &lt; 3) continue; sItemID = strdup(vsItems[0].c_str()); if (strcmp(sItemIDprev, sItemID) != 0) { // item changed - post process previous item if (pstSS != NULL) PostProcessItem(pstSS, mapS, out); } nShopID = atoi(vsItems[1].c_str()); nAmount = atoi(vsItems[2].c_str()); auto ss = mapSS-&gt;find(sItemID); if (ss == mapSS-&gt;end()) { // not found, so we need to create a new one pstSS = new ShopStockStruct(); pstSS-&gt;sItemID = sItemID; pstSS-&gt;mapAv = new AvailabilitiesMap(); // and store it, we'll add from value a bit later (* mapSS)[sItemID] = *pstSS; } else { // found group already, get a pointer to it for adding nGroupFrom // value later pstSS = &amp;(ss-&gt;second); } // in any case (found or not), we've to add GroupFrom value // to do: create struct, and store it in map pstAV = new AvailabilityStruct(); pstAV-&gt;nShopID = nShopID; pstAV-&gt;nAmount = nAmount; pstAV-&gt;nTotalAmount = 0; pstAV-&gt;nTotalAmount10k = 0; (*(pstSS-&gt;mapAv))[nShopID] = *pstAV; nSSs++; } // process the last item if exists if (pstSS != NULL) PostProcessItem(pstSS, mapS, out); printf("Total %d ShopStocks loaded.\n", nSSs); } // }}} // {{{ Generic split to vector function std::vector&lt;std::string&gt; &amp;split(const std::string &amp;s, char delim, std::vector&lt;std::string&gt; &amp;elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); // printf("\t%s\n", item.c_str()); } return elems; } std::vector&lt;std::string&gt; split(const std::string &amp;s, char delim) { std::vector&lt;std::string&gt; elems; split(s, delim, elems); return elems; } // }}} </code></pre> <hr> <h2>Makefile:</h2> <pre><code>PROGRAM = shop-stock-total CXX=g++ CXXFLAGS := -g -std=c++11 -Wall -O3 -march=native -mtune=native LDFLAGS := -g -L /usr/lib:/usr/lib/x86_64-linux-gnu all: $(PROGRAM) $(PROGRAM): $(PROGRAM).gcda $(PROGRAM).o $(CXX) $(CXXFLAGS) -fprofile-use -o $@ $(PROGRAM).o $(LDFLAGS) $(PROGRAM).gcda: profile/$(PROGRAM) ./profile/$(PROGRAM) &gt;/dev/null cp profile/$(PROGRAM).gcda ./ profile/$(PROGRAM): $(PROGRAM).cpp $(PROGRAM).h [[ -d profile ]] || mkdir profile cp $(PROGRAM).cpp profile/ cp $(PROGRAM).h profile/ cd profile &amp;&amp; $(CXX) -c $(CXXFLAGS) -fprofile-generate $(PROGRAM).cpp cd profile &amp;&amp; $(CXX) $(CXXFLAFS) -fprofile-generate -o $(PROGRAM) $(PROGRAM).o $(LDFLAGS) shop-stock-total.o: $(PROGRAM).cpp $(PROGRAM).h $(CXX) -c $(CXXFLAGS) -fprofile-use $(PROGRAM).cpp clean: @rm -rf *.o $(PROGRAM) ./profile *.gcda </code></pre> <hr>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-28T16:16:53.860", "Id": "380581", "Score": "0", "body": "For better performance, try to 1) replace all uses of `std::list` with `std::vector` 2) reduce pointer usage the items pointed to can often be stored by value instead." }, { ...
[ { "body": "<p>I see a number of things that may help you improve your program.</p>\n\n<h2>Don't abuse <code>using namespace std</code></h2>\n\n<p>Putting <code>using namespace std</code> at the top of every program is <a href=\"http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad...
{ "AcceptedAnswerId": "197999", "CommentCount": "16", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-28T15:42:18.153", "Id": "197436", "Score": "8", "Tags": [ "c++", "c++11", "csv", "hash-map", "makefile" ], "Title": "Calculating effective shop inventories from CSV files" }
197436
<p>This is a follow my rock-paper-scissors program, original post here: <a href="https://codereview.stackexchange.com/questions/195912/simple-rock-paper-scissors-game">Simple rock-paper-scissors game</a></p> <p>Looking for any feedback and recommendations on ways to keep improving.</p> <p>Quick notes on changes:</p> <ul> <li>Removed the use of using namespace std;</li> <li>Added inheritance structure.</li> <li>Added the use of enum variables to replace strings to ease computational expense while still maintaining code readability.</li> <li>Simplified the logic of the whoWon function.</li> <li>Changed the scope whoWon function to deal with a singular task</li> <li>Removed the use of rand and replaced it with a normal distribution from the random library.</li> <li>Added the option of choosing from three types of play: Player vs Computer, Player vs Player(Local), and Computer vs Computer. </li> <li>Move choices given by Human players will no longer be echoed onto the application window to ensure player's do not unfairly see each-other's choices.</li> <li>Added a moveToString function so that each player's move choice can be displayed after the winner is determined.</li> <li>Changed main.cpp loop structure to be do-while, so it will run atleast once.</li> </ul> <p>Code:</p> <p>rock-paper-scissors_v2.h:</p> <pre><code>#ifndef ROCK_PAPER_SCISSORS_V2_H #define ROCK_PAPER_SCISSORS_V2_H #include &lt;iostream&gt; #include &lt;random&gt; #include &lt;string&gt; #include &lt;unordered_map&gt; #include &lt;termios.h&gt; #include &lt;unistd.h&gt; enum rock_paper_scissors{ rock = 0, paper = 1, scissors = 2 }; class Player{ protected: rock_paper_scissors move_choice; public: virtual void setMoveChoice() = 0; virtual rock_paper_scissors getMoveChoice() = 0; std::string moveToString(rock_paper_scissors); }; class ComputerPlayer : public Player{ public: void setMoveChoice(); rock_paper_scissors getMoveChoice(); }; class HumanPlayer : public Player{ private: std::string player_name; public: HumanPlayer(); void setMoveChoice(); rock_paper_scissors getMoveChoice(); }; #endif /* ROCK_PAPER_SCISSORSS_H */ </code></pre> <p>rock-paper-scissors_v2.cpp:</p> <pre><code>#include "rock-paper-scissors_v2.h" using std::cin; using std::cout; std::string Player:: moveToString(rock_paper_scissors move){ std::string move_as_string; if(move == rock) move_as_string = "rock"; else if(move == paper) move_as_string = "paper"; else move_as_string = "scissors"; return move_as_string; } void ComputerPlayer :: setMoveChoice(){ //Simulate the computer randomly choosing a move std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution&lt;int&gt; distribution(0,2); int num_generated = distribution(gen); move_choice= (rock_paper_scissors)num_generated; } rock_paper_scissors ComputerPlayer :: getMoveChoice(){ return move_choice; } HumanPlayer :: HumanPlayer(){ cout&lt;&lt;"Please enter your name: "; cin&gt;&gt;player_name; cout&lt;&lt;"Hello "&lt;&lt;player_name&lt;&lt;", welcome to Rock-Paper-Scissors! \n"; } void HumanPlayer :: setMoveChoice(){ cout&lt;&lt;player_name&lt;&lt;", please enter the move you wish to make: \n"; termios oldt; tcgetattr(STDIN_FILENO, &amp;oldt); termios newt = oldt; newt.c_lflag &amp;= ~ECHO; tcsetattr(STDIN_FILENO, TCSANOW, &amp;newt); std::string move; cin&gt;&gt;move; //Use a hashmap to map user string input to enum std::unordered_map&lt;std::string,rock_paper_scissors&gt; valid_moves = { {"rock",rock},{"paper",paper},{"scissors",scissors} }; //Check for valid user input while(valid_moves.find(move) == valid_moves.end()){ cout&lt;&lt;"Error, invalid move! Please enter rock, paper, or scissors \n"; getline(cin,move); } move_choice = valid_moves[move]; } rock_paper_scissors HumanPlayer :: getMoveChoice(){ return move_choice; } </code></pre> <p>main.cpp:</p> <pre><code>#include "rock-paper-scissors_v2.h" using std::cin; using std::cout; int whoWon(rock_paper_scissors &amp;p1_move, rock_paper_scissors &amp;p2_move){ // Function will return 1 if player 1 wins, 2 if player 2 wins, and 3 for a tie //Both players making the same move results in a tie if(p1_move == p2_move){ return 3; } //If not a tie, check for player 1 being the winner else if((p1_move == rock &amp;&amp; p2_move == scissors) || (p1_move == paper &amp;&amp; p2_move == rock) || (p1_move == scissors &amp;&amp; p2_move == paper)){ return 1; } // If none of the above are true, player 2 wins else{ return 2; } } int main(int argc, char** argv) { char play_again; do{ //Initiate the Title Screen cout&lt;&lt;"Rock-Paper-Scissors \n"; cout&lt;&lt;"-------------------\n"; cout&lt;&lt;"Enter the number of the mode you wish to play: \n"; cout&lt;&lt;"1.) Player vs Computer \n2.) Player vs Player(Local Only) \n3.) Computer vs Computer(Simulation) \n"; int mode_selected; cin&gt;&gt;mode_selected; Player *player_1; Player *player_2; switch(mode_selected){ case 1:{ ComputerPlayer com; HumanPlayer hum; player_1 = &amp;hum; player_2 = &amp;com; break; } case 2:{ HumanPlayer hum_1; HumanPlayer hum_2; player_1 = &amp;hum_1; player_2 = &amp;hum_2; break; } case 3:{ ComputerPlayer com_1; ComputerPlayer com_2; player_1 = &amp;com_1; player_2 = &amp;com_2; break; } } player_1-&gt;setMoveChoice(); rock_paper_scissors p1_move = player_1-&gt;getMoveChoice(); player_2-&gt;setMoveChoice(); rock_paper_scissors p2_move = player_2-&gt;getMoveChoice(); int winner = whoWon(p1_move,p2_move); if(winner == 1){ cout&lt;&lt;"Player one chose "&lt;&lt;player_1-&gt;moveToString(p1_move)&lt;&lt;" and Player 2 chose "&lt;&lt;player_1-&gt;moveToString(p2_move)&lt;&lt; ". Player 1 wins! \n"; } else if(winner == 2){ cout&lt;&lt;"Player one chose "&lt;&lt;player_1-&gt;moveToString(p1_move)&lt;&lt;" and Player 2 chose "&lt;&lt;player_1-&gt;moveToString(p2_move)&lt;&lt; ". Player 2 wins! \n"; } else{ cout&lt;&lt;"Player one chose "&lt;&lt;player_1-&gt;moveToString(p1_move)&lt;&lt;" and Player 2 chose "&lt;&lt;player_1-&gt;moveToString(p2_move)&lt;&lt; ". It's a tie! \n"; } cout&lt;&lt;"Would you like to play again?(y/n) \n"; cin&gt;&gt;play_again; } while(play_again == 'y'); return 0; } </code></pre> <p>Additional Questions:</p> <ul> <li>What are some good sources to look at for adding simple PvP online play?</li> <li>Any tips/ resource recommendations for improving the current "menu" UI?</li> </ul>
[]
[ { "body": "<p>Visually, your indentation and spacing are a little inconsistent, making parts of the code harder to read.</p>\n\n<p>You should include the <code>override</code> keyword in your <code>ComputerPlayer</code> and <code>HumanPlayer</code> classes if your compiler supports it.</p>\n\n<p>The <code>getMo...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-28T16:07:38.633", "Id": "197438", "Score": "2", "Tags": [ "c++", "object-oriented", "rock-paper-scissors" ], "Title": "Simple rock-paper-scissors game [Follow Up 1]" }
197438
<p>My idea was to take in the function and perform a self cross product so that I could check every pair against every other pair. I'm new to Haskell so this solution is probably rough.</p> <p>My question is, is there a better way to emulate a nested for loop rather than a cross product? Also, is there any way to collapse my ugly <code>valid</code> and <code>valid'</code> into one clean function?</p> <pre><code>valid :: [(Int, Int)] -&gt; Bool valid f = valid' $ [(x,y) | x &lt;- f, y &lt;- f] valid' :: [((Int,Int),(Int,Int))] -&gt; Bool valid' [] = True valid' (((x,y),(x1,y1)):xs) = valid' xs &amp;&amp; if x == x1 then (if y == y1 then True else False) else True </code></pre>
[]
[ { "body": "<p>To start, <code>if y == y1 then True else False</code> can be simplified to <code>y == y1</code>:</p>\n\n<pre><code>valid' (((x,y),(x1,y1)):xs) = valid' xs &amp;&amp; if x == x1 then y == y1 else True\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "Conte...
{ "AcceptedAnswerId": "197526", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-28T16:48:18.337", "Id": "197441", "Score": "5", "Tags": [ "haskell" ], "Title": "Determining if a set of 2d vectors is a valid function" }
197441
<p>Please provide general and any specific criticism of the following which is intended to provide a map of SF transit cars. The code can be viewed in <a href="https://www.jimmont.com/sfmuni/" rel="nofollow noreferrer">the working version</a> and also <a href="https://gist.github.com/jimmont/2b8c21b9b3810b3662f8f6a63fccc59f" rel="nofollow noreferrer">in a group of gists</a>.</p> <p>If this isn't the appropriate place or way to request a review please let me know. Feedback received so far indicates the solution is amateurish and I would like to better understand the better/preferred solutions--specifically what and where to focus. Overall this was a first-pass at a solution intended to reflect a productive day's work. </p> <pre><code>import './the-controls.js'; class TheMap extends HTMLElement{ constructor(){ super(); this.attachShadow({mode:'open'}).innerHTML = ` &lt;style&gt; :host{display:block;width:100%;height:100%;} svg{border:1px dotted #555;background:#0df;height:100%;width:100%;position:fixed;} g[src*='neighborhoods']{fill:green;stroke:#ccff0033;stroke-width:4px;} g[src*='arteries']{display:none;fill:none;stroke:#000;stroke-width:0.5;} g[src*='freeways']{display:none;fill:none;stroke:#fff;stroke-opacity:0.7;stroke-width:0.5;} g[src*='streets']{display:none;stroke:#fff;fill:none;stroke-opacity:0.8;stroke-width:0.2px;} .show-freeways g[src*='freeways'], .show-streets g[src*='streets'], .show-arteries g[src*='arteries']{display:inline;} .vehicles circle{fill:red;fill-opacity:0.7;} .vehicles circle:hover{fill:#cf0;fill-opacity:1;stroke:#555;stroke-width:0.1;} .vehicles text{display:none;fill:var(--dark);font-size:1rem;pointer-events:none;} .vehicles g:active text, .vehicles g:hover text{display:block;} button{font-weight:bold;} button.active{background-color:var(--dark);color:white;} /*.vehicles g{transition:all 500ms;}*/ &lt;/style&gt; &lt;svg&gt; &lt;g class=layers&gt;&lt;/g&gt; &lt;g class=overlay&gt; &lt;foreignobject class="filter" x="2.5rem" y="2rem" width="150" height="100%"&gt; &lt;the-controls&gt;&lt;/the-controls&gt; &lt;/foreignobject&gt; &lt;/g&gt; &lt;/svg&gt; `; this._setup = false; this.map = d3.select(this.shadowRoot.querySelector('svg')) this.layers = d3.select(this.shadowRoot.querySelector('.layers')) this.controls = this.shadowRoot.querySelector('the-controls') this.data = { time: 0 //'http://webservices.nextbus.com/service/publicJSONFeed?command=vehicleLocations&amp;a=sf-muni&amp;t=0' ,tags: {} ,taglist: [] ,vehicles: [] ,timer: 0 ,interval: 30 ,scale: 100000 // San Francisco ,lon: -122.4, lat: 37.76 ,projection: null ,pathprojector: null // ,content: './sfmaps/neighborhoods.json ./sfmaps/arteries.json ./sfmaps/freeways.json ./sfmaps/streets.json' } this.addEventListener('change-active', this.vehicleDrawer) } tagisactive(active, tag){ if(tag.active) active[ tag.name ] = tag; return active; } vehicleisactive(item){ return this[ item.routeTag ] ? true : false; } vehicleDrawer(){ // show the active-tag vehicles var data = this.data, $, vehicleList = data.vehicles.filter(this.vehicleisactive, data.taglist.reduce(this.tagisactive, {}) ); requestAnimationFrame(()=&gt;{ // update $ = this.layers .select('g.vehicles') .selectAll("g") .data(vehicleList) .each(this.vehicleDetails) ; // enter $.enter() .append("g") .each(this.vehicleDetails) ; // exit $.exit().remove(); }) } //item = {dirTag:"7____O_F00", heading:"225", id:"6719", lat:"37.784794", lon:"-122.403969", predictable:"true", routeTag:"7", secsSinceReport:"17", speedKmHr:"19"} vehicleDetails(item, i, vehicleList){ var $; this.setAttribute('transform', `translate(${item.position[0]}, ${item.position[1]}) scale(0.5)`); $ = this.querySelector('text'); if($){ $.textContent = item.routeTag; }else{ this.innerHTML = `&lt;circle cx=0 cy=0 r=5 /&gt;&lt;text&gt;${ item.routeTag }&lt;/text&gt;`; }; } vehiclePostion(item){ item.position = this.projection([+item.lon, +item.lat]); } tagSorter(a,b){ return a.name &lt; b.name ? -1 :(a.name &gt; b.name ? 1 : 0); } updateFinish(res){ this.data.timer = setTimeout(()=&gt;{ this.update(); }, 1000 * this.data.interval); console.log('updated',res); return res; } update(){ clearTimeout(this.data.timer); d3.json(`http://webservices.nextbus.com/service/publicJSONFeed?command=vehicleLocations&amp;a=sf-muni&amp;t=${this.data.time}`) .then((json)=&gt;{ var taglist, data = this.data; // get all the unique routeTags as a sorted list taglist = json.vehicle.reduce(this.vehiclehash, data).taglist; data.taglist = taglist = Array.from(new Set(taglist)).sort(this.tagSorter); data.vehicles = json.vehicle; // easier to interpret the position here than passing the pieces and parts around data.vehicles.forEach(this.vehiclePostion, data) this.vehicleDrawer(); this.controls.model = data; return this.updateFinish(json); }).catch((res)=&gt;{ return this.updateFinish(json); }); } vehiclehash(data, item){ var name = item.routeTag, tag = data.tags[ name ]; if(!tag){ tag = data.tags[ name ] = {name:name, active:true}; }; data.taglist.push( tag ); item.tag = tag; return data; } layerDrawer(json){ requestAnimationFrame(()=&gt;{ var data = this.data, $; $ = this.layers .select(`g[src="${json.path}"]`) .selectAll("path") .data(json.features) .attr("d", data.pathprojector) ; $.enter() .append("path") .attr("d", data.pathprojector) ; $.exit().remove(); }); } // zooming adjusts transform and visible layers/detail mapView(position={}){ cancelAnimationFrame(this._rafmap); this._rafmap = requestAnimationFrame(()=&gt;{ var z = position.k, view, layer, layers = this.layers; // I don't know d3 view = layers._groups[0][0].classList; layer = 'show-streets'; if(view.contains(layer)){ if(z &lt;= 6) view.remove(layer); }else if(z &gt; 6){ view.add(layer); }; layer = 'show-arteries'; if(view.contains(layer)){ if(z &lt;= 3) view.remove(layer); }else if(z &gt; 3){ view.add(layer); }; layer = 'show-freeways'; if(view.contains(layer)){ if(z &lt;= 1.5) view.remove(layer); }else if(z &gt; 1.5){ view.add(layer); }; layers.attr("transform", position); }); } connectedCallback(){ var data; if(!this._setup){ // initial setup: projection, load and draw layers, start updating data = this.data; data.projection = d3.geoMercator().scale(data.scale).center([+data.lon, +data.lat]); data.pathprojector = d3.geoPath().projection(data.projection); this.map.call( d3.zoom() .scaleExtent([1,30]) .on('zoom', ()=&gt;{ this.mapView(d3.event.transform) }) ) data.content.trim().split(/\s+/).map((path, i) =&gt; { this.layers.append('g').attr('src', path) d3.json(path) .then((json)=&gt;{ json.path = path; this.layerDrawer(json); return json; }) .catch((err)=&gt;{ console.warn('problem layer',path,err); return err; }) return path; }); this.layers.append('g').attr('class','vehicles'); } this.update(); } disconnectedCallback(){ // stop updating clearTimeout(this.data.timer); } } window.customElements.define('the-map', TheMap); class TheControls extends HTMLElement{ constructor(){ super(); this.attachShadow({mode:'open'}); // {tags: {N: {}...}, taglist: []} this.data = {}; this.addEventListener('click', this.clicked); } clicked(e){ var $ = e.composedPath()[0], tags = this.data.tags, prev; e.stopPropagation(); switch($.nodeName){ case 'INPUT': switch($.value){ case 'all': Array.from(this.shadowRoot.querySelectorAll('button')).forEach(($)=&gt;{ tags[$.value].active = true; $.classList.add('active'); }); break; case 'clear': Array.from(this.shadowRoot.querySelectorAll('button')).forEach(($)=&gt;{ tags[$.value].active = false; $.classList.remove('active'); }); break; }; this._previous = ''; this.dispatchEvent(new CustomEvent('change-active', {detail: this.data, cancelable: true, composed: true, bubbles: true})); break; case 'BUTTON': if(e.metaKey || e.ctrlKey){ prev = this.shadowRoot.querySelector(`button[value="${this._previous}"]`); if(prev &amp;&amp; prev !== $){ tags[prev.value].active = prev.classList.toggle('active'); } }; this._previous = $.value; tags[$.value].active = $.classList.toggle('active'); this.dispatchEvent(new CustomEvent('change-active', {detail: this.data, cancelable: true, composed: true, bubbles: true})); break; }; } //&lt;button value="10" class="active"&gt;10&lt;/button&gt; tagHTML(item){ return `&lt;button value="${ item.name }" class="${ item.active ? 'active':'' }"&gt;${ item.name }&lt;/button&gt;` } render(){ this.shadowRoot.innerHTML = ` &lt;style&gt; button{font-weight:bold;} button.active{background-color:var(--dark);color:white;} &lt;/style&gt; &lt;input type=button value=all&gt; &lt;input type=button value=clear&gt; &lt;br&gt; ${ this.data.taglist.map(this.tagHTML).join(' ') } `; } get model(){ return this.data; } set model(data){ this.data = data; this.render(); return true; } } window.customElements.define('the-controls', TheControls); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T05:41:35.020", "Id": "380661", "Score": "1", "body": "Welcome to Code Review: this is indeed the appropriate SE place to ask your question. Well, I'm pretty much the only D3 answerer around here these days, so here is my 2 cents: yo...
[ { "body": "<p>Just as <a href=\"https://codereview.stackexchange.com/questions/197446/map-of-sf-transit-cars/201904#comment380661_197446\">Gerardo hinted at in comments</a>, I admit that I am not well-versed with d3 and at most can offer general JavaScript feedback. Nonetheless here is what I came up with:</p>\...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-28T19:04:26.913", "Id": "197446", "Score": "6", "Tags": [ "javascript", "ecmascript-6", "html5", "dom", "d3.js" ], "Title": "map of SF transit cars" }
197446
<p>I have written this code in C# to connect to an Oracle Database, omitting the tnsnames.ora file, then place results from a query into a CSV File.</p> <p>Is there more efficient way to do this? (Such as reading in the data into a DataReader rather than a DataTable)</p> <p>Please review and tell me what you would change.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Oracle.ManagedDataAccess.Client; using System.Configuration; using System.Data; using FileHelpers; using System.IO; namespace oracle_test { class Program { static void Main(string[] args) { OraTest ot = new OraTest(); ot.Connect(); } class OraTest { public void Connect() { var constr = new OracleConnectionStringBuilder() { DataSource = @"(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST = 10.100.100.10)(PORT = 1521)))(CONNECT_DATA =(SERVICE_NAME = ONE10)))", UserID = "100", Password = "100", }.ConnectionString; using (var con = new OracleConnection(constr)) { string prfbalqry = "select * from ati where be = 0"; OracleCommand cmd = new OracleCommand(prfbalqry, con); cmd.CommandType = System.Data.CommandType.Text; con.Open(); DataTable pbResults = new DataTable(); OracleDataAdapter oda = new OracleDataAdapter(cmd); oda.Fill(pbResults); StringBuilder sb = new StringBuilder(); IEnumerable&lt;string&gt; columnNames = pbResults.Columns.Cast&lt;DataColumn&gt;().Select(column =&gt; column.ColumnName); sb.AppendLine(string.Join(",", columnNames)); foreach (DataRow row in pbResults.Rows) { IEnumerable&lt;string&gt; fields = row.ItemArray.Select(field =&gt; field.ToString()); sb.AppendLine(string.Join(",", fields)); } File.WriteAllText(@"C:\Financial Reporting\Output Path\pbresults.csv", sb.ToString()); } } } } } </code></pre>
[]
[ { "body": "<p><code>OraTest</code> is not a useful name. Call it <code>OracleToCSVWriter</code> or something like that.</p>\n\n<hr>\n\n<p>Mind the naming of variables etc: <code>oda</code> is not very descriptive - <code>adapter</code> would maybe be better.</p>\n\n<hr>\n\n<p>Hardcoded username/password is rare...
{ "AcceptedAnswerId": "197470", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-28T20:33:40.037", "Id": "197447", "Score": "0", "Tags": [ "c#", ".net", "csv", ".net-datatable" ], "Title": "Pull From Oracle into CSV File" }
197447
<p>I have the following code that causes my excel to 'not respond' however if I step through put a breakpoint at the loop <code>For thisScen = 1 To UBound(stressScenMapping, 1)</code> to <code>Next thisScen</code> and run it next by next it works but takes long. When running at once it takes so long. It slows down at this For triple loop.</p> <p>It does run fast in excel 2010 (3 seconds). I currently run excel 2013.</p> <p>Why does it run fast in excel 2010, but 2013 is giving me big issues?</p> <p>The code does some mapping between sheets and writes to database.</p> <pre><code>Public Sub calc() Application.ScreenUpdating = False Dim i As Long, thisScen As Long, nRows As Long, nCols As Long Dim stressWS As Worksheet Set stressWS = Worksheets("EQ_Shocks") Unprotect_Tab ("EQ_Shocks") nRows = lastWSrow(stressWS) nCols = lastWScol(stressWS) Dim readcols() As Long ReDim readcols(1 To nCols) For i = 1 To nCols readcols(i) = i Next i Dim eqShocks() As Variant eqShocks = colsFromWStoArr(stressWS, readcols, False) 'read in database columns Dim dataWs As Worksheet Set dataWs = Worksheets("database") nRows = lastrow(dataWs) nCols = lastCol(dataWs) Dim dataCols() As Variant Dim riskSourceCol As Long riskSourceCol = getWScolNum("header1", dataWs) ReDim readcols(1 To 4) readcols(1) = getWScolNum("header2", dataWs) readcols(2) = getWScolNum("header3", dataWs) readcols(3) = getWScolNum("header4", dataWs) readcols(4) = riskSourceCol dataCols = colsFromWStoArr(dataWs, readcols, True) 'read in scenario mappings Dim mappingWS As Worksheet Set mappingWS = Worksheets("mapping_ScenNames") Dim stressScenMapping() As Variant ReDim readcols(1 To 2): readcols(1) = 1: readcols(2) = 2 stressScenMapping = colsFromWStoArr(mappingWS, readcols, False, 2) 'include two extra columns to hold column number for IR and CR shocks For i = 1 To UBound(stressScenMapping, 1) stressScenMapping(i, 3) = getWScolNum(stressScenMapping(i, 2), dataWs) If stressScenMapping(i, 2) &lt;&gt; "NA" And stressScenMapping(i, 3) = 0 Then MsgBox ("Could not find " &amp; stressScenMapping(i, 2) &amp; " column in database") Exit Sub End If Next i ReDim readcols(1 To 4): readcols(1) = 1: readcols(2) = 2: readcols(3) = 3: readcols(4) = 4 stressScenMapping = filterOut(stressScenMapping, 2, "NA", readcols) 'calculate stress and write to database Dim thisEqShocks() As Variant Dim keepcols() As Long ReDim keepcols(1 To UBound(eqShocks, 2)) For i = 1 To UBound(keepcols) keepcols(i) = i Next i Dim thisCurrRow As Long For thisScen = 1 To UBound(stressScenMapping, 1) thisEqShocks = filterIn(eqShocks, 2, stressScenMapping(thisScen, 1), keepcols) If thisEqShocks(1, 1) = "#EMPTY" Then For i = 2 To nRows If dataCols(i, 4) &lt;&gt; "stack" And dataCols(i, 4) &lt;&gt; "overflow" And (dataCols(i, 1) = "Equity|Public" Or dataCols(i, 1) = "Equity|Private") Then dataWs.Cells(i, stressScenMapping(thisScen, 3)).value = "No shock found" End If Next i Else 'calculate shocks Call quicksort(thisEqShocks, 3, 1, UBound(thisEqShocks, 1)) For i = 2 To nRows If dataCols(i, 4) &lt;&gt; "stack" And dataCols(i, 4) &lt;&gt; "ITS" And (dataCols(i, 1) = "Equity|Public" Or dataCols(i, 1) = "Equity|Private" Or dataCols(i, 1) = "Pref Shares") Then thisCurrRow = findInArrCol(dataCols(i, 3), 3, thisEqShocks) If thisCurrRow = 0 Then 'could not find currency so use generic shock thisCurrRow = findInArrCol("OTHERS", 3, thisEqShocks) End If If thisCurrRow = 0 Then dataWs.Cells(i, stressScenMapping(thisScen, 3)).value = "No shock found" Else dataWs.Cells(i, stressScenMapping(thisScen, 3)).value = Replace(dataCols(i, 2), "-", 0) * (thisEqShocks(thisCurrRow, 4) - 1) End If End If Next i End If Next thisScen Application.ScreenUpdating = True End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-28T21:23:25.420", "Id": "380616", "Score": "0", "body": "@Close-Voter(s): the code *does* work as intended, just too slow. Nothing in the OP suggests anything is broken." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate...
[ { "body": "<p>This is essentially what you're doing <em>on a sheet</em></p>\n\n<pre><code>FOR every item in stressScenMapping\n Make thisEqShocks\n IF thisEqShocks(1,1) = empty then\n FOR EVERY ROW\n if EACH ROW IS THESE THEN\n WRITE ON THAT ROW\n END IF\n ...
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-28T21:08:43.550", "Id": "197450", "Score": "1", "Tags": [ "vba", "excel" ], "Title": "Mapping between 3 sheets, write to final sheet" }
197450
<p>I am attempting to make an eCommerce site from scratch. Right now I have the following code that gets all the items from a Firebase Firestore database and then adds HTML into an items div element based on the item's info.</p> <pre><code>var items = []; var itemsDiv = document.getElementsByClassName("items")[0]; db.collection("items").get().then((querySnapshot) =&gt; { querySnapshot.forEach((doc) =&gt; { var docData = doc.data(); items.push(docData); }); renderItems(); }); function renderItems() { console.log(items); items.forEach(function(item) { itemsDiv.innerHTML += ` &lt;div class="item"&gt; &lt;img class="itemImgBackground" src="assets/${item.name.replace(" ", "")}.png"&gt; &lt;img class="itemImg" src="assets/${item.name.replace(" ", "")}.png"&gt; &lt;span class="itemName"&gt;${item.name}&lt;/span&gt; &lt;span class="itemCondition"&gt;${item.condition}&lt;/span&gt; &lt;span class="itemPrice"&gt;${item.price}&lt;/span&gt; &lt;/div&gt; ` }); } </code></pre> <p>What can I do to make my code better?</p>
[]
[ { "body": "<p>Here are a few things:</p>\n\n<ul>\n<li><p>good you're using <code>`</code> (template literals) to format your HTML inside the JavaScript code</p></li>\n<li><p>don't use <code>innerHTML +=</code> as it forces the browser to re-render the DOM when called. Read more here: <a href=\"https://stackover...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-28T22:29:25.970", "Id": "197453", "Score": "4", "Tags": [ "javascript", "functional-programming", "ecmascript-6", "iterator", "firebase" ], "Title": "Loading items for an eCommerce site" }
197453
<p>I am implementing a program to draw a box of text next to some other drawn object (that can have any position and dimensions) and the text box should always be visible, even if the drawn object's width is of the entire screen and vice versa. They should simply not overlap.</p> <p>This is a code to position the text on some relatively good coordinates.</p> <pre><code>if(x &gt; (box_w + 20)) box_x = x - (box_w + 20); else box_x = w + 20; if(y &gt; (box_h + 20)) box_y = y - (box_h + 20); else box_y = h + 20; if(w &gt; width - (box_h + 20) || x + w + box_w + 20 &gt; width) { box_x = 20; if(y &lt; box_h + 20) { box_y = h + 20; } else box_y = y - (box_h + 20); } </code></pre> <p><code>x</code>, <code>y</code>, <code>w</code>, <code>h</code> are the coords and dimensions for the object; <code>box_x</code>, <code>box_y</code>, <code>box_w</code> and <code>box_y</code> are for the text box and width/height is the dimension of the area.</p> <p>Here is schematically how this code positions text (darker blue) near the object (lighter blue) <a href="https://i.stack.imgur.com/uNYNs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uNYNs.png" alt="box positioning examples"></a></p> <p>It is quite obvious that it could have been written much better. To target performance, but more importantly - code space.</p> <p>Can anyone suggest a better way to find good coordinates for the text box?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-28T23:49:51.573", "Id": "380633", "Score": "1", "body": "Could you add more of your code for context? This is not much to go on, just a series of conditionals, seeing the code that makes the box and draws it would help clarify." }, ...
[ { "body": "<p>This is a definite candidate for using rect / point structures, but I don't know what the rest of your code-base looks like, so just talking about the algorithm alone, one approach would be:</p>\n\n<pre><code>void FindNonOverlappingPosition(\n uint canvasWidth, uint canvasHeight,\n uint x1, ...
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-28T23:26:52.813", "Id": "197457", "Score": "2", "Tags": [ "performance", "c", "coordinate-system" ], "Title": "Calculations to position a text box next to another object" }
197457
<p>This is a form that I want to use to enter users into a database. I used MySQLi with prepared statements. I want to make sure that I sanitized my data well.</p> <pre><code>&lt;?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ require_once './db_con.php'; $id = ''; $firstname = trim(filter_input(INPUT_POST, 'firstname', FILTER_SANITIZE_FULL_SPECIAL_CHARS)); $lastname = trim(filter_input(INPUT_POST, 'lastname', FILTER_SANITIZE_FULL_SPECIAL_CHARS)); $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL); //$val_email = trim(filter_var($email, FILTER_VALIDATE_EMAIL)); $password = trim(filter_input(INPUT_POST, 'password', FILTER_SANITIZE_FULL_SPECIAL_CHARS)); $password2 = trim(filter_input(INPUT_POST, 'password2', FILTER_SANITIZE_FULL_SPECIAL_CHARS)); $errs = array(); #firstname if ( empty($firstname) ) { $errs[] = "Please enter your first name."; } #lastname if ( empty($lastname) ) { $errs[] = "Please enter your last name."; } #email if ( empty($email) ) { $errs[] = "Please enter your E-mail."; } #email validation if ( !filter_var($email, FILTER_VALIDATE_EMAIL) ) { $errs[] = "Please enter a valid E-mail."; } #check if email exist if ( email_exists($email,$connection) ) { $errs[] = "Your E-mail already exists."; } #password if ( empty($password) ) { $errs[] = "Please enter your password."; } elseif (strlen($password) &lt; 6) { $errs[] = "Your password must have at least 6 characters."; } #confirm-password if ( empty($password2) ) { $errs[] = "Please confirm your password."; } else { #matching-passwords if ( $password !== $password2 ) { $errs[] = "Password didn't match."; } } if ( !empty( $errs ) ) { foreach ($errs as $err) { echo $err.'&lt;/br &gt;'; } } else { $hashed_password = password_hash($password, PASSWORD_DEFAULT); $stmt = $connection-&gt;prepare("INSERT INTO `users` (`id`, `firstname`, `lastname`, `email`, `password`) VALUES (?, ?, ?, ?, ?)"); $stmt-&gt;bind_param("sssss", $id, $firstname, $lastname, $email, $hashed_password); if ( !($stmt-&gt;execute()) ) { echo "There was a problem, Try again."; } else { echo "You are registered now."; } $stmt-&gt;close(); } #functions function email_exists($email,$connection) { $stmt = $connection-&gt;prepare("SELECT * FROM `users` WHERE `email` = ?"); $stmt-&gt;bind_param("s", $email); $stmt-&gt;execute(); $result = $stmt-&gt;get_result(); $rows_count = $result-&gt;num_rows; if ( $rows_count &gt;= 1 ) { return TRUE; } $stmt-&gt;close(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T11:12:41.750", "Id": "380699", "Score": "1", "body": "This question [is being discussed on meta](https://codereview.meta.stackexchange.com/q/8895/31503)" } ]
[ { "body": "<p>This code is perfectly safe. The only issue with sanitization in this code is that it makes the data, so to say, <em>overly-sanitized</em>.</p>\n\n<p>The way you are getting your input variables, makes them suitable for the HTML output. But there is no HTML output in the code present. Which makes ...
{ "AcceptedAnswerId": "197493", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-28T23:33:48.860", "Id": "197458", "Score": "1", "Tags": [ "php", "mysqli" ], "Title": "Entering users into a MySQLi database" }
197458
<p>I have a contact form that will perform validation on the server. Right now the form checks if the fields are empty or not. My goal is to expand it following:</p> <p>Check the fields for particular format, if it is a proper email format, phone number format, etc Set the field as required or not</p> <p>My form is as below, I appreciate any suggestions on how to clean it up and make it easier to adjust and overall cleaner.</p> <pre><code>&lt;?php ini_set("log_errors", 1); ini_set("error_log", "php-error.log"); error_log( "Errors" ); include "recaptcha.php"; include 'email.php'; use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require 'Exception.php'; require 'PHPMailer.php'; require 'SMTP.php'; $errors = array(); // array to hold validation errors $data = array(); // array to pass back data // validate the variables ====================================================== // if any of these variables don't exist, add an error to our $errors array if (empty($_POST['firstName'])) $errors['firstName'] = 'First Name is required.'; if (empty($_POST['lastName'])) $errors['lastName'] = 'Last Name is required.'; if (empty($_POST['companyName'])) $errors['companyName'] = 'Company Name is required.'; if (empty($_POST['companyAddress'])) $errors['companyAddress'] = 'Company Address is required.'; if (empty($_POST['city'])) $errors['city'] = 'City is required.'; if (empty($_POST['state'])) $errors['state'] = 'State is required.'; if (empty($_POST['emailAddress'])) $errors['emailAddress'] = 'Email Address is required.'; if (empty($_POST['comment'])) $errors['comment'] = 'Comment is required.'; if (empty($_POST['g-recaptcha-response'])) $errors['recaptcha'] = 'Captcha is required.'; // return a response =========================================================== // Check ReCaptcha Validation if(!validateRecaptcha($secret, $_POST['g-recaptcha-response'], $_SERVER["REMOTE_ADDR"])) { $errors['recaptcha'] = 'Captcha is required.'; } if ( ! empty($errors)) { // if there are items in our errors array, return those errors $data['success'] = false; $data['errors'] = $errors; } else { // if there are no errors process our form, then return a message // DO ALL YOUR FORM PROCESSING HERE // THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER) // show a message of success and provide a true success variable $data['success'] = true; $data['message'] = 'Success!'; } // return all our data to an AJAX call echo json_encode($data); //Begin of send email $mail = new PHPMailer; //Enable SMTP debugging. $mail-&gt;SMTPDebug = 3; //Set PHPMailer to use SMTP. $mail-&gt;isSMTP(); //Set SMTP host name $mail-&gt;Host = "smtp.server.com"; //Set this to true if SMTP host requires authentication to send email $mail-&gt;SMTPAuth = true; //Provide username and password $mail-&gt;Username = "user@server.com"; $mail-&gt;Password = "super_secret_password"; //If SMTP requires TLS encryption then set it $mail-&gt;SMTPSecure = "tls"; //Set TCP port to connect to $mail-&gt;Port = 587; $mail-&gt;From = $emailAddress; $mail-&gt;addAddress("name@server.com", "Recepient Name"); $mail-&gt;isHTML(true); $mail-&gt;Subject = "Subject Text"; $mail-&gt;Body = $emailBody; if(!$mail-&gt;send()) { $data['success'] = false; $data['errors'] = "Mailer Error: " . $mail-&gt;ErrorInfo; } else { $data['message'] = 'Success!'; } ?&gt; </code></pre>
[]
[ { "body": "<h3>General inconsistency</h3>\n<p>Basically your code is borderline off topic. Although it could work, it is not a working code in the sense a programmer could take it; but rather a set of copy-pasted code blocks loosely (and wrongly) connected to each other.</p>\n<p>The main problem is inconsistent...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-28T23:35:21.243", "Id": "197459", "Score": "0", "Tags": [ "php", "form", "ajax" ], "Title": "Writing cleaner PHP code to add additional options" }
197459
<p>I want to substring a String from given start index and given substring length.</p> <ol> <li>if the string is empty then returns String.Empty </li> <li>if the string length is greater than start index then it substrings from given start index to given length...</li> <li>if the string length is less than start index then it returns from start index to last index</li> </ol> <p>I just want to know if it can be improved and shorter with all these checks.</p> <ol> <li>if the string is null or empty</li> <li>if the start index is not less than zero </li> <li>if the start index is less than the length of given input string.</li> <li>if the given input string length is less than the desired substring length. </li> <li>if the given input string length is greater than the desired substring length. </li> </ol> <p><strong>Sample Input and Ouput for my program:</strong></p> <pre><code>SplitEntity("", 1, 15) =&gt; "" SplitEntity("abcdef", 0, 3) =&gt; "abc" SplitEntity("abcdef", 3, 100) =&gt; "def" SplitEntity("abcdef", 0, 100) =&gt; "abcdef" SplitEntity("abcdef", -1, 100) =&gt; "" </code></pre> <p><strong>My function is below:</strong></p> <pre><code>Public Function SplitEntity(entity As String, startIndex As Integer, subStringLength As Integer) As String Dim spilttedString As String = String.Empty If (Not String.IsNullOrEmpty(entity) AndAlso startIndex &gt;=0 ) Then If (entity.Length &gt; startIndex) Then If entity.Length &gt;= (startIndex + subStringLength) Then spilttedString = entity.Substring(startIndex, subStringLength) ElseIf entity.Length &lt; (startIndex + subStringLength) Then spilttedString = entity.Substring(startIndex, (entity.Length - startIndex)) End If End If End If Return spilttedString End Function </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T01:20:15.943", "Id": "380643", "Score": "0", "body": "Welcome to Code Review! I hope you get some good answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T01:42:22.280", "Id": "380647", "...
[ { "body": "<p>for something like this I would suggest making it an <a href=\"https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/procedures/how-to-write-an-extension-method\" rel=\"nofollow noreferrer\">Extension Method</a>.</p>\n\n<p>To that end I would suggest a name chang...
{ "AcceptedAnswerId": "197469", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T01:01:44.673", "Id": "197460", "Score": "2", "Tags": [ ".net", "vb.net" ], "Title": "Substring a String from given start index and given substring length" }
197460
<p>To learn network programming in Python, I have written a small piece of code which is constituted of 2 modules, a client and a server. The server listens to a specific port provided on command line, then the client connects to the server, and send a file to it.</p> <p>The client sends the size of file at first, then the content of file. During data transmission, both side of socket update a SHA256 object, and when transmission is completed, they calculate the hash digests and print them on screen.</p> <p>I know my code is still far from being a robust implementation, so I am looking for your opinions. Any criticism is welcome. Thank you.</p> <p>Module <code>bigfile_server.py</code>:</p> <pre><code># -*- encoding: utf-8 -*- import sys import struct import getopt import socket import hashlib from datetime import datetime FILE_BUFFER_SIZE = 524288 def usage(): print('Usage: bigfile_server.py &lt;SERVER_PORT&gt;') print('SERVER_PORT: Port to which server will listen.') def random_filename(): dt_now = datetime.now() return dt_now.strftime('%Y%m%d%H%M%S%f') def readn(sock, count): data = b'' while len(data) &lt; count: packet = sock.recv(count - len(data)) if packet == '': return '' data += packet return data if __name__ == '__main__': server_port = '' opts, args = getopt.gnu_getopt(sys.argv[1:], 'p:', ['port=']) for opt, arg in opts: if opt in ('-p', '--port'): server_port = arg if server_port == '': print('Server port missing.', file=sys.stderr) usage() sys.exit(1) if not server_port.isdecimal(): print('Server port contains invalid characters.', file=sys.stderr) sys.exit(2) print('Launching bigfile server.') serv_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: serv_sock.bind(('', int(server_port))) serv_sock.listen(5) except socket.error as e: print('Failed to launch server:', e) sys.exit(3) else: print('Server launched, waiting for new connection.') try: clnt_sock, clnt_addr = serv_sock.accept() except socket.error as e: print ('Failed to accept new connection:', e) sys.exit(3) else: print('New connection from:', clnt_sock) size_buff = readn(clnt_sock, 4) if size_buff == '': print('Failed to receive file size.', file=sys.stderr) clnt_sock.close() serv_sock.close() sys.exit(3) size_unpacked = struct.unpack('!I', size_buff) file_size = size_unpacked[0] print('Will receive file of size', file_size, 'bytes.') hash_algo = hashlib.sha256() filename = random_filename() try: with open(filename, 'wb') as file_handle: while file_size &gt; 0: buffer = clnt_sock.recv(FILE_BUFFER_SIZE) print(len(buffer), 'bytes received.') if buffer == '': print('End of transmission.') break hash_algo.update(buffer) file_handle.write(buffer) file_size -= len(buffer) if file_size &gt; 0: print('Failed to receive file,', file_size, 'more bytes to go.') except socket.error as e: print('Failed to receive data:', e, file=sys.stderr) clnt_sock.close() serv_sock.close() sys.exit(3) except IOError as e: print('Failed to write file:', e, file=sys.stderr) clnt_sock.close() serv_sock.close() sys.exit(3) else: print('File transmission completed.') clnt_sock.shutdown(socket.SHUT_RD) clnt_sock.close() serv_sock.close() print('Server shutdown.') print('SHA256 digest:', hash_algo.hexdigest()) sys.exit(0) </code></pre> <p>Module <code>bigfile_client.py</code>:</p> <pre><code># -*- encoding: utf-8 -*- import os import sys import struct import getopt import socket import hashlib FILE_BUFFER_SIZE = 524288 def usage(): print('Usage: bigfile_client.py &lt;ARGUMENTS&gt;') print('ARGUMENTS:') print('[-f|--file]: Source file to send.') print('[-h|--host]: Server address.') print('[-p|--port]: Server port number.') if __name__ == '__main__': source_file, server_addr, server_port = '', '', '' opts, args = getopt.gnu_getopt(sys.argv[1:], 'f:h:p:', ['file=', 'host=', 'port=']) for opt, arg in opts: if opt in ('-f', '--file'): source_file = arg elif opt in ('-h', '--host'): server_addr = arg elif opt in ('-p', '--port'): server_port = arg if source_file == '': print('Source file missing.', file=sys.stderr) usage() sys.exit(1) elif server_addr == '': print('Server address missing.', file=sys.stderr) usage() sys.exit(1) elif server_port == '': print('Server port number missing.', file=sys.stderr) usage() sys.exit(1) if not os.path.isfile(source_file): print('Source file cannot be found.', file=sys.stderr) sys.exit(2) elif not server_port.isdecimal(): print('Server port number contains invalid characters.', file=sys.stderr) sys.exit(2) file_size = os.path.getsize(source_file) print('Sending file {0} to {1}:{2}.'.format(source_file, server_addr, server_port)) print('Source file size:', file_size, 'bytes.') print('Connecting to remote server.') conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: conn.connect((server_addr, int(server_port))) except socket.error as e: print('Failed to connect to server:', e) sys.exit(3) else: print('Connection established.') print('Sending file size to remote server.') buffer = b'' buffer = struct.pack('!I', file_size) print('File size packed into binary format:', buffer) try: conn.sendall(buffer) except socket.error as e: print('Failed to send file size:', e) sys.exit(3) else: print('File size sent.') hash_algo = hashlib.sha256() print('Start to send file content.') try: with open(source_file, 'rb') as file_handle: buffer = file_handle.read(FILE_BUFFER_SIZE) while len(buffer) &gt; 0: conn.sendall(buffer) hash_algo.update(buffer) buffer = file_handle.read(FILE_BUFFER_SIZE) except IOError as e: print('Failed to open source file', source_file, ':', e, file=sys.stderr) sys.exit(3) conn.shutdown(socket.SHUT_WR) conn.close() print('File sent, connection closed.') print('SHA256 digest:', hash_algo.hexdigest()) sys.exit(0) </code></pre>
[]
[ { "body": "<p>If I’m reading this correctly - I did not test it, the file cannot be larger than a 4 byte integer of bytes which is only a 4gb file, which in 2018 I wouldn’t have considered large since it fits in memory for most laptops.</p>\n<p>I love that you are using getopts!</p>\n<p>What I’m not loving is t...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T01:59:26.243", "Id": "197462", "Score": "4", "Tags": [ "python", "python-3.x", "socket" ], "Title": "Large file transmission over socket in Python" }
197462
<p>I have two lists of numbers:</p> <p>$$\{i_1, i_2, i_3,i_4\}$$ and $$\{j_1,j_2,j_3,j_4\}$$</p> <p>The problem I want to solve is: Inside a loop, if the following two conditions are satisfied, then it will do something I want, otherwise it just cycle the loop. The conditions are:</p> <ol> <li>Both lists contain four different numbers;</li> <li>If ignoring the ordering, in other words, we view these two lists as two set, then they are the same.</li> </ol> <p>I want to find a very fast way to get the answer to the problem. I have very slow Fortran code as follows:</p> <pre><code>if (i2==i1) cycle if (i3==i1) cycle if (i3==i2) cycle if (i4==i1) cycle if (i4==i2) cycle if (i4==i3) cycle if (j2==j1) cycle if (j3==j1) cycle if (j3==j2) cycle if (j4==j1) cycle if (j4==j2) cycle if (j4==j3) cycle q1=0 q2=0 q3=0 q4=0 if (i1==j1)q1=1 if (i1==j2)q1=2 if (i1==j3)q1=3 if (i1==j4)q1=4 if (i2==j1)q2=1 if (i2==j2)q2=2 if (i2==j3)q2=3 if (i2==j4)q2=4 if (i3==j1)q3=1 if (i3==j2)q3=2 if (i3==j3)q3=3 if (i3==j4)q3=4 if (i4==j1)q4=1 if (i4==j2)q4=2 if (i4==j3)q4=3 if (i4==j4)q4=4 if (q1*q2*q3*q4==24)then Something I want to do endif </code></pre> <p>I think to find a good program, the following should also be considered as well as cutting down the number of instructions:</p> <ol> <li>The probability to have four different numbers in both lists are about 1/10;</li> <li>The probability to have for these two lists containing two same set of numbers are very small, about 10^(-11); </li> <li>I really have to do many loops.</li> </ol> <p>Could someone help me out? I think a good idea can really boost the code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T14:12:00.880", "Id": "380721", "Score": "0", "body": "What are the ranges of the loops? Are those if statements at the inner-most loop, or are they located at the top level of the loop(s)?" }, { "ContentLicense": "CC BY-SA 4...
[ { "body": "<p>The only way to reduce the number of operations is to sort one of the arrays. But 4 elements is hardly worth it. </p>\n\n<p>Perhaps when adding the numbers to the array then add them in a sorted order, otherwise quicksort is good for arrays under 10 elements in size.</p>\n\n<p>Performing a binary ...
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T03:45:43.047", "Id": "197465", "Score": "1", "Tags": [ "sorting", "complexity", "fortran" ], "Title": "Checking whether two lists contain the same elements" }
197465
<p>I have a list of 2D arrays which comes from a time evolution PDE (in \$(x, y, t)\$) that I solved numerically. There are \$k\$ arrays, which all have the same dimensions, and the arrays correspond to a solution field of the PDE at times \$t = 0, 0.1, \dots, 0.1k\$. I wrote a program that takes in this list and computes the autocorrelation between the arrays for varying lag times. </p> <p>From the <a href="https://en.wikipedia.org/wiki/Autocorrelation#Statistics" rel="nofollow noreferrer">definition of the autocorrelation function for wide-sense stationary processes</a>, we have </p> <p>$$R(\tau) = \frac{\mathbb{E}[(X_{t} - \mu)(X_{t + \tau} - \mu)]}{\sigma^{2}} = \frac{1}{\sigma^{2}} \sum_{t = 0}^{k-\tau} (X_{t} - \mu)(X_{t + \tau} - \mu)$$</p> <p>Here, \$X_{t}\$ represents our 2D array at time \$t\$ and \$\mu\$, \$\sigma\$ the average and standard deviation, respectively, of the entire list of 2D arrays. My code for this is as follows</p> <pre><code>import numpy as np import matplotlib.pyplot as plt ### Data # List of data arrays called 'Data'. ### Expectation New_Data = [] O = np.ones((len(Data[0][0]),len(Data[0][1]))) # Resolution of data arrays. A = sum(Data)/len(Data) # Average 2D array M = np.mean(A) # Average of average 2D array S = np.std(A) # Standard deviation of average 2D array for i in range(len(Data)): New_Data.append((Data[i]-M*O)/S) # (X_t-mu)/sigma ### Autocorrelation for varying lags. Count = 1 R = [] while Count &lt; len(New_Data)//2: # Arbitrary choice for max lag time. Matrix_Multiply = [] for j in range(len(New_Data)-Count): Matrix_Multiply.append(np.multiply(New_Data[j],New_Data[j+Count])) R.append(sum(Matrix_Multiply)) Count = Count+1 Solution = [] for k in range(len(R)): Solution.append(np.mean(R[k])) t = [0.1*k for k in range(1,len(Solution)+1)] ### Plotting plt.xlabel('Lag time') plt.ylabel('Matrix sum') plt.title('Field autocorrelation over time') plt.semilogy(t, Solution) plt.savefig('I_hope_this_works.png') </code></pre> <p>I'm sure there are some redundant steps in there, so I was wondering if anyone can see how I could make the code cleaner? Also, if anyone knows how to apply <a href="http://numba.pydata.org/numba-doc/0.33.0/index.html" rel="nofollow noreferrer">pythons numba package</a> to make the code faster, it would be greatly appreciated, as I haven't been able to figure it out from the documentation in the hyperlink. </p> <p><strong>EDIT</strong></p> <p>In response to the comment below, here is some arbitrary data to use</p> <pre><code>Data = [] n = 20 for k in range(n): Data.append(np.random.randint(n, size=(n,n))) </code></pre> <p>For my data, I have ~800 arrays of size 256x256. I don't think I'm able to upload that for anyone to use.</p> <p><strong>EDIT 2</strong></p> <p>I just realised that we don't need to keep the data in the R list, so we can remove it as well as the lines</p> <pre><code>Solution = [] for k in range(len(R)): Solution.append(np.mean(R[k])) </code></pre> <p>and edit the while loop to</p> <pre><code>### Autocorrelation for varying lags. Count = 1 Solution = [] while Count &lt; len(New_Data)//2: # Arbitrary choice for max lag time. Matrix_Multiply = [] for j in range(len(New_Data)-Count): Matrix_Multiply.append(np.multiply(New_Data[j],New_Data[j+Count])) R = sum(Matrix_Multiply) Solution.append(np.mean(R)) Count = Count+1 </code></pre> <p>though it doesn't provide much of a markup in terms of speed.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T12:44:30.607", "Id": "380710", "Score": "0", "body": "It would help if you could provide some example data. Right now it is very hard to test any alternative approach." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDat...
[ { "body": "<p>So here is a slightly simplified version that uses more <code>numpy</code> functionalities, where your solution manually iterates over the outer lists:</p>\n\n<pre><code>def autocorrelate_graipher(Data):\n Data = np.array(Data)\n A = Data.mean(axis=0) # Average 2D arra...
{ "AcceptedAnswerId": "197500", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T05:48:40.303", "Id": "197467", "Score": "6", "Tags": [ "python", "numpy", "statistics", "matplotlib" ], "Title": "Computing the autocorrelation between 2D time series arrays in python" }
197467
<p>Could I please have some ideas how to improve this conversion calculator I have made. I am currently not looking to add any more quantities, but rather trying to enhance the usability and add some quality of life changes to it. </p> <p>If there are any major ways I could make the program more efficient that would be helpful as well.</p> <p>Here is my <a href="https://github.com/APOCHA/Conversion-Calculator/blob/master/calc%20shortening.py" rel="nofollow noreferrer">code</a>:</p> <pre><code># Conversion Calculator # #rid input unit from tkinter import * from tkinter import ttk class GUI(): def __init__(self, master): self.master = master master.resizable(False, False) master.title('Conversion Calculator') self.tabControl = ttk.Notebook(master) # Tab Formatting self.tab1 = ttk.Frame(self.tabControl) self.tabControl.add(self.tab1, text='Weight') self.tab2 = ttk.Frame(self.tabControl) self.tabControl.add(self.tab2, text='Length') self.tab3 = ttk.Frame(self.tabControl) self.tabControl.add(self.tab3, text='Tempurature') self.tabControl.pack(expand=1, fill="both") self.intial_wording11 = StringVar(self.tab1) # Tab 1 Formatting self.intial_wording11.set('Unit') self.intial_wording12 = StringVar(self.tab1) self.intial_wording12.set('Unit') self.entrybox1 = ttk.Entry(self.tab1, width=12) self.entrybox1.grid(column=0, row=1) self.entrybox1.focus_set() self.Iunit1 = StringVar() self.input_unit1 = ttk.Combobox(self.tab1, width=12, textvariable=self.Iunit1, state="readonly", values = ['Unit', 'Grams', 'Kilograms', 'Tons', 'Ounces', 'Pounds']) self.input_unit1.grid(column=1, row=1) self.input_unit1.current(0) self.convert_bttn1 = ttk.Button(self.tab1, text='Convert', command=self.weight) self.convert_bttn1.grid(column=0, row=3) self.outputbox1 = ttk.Entry(self.tab1, width=12, state="readonly") self.outputbox1.grid(column=0, row=4) self.Ounit1 = StringVar() self.output_unit1 = ttk.Combobox(self.tab1, width=12, textvariable=self.Ounit1, state="readonly", values = ['Unit', 'Grams', 'Kilograms', 'Tons', 'Ounces', 'Pounds']) self.output_unit1.grid(column=1, row=4) self.output_unit1.current(0) self.intial_wording21 = StringVar(self.tab2) # self.tab 2 Formatting # self.intial_wording21.set('Unit') self.intial_wording22 = StringVar(self.tab2) self.intial_wording22.set('Unit') self.entrybox2 = ttk.Entry(self.tab2, width=12) self.entrybox2.grid(column=0, row=1) self.entrybox2.focus_set() self.Iunit2 = StringVar() self.input_unit2 = ttk.Combobox(self.tab2, width=12, textvariable=self.Iunit2, state="readonly", values = ['Unit', 'Millimeters', 'Centimeters', 'Meters', 'Kilometers', 'Miles', 'Feet', 'Inches', 'Yards']) self.input_unit2.grid(column=1, row=1) self.input_unit2.current(0) self.convert_bttn2 = ttk.Button(self.tab2, text='Convert', command=self.length) self.convert_bttn2.grid(column=0, row=3) self.outputbox2 = ttk.Entry(self.tab2, width=12, state="readonly") self.outputbox2.grid(column=0, row=4) self.Ounit2 = StringVar() self.output_unit2 = ttk.Combobox(self.tab2, width=12, textvariable=self.Ounit2, state="readonly", values = ['Unit', 'Millimeters', 'Centimeters', 'Meters', 'Kilometers', 'Miles', 'Feet', 'Inches', 'Yards']) self.output_unit2.grid(column=1, row=4) self.output_unit2.current(0) self.intial_wording31 = StringVar(self.tab3) # self.tab 3 Formatting # self.intial_wording31.set('Unit') self.intial_wording32 = StringVar(self.tab3) self.intial_wording32.set('Unit') self.entrybox3 = ttk.Entry(self.tab3, width=12) self.entrybox3.grid(column=0, row=1) self.entrybox1.focus_set() self.Iunit3 = StringVar() self.input_unit3 = ttk.Combobox(self.tab3, width=12, textvariable=self.Iunit3, state="readonly", values = ['Unit', 'Celcius', 'Farenheit', 'Kelvin']) # self.intial_wording self.input_unit3.grid(column=1, row=1) self.input_unit3.current(0) self.convert_bttn3 = ttk.Button(self.tab3, text='Convert', command=self.tempurature) self.convert_bttn3.grid(column=0, row=3) self.outputbox3 = ttk.Entry(self.tab3, width=12, state="readonly") self.outputbox3.grid(column=0, row=4) self.Ounit3 = StringVar() self.output_unit3 = ttk.Combobox(self.tab3, width=12, textvariable=self.Ounit3, state="readonly", values = ['Unit', 'Celcius', 'Farenheit', 'Kelvin'])#self.intial_wording2, self.output_unit3.grid(column=1, row=4) self.output_unit3.current(0) self.master.bind('&lt;Return&gt;', self.keybind) class Logic(GUI): def keybind (self, event): self.convert_bttn1.invoke() self.convert_bttn2.invoke() self.convert_bttn3.invoke() def weight(self): Weight_Conversion_Values = {'Grams': 1, 'Kilograms': 1000, 'Tons': 1000000, 'Ounces': 28.3495, 'Pounds': 453.592} self.outputbox1.delete(0, END) if self.Iunit1.get() != '': if self.Ounit1.get() != '': try: self.outputbox1.config(state='NORMAL') self.outputbox1.delete(0, 'end') self.outputbox1.config(state='readonly') text = float(self.entrybox1.get()) newtext = text*(Weight_Conversion_Values[self.Iunit1.get()])*(int(1)/(Weight_Conversion_Values[self.Ounit1.get()])) self.outputbox1.config(state='NORMAL') self.outputbox1.insert(0, newtext) self.outputbox1.config(state='readonly') except ValueError: error_message = 'non-int error' self.outputbox1.config(state='NORMAL') self.outputbox1.insert(0, error_message) self.outputbox1.config(state='readonly') def length(self): Length_Conversion_Values = {'Meters': 1, 'Kilometers': 1000, 'Centimeters': 0.01, 'Millimeters': 0.001, 'Miles': 1609.344498, 'Feet': 0.304799999, 'Inches': 0.02539998, 'Yards': 0.9144027578} self.outputbox2.delete(0, END) if self.Iunit2.get() != '': if self.Ounit2.get() != '': try: self.outputbox2.config(state='NORMAL') self.outputbox2.delete(0, 'end') self.outputbox2.config(state='readonly') text = float(self.entrybox2.get()) newtext = text*(Length_Conversion_Values[self.Iunit2.get()])*(int(1)/(Length_Conversion_Values[self.Ounit2.get()])) self.outputbox2.config(state='NORMAL') self.outputbox2.insert(0, newtext) self.outputbox2.config(state='readonly') except ValueError: error_message = 'non-int error' self.outputbox2.config(state='NORMAL') self.outputbox2.insert(0, error_message) self.outputbox2.config(state='readonly') def tempurature(self): self.outputbox3.delete(0, END) if self.Iunit3.get() == 'Celcius': self.outputbox3.config(state='NORMAL') self.outputbox3.delete(0, 'end') self.outputbox3.config(state='readonly') try: if self.Ounit3.get() == 'Kelvin': if float(self.entrybox3.get()) &gt;= -273.15: text = float(self.entrybox3.get()) newtext = text + 273.15 self.outputbox3.config(state='NORMAL') self.outputbox3.insert(0, newtext) self.outputbox3.config(state='readonly') else: error_message = 'X ≥ -273.15' self.outputbox3.config(state='NORMAL') self.outputbox3.insert(0, error_message) self.outputbox3.config(state='readonly') if self.Ounit3.get() == 'Farenheit': if float(self.entrybox3.get()) &gt;= -273.15: text = float(self.entrybox3.get()) newtext = text*9/5 + 32 self.outputbox3.config(state='NORMAL') self.outputbox3.insert(0, newtext) self.outputbox3.config(state='readonly') else: error_message = 'X ≥ -273.15' self.outputbox3.config(state='NORMAL') self.outputbox3.insert(0, error_message) self.outputbox3.config(state='readonly') except ValueError: error_message = 'non-int error' self.outputbox3.config(state='NORMAL') self.outputbox3.insert(0, error_message) self.outputbox3.config(state='readonly') if self.Iunit3.get() == 'Farenheit': self.outputbox3.config(state='NORMAL') self.outputbox3.delete(0, 'end') self.outputbox3.config(state='readonly') try: if self.Ounit3.get() == 'Kelvin': if float(self.entrybox3.get()) &gt;= -459.67: text = float(self.entrybox3.get()) newtext = (text+459.67)*5/9 self.outputbox3.config(state='NORMAL') self.outputbox3.insert(0, newtext) self.outputbox3.config(state='readonly') else: error_message = 'X ≥ -459.67' self.outputbox3.config(state='NORMAL') self.outputbox3.insert(0, error_message) self.outputbox3.config(state='readonly') if self.Ounit3.get() == 'Celcius': if float(self.entrybox3.get()) &gt;= -459.67: text = float(self.entrybox3.get()) newtext = text*5/9 - 32 self.outputbox3.config(state='NORMAL') self.outputbox3.insert(0, newtext) self.outputbox3.config(state='readonly') else: error_message = 'X ≥ -459.67' self.outputbox3.config(state='NORMAL') self.outputbox3.insert(0, error_message) self.outputbox3.config(state='readonly') except ValueError: error_message = 'non-int error' self.outputbox3.config(state='NORMAL') self.outputbox3.insert(0, error_message) self.outputbox3.config(state='readonly') if self.Iunit3.get() == 'Kelvin': self.outputbox3.config(state='NORMAL') self.outputbox3.delete(0, 'end') self.outputbox3.config(state='readonly') try: if self.Ounit3.get() == 'Celcius': if float(self.entrybox3.get()) &gt;= 0: text = float(self.entrybox3.get()) newtext = text - 273.15 self.outputbox3.config(state='NORMAL') self.outputbox3.insert(0, newtext) self.outputbox3.config(state='readonly') else: error_message = 'X ≥ 0' self.outputbox3.config(state='NORMAL') self.outputbox3.insert(0, error_message) self.outputbox3.config(state='readonly') if self.Ounit3.get() == 'Farenheit': if float(self.entrybox3.get()) &gt;= 0: text = float(self.entrybox3.get()) newtext = text*9/5 - 459.67 self.outputbox3.config(state='NORMAL') self.outputbox3.insert(0, newtext) self.outputbox3.config(state='readonly') else: error_message = 'X ≥ 0' self.outputbox3.config(state='NORMAL') self.outputbox3.insert(0, error_message) self.outputbox3.config(state='readonly') except ValueError: error_message = 'non-int error' self.outputbox3.config(state='NORMAL') self.outputbox3.insert(0, error_message) self.outputbox3.config(state='readonly') if __name__ == "__main__": root = Tk() test = Logic(root) </code></pre>
[]
[ { "body": "<p>One of the smartest programmer's I've ever known once told me that code is read way more often than it is written, so optimize for the reader<sup>1</sup></p>\n\n<p>While it's true that code should be efficient, it also needs to be understandable and maintainable. Also, efficiency is relative. If y...
{ "AcceptedAnswerId": "197491", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T07:35:38.443", "Id": "197473", "Score": "3", "Tags": [ "python", "python-3.x", "gui", "tkinter", "unit-conversion" ], "Title": "Enhancing a Conversion calculator" }
197473
<p>Yesterday someone guided me through this <a href="https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/" rel="nofollow noreferrer">article</a> and I'm wondering whether I should use try-catch implementation or not? I have the following code below which is actually a RESTful service and I have implemented the try-catch pattern. I'm throwing errors only in debug mode just for testing purpose and during the release mode, I'm catching errors and returning the meaningful error messages such as Http Status Codes.</p> <p>After reading this article, I'm confused whether I'm on the right track and if not, do I need to remove try-catch and throw errors instead of such meaningful messages to the end user? </p> <p>Any code review/feedback is appreciated. </p> <pre><code>namespace NewEmployeeBuddy.Facade.Controllers.Employee { [RoutePrefix("api/employee")] [RequireHttps] [BasicAuthorization] public class EmployeeController : ApiController { #region Properties private IEmployeeService _employeeService { get; set; } #endregion #region Constructor public EmployeeController() { //_employeeService = new EmployeeService(); } public EmployeeController(IEmployeeService employeeService) { _employeeService = employeeService; } #endregion #region Actions [HttpPost, Route("add")] [ValidateRequest] public IHttpActionResult AddEmployee(AddEmployeeRequestDTO request) { try { if (request == null) return Content(HttpStatusCode.BadRequest, ErrorCodes.E002); var response = _employeeService.AddEmployee(request); if (response.OperationResult) return Content(HttpStatusCode.Created, response); return Content(HttpStatusCode.InternalServerError, ErrorCodes.E001); } catch (Exception ex) { #if (DEBUG) Logger.Instance.Error(ex); throw ex; #endif //Logger.Instance.Error(ex); //return Content(HttpStatusCode.InternalServerError, ErrorCodes.E001); } } #endregion } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T09:04:29.940", "Id": "380685", "Score": "1", "body": "_`//No need to create the concrete instance. Autofac takes care of it.`_ - this is not true if you use this constructor." }, { "ContentLicense": "CC BY-SA 4.0", "Crea...
[ { "body": "<blockquote>\n<pre><code>throw ex;\n</code></pre>\n</blockquote>\n\n<p>This is a fatal mistake. It'll create a new stack-trace and you won't be able to tell where the actual exception occured. If you want to rethrow it then use just</p>\n\n<pre><code>throw;\n</code></pre>\n\n<p>without <code>ex</cod...
{ "AcceptedAnswerId": "197477", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T09:02:07.363", "Id": "197476", "Score": "6", "Tags": [ "c#", "error-handling", "rest", "controller", "asp.net-web-api" ], "Title": "ASP.NET REST controller with try-catch error handling" }
197476
<p>This code needs to get two inputs: </p> <ul> <li>one is the full address of a directory</li> <li>and another the file extension that it will be changed. </li> </ul> <p>These inputs cab be added in the default section of <code>parser.add_argument</code> as in the example. It will overwrite the files with the new copyright:</p> <pre><code>import csv import argparse import os class change_logo(object): def __init__(self, key): self.keyword = key self.case = 1 self.counter1 = 0 self.counter2 = 0 self.counter3 = 0 def read_line(self, key): with open(key, 'rb') as f: reader = csv.reader(f, delimiter=',') lista = [] s_index = -2 for row in reader: lista.append(row) for index in range(0, len(lista)): if any("# Copyright: (c) 2011 Comp1 Ltd. All Rights Reserved" in s for s in lista[index]): s_index = index self.counter1 = self.counter1+ 1 if any("# Copyright: (c) 2018 Comp2 Ltd. All Rights Reserved" in s for s in lista[index]): print("COPYRIGHT ALREADY EXISTS") self.case = 2 self.counter2 = self.counter2 + 1 return s_index if s_index == -2: self.counter3 = self.counter3 + 1 print("NO COPYRIGHT IN THIS FILE") else: print(s_index + 1) return s_index def replace_copyright(self, key): s_index = self.read_line(key) if self.case == 2: self.case = 1 return 0 if s_index != -2: s = open(key).read() s = s.replace('# Copyright: (c) 2011 Comp1 Ltd. All Rights Reserved', '# Copyright: (c) 2018 Comp2 Ltd. All Rights Reserved') f = open(key, 'w') f.write(s) f.close() print("COPYRIGHT ADDED IN LINE %d OF THE FILE" % (s_index + 1)) else: s = open(key).read() f = open(key, 'w') f.write('# Copyright: (c) 2018 Comp2 Ltd. All Rights Reserved' + '\n' + s) f.close() print("COPYRIGHT ADDED IN THE BEGINNING OF THE FILE") # This class returns a list of addresses class file_traverser(object): # The user sends the path address and file extension that wants changed def __init__(self, key): self.path = key[0] self.file_extension = key[1] def file_walker(self): directory = [] # Iterate through all file paths and append the list for root, dirs, files in os.walk(self.path): for file_ in files: if self.file_extension in os.path.join(root, file_): directory.append(os.path.join(root, file_)) return directory # This method parses user's arguments from cmd prompt def parser_arg(): parser = argparse.ArgumentParser('--help') parser.add_argument( "--path", nargs="+", help="Give a valid directory path and a fileextension to be scanned and changed", default=['C:\Users', ".py"] # put a directory path and also you can change the extension to .csv or anything else ) args = parser.parse_args() path = args.path return path if __name__ == '__main__': counter = 0 counter1, counter2, counter3 = 0, 0, 0 test1 = file_traverser(parser_arg()) files = test1.file_walker() for index in range(0, len(files)): try: print(files[index]) test = change_logo(files[index]) test.replace_copyright(files[index]) counter = counter + 1 counter1 = counter1 + test.counter1 counter2 = counter2 + test.counter2 counter3 = counter3 + test.counter3 except Exception: index = index + 1 print ("number of files read : %d" % counter) print ("number of files replaced with the new COPYRIGHT : %d" % counter1) print ("number of files that COPYRIGHT ALREADY EXISTS : %d" % counter2) print ("number of files that NO COPYRIGHT EXISTS : %d" % counter3) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T09:58:11.430", "Id": "197480", "Score": "3", "Tags": [ "python", "python-2.x", "text-editor" ], "Title": "code for changing from old copyright to a new one in python" }
197480
<p>I am relatively new to redux - I wanted to keep the actions in the same detectJsCamera function which is why I decided to resolve a promise to detectCamera - hence the set timeout.</p> <p>I am not sure how I would go about testing this.</p> <pre><code>xport function detectJsCamera() { return async(dispatch) =&gt; { dispatch({type: types.JS_DETECTING_CAMERA}); try { await detectCamera(); await dispatch({type: types.JS_CAMERA_DETECTED}); } catch (error) { throw error; // this.props.history.push('/setup/positioning') }; } } const detectCamera = () =&gt; new Promise((resolve, reject) =&gt; { const checkIfReady = () =&gt; { if (webgazer.isReady()) { resolve('success'); } else { setTimeout(checkIfReady, 100); } } setTimeout(checkIfReady,100); }); </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T10:57:44.353", "Id": "197484", "Score": "1", "Tags": [ "javascript", "redux" ], "Title": "Dispatches an event to detect a camera - Once the camera has initialised resolve a promise to say the camera is detected" }
197484
<p>I'm currently trying to implement the singleton pattern in C++. After reading about it for a while now, it seems like there are a really large amount of different ways to do this. </p> <p>Is the way I ended up doing it correct or did I miss out on something important here? Is this implementation thread safe in modern C++ (I read there were some changes to that in particular with C++11)? In addition I am not sure at all about the way I am accessing the class within <code>MyFunction()</code>. </p> <p>Is it really necessary to use a raw pointer there? Does this code contain any memory leaks?</p> <pre><code>#include &lt;iostream&gt; class Singleton { private: Singleton(); ~Singleton(); public: static Singleton&amp; instance() { static Singleton INSTANCE; return INSTANCE; } void Test(); }; void Singleton::Test() { std::cout &lt;&lt; "Test() called" &lt;&lt; std::endl; } Singleton::Singleton() { std::cout &lt;&lt; "CONSTRUCTOR CALLED" &lt;&lt; std::endl; } Singleton::~Singleton() { std::cout &lt;&lt; "DESTRUCTOR CALLED" &lt;&lt; std::endl; } void MyFunction() { // use the singleton class Singleton * MySingleton = &amp;Singleton::instance(); MySingleton-&gt;Test(); } int main() { MyFunction(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T12:40:33.973", "Id": "380708", "Score": "2", "body": "I'd disable copyctor and `=` so that you won't accidentally copy the object." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T12:41:42.030", "I...
[ { "body": "<h1>Thread safety</h1>\n<p>Accessing the singleton is thread-safe. The change in C++11 has forced compilers to implement the construction of local <code>static</code> variables (like <code>INSTANCE</code>) in a thread-safe manner.</p>\n<p>Note, however, that this doesn't make <code>Singleton</code> t...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T11:12:58.887", "Id": "197486", "Score": "5", "Tags": [ "c++", "c++11", "singleton" ], "Title": "Singleton class and correct way to access it in C++" }
197486
<p>Yesterday, I very quickly, in an hour, wrote the very first version of my long-term archiving + encrypting shell script.</p> <p>I am aware it may have too many flaws, but none of them really prevent it from normal operation, so before I take another step and restructure it with <code>printf</code> and better error reporting, structure, exit codes, etc. I would like you to have a look first.</p> <p>What it does:</p> <ol> <li>It archives a given directory into a tarball.</li> <li>It compresses (with maximum effort) that tarball using <code>xz</code>.</li> <li>It encrypts that <code>xz</code> archive using <code>openssl</code> and AES-256.</li> <li>It creates and checks the created SHA-512 sum file.</li> <li>It then decrypts the created file to a temporary file.</li> <li>Finally, it compares the decrypted file with the original <code>xz</code> archive.</li> </ol> <p>I am prepared to waste time and effort in order to be 100% sure before burning my precious data to Blu-ray M-disc.</p> <p>I know I should not have to do steps 5 and 6 just because there is almost a 0% chance for the data to get corrupted in the process. But since I have a rather large NVMe SSD drive, and relatively fast CPU, it should not be so shocking that I wrote it with motto <em>better safe than sorry</em>.</p> <pre><code>#!/bin/sh [ -z "$1" ] &amp;&amp; echo "You need to give me one directory!" &amp;&amp; exit 1 [ ! -d "$1" ] &amp;&amp; echo "This is not a directory!" &amp;&amp; exit 1 [ ! -w "$PWD" ] &amp;&amp; echo "The current directory is not writable by you!" &amp;&amp; exit 1 dir=$(basename "$1") today=$(date +%Y-%m-%d) backupdir="${dir}_${today}" # backupdir="${dir}" backupfile="${backupdir}.tar" bold=$(tput bold) red=$(tput setaf 1) yellow=$(tput setaf 3) nocolor=$(tput sgr0) bold_red="$bold$red" bold_yellow="$bold$yellow" echo echo "${bold_yellow}1/6: TAR is archiving your directory '${bold_red}$dir${bold_yellow}' into '${bold_red}$backupfile${bold_yellow}'${nocolor}" echo if ! tar -cf "$backupfile" "$1" --totals then echo "TAR failed to archive your directory" exit 1 fi echo echo "${bold_yellow}2/6: XZ is compressing your '${bold_red}$backupfile${bold_yellow}' into '${bold_red}$backupfile.xz${bold_yellow}'${nocolor}" echo if ! xz --format=xz --check=sha256 -9 --threads=8 --keep --verbose --verbose --extreme "$backupfile" then echo "XZ failed to compress your backup file" exit 1 fi echo echo "${bold_yellow}3/6: OpenSSL is encrypting your '${bold_red}$backupfile.xz${bold_yellow}' into '${bold_red}$backupfile.xz.enc${bold_yellow}'${nocolor}" echo if ! pv -W "$backupfile.xz" | openssl enc -aes-256-cbc -md sha256 -salt -out "$backupfile.xz.enc" -pass file:/home/vlastimil/.blablablabla 2&gt; /dev/null then echo "OpenSSL failed to encrypt your compressed file" exit 1 fi echo echo "${bold_yellow}4/6: sha512sum is creating hash file '${bold_red}$backupfile.xz.enc.SHA512SUM${bold_yellow}'${nocolor}" echo if ! sha512sum -b "$backupfile.xz.enc" &gt; "$backupfile.xz.enc.SHA512SUM" then echo "sha512sum failed to compute hashsum file" exit 1 fi sha512sum -c "$backupfile.xz.enc.SHA512SUM" echo echo "${bold_yellow}5/6: Decrypting your '${bold_red}$backupfile.xz.enc${bold_yellow}' into a temporary file '${bold_red}$backupfile.xz.dec${bold_yellow}'${nocolor}" echo if ! pv -W "$backupfile.xz.enc" | openssl enc -aes-256-cbc -md sha256 -salt -out "$backupfile.xz.dec" -d -pass file:/home/vlastimil/.blablablabla 2&gt; /dev/null then echo "OpenSSL failed to decrypt your encrypted file" exit 1 fi echo echo "${bold_yellow}6/6: Comparing your un-encrypted, compressed, archived, directory file '${bold_red}$backupfile.xz${bold_yellow}' with a temporary file '${bold_red}$backupfile.xz.dec${bold_yellow}'${nocolor}" echo if ! cmp "$backupfile.xz" "$backupfile.xz.dec" then echo "Failed to compare files" exit 1 else echo "Your directory '${bold_red}$dir${nocolor}' has been successfully stored as '${bold_red}$backupfile.xz.enc${nocolor}'" rm "$backupfile.xz.dec" rm "$backupfile.xz" rm "$backupfile" fi </code></pre>
[]
[ { "body": "<p>It's a fine script. Even <a href=\"https://www.shellcheck.net/#\" rel=\"nofollow noreferrer\">shellcheck</a> doesn't find anything in it. Well done!</p>\n\n<p>I only have minor comments.</p>\n\n<p>You can safely omit the <code>sha512sum -c</code>.\nIt would only fail if the previous command failed...
{ "AcceptedAnswerId": "197516", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T13:10:30.137", "Id": "197490", "Score": "1", "Tags": [ "linux", "aes", "sh", "posix", "openssl" ], "Title": "Long-term archiving + encrypting shell script" }
197490
<p>Here I have implemented code for Round Robin CPU Scheduling Algorithm. scheduling.h header file is also used in Shortest Job First Scheduling Algorithm and Priority Scheduling Algorithm, so it contains common data members and member functions.</p> <p>First I have calculated end time in <code>calcEndTime()</code> then using formula <code>turnAroundTime = endTime - arrivalTime</code> calculated Turnaround time and using <code>waitingTime = turnAroundTime - burstTime</code> calculated Waiting time.</p> <p>Please help me to improve and optimize this code using more C++11 and C++14 features.</p> <p>scheduling.h</p> <pre><code>#ifndef SCHEDULING_H_ #define SCHEDULING_H_ #include &lt;vector&gt; class Scheduling { uint currActiveProcessID; uint timeCounter = 0; double avgWaitingTime; double avgTurnAroundTime; std::vector&lt;unsigned&gt; arrivalTime; //When process start to execute std::vector&lt;unsigned&gt; burstTime; //process wait to execute after they have arrived std::vector&lt;unsigned&gt; waitingTime; //total time taken by processes std::vector&lt;unsigned&gt; turnAroundTime; //time when a process end std::vector&lt;unsigned&gt; endTime; public: Scheduling(unsigned num = 0); Scheduling(const Scheduling&amp;) = delete; Scheduling &amp;operator=(const Scheduling&amp;) = delete; Scheduling(Scheduling&amp;&amp;) = delete; Scheduling &amp;operator=(Scheduling&amp;&amp;) = delete; ~Scheduling() = default; void calcWaitingTime(); void calcTurnAroundTime(); void calcEndTime(); void printInfo(); private: void sortAccordingArrivalTime(); }; #endif </code></pre> <p>roundrobin.cpp</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; // std::find #include &lt;iterator&gt; // std::begin, std::end #include &lt;limits&gt; //std::numeric_limits #include "scheduling.h" unsigned timeQuantum = 0; Scheduling::Scheduling(unsigned num) { unsigned arrivalVal, burstVal; currActiveProcessID = 0; timeCounter = 0; std::cout &lt;&lt; "\nEnter time quantum : "; std::cin &gt;&gt; timeQuantum; arrivalTime.reserve(num); burstTime.reserve(num); endTime.reserve(num); std::cout &lt;&lt; "\nEnter arrival time and burst time eg(5 18)\n"; for (unsigned i = 0; i &lt; num; i++) { std::cout &lt;&lt; "\nProcess" &lt;&lt; i+1 &lt;&lt; ": "; std::cin &gt;&gt; arrivalVal &gt;&gt; burstVal; arrivalTime.push_back(arrivalVal); burstTime.push_back(burstVal); } } void Scheduling::sortAccordingArrivalTime() { for (std::size_t i = 0; i &lt; arrivalTime.size(); i++) { for (std::size_t j = i+1; j &lt; arrivalTime.size(); j++) { if (arrivalTime[i] &gt; arrivalTime[j]) { std::swap(arrivalTime[i], arrivalTime[j]); std::swap(burstTime[i], burstTime[j]); } } } } void Scheduling::calcEndTime() { //If arrival time is not sorted //sort burst time according to arrival time sortAccordingArrivalTime(); //copy values of burst time in new vector std::vector&lt;unsigned&gt; burstTimeCopy; std::copy(burstTime.begin(), burstTime.end(), std::back_inserter(burstTimeCopy)); while (!(std::all_of(burstTimeCopy.begin(), burstTimeCopy.end(), [] (unsigned e) { return e == 0; }))) { currActiveProcessID = 0; auto it = burstTimeCopy.begin(); while (it != burstTimeCopy.end()) { if (burstTimeCopy[currActiveProcessID] &gt; timeQuantum) { burstTimeCopy[currActiveProcessID] -= timeQuantum; timeCounter += timeQuantum; } else if (burstTimeCopy[currActiveProcessID] &gt; 0) { timeCounter += burstTimeCopy[currActiveProcessID]; burstTimeCopy[currActiveProcessID] = 0; endTime[currActiveProcessID] = timeCounter; } currActiveProcessID++; it++; } } } void Scheduling::calcTurnAroundTime() { double sum = 0.00; for (std::size_t i = 0; i &lt; arrivalTime.size(); i++) { unsigned val = endTime[i] - arrivalTime[i]; turnAroundTime.push_back(val); sum += (double)val; } avgTurnAroundTime = sum / turnAroundTime.size(); } void Scheduling::calcWaitingTime() { double sum = 0.00; for (std::size_t i = 0; i &lt; burstTime.size(); i++) { unsigned val = turnAroundTime[i] - burstTime[i]; waitingTime.push_back(val); sum += (double)val; } avgWaitingTime = sum / waitingTime.size(); } void Scheduling::printInfo() { std::cout &lt;&lt; "ProcessID\tArrival Time\tBurst Time\tEnd Time\tWaiting Time"; std::cout &lt;&lt; "\tTurnaround Time\n"; for (std::size_t i = 0; i &lt; arrivalTime.size(); i++) { std::cout &lt;&lt; i+1 &lt;&lt; "\t\t" &lt;&lt; arrivalTime[i] &lt;&lt; "\t\t" &lt;&lt; burstTime[i]; std::cout &lt;&lt; "\t\t"&lt;&lt;endTime[i] &lt;&lt; "\t\t" &lt;&lt; waitingTime[i] &lt;&lt;"\t\t"; std::cout &lt;&lt; turnAroundTime[i] &lt;&lt;'\n'; } std::cout &lt;&lt; "Average Waiting Time : " &lt;&lt; avgWaitingTime &lt;&lt; '\n'; std::cout &lt;&lt; "Average Turn Around Time : " &lt;&lt; avgTurnAroundTime &lt;&lt; '\n'; } int main() { int num; std::cout &lt;&lt; "Enter number of process: "; std::cin &gt;&gt; num; Scheduling roundRobin(num); roundRobin.calcEndTime(); roundRobin.calcTurnAroundTime(); roundRobin.calcWaitingTime(); roundRobin.printInfo(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T16:47:54.403", "Id": "380739", "Score": "0", "body": "There's no definition for `uint`. Was this intended to be `unsigned`, or is the definition missing entirely (e.g. by missing an `#include`)?" }, { "ContentLicense": "CC B...
[ { "body": "<p>Where does the <code>uint</code> type come from?</p>\n\n<p>The <code>currActiveProcessID</code> member of <code>Scheduling</code> can be removed from the class, as it is only used internally to <code>calcEndTime()</code>.</p>\n\n<p><code>timeQuantum</code> should be entered in <code>main</code> (o...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T15:52:32.487", "Id": "197498", "Score": "1", "Tags": [ "c++", "c++11" ], "Title": "Round Robin Scheduling Algorithm" }
197498
<p>I've just started with Java. The code below calculates Body Mass Index (BMI).</p> <p>Could someone look for my code and assess it? Maybe I should write something more? All advice will be very helpful.</p> <pre><code>import java.util.Scanner; public class BMI { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); double weight = 0; double height = 0; double bmi = 0; System.out.println(&quot;Please enter your details to calculate your Body Mass Index.&quot;); System.out.println(&quot;Enter your weight in kilograms:&quot;); weight = scanner.nextDouble(); System.out.println(&quot;Enter your height in metres:&quot;); height = scanner.nextDouble(); bmi = (weight / (height * height)); System.out.println(&quot;Your BMI is: &quot; + bmi); if (bmi &gt;= 40) { System.out.println(&quot;Serious obesity&quot;); } else if (bmi &gt;= 30) { System.out.println(&quot;Obesity&quot;); } else if (bmi &gt;= 25) { System.out.println(&quot;Overweight&quot;); } else if (bmi &gt;= 18) { System.out.println(&quot;Standard&quot;); } else { System.out.println(&quot;Underweight&quot;); } scanner.close(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T16:44:00.343", "Id": "380734", "Score": "1", "body": "You definitely should write more. Please [edit] your question and tell us what this assesment is about?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-...
[ { "body": "<p>Because this is such a simple program, there are really only a few basic things that can make it good or bad (beyond the fact that it actually works). </p>\n\n<p>The good:</p>\n\n<ul>\n<li><strong>Formatting</strong> - this is all consistent, and matches the standard Java formatting</li>\n<li><str...
{ "AcceptedAnswerId": "197506", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T16:32:25.600", "Id": "197501", "Score": "1", "Tags": [ "java", "beginner", "calculator" ], "Title": "BMI calculator/assessor" }
197501
<p>For a project, I need to write a basic template manager who will be responsible to load the requested HTML or PHP template when the user clicks on a menù link. It's like a page loader since that all the loaded templates are static HTML pages. I want to improve it if is it possible. Here is the code.</p> <p>on the main index of the project I have a jQuery code like this:</p> <pre><code>&lt;script&gt; $(document).ready(function(){ $('.contents').load('templates/home.php'); $(document).on('click','a',function(e){ e.preventDefault(); $('#nav-modal').modal('hide'); var url = $(this).attr('href'); if(url == 'booking/'){ window.location.href= 'booking/'; } else { $.ajax({ type: 'GET', url: 'templates/TemplateController.php'+url, cache: false, dataType: 'html', success: function(response){ $('.contents').empty() .html(response); } }); } }); }); &lt;/script&gt; </code></pre> <p>on the PHP 'controller' side I have this code who will only call a class to obtain the needed files. The URL passed from <code>AJAX</code> to the controller is something like this: <code>?tpl=atemplate</code></p> <pre><code>&lt;?php require_once 'Autoloader.php'; if(isset($_GET['tpl'])){ $tpl = new TemplateLoader; echo $tpl-&gt;render($_GET['tpl']); } ?&gt; </code></pre> <p>And then in the simple class, I have only a <code>switch</code> control that will select what is the requested template to load on the index</p> <pre><code>&lt;?php class TemplateLoader{ public function __construct(){ #$this-&gt;path = $path; } public function render($tpl){ switch($tpl){ case 'home': echo file_get_contents('home.php'); break; case 'about': echo file_get_contents('about.php'); break; case 'services': echo file_get_contents('services.php'); break; case 'contacts': echo file_get_contents('contacts.php'); break; case 'prices': echo file_get_contents('prices.php'); break; } } } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-30T04:37:54.697", "Id": "380803", "Score": "0", "body": "Instead of using `jQuery.ajax()` for your requests, you should consider the benefits of the fetch API. Importantly, fetch works asynchronously and it also won't reject on HTTP er...
[ { "body": "<h1>Technical mistakes</h1>\n\n<h3>echo void</h3>\n\n<pre><code>echo $tpl-&gt;render($_GET['tpl']);\n</code></pre>\n\n<p>This echo will display empty string (null), because you've already output a string with echo within method and have void return type (implicit <code>return null</code>). Make <code...
{ "AcceptedAnswerId": "197533", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T16:36:22.610", "Id": "197502", "Score": "2", "Tags": [ "php", "template", "ajax" ], "Title": "Basic PHP template loader" }
197502
<p>I'm relatively new to Go, which is why I decided to post some code here. My goal is to en-/decode a TCP stream. The individual data packets length-based. The first two bytes are the unsigned size in little-endian byte order. The size includes the size field itself. The methods I wrote seem to en-/decode the packets as expected.</p> <p>Is there a more efficient way to achieve this? Does Go perhaps already implement such methods somewhere.</p> <hr> <pre><code>func GetPacketByLength(source io.Reader) ([]byte, error) { s := make([]byte, 2) if _, err := io.ReadFull(source, s); err != nil { return nil, err } // Little-endian uint16 size := uint16(s[0]) | uint16(s[1])&lt;&lt;8 - 2 p := make([]byte, size) if _, err := io.ReadFull(source, p); err != nil { return nil, err } return p, nil } func PutPacketByLength(target io.Writer, p []byte) error { s := make([]byte, 2) // Little-endian uint16 s[0] = byte((len(p) + 2)) s[1] = byte((len(p) + 2) &gt;&gt; 8) if _, err := target.Write(s); err != nil { return err } if _, err := target.Write(p); err != nil { return err } return nil } </code></pre>
[]
[ { "body": "<p>You may consider to use <a href=\"https://golang.org/pkg/encoding/binary/#Read\" rel=\"nofollow noreferrer\"><code>binary.Read</code></a>. I find this more readable and self documented. See <a href=\"https://play.golang.org/p/6v_sjL4M6-h\" rel=\"nofollow noreferrer\">this example</a>.</p>\n\n<pre>...
{ "AcceptedAnswerId": "197507", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T17:25:42.017", "Id": "197504", "Score": "4", "Tags": [ "performance", "io", "go" ], "Title": "Length-Based Frame Stream En-/Decoding in Go" }
197504
<p>Using Qt, I've got this code in order to protect access to some shared data between threads. I'm pretty sure the idea is correct, but I don't know if RVO and/or RAII could potentially screw the <code>get</code> function. I'm much more used to C and while I understand the idea, I'm not totally familiar with all the "gotchas" for these two concepts.</p> <pre><code>class DataManager { Q_OBJECT private: QVector&lt;DataType&gt; data; QReadWriteLock* rwLock; public: DataManager() { rwLock = new QReadWriteLock(); } ~DataManager() { delete rwLock; } Q_DISABLE_COPY(DataManager) QVector&lt;DataType&gt; getData() { QReadWriteLocker lock(rwLock); return data; } QVector&lt;DataType&gt;* beginModifyData() { rwLock-&gt;lockForWrite(); return &amp;data; } void endModifyData() { rwLock-&gt;unlock(); emit dataChanged(); } signals: void dataChanged(); }; </code></pre> <p>In the <code>get</code> function, is it possible that the RAII-type class <code>QReadWriteLocker</code> unlocks the lock before the return copy is made? Thus allowing some thread, that was waiting to write, to overwrite the data being returned.</p> <p>Also, if somebody writes</p> <pre><code>QVector&lt;DataType&gt;&amp; myData = dataManager-&gt;getData(); </code></pre> <p>Is it possible, due to RVO, that they get a reference to the <em>actual</em> data?</p> <p>Also, I'd like to receive comments on the code and idea itself. Below I've outlined the reasons why I chose this approach.</p> <ol> <li>Simple to use. Since one can only read a copy of the data, they don't have to worry about synchronization and locking.</li> <li>Taking advantage of the implicit sharing of Qt containers, no <em>actual</em> copies will ever be made when using <code>getData()</code>, thus making read-only access very fast.</li> <li>Since, when modifying the data, one gets a pointer to the actual data, again, in most cases, no copies will be made, unless some thread is caching the data (or one of the copies has not yet gone out of scope of whatever got it).</li> <li>Looking at the documentation and code, a non-recursive QReadWriteLock is ultra fast in the non-contended case, not doing any waiting or context-switching (uses atomic operations on an integer).</li> <li>I could potentially do some data validation/fixup in the <code>endModifyData</code> function if needed.</li> </ol> <p>Thanks.</p>
[]
[ { "body": "<h1>Locking</h1>\n<p>Let's see what these member functions actually do, and what can go wrong:</p>\n<h3><code>getData</code></h3>\n<p>The lock acquired in <code>getData</code> basically only ensures that nobody is currently modifying <code>data</code> while inside. As soon as the caller gets the retu...
{ "AcceptedAnswerId": "197519", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T19:05:25.430", "Id": "197511", "Score": "2", "Tags": [ "c++", "multithreading", "concurrency", "qt" ], "Title": "Concurrent access to data with QReadWriteLock" }
197511
<p>Here is my code:</p> <pre><code>import sys import math def dist(a,b): return math.hypot((b[0]-a[0]),(b[1]-a[1])) def minimum_distance(x, y): points = list(zip(x,y)) points_y = sorted(points, key= lambda z:z[1]) points.sort(key=lambda g:g[0]) return min_dist(points,points_y) def min_dist(points,points_y): if len(points)==2: return dist(points[0],points[1]) elif len(points)==3: return min(dist(points[0],points[1]),dist(points[0],points[2]),dist(points[1],points[2])) ave = (len(points)+1)//2 yleft = [t for t in points_y if t[0]&lt;=points[ave-1][0]] yright = [q for q in points_y if q[0]&gt;=points[ave][0]] d1 = min_dist(points[0:ave],yleft) d2 = min_dist(points[ave:len(points)],yright) d = min(d1,d2) arr_split = [point for point in points_y if abs(point[0]- points[ave][0]) &lt;= d] d_=2*(10**18) for i in range(len(arr_split)-1): for j in range(i+1,min(len(arr_split),i+7)): temp = dist(arr_split[i],arr_split[j]) if temp&lt;d_:d_=temp return min(d,d_) </code></pre> <p>Example input:([2,5,1],[3,6,2]) and output is \$ \sqrt 2 \$ since (2,3) and (1,2) are the closest points. The input arrays to minimum_distance are the x and y values of each point respectively and the inputs to min_dist are the points sorted based on their x values and y values respectively. </p> <p>I have implemented pre-sort and have used computational geometric theory (comparison between 7 points only in the strip) to make the time complexity \$ O(n \log n) \$ and my code works swiftly and correctly for most test cases. However, for some hidden test cases generated by Coursera, my code is taking more than 20 seconds. Any optimisations/ corrections?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T19:43:42.953", "Id": "380767", "Score": "0", "body": "Can you provide an example input and output -- from my understanding of the problem you could easily come up with an O(n) solution." }, { "ContentLicense": "CC BY-SA 4.0"...
[ { "body": "<h3>Coding style</h3>\n\n<p>Your code is difficult to read because it is written very condensed.</p>\n\n<p>There is a well-established coding style for Python, the \n<a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8 coding style</a>,\nand conformance to that style...
{ "AcceptedAnswerId": "197560", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T19:10:00.560", "Id": "197512", "Score": "1", "Tags": [ "python", "python-3.x", "time-limit-exceeded", "computational-geometry", "clustering" ], "Title": "Finding the distance between the two closest points in a 2-D plane" }
197512
<p>Since the previous question I posted here was not found as interesting as I expected, I decided to post a new one. I made a function solely for the purpose of having fun. That is, a function that checks if two strings are similar with a given %.</p> <pre><code>int case_insensitive_chrcmp (int ch1, int ch2) { return ch1 == ch2 || ch1 + ' ' == ch2 || ch1 - ' ' == ch2; } int strpcmp (char* str1, char* str2, unsigned setting) { int szStr1 = strlen(str1); int szStr2 = strlen(str2); int szMax = max(szStr1, szStr2); int szMin = 0; int chars = 0; if(setting &gt; 100) setting = 100; if(szStr1 == szMax) szMin = szStr2; else szMin = szStr1; chars = szMax * setting / 100; int cur = 0; for(int i = 0; i &lt; szMin; i++) { if(case_insensitive_chrcmp(str1[i], str2[i])) cur++; else cur = 0; if(cur &gt;= chars) return 1; } return 0; } </code></pre> <p>(you may need to provide your own definition for <code>min</code> and <code>max</code> since I think they are not supported by all compilers)</p> <hr> <p>Example usage:</p> <pre><code>char* str1 = "Hello"; char* str2 = "Hey"; int percentage = 50%101; // or just 50 or w/e printf("%s %i%% %s - %s\n", str1, percentage, str2, strpcmp(str1, str2, percentage) ? "true" : "false"); </code></pre> <p>Output:</p> <blockquote> <p>Hello 50% Hey - true</p> <hr> </blockquote> <h2>More info on what the function is supposed to do:</h2> <p>It calculates how many characters must match consecutively based on percentage in order to return true. The comparison between characters is also done in case insensitive manner.</p> <h2>More info on how the function is required to work:</h2> <p>Regarding safety, this function can do much more, check against null pointers, re-entrancy guarding, MT-safety and that shouldn't really damage the performance level. Speaking of performance, I am a performancecholic and the first thing I can see that is bothering me here is the two <code>strlens</code> - the size of the two strings can be obtained within a single loop. Otherwise there are redundant iterations.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-30T12:53:09.470", "Id": "380835", "Score": "1", "body": "You probably want to use [edit distance](https://en.wikipedia.org/wiki/Edit_distance) instead." } ]
[ { "body": "<p>Alright I have a hole in my schedule, so I will give it a review myself.</p>\n\n<hr>\n\n<h2>Let's start with the function <code>case_insensitive_chrcmp</code></h2>\n\n<ol>\n<li><p>The name mixes two standards for function name, the well-descriptive, but long snake_case and the less descriptive but...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T20:05:37.783", "Id": "197517", "Score": "4", "Tags": [ "c", "strings", "edit-distance" ], "Title": "Function to check whether two strings are similar at given %" }
197517
<p>I've written a script in scrapy to grab different <code>names</code> and <code>links</code> from different pages of a website and write those parsed items in a csv file. When I run my script, I get the results accordingly and find a data filled in csv file. I'm using python 3.5, so when I use scrapy's built-in command to write data in a csv file, I do get a csv file with blank lines in every alternate row. Eventually, I tried the below way to achieve the flawless output (with no blank lines in between). Now, It produces a csv file fixing blank line issues. I hope I did it in the right way. However, if there is anything I can/should do to make it more robust, I'm happy to cope with.</p> <p>This is my script which provides me with a flawless output in a csv file:</p> <pre><code>import scrapy ,csv from scrapy.crawler import CrawlerProcess class GetInfoSpider(scrapy.Spider): name = "infrarail" start_urls= ['http://www.infrarail.com/2018/exhibitor-profile/?e={}'.format(page) for page in range(65,70)] def __init__(self): self.infile = open("output.csv","w",newline="") def parse(self, response): for q in response.css("article.contentslim"): name = q.css("h1::text").extract_first() link = q.css("p a::attr(href)").extract_first() yield {'Name':name,'Link':link} writer = csv.writer(self.infile) writer.writerow([name,link]) c = CrawlerProcess({ 'USER_AGENT': 'Mozilla/5.0', }) c.crawl(GetInfoSpider) c.start() </code></pre> <p>Btw, I used <code>.CrawlerProcess()</code> to be able to run my spider from sublime text editor.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-30T08:00:43.543", "Id": "380810", "Score": "0", "body": "Welcome to Code Review! That's quite a well-written question, especially for a new user. Well done." } ]
[ { "body": "<p>I'd like to mention, that there is a special way of making output files in scrapy - <a href=\"https://doc.scrapy.org/en/latest/topics/item-pipeline.html\" rel=\"nofollow noreferrer\">item pipelines</a>. So, in order to make it right, you should write your own pipeline (or modify standard one via s...
{ "AcceptedAnswerId": "197546", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T20:06:31.387", "Id": "197518", "Score": "5", "Tags": [ "python", "python-3.x", "csv", "web-scraping", "scrapy" ], "Title": "Writing to a csv file in a customized way using scrapy" }
197518
<p>I just started coding programs with python. As a challenge I wanted to program something to print out the Fibonacci Numbers. It looks like I've done what I wanted to do (I checked the first few numbers) and because I just started coding, I obviously don't know if this is a legitimate code and somebody would code it like that. Keep in mind that I have only done some basic lessons in python so I just want to get some feedback and advice for better code. </p> <pre><code>def spiral(sequence): numbers = [] for i in sequence: numbers.append(0) if i == 0 or i == 1: numbers[i] = 1 continue numbers[i] = numbers[i-1] + numbers[i-2] return numbers times = range(int(input("How many times do you want to go through? "))) fibonacci = spiral(times) print(fibonacci) </code></pre>
[]
[ { "body": "<p>The way <code>sequence</code> is used guarantees that the results will be wrong for the majority of inputs. It's clearly intended that <code>sequence</code> should be a continuous range starting at <code>0</code>. So rather than require the range as input, it would make more sense to require the l...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T20:37:20.523", "Id": "197522", "Score": "1", "Tags": [ "python", "beginner", "fibonacci-sequence" ], "Title": "Display Fibonacci numbers" }
197522
<p>This is short Angular 5 code which works as intended: check boxes behave like radio buttons - only one can be selected at a time.</p> <p>Both versions of 'toggleCheckbox' works but I am interested is if there is better, more elegant way to set 'checkbox1' and 'checkbox2'?</p> <p>template-driven-form.component.ts</p> <pre><code>import {Component, OnInit} from '@angular/core'; import {User} from './domain/user'; @Component({ selector: 'app-template', templateUrl: './template-driven-form.component.html', styleUrls: ['./style.css'] }) export class TemplateDrivenFormComponent implements OnInit { user = new User(); ngOnInit() { this.setDefaultValues(); } constructor() { } // toggleCheckbox(event) { // if (event.target.id === 'checkbox1') { // this.user.checkbox1 = true; // this.user.checkbox2 = false; // } else { // this.user.checkbox1 = false; // this.user.checkbox2 = true; // } // } toggleCheckbox(event) { event.target.id === 'checkbox1' ? (this.user.checkbox1 = true, this.user.checkbox2 = false) : (this.user.checkbox2 = true, this.user.checkbox1 = false); } setDefaultValues() { this.user.checkbox1 = true; this.user.checkbox2 = false; } } </code></pre> <p>template-driven-form.component.html</p> <pre><code>&lt;h3&gt;Template Driven Form&lt;/h3&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt; &lt;label for="checkbox1"&gt;Label 1&lt;/label&gt;&lt;input type="checkbox" id="checkbox1" name="checkbox1" [ngModel]="user.checkbox1" (change)="toggleCheckbox($event)" [checked]="user.checkbox1"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;label for="checkbox2"&gt;Label 2&lt;/label&gt;&lt;input type="checkbox" id="checkbox2" name="checkbox2" [ngModel]="user.checkbox2" (change)="toggleCheckbox($event)" [checked]="user.checkbox2"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T21:26:53.750", "Id": "197523", "Score": "1", "Tags": [ "form", "typescript", "angular-2+" ], "Title": "Checkboxes behave like radio buttons with angular" }
197523
<p>I am using Java to create an Android app. I have the main activity read a CSV file, create objects, and then save them into a singleton class so the rest of the activities in the app can access them easily.</p> <p>This is working perfectly fine but I am not sure if there are some other ways to achieve the same result that are considered better practice, or if perhaps my solution could cause issues down the line that I am not aware of.</p> <p>MainActivity extends AppCompatActivity </p> <pre><code>@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); createItemObjects(); } public void createItemObjects(){ InputStream is = getResources().openRawResource(R.raw.items_csv); BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); ArrayList&lt;Item&gt; items = new ArrayList&lt;Item&gt;(); String line = ""; try { while((line = reader.readLine())!=null) { String[] values = line.split(","); String img = values[0]; int imgID = getResources().getIdentifier(img , "drawable", getPackageName()); items.add(new Item(imgID, values[1], values[2])); } } catch (IOException e) { Log.v("Main Activity", "Error Reading File on Line " + line, e); e.printStackTrace(); } ItemListHolder.getInstance().setItemsArrayList(items); } </code></pre> <p>So as you can see, when the app launches it reads the CSV file, creates <code>Item</code> objects, creates an <code>ArrayList</code> to store those <code>Item</code> objects, then sends it into the <code>ItemListHolder</code> singleton, so that all the Activities in the app can use <code>ItemListHolder.getInstance().getItemsArrayList()</code> to retrieve the <code>ArrayList</code> of <code>Item</code>. Each <code>Item</code> is constructed with an image ID, name, and description from a line in the CSV file.</p> <p>This works without any issues, but my question is: Is having your Android app create objects from a CSV file everytime it restarts considered good practice/safe to use/efficient ect, or should you be storing your objects in some other way, such as shared preferences, so that they are actually saved in memory and do not need to be created everytime the app launches and then held inside a class.</p> <p>I am familiar with Java but am very new to Android so I really have no idea what other ways of saving objects may or may not exist, or what is considered good to use. Is it better to save them to the fileOutputStream? Is it better to save them to sharedPreferences? Is there some other storage method that is better?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-30T00:07:57.933", "Id": "380794", "Score": "0", "body": "Just changes the title so it clearly state what this code accomplishes. For the Item class, the second argument is a string that gets assigned to an instance variable called name...
[ { "body": "<p>People from Android have a really comprehensive documentation about it at <a href=\"https://developer.android.com/guide/topics/data/data-storage\" rel=\"nofollow noreferrer\">https://developer.android.com/guide/topics/data/data-storage</a>.</p>\n\n<p>Short answer: yes, there are better ways: Share...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T21:39:22.867", "Id": "197525", "Score": "4", "Tags": [ "java", "android", "csv" ], "Title": "Initializing an Android activity by reading a CSV file with image IDs, names, and descriptions" }
197525
<p>For a Seesaw (Swing) app I'm writing, I need to be able to flash a component for a certain duration. Here's the basic function I came up with that accomplishes this:</p> <pre><code>; Note, this isn't what I want reviewed. See below. (defn flash-property [component prop-key flash-value duration] (let [old-value (sc/config component prop-key)] (sc/config! component prop-key flash-value) (sc/timer (fn [_] (sc/config! component prop-key old-value)) :initial-delay duration, :repeats? false))) </code></pre> <p>It reads the current property value into <code>old-value</code>, sets the new value, then in a timer reverts the old value after <code>duration</code> many milliseconds. If I wanted to create a button that flashes for half a second when pressed, I could write:</p> <pre><code>(let [btn (sc/button :text "Button")] (sc/listen btn :action (fn [_] (flash-property btn :background :red 500))) btn) </code></pre> <p>I had a problem that if you start a new flash before the old one has finished, <code>old-value</code> becomes the flash color from the previous flash, and the component gets stuck as the flash color.</p> <p>To get around this, I had to rely on a "static variable" that keeps track of what is currently being flashed. I tried to extract as much as I could out of the decider function, but I'm still unhappy with it. The atom, while in a restricted scope, still feels like a hack to cover up a bad design. I've never used a <code>let</code> at the top level before, and it feels kind of dirty.</p> <p>Of course, I could create some kind of a "flash handler" that gets passed back and forth and keeps track of what's being flashed, but that would be it's own flavour of mess. Then the caller would need to maintain it somehow. Considering the flash gets triggered in a button handler, I'd probably have to maintain an atom there anyways.</p> <p>Can anyone see how to cleanly avoid the "static variable" <code>flashing?-atom</code>?</p> <pre><code>(ns pet-redo.full-ui.helpers (:require [seesaw.core :as sc])) (defn flash-property "Alters the property at prop-key to flash-value for duration-many milliseconds, then reverts the property back to the original value. Will break if a new flash is started before a previous one ends." [component prop-key flash-value duration component-done-callback] (let [old-value (sc/config component prop-key)] (sc/config! component prop-key flash-value) (sc/timer (fn [_] (sc/config! component prop-key old-value) (component-done-callback)) :initial-delay duration, :repeats? false))) (let [flashing?-atom (atom #{})] (defn maybe-flash-background! "Alters the property at prop-key to flash-value for duration-many milliseconds, then reverts the property back to the original value. Does nothing if the element is already being flashed. Returns whether or not a flash was triggered." [component flash-color duration] (when-not (@flashing?-atom component) (swap! flashing?-atom conj component) (flash-property component :background flash-color duration #(swap! flashing?-atom disj component)) true))) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-29T23:29:55.807", "Id": "197528", "Score": "1", "Tags": [ "swing", "animation", "clojure" ], "Title": "Cleanly preventing flashing an element from corrupting future flashes" }
197528
<p>Essentially the AJAX component of <a href="https://codereview.stackexchange.com/q/152699/127828">this question</a>, reimplemented in ES2017 style async/await. The code connects to a remote JSON API and scrapes it using a limited number of streams to avoid triggering rate limiting when the number of pages is large. Each stream retries on server-side errors and when rate limiting kicks in, up to 3 times by default. A rate limiting 429 response also results in a 5-second wait before further requests, increasing 50% each time up to 30 seconds. Other network errors result in a thrown error with a custom message.</p> <pre><code>const Module = {}; Module.HttpError = class HttpError extends TypeError { constructor(result = "Network Error", ...args) { super(result, ...args); this.message = "Network access failed with status code " + result.status + ": " + result.statusText + " at " + result.url + ". Check your network connection."; } }; /** * Local copy of a remote API endpoint. */ Module.Remote = class Remote { constructor(path, query = {}) { this.remote = new URL(path, "https://online-go.com/api/v1/"); this.remote.searchParams.set("format", "json"); for (let i of Object.keys(query)) this.remote.searchParams.set(i, query[i]); this.meta = fetch(new URL("?page_size=1", this.remote)) .then(r=&gt;{ if(r.ok) { r.json(); } else { throw new Module.HttpError(r); } }); } /** * Fetches everything from the API path specified, using a number of streams. * * @param {number=} maxStreams - number of simultaneous streams. * @param {number=} pageSize - size of pages to fetch. * * @return {(Array&lt;Object&gt;|Object)} An array of pages */ async scrape(maxStreams = 5, pageSize = 100) { const meta = await this.meta; if ("count" in meta) { // Check number of pages from API metadata. let target = this.remote; target.searchParams.set("page_size", pageSize); const numP = Math.ceil((meta.count)/pageSize); let q = Array.from({length: numP}, (v, i) =&gt; i+1); let pages = []; let wait = 0; /** * Creates a stream that fetches pages from the shared queue, * then saves the result to the array pages. * * @param {!URL} target - the URL and path of the remote. * @param {number} page - the page number to fetch. * @param {number=} retries - maximum number of retries before error. * @return {number} zero on sucessful completion. */ async function stream (target, page, retries=3) { if(wait) await sleep(5000*1.5**wait); target.searchParams.set("page", page); let result = await fetch(target); if(result.ok) { pages[page-1] = result.json(); // When queue is empty, return 0. return q.length?stream(target, q.shift()):0; } else if(result.status === 429 &amp;&amp; retries) { wait&gt;4||(wait+=1/maxStreams); // Max wait = 5 or ~ 30 secs console.warn("Too many requests! Backing off."); return stream(target, page, retries-1); } else if(500&lt;=result.status &amp;&amp; retries) { console.warn("Server error, retrying"); return stream(target, page, retries-1); } else { throw new dvt.HttpError(result); } } await Promise.all(Array.from({length: maxStreams}, v =&gt; stream(target, q.shift()))); console.info("Final wait level: " + wait); this.pages = pages; return this.pages; } else { return this.meta; } } }; export default Module; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-30T09:20:00.853", "Id": "197543", "Score": "1", "Tags": [ "javascript", "performance", "web-scraping", "concurrency", "ajax" ], "Title": "JSON API Scraper v2: Limited concurrency AJAX from a shared queue (ES2017)" }
197543
<p>This is a solution for the Day 8 hackerrank.com challenge. The basic idea of the challenge is to create a mapping of names to phone numbers based on the the given input, and later look up the phone numbers for certain names. If the entry exists, print it and its number. If it doesn't, print out "Not found".</p> <p>Here's my solution in C++:</p> <pre><code>#include&lt;iostream&gt; #include&lt;map&gt; using namespace std; int main() { int i, n; cin&gt;&gt;n; string name, number, key; map&lt;string, string&gt; phone_dir; for(i=0; i&lt;n; i++) { cin&gt;&gt;name&gt;&gt;number; phone_dir.insert(pair &lt;string, string&gt; (name, number)); } while(cin&gt;&gt;key) { if (phone_dir.find(key) != phone_dir.end()) { cout&lt;&lt;key&lt;&lt;"="&lt;&lt;phone_dir.find(key)-&gt;second&lt;&lt; endl; } else cout&lt;&lt; "Not found"&lt;&lt;endl; } return 0; } </code></pre> <p>Is there a more efficient solution in C++ for this problem?</p>
[]
[ { "body": "<ol>\n<li><p>You should not use <code>using namespace std;</code> This is bad practice that will get you into trouble once you want to use a function that has the same name.</p></li>\n<li><p>You can use descriptive names. So instead of \"n\" use \"numEntries\" or whatever.</p></li>\n<li><p>You should...
{ "AcceptedAnswerId": "197545", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-30T11:44:19.937", "Id": "197544", "Score": "4", "Tags": [ "c++", "programming-challenge", "hash-map" ], "Title": "Hackerrank Day 8: Dictionaries and Maps solution in C++" }
197544
<p>The following code is my solution to a code challenge I submitted a few days ago. I got rejected straight away with no feedback and I've wondered why.</p> <p><a href="https://github.com/AyaAzzam/toy-robot-puzzle" rel="nofollow noreferrer">Here</a> is the full code repo.</p> <blockquote> <p><strong>Requirements</strong></p> <p>The application is a simulation of a toy robot moving on a square tabletop, of dimensions 5 x 5 units. There are no other obstructions on the table surface. The robot is free to roam around the surface of the table, but must be prevented from falling to destruction. Any movement that would result in the robot falling from the table must be prevented, however further valid movement commands must still be allowed. Create an application that can read in commands of the following form:</p> <p>PLACE X,Y,F</p> <p>MOVE</p> <p>LEFT</p> <p>RIGHT</p> <p>REPORT</p> <p>PLACE will put the toy robot on the table in position X,Y and facing NORTH, SOUTH, EAST or WEST.</p> <p>The origin (0,0) can be considered to be the SOUTH WEST most corner.</p> <p>MOVE will move the toy robot one unit forward in the direction it is currently facing.</p> <p>LEFT and RIGHT will rotate the robot 90 degrees in the specified direction without changing the position of the robot.</p> <p>REPORT will announce the X,Y and F of the robot.</p> <p>Constraints:</p> <ul> <li>The application must be a Spring-Boot-Application</li> <li>Input must be realised over the REST-API, take care when designing the REST-API</li> <li>The robot that is not on the table can choose the ignore the MOVE, LEFT, RIGHT and REPORT commands.</li> <li>The robot must not fall off the table during movement. This also includes the initial placement of the toy robot.</li> <li>Any move that would cause the robot to fall must be ignored.</li> <li>It is not required to provide any graphical output showing the movement of the toy robot.</li> </ul> <p>Plain input Examples:</p> <p>PLACE 0,0,NORTH MOVE REPORT</p> <p>Output: 0,1,NORTH</p> <p>PLACE 0,0,NORTH LEFT REPORT</p> <p>Output: 0,0,WEST</p> <p>PLACE 1,2,EAST MOVE MOVE LEFT MOVE REPORT</p> <p>Output: 3,3,NORTH</p> <p>MOVE REPORT</p> <p>Output: ROBOT MISSING</p> </blockquote> <p><strong>Solution</strong></p> <p><strong>ToyRobotApplication.java</strong> </p> <pre><code>package com.puzzle.toyrobot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ToyRobotApplication { public static void main(String[] args) { SpringApplication.run(ToyRobotApplication.class, args); } } </code></pre> <p><strong>RobotSimulationController.java</strong></p> <pre><code>package com.puzzle.toyrobot.controller; import com.puzzle.toyrobot.model.Report; import com.puzzle.toyrobot.model.SimulationRound; import com.puzzle.toyrobot.service.RobotSimulationService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class RobotSimulationController { private RobotSimulationService simulationService; @Autowired public RobotSimulationController(RobotSimulationService simulationService) { this.simulationService = simulationService; } @PostMapping @RequestMapping("/robot/simulation") public ResponseEntity&lt;Report&gt; newSimulationRound(@RequestBody SimulationRound simulationRound) { Report report = simulationService.start(simulationRound); return ResponseEntity.ok(report); } } </code></pre> <p><strong>RobotSimulationService.java</strong></p> <pre><code>package com.puzzle.toyrobot.service; import com.puzzle.toyrobot.model.Report; import com.puzzle.toyrobot.model.Robot; import com.puzzle.toyrobot.model.SimulationRound; import com.puzzle.toyrobot.model.command.Command; import com.puzzle.toyrobot.model.command.CommandFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; @Service public class RobotSimulationService { private final Logger log = LoggerFactory.getLogger(RobotSimulationService.class); public Report start(SimulationRound simulationRound) { Robot robot = new Robot(); Report report = new Report(); for (String commandString : simulationRound.getCommands()) { Command command = CommandFactory.getCommand(commandString); if (command != null) { command.execute(robot, report); } else { log.debug("Wrong command: " + commandString); } } return report; } } </code></pre> <p><strong>SimulationRound.java</strong></p> <pre><code>package com.puzzle.toyrobot.model; import java.util.ArrayList; import java.util.List; public class SimulationRound { private List&lt;String&gt; commands = new ArrayList&lt;&gt;(); public List&lt;String&gt; getCommands() { return commands; } public void setCommands(List&lt;String&gt; commands) { this.commands = commands; } public void addCommand(String command) { commands.add(command); } } </code></pre> <p><strong>Robot.java</strong></p> <pre><code>package com.puzzle.toyrobot.model; public class Robot { public static final Integer MAX_POSITION = 4; public static final Integer MIN_POSITION = 0; private Integer xPosition; private Integer yPosition; private CardinalDirection cardinalDirection; public Robot() { } public Robot(Integer xPosition, Integer yPosition, CardinalDirection cardinalDirection) { this.xPosition = xPosition; this.yPosition = yPosition; this.cardinalDirection = cardinalDirection; } public Integer getXPosition() { return xPosition; } public void setXPosition(Integer xPosition) { this.xPosition = xPosition; } public Integer getYPosition() { return yPosition; } public void setYPosition(Integer yPosition) { this.yPosition = yPosition; } public CardinalDirection getCardinalDirection() { return cardinalDirection; } public void setCardinalDirection(CardinalDirection cardinalDirection) { this.cardinalDirection = cardinalDirection; } public boolean isOnTable() { return xPosition != null &amp;&amp; yPosition != null &amp;&amp; cardinalDirection != null; } public String getCurrentStatus() { return String.join(",", xPosition.toString(), yPosition.toString(), cardinalDirection.toString()); } public void increaseYPosition() { yPosition++; } public void decreaseYPosition() { yPosition--; } public void increaseXPosition() { xPosition++; } public void decreaseXPosition() { yPosition++; } } </code></pre> <p><strong>Report.java</strong> package com.puzzle.toyrobot.model;</p> <pre><code>import java.util.ArrayList; import java.util.List; import java.util.Objects; public class Report { private List&lt;String&gt; output = new ArrayList&lt;&gt;(); public List&lt;String&gt; getOutput() { return output; } public void setOutput(List&lt;String&gt; output) { this.output = output; } public void addOutput(String outupt) { this.output.add(outupt); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Report report = (Report) o; return Objects.equals(output, report.output); } @Override public int hashCode() { return Objects.hash(output); } } </code></pre> <p><strong>CardinalDirection.java</strong></p> <pre><code>package com.puzzle.toyrobot.model; public enum CardinalDirection { EAST, WEST, SOUTH, NORTH } </code></pre> <p><strong>Command.java</strong></p> <pre><code>package com.puzzle.toyrobot.model.command; import com.puzzle.toyrobot.model.Report; import com.puzzle.toyrobot.model.Robot; public abstract class Command { public abstract void execute(Robot robot, Report report); } </code></pre> <p><strong>CommandFactory.java</strong></p> <pre><code>package com.puzzle.toyrobot.model.command; public class CommandFactory { private static final String PLACE_COMMAND_REGEX = "^(PLACE)\\s\\d+,\\d+,(NORTH|WEST|EAST|SOUTH)$"; public static Command getCommand(String commandString) { if (commandString.matches(PLACE_COMMAND_REGEX)) { return new PlaceCommand(commandString); } else if (commandString.equals(CommandType.LEFT.name())) { return new LeftCommand(); } else if (commandString.equals(CommandType.RIGHT.name())) { return new RightCommand(); } else if (commandString.equals(CommandType.REPORT.name())) { return new ReportCommand(); } else if (commandString.equals(CommandType.MOVE.name())) { return new MoveCommand(); } return null; } } </code></pre> <p><strong>CommandType,java</strong> </p> <pre><code>package com.puzzle.toyrobot.model.command; public enum CommandType { PLACE, MOVE, LEFT, RIGHT, REPORT } </code></pre> <p><strong>LeftCommand.java</strong></p> <pre><code>package com.puzzle.toyrobot.model.command; import com.puzzle.toyrobot.model.CardinalDirection; import com.puzzle.toyrobot.model.Report; import com.puzzle.toyrobot.model.Robot; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LeftCommand extends Command { private final Logger log = LoggerFactory.getLogger(LeftCommand.class); public void execute(Robot robot, Report report) { if (!robot.isOnTable()) { log.debug("Left command ignored"); } else { switch (robot.getCardinalDirection()) { case NORTH: robot.setCardinalDirection(CardinalDirection.WEST); break; case SOUTH: robot.setCardinalDirection(CardinalDirection.EAST); break; case EAST: robot.setCardinalDirection(CardinalDirection.NORTH); break; case WEST: robot.setCardinalDirection(CardinalDirection.SOUTH); break; } log.debug("The robot is rotating 90 degree to " + robot.getCardinalDirection()); } } } </code></pre> <p><strong>MoveCommand.java</strong></p> <pre><code>package com.puzzle.toyrobot.model.command; import com.puzzle.toyrobot.model.Report; import com.puzzle.toyrobot.model.Robot; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MoveCommand extends Command { private final Logger log = LoggerFactory.getLogger(MoveCommand.class); @Override public void execute(Robot robot, Report report) { if (!robot.isOnTable()) { log.debug("Move command ignored"); } else { switch (robot.getCardinalDirection()) { case NORTH: if (robot.getYPosition() &lt; Robot.MAX_POSITION) { robot.increaseYPosition(); log.debug("The robot is moving"); } else { log.debug("Move command ignored"); } break; case SOUTH: if (robot.getYPosition() &gt; Robot.MIN_POSITION) { robot.decreaseYPosition(); log.debug("The robot is moving"); } else { log.debug("Move command ignored"); } break; case EAST: if (robot.getXPosition() &lt; Robot.MAX_POSITION) { robot.increaseXPosition(); log.debug("The robot is moving"); } else { log.debug("Move command ignored"); } break; case WEST: if (robot.getXPosition() &gt; Robot.MIN_POSITION) { robot.decreaseXPosition(); log.debug("The robot is moving"); } else { log.debug("Move command ignored"); } break; } } } } </code></pre> <p><strong>PlaceCommand.java</strong></p> <pre><code>package com.puzzle.toyrobot.model.command; import com.puzzle.toyrobot.model.CardinalDirection; import com.puzzle.toyrobot.model.Report; import com.puzzle.toyrobot.model.Robot; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PlaceCommand extends Command { private final Logger log = LoggerFactory.getLogger(PlaceCommand.class); private String commandString; PlaceCommand(String commandString) { this.commandString = commandString; } @Override public void execute(Robot robot, Report report) { String placementArgs = StringUtils.substringAfter(commandString, CommandType.PLACE.name()); String[] args = StringUtils.split(placementArgs, ","); Integer initialX = Integer.parseInt(args[0].trim()); Integer initialY = Integer.parseInt(args[1].trim()); if (initialX &lt;= Robot.MAX_POSITION &amp;&amp; initialX &gt;= Robot.MIN_POSITION &amp;&amp; initialY &lt;= Robot.MAX_POSITION &amp;&amp; initialY &gt;= Robot.MIN_POSITION) { robot.setXPosition(initialX); robot.setYPosition(initialY); robot.setCardinalDirection(CardinalDirection.valueOf(args[2].trim())); log.debug("Robot is placed at " + robot.getCurrentStatus()); } else { log.debug("Place command ignored"); } } } </code></pre> <p><strong>ReportCommand.java</strong></p> <pre><code>package com.puzzle.toyrobot.model.command; import com.puzzle.toyrobot.model.Report; import com.puzzle.toyrobot.model.Robot; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ReportCommand extends Command { private final Logger log = LoggerFactory.getLogger(ReportCommand.class); @Override public void execute(Robot robot, Report report) { if (!robot.isOnTable()) { log.debug("Missing Robot"); report.addOutput("ROBOT MISSING"); } else { report.addOutput(robot.getCurrentStatus()); } } } </code></pre> <p><strong>RightCommand.java</strong></p> <pre><code>package com.puzzle.toyrobot.model.command; import com.puzzle.toyrobot.model.CardinalDirection; import com.puzzle.toyrobot.model.Report; import com.puzzle.toyrobot.model.Robot; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RightCommand extends Command { private final Logger log = LoggerFactory.getLogger(RightCommand.class); @Override public void execute(Robot robot, Report report) { if (!robot.isOnTable()) { log.debug("Right command ignored"); } else { switch (robot.getCardinalDirection()) { case NORTH: robot.setCardinalDirection(CardinalDirection.EAST); break; case SOUTH: robot.setCardinalDirection(CardinalDirection.WEST); break; case EAST: robot.setCardinalDirection(CardinalDirection.SOUTH); break; case WEST: robot.setCardinalDirection(CardinalDirection.NORTH); break; } log.debug("The robot is rotating 90 degree to " + robot.getCardinalDirection()); } } } </code></pre> <p><strong>pom.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.puzzle&lt;/groupId&gt; &lt;artifactId&gt;toy-robot&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;packaging&gt;jar&lt;/packaging&gt; &lt;name&gt;toy-robot&lt;/name&gt; &lt;description&gt;Toy Robot coding puzzle&lt;/description&gt; &lt;parent&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt; &lt;version&gt;2.0.3.RELEASE&lt;/version&gt; &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt; &lt;/parent&gt; &lt;properties&gt; &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt; &lt;project.reporting.outputEncoding&gt;UTF-8&lt;/project.reporting.outputEncoding&gt; &lt;java.version&gt;1.8&lt;/java.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.commons&lt;/groupId&gt; &lt;artifactId&gt;commons-lang3&lt;/artifactId&gt; &lt;version&gt;3.7&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p>and Finally a controller test </p> <pre><code>package com.puzzle.toyrobot.controller; import com.puzzle.toyrobot.model.Report; import com.puzzle.toyrobot.model.SimulationRound; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class RobotSimulationControllerTest { @Autowired private TestRestTemplate template; @Test public void simulationReportAsExpectedTest() { Report report = new Report(); report.addOutput("0,1,NORTH"); SimulationRound round = new SimulationRound(); round.addCommand("PLACE 0,0,NORTH"); round.addCommand("LEFT"); round.addCommand("RIGHT"); round.addCommand("MOVE"); round.addCommand("REPORT"); HttpEntity&lt;Object&gt; simulationRound = getHttpEntity(round); ResponseEntity&lt;Report&gt; resultAsset = template.postForEntity("/robot/simulation", simulationRound, Report.class); Assert.assertEquals(resultAsset.getBody(), report); } @Test public void missingRobotTest() { Report report = new Report(); report.addOutput("ROBOT MISSING"); SimulationRound round = new SimulationRound(); round.addCommand("MOVE"); round.addCommand("REPORT"); HttpEntity&lt;Object&gt; simulationRound = getHttpEntity(round); ResponseEntity&lt;Report&gt; resultAsset = template.postForEntity("/robot/simulation", simulationRound, Report.class); Assert.assertEquals(resultAsset.getBody(), report); } @Test public void ignoringWrongCommandTest() { Report report = new Report(); report.addOutput("0,0,WEST"); SimulationRound round = new SimulationRound(); round.addCommand("PLACE 0,0,WEST"); round.addCommand("MOVEEEE"); round.addCommand("REPORT"); HttpEntity&lt;Object&gt; simulationRound = getHttpEntity(round); ResponseEntity&lt;Report&gt; resultAsset = template.postForEntity("/robot/simulation", simulationRound, Report.class); Assert.assertEquals(resultAsset.getBody(), report); } @Test public void ignoringCommandThatCausesFailTest() { Report report = new Report(); report.addOutput("0,0,SOUTH"); SimulationRound round = new SimulationRound(); round.addCommand("PLACE 0,0,SOUTH"); round.addCommand("MOVE"); round.addCommand("REPORT"); HttpEntity&lt;Object&gt; simulationRound = getHttpEntity(round); ResponseEntity&lt;Report&gt; resultAsset = template.postForEntity("/robot/simulation", simulationRound, Report.class); Assert.assertEquals(resultAsset.getBody(), report); } @Test public void simulationRoundWithoutReportTest() { Report report = new Report(); SimulationRound round = new SimulationRound(); round.addCommand("PLACE 1,2,EAST"); round.addCommand("MOVE"); round.addCommand("MOVE"); round.addCommand("LEFT"); HttpEntity&lt;Object&gt; simulationRound = getHttpEntity(round); ResponseEntity&lt;Report&gt; resultAsset = template.postForEntity("/robot/simulation", simulationRound, Report.class); Assert.assertEquals(resultAsset.getBody(), report); } private HttpEntity&lt;Object&gt; getHttpEntity(Object body) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return new HttpEntity&lt;&gt;(body, headers); } } </code></pre> <p><strong>Notes on solution:</strong></p> <ul> <li>All commands will be ignored until a valid PLACE command.</li> <li>The robot can be re-PLACEd at any time.</li> <li>Any number of REPORT commands are allowed.</li> <li>The REST-API request body is a Simulation Round object that contains a list of commands.</li> <li>The REST-API response object is a Report object that contains a list of reports, which is the output of the REPORT command if any.</li> <li>Many Integration tests are added.</li> </ul>
[]
[ { "body": "<p>I didn't examine all the classes. Here is my (partial) analysis:</p>\n\n<h2>REST API</h2>\n\n<p>Your API consists of one call. This is clearly not what was intended by the question (they did state that they regard the design of the API as important...) </p>\n\n<p>First thing when designing a RE...
{ "AcceptedAnswerId": "197598", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-30T13:43:42.630", "Id": "197547", "Score": "1", "Tags": [ "java", "api", "rest", "spring" ], "Title": "Toy Robot coding puzzle with Java" }
197547
<p>I'm doing some recreational programming in C (after spending some time in C++, but professionally using only PHP/JavaScript).</p> <p>I wrote a UTF8 to UTF32 converter and just wanted to know if I made some obvious mistakes. (For example, is it a big no-no to <code>malloc</code> inside a function (because of possible memory leaks) – and if yes – how would you rather do it?)</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdint.h&gt; size_t utf8_strlen(uint8_t* text) { size_t i = 0; size_t num_chars = 0; while (text[i] != 0) { num_chars++; if ((text[i] &amp; 0b10000000) == 0) { // 1 byte code point, ASCII i += 1; } else if ((text[i] &amp; 0b11100000) == 0b11000000) { // 2 byte code point i += 2; } else if ((text[i] &amp; 0b11110000) == 0b11100000) { // 3 byte code point i += 3; } else { // 4 byte code point i += 4; } } return num_chars; } uint32_t* utf8_to_utf32(uint8_t* text) { size_t num_chars = utf8_strlen(text); uint32_t* c = malloc(sizeof(uint32_t) * num_chars); size_t i = 0; for (size_t n = 0; n &lt; num_chars; n++) { if ((text[i] &amp; 0b10000000) == 0) { // 1 byte code point, ASCII c[n] = (text[i] &amp; 0b01111111); i += 1; } else if ((text[i] &amp; 0b11100000) == 0b11000000) { // 2 byte code point c[n] = (text[i] &amp; 0b00011111) &lt;&lt; 6 | (text[i + 1] &amp; 0b00111111); i += 2; } else if ((text[i] &amp; 0b11110000) == 0b11100000) { // 3 byte code point c[n] = (text[i] &amp; 0b00001111) &lt;&lt; 12 | (text[i + 1] &amp; 0b00111111) &lt;&lt; 6 | (text[i + 2] &amp; 0b00111111); i += 3; } else { // 4 byte code point c[n] = (text[i] &amp; 0b00000111) &lt;&lt; 18 | (text[i + 1] &amp; 0b00111111) &lt;&lt; 12 | (text[i + 2] &amp; 0b00111111) &lt;&lt; 6 | (text[i + 3] &amp; 0b00111111); i += 4; } } return c; } </code></pre> <h2>Edit:</h2> <p>I've posted an updated version of the code to GitHub for anyone that is interested: <a href="https://github.com/s22h/cutils/blob/master/src/unicode.h" rel="nofollow noreferrer">https://github.com/s22h/cutils/blob/master/src/unicode.h</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-30T16:24:54.000", "Id": "380858", "Score": "1", "body": "I just realised that I'm missing the null terminator at the end of the UTF32 string." } ]
[ { "body": "<h1>Magic numbers</h1>\n\n<p>The implementation uses them a lot. While the bit-notation helps with indicating what is happening, it doesn't show the intention. What reads clearer:</p>\n\n<pre><code>if((text[i] &amp; 0b1000000) == 0)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>if((text[i] &amp; UTF8_ONE...
{ "AcceptedAnswerId": "197564", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-30T15:39:04.857", "Id": "197548", "Score": "8", "Tags": [ "c", "unicode", "utf-8", "c11" ], "Title": "Convert UTF8 string to UTF32 string in C" }
197548
<p>I am trying to implement a controlled job with java that initiates a new thread and provides a method to stop the execution of the thread without having to maintain the context.</p> <p>The interface looks like:</p> <pre><code>public interface ControlledJob { void stop(); void start(); boolean isJobRunning(); } </code></pre> <p>And the implementation looks like:</p> <pre><code>import com.google.common.base.Preconditions; public class SampleControlledJob implements ControlledJob { private static final String JOB_ALREADY_RUNNING_EXCEPTION_MESSAGE = "Job is already running."; private static final String JOB_ALREADY_STOPPED_EXCEPTION_MESSAGE = "Job is already stopped."; private final static SampleControlledJob SAMPLE_CONTROLLED_JOB = new SampleControlledJob(); private final Process process; private boolean isJobRunning = false; private boolean toContinue = false; private Thread thread; private String threadName; private SampleControlledJob() { this.process = new Process(); } public static ControlledJob getInstance() { return SAMPLE_CONTROLLED_JOB; } @Override public void start() { Preconditions.checkArgument(!this.isJobRunning, JOB_ALREADY_RUNNING_EXCEPTION_MESSAGE); this.threadName = "Thread:" + System.currentTimeMillis(); this.thread = new Thread(this.process, threadName); this.toContinue = true; this.isJobRunning = true; this.thread.start(); } @Override public void stop() { Preconditions.checkArgument(this.isJobRunning, JOB_ALREADY_STOPPED_EXCEPTION_MESSAGE); this.toContinue = false; } @Override public boolean isJobRunning() { return isJobRunning; } private class Process implements Runnable { public void run() { while (toContinue) { System.out.println(threadName + ", prints hello::" + System.currentTimeMillis()); } isJobRunning = false; } } } </code></pre> <p>The client can use the API like:</p> <pre><code>SampleControlledJob.getInstance().start(); SampleControlledJob.getInstance().stop(); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-10T12:21:57.727", "Id": "382223", "Score": "1", "body": "Smaller things: when multithreading like this, use volatile keyword. The Thread will be instantiated every time you call start (that might be okay). Thread name is based on times...
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-30T16:48:37.213", "Id": "197550", "Score": "1", "Tags": [ "java", "multithreading" ], "Title": "Implementation of a controlled job with Java" }
197550
<p>So I am working on writing a discord bot with <a href="https://github.com/Rapptz/discord.py" rel="noreferrer">discord.py</a>.</p> <p>I decided, rather than making a serie of if/elif, to map the messages to the functions in a dictionnary, like so:</p> <p><code>my_dict = { "!trigger": func }</code></p> <p>I then wanted to parse this dictionnary into an <code>async for</code> loop, but ran into some problems. To face those problems, I decided to write a <code>dict()</code> subclass, which I called <code>AsyncDict</code>. I just want to know if this is safe to work like this, or not? The main purpose of this little class is to avoid errors like "an async for loop needs an item that defines the function <code>__aiter__</code>" </p> <p><strong>AsyncDict class:</strong></p> <pre><code>class AsyncDict(dict): def __init__(self, *args, **kwargs): super(AsyncDict, self).__init__(*args, **kwargs) async def items(self): items = super().items() for item in items: yield item async def keys(self): keys = super().keys() for key in keys: yield key async def values(self): values = super().values() for value in values: yield </code></pre> <p>Once this is done, I just create my dictionary "as usual": <code>calls = AsyncDict([("!ping", ping)])</code></p> <p>Here is the relevant code in my <strong>main.py:</strong></p> <pre><code>import discord import asyncio async def ping(message): await client.send_message(message.channel, 'pong') calls = AsyncDict([("!ping", ping)]) @client.event async def on_message(message): async for k, v in calls.items(): if message.content.startswith(k): await v(message) </code></pre> <p>I just want to know if it's "safe" to work like this (cf.: AsyncDict)? I'm quite new to asynchronous development and I don't know if I'm missing something.</p>
[]
[ { "body": "<p>I saw your post on python-ideas. I think you have a misconception about native coroutines (i.e. <code>async def</code>). For example, this method in <code>AsyncDict</code>:</p>\n\n<pre><code>async def items(self):\n items = super().items()\n for item in items:\n yield item\n</code></p...
{ "AcceptedAnswerId": "202067", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-30T16:51:16.353", "Id": "197551", "Score": "5", "Tags": [ "python", "python-3.x", "hash-map", "async-await" ], "Title": "Asynchronous dictionary in Python" }
197551
<p>A few notes:</p> <ul> <li><p>There is currently no non exception-based way of knowing whether a key is present in the table or not. This is intentional for my use case.</p></li> <li><p>Unlike the lookup process, the baking process is definitely not appropriate for a real-time application. That's ok as it's meant to be run offline.</p></li> <li><p>Obviously, this is only appropriate for storing trivial types.</p></li> </ul> <p>What I'm particularly interested in is:</p> <ol> <li><p>I "think" I managed to pull this off without any Undefined Behavior, but I'd really want some other pairs of eyes checking for this, as I'm in dodgy territory on that front.</p></li> <li><p>As usual, any and all criticism on general code quality.</p></li> </ol> <p>Thanks!</p> <pre><code>#include &lt;cassert&gt; #include &lt;cstdint&gt; #include &lt;cstring&gt; #include &lt;functional&gt; #include &lt;type_traits&gt; #include &lt;unordered_set&gt; #include &lt;utility&gt; // The flat hash table is meant to be used when a hash table is baked once, // typically during a build process, and then used repeatadly. It can be // initialized by simply pointing it at a memory location containing the // raw data. // The table does NOT maintain ownership over the data. template &lt;typename ValT, typename HashT = std::uint64_t&gt; class flat_hash_table { static_assert(std::is_trivial_v&lt;ValT&gt;); static_assert(std::is_trivial_v&lt;HashT&gt;); public: flat_hash_table(char const* mem_loc, std::size_t mem_len) : mem_loc_(mem_loc) { if (mem_len &lt; sizeof(bucket_count_)) { throw std::invalid_argument("invalid flat hash data"); } char const* read_ptr = mem_loc; std::memcpy(&amp;bucket_count_, read_ptr, sizeof(bucket_count_)); read_ptr += sizeof(bucket_count_); if (mem_len &lt; sizeof(bucket_count_) + bucket_count_ * sizeof(bucket_t)) { throw std::invalid_argument("invalid flat hash data"); } if (std::uintptr_t(read_ptr) % alignof(bucket_t) != 0) { throw std::invalid_argument("flat hash data appears to be misaligned"); } static_assert(std::is_trivially_constructible_v&lt;bucket_t&gt;); buckets_ = new (const_cast&lt;char*&gt;(read_ptr)) bucket_t[bucket_count_]; for (std::uint32_t i = 0; i &lt; bucket_count_; ++i) { if (buckets_[i].offset + buckets_[i].count * sizeof(elem_t) &gt; mem_len) { throw std::invalid_argument("invalid flat hash data"); } auto bucket_loc = mem_loc_ + buckets_[i].offset; if (std::uintptr_t(bucket_loc) % alignof(elem_t) != 0) { throw std::invalid_argument("flat hash data appears to be misaligned"); } static_assert(std::is_trivially_constructible_v&lt;elem_t&gt;); new (const_cast&lt;char*&gt;(bucket_loc)) elem_t[buckets_[i].count]; } } // Lookup a value from the hash table, throws if the value is not // present. template &lt;typename KeyT&gt; ValT const&amp; at(KeyT const&amp; key) { HashT key_hash = std::hash&lt;KeyT&gt;{}(key); auto const&amp; bucket = buckets_[key_hash % bucket_count_]; if (bucket.count &gt; 0) { elem_t const* elem_table = reinterpret_cast&lt;elem_t const*&gt;(mem_loc_ + bucket.offset); auto end = elem_table + bucket.count; // Elements within a bucket are stored as a sorted vector, so we // can do a binary search. auto found = std::lower_bound( elem_table, end, key_hash, [](elem_t const&amp; lhs, HashT const&amp; rhs) { return lhs.key &lt; rhs; }); if (found != end &amp;&amp; found-&gt;key == key_hash) { return found-&gt;val; } } throw std::out_of_range("element not present in flat hash table"); } private: char const* mem_loc_; struct bucket_t { std::uint32_t count; std::uint32_t offset; }; // This cannot be a std::pair&lt;&gt; because the default constructor is not trivial struct elem_t { HashT key; ValT val; }; std::uint32_t bucket_count_; bucket_t const* buckets_; template &lt;typename K, typename V, typename H&gt; friend std::vector&lt;char&gt; bake_flat_hash_table( std::vector&lt;std::pair&lt;K, V&gt;&gt; const&amp;); }; // Bakes a dataset into a flat_has_table raw data chunk. template &lt;typename KeyT, typename ValT, typename HashT = std::uint64_t&gt; std::vector&lt;char&gt; bake_flat_hash_table( std::vector&lt;std::pair&lt;KeyT, ValT&gt;&gt; const&amp; data) { using table_t = flat_hash_table&lt;ValT, HashT&gt;; using elem_t = typename table_t::elem_t; using bucket_t = typename table_t::bucket_t; static_assert(std::is_trivial_v&lt;ValT&gt;); static_assert(std::is_trivial_v&lt;HashT&gt;); // TODO: Better process to determine optimal bucket count. std::uint32_t bucket_count = data.size() / 2 + 1; std::vector&lt;std::vector&lt;elem_t&gt;&gt; buckets(bucket_count); { // Keep track of seen hashes since we do not tolerate true collisions. std::unordered_set&lt;HashT&gt; hash_values_set; for (auto const&amp; d : data) { HashT hash_val = HashT(std::hash&lt;KeyT&gt;{}(d.first)); if (hash_values_set.count(hash_val) != 0) { throw std::runtime_error( "True hash collision in dataset, cannot make a flat hash table out " "of it."); } hash_values_set.insert(hash_val); buckets[hash_val % bucket_count].emplace_back(elem_t{hash_val, d.second}); } } std::size_t header_mem_size = 0; header_mem_size += sizeof(std::uint32_t); // for bucket_count header_mem_size += sizeof(bucket_t) * bucket_count; // bucket table // Make sure the actual value payloads is correctly aligned constexpr auto elem_align = alignof(elem_t); static_assert((elem_align &amp; (elem_align - 1)) == 0); header_mem_size = (header_mem_size + (elem_align - 1)) &amp; ~(elem_align - 1); auto mem_size = header_mem_size + sizeof(elem_t) * data.size(); std::vector&lt;char&gt; result(mem_size); char* header_w_ptr = result.data(); char* data_w_ptr = result.data() + header_mem_size; auto write = [&amp;](char*&amp; dst, auto const&amp; v) { assert(dst + sizeof(v) &lt;= result.data() + result.size()); std::memcpy(dst, &amp;v, sizeof(v)); dst += sizeof(v); }; write(header_w_ptr, bucket_count); for (auto&amp; b : buckets) { std::sort(b.begin(), b.end(), [](auto const&amp; lhs, auto const&amp; rhs) { return lhs.key &lt; rhs.key; }); auto offset = data_w_ptr - result.data(); bucket_t bucket_header{std::uint32_t(b.size()), std::uint32_t(offset)}; write(header_w_ptr, bucket_header); for (auto const&amp; e : b) { write(data_w_ptr, e); } } return result; } #include &lt;iostream&gt; #include &lt;string_view&gt; #include &lt;vector&gt; int main() { std::vector&lt;std::pair&lt;std::string, float&gt;&gt; raw_values = { {"hi", 12.0f}, {"yo", 10.0f}, {"sup", 3.0f}, }; std::vector&lt;char&gt; raw_data = bake_flat_hash_table(raw_values); flat_hash_table&lt;float&gt; values(raw_data.data(), raw_data.size()); std::cout &lt;&lt; values.at(std::string_view("yo")) &lt;&lt; "\n"; std::cout &lt;&lt; values.at(std::string_view("sup")) &lt;&lt; "\n"; std::cout &lt;&lt; values.at(std::string_view("hi")) &lt;&lt; "\n"; return 0; } </code></pre> <p>Obvious next steps / stuff I'm already aware of:</p> <ul> <li>Endianness handling</li> <li>Proper iterator-based lookup interface</li> <li>Better bucket counting</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-30T21:46:24.950", "Id": "380881", "Score": "0", "body": "Is internal layout of hashmap part of public interface? Code says yes, but I just wanted to be sure." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-...
[ { "body": "<p>I'm no expert, but it seems like the code doesn't invoke UB. It is already great, but there are some small issues here and there.</p>\n\n<h2>Missing header</h2>\n\n<p><code>std::sort()</code> is used in <code>bake_flat_hash_table()</code>, but <code>&lt;algorithm&gt;</code> is not added.</p>\n\n<h...
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-30T17:00:13.537", "Id": "197552", "Score": "3", "Tags": [ "c++", "memory-management", "hash-map", "c++17" ], "Title": "Pre-baked Hash table with a flat memory layout" }
197552
<p>This function <code>word_break(s, dictionary)</code> receives a string <code>s</code> and a set of all valid words <code>dictionary</code>, and must return all possible ways the string <code>s</code> can be split into valid words, if any. </p> <p>For example, a string <code>catsanddog</code> with dictionary <code>{'cat', 'cats', 'sand', 'and', 'dog'}</code> can be broken in two ways: <code>cats and dog</code> and <code>cat sand dog</code>.</p> <p>My solution to this recursively breaks the input string at various index (offset), and uses memoization as I realized we may be breaking at the same offset multiple times.</p> <p>Here is the full code along with a test case, in Python 2.x:</p> <pre><code>def memoize(fn): memo = {} def wrapped_fn(*args): if args not in memo: memo[args] = fn(*args) return memo[args] return wrapped_fn def word_break(s, dictionary): @memoize def _word_break(offset): if offset == len(s): return [] breaks_from_offset = [] if s[offset:] in dictionary: breaks_from_offset.append([s[offset:]]) for i in range(offset+1, len(s)): if s[offset:i] in dictionary: for break_from_i in _word_break(i): breaks_from_offset.append([s[offset:i]] + break_from_i) return breaks_from_offset return [' '.join(words) for words in _word_break(0)] # print word_break('catsanddog', {'cat', 'cats', 'sand', 'and', 'dog'}) # -&gt; [cat sand dog', 'cats and dog'] </code></pre> <p>Based on LeetCode question Word Break II: <a href="https://leetcode.com/problems/word-break-ii/description/" rel="nofollow noreferrer">https://leetcode.com/problems/word-break-ii/description/</a></p> <p>As this is an "interview" algorithm question, I would love feedback that keeps that setting in mind. That said, I also appreciate any feedback to help me write more production-ready Python code :) </p>
[]
[ { "body": "<p>Honestly it looks like you're doing this wrong. Currently you're splitting the word into \\$n^2\\$ words and checking if they are in the dictionary. Rather than doing this you can traverse a <a href=\"https://en.wikipedia.org/wiki/Trie\" rel=\"nofollow noreferrer\">Trie</a> and loop through the in...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-30T18:34:42.003", "Id": "197558", "Score": "2", "Tags": [ "python", "algorithm", "recursion", "memoization" ], "Title": "Determine all ways a string can be split into valid words, given a dictionary of all words" }
197558
<p>This is a very simple ball game in which we have to avoid projectiles falling from the sky. This is my second project and first game. Please review and tell where I can improve.</p> <pre><code>import time import random import pygame pygame.init() #colors black=(0,0,0) white=(255,255,255) red=(255,0,0) green=(0,255,0) blue=(0,0,255) darkViolet=(148,0,211) #display displayWidth=1024 displayHeight=600 display=pygame.display.set_mode((displayWidth, displayHeight)) pygame.display.set_caption('PHY') heart=pygame.image.load('heart.png') myfont=pygame.font.SysFont('Terminal', 18) clock=pygame.time.Clock() endTime=time.time() #physics x,y=displayWidth/2,displayHeight/2 ux, uy, ax, ay= 0, 0, 0, 0 # u means velocity, a means acceleration yp1, up1, ap = 0, 50, 50 #p for projectile xp1,yp1,up1,ap1=[],0,50,50 #projectile variables. xp1 list coz multiple projectiles uc, ac = 20, 5 # c stands for the amount of change on key press score, lives=0,3 touching=False running=True #misc projectile=pygame.Surface((10,20)) projectile.fill(darkViolet) #adding random locations for projectiles to spawn in for _ in range(20): xp1.append(random.randint(0,displayWidth)) while running: #taking dt to be a small value which will depend on the processing power startTime=time.time() t=startTime-endTime #changing the postions and velocities with time ux+=ax*t uy+=ay*t x+=ux*t y+=uy*t up1+=ap*t yp1+=up1*t endTime=time.time() #checking for collision of ball with boundaries if x&lt;0: x=0 ux=-ux/3 if x&gt;displayWidth: x=displayWidth ux=-ux/3 if y&lt;0: y=0 uy=-uy/3 if y&gt;displayHeight: y=displayHeight uy=-uy/3 for ev in pygame.event.get(): if ev.type == pygame.QUIT: running=False elif ev.type == pygame.KEYDOWN: #acts on pressing and not on holding key if ev.key == pygame.K_UP: ay-=ac uy-=uc if ev.key == pygame.K_DOWN: ay+=ac uy+=uc if ev.key == pygame.K_LEFT: ax-=ac ux-=uc if ev.key == pygame.K_RIGHT: ax+=ac ux+=uc elif ev.type == pygame.KEYUP: if ev.key == pygame.K_UP: ay=0 if ev.key == pygame.K_DOWN: ay=0 if ev.key == pygame.K_LEFT: ax=0 if ev.key == pygame.K_RIGHT: ax=0 #condition for when the projectile crosses the screen if yp1&gt;displayHeight: yp1=0 up1=3*up1/5 ap+=5 xp1=[] score+=1 for _ in range(20): xp1.append(random.randint(0,displayWidth)) #checking for collision between ball and projectile for g in range(20): if x&gt;xp1[g]-10 and x&lt;10+xp1[g] and y&gt;yp1-15 and y&lt;yp1+15: touching=True xp1[g]=1050 if touching: if lives&gt;1: lives-=1 touching=False else: running=False #displaying display.fill(black) for g in range(lives): #displaying the lives as hearts display.blit(heart, (950+g*25,25)) for g in range(20): #displaying the same projectile at 20 places display.blit(projectile, (xp1[g], yp1)) textDisp=myfont.render('SCORE: %s'%(score),False,white) pygame.draw.circle(display, red, (int(x),int(y)), 10, 0) #displaying the ball display.blit(textDisp,(950,50)) #displaying the score pygame.display.update() clock.tick(60) pygame.quit() quit() </code></pre>
[]
[ { "body": "<p>Follow standard identifier conventions. Variable are <code>lower_case</code>, class names should be <code>CamelCase</code>, and constants should be <code>UPPER_CASE</code>. With this in mind, your block of colours at the start should be altered:</p>\n\n<pre><code># Colours\nBLACK = (0, 0, 0)\nWH...
{ "AcceptedAnswerId": "197587", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-30T18:49:39.243", "Id": "197559", "Score": "2", "Tags": [ "python", "python-3.x", "pygame" ], "Title": "ball-game created in Python 3" }
197559
<p>This is a school project I've written. It works, but I feel it could be done better. </p> <p>The program generate an array of 1'000 random numbers, and searches for a number typed into console, and displays the index if found.</p> <pre><code>int inp, zuf, i, num, trig=0; const int amount = 1000; int arr[amount]; cout &lt;&lt; "Numbers" &lt;&lt; endl &lt;&lt; "======" &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; "Please type in a nuber between 1 and 1000: " &lt;&lt; endl; cin &gt;&gt; inp; srand(time(NULL)); for (int i = 1; i &lt; amount + 1; i++) { zuf = rand(); zuf = (zuf % amount) + 1; arr[i] = zuf; num = i; if (inp== arr[num] &amp;&amp; trig == 0) { cout &lt;&lt; "The number exists at the position: "; trig++; } if (inp== arr[num]) { cout &lt;&lt; num &lt;&lt; ", "; num++; trig++; } } if (trig == 0) cout &lt;&lt; "This number doesn't exist." &lt;&lt; endl; else cout &lt;&lt; "\b\b." &lt;&lt; endl; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-30T19:42:48.263", "Id": "380870", "Score": "0", "body": "Are you intentionally writing pre-C++11 code? This would change the nature of the feedback quite a lot." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-...
[ { "body": "<h2>Do not using <code>using namespace std</code></h2>\n\n<p>bringing in entire namespaces can be convenient, but in the long run, it's a really bad habit.</p>\n\n<p>You should explicitly use <code>std::cout</code> and the like instead. </p>\n\n<h2>Declare variables as close as possible to their firs...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-30T18:59:43.057", "Id": "197561", "Score": "6", "Tags": [ "c++", "homework" ], "Title": "Generate array with random numbers and search for an element in it" }
197561
<p>Its meant to password protect python scripts by using encryption It should use <code>os.urandom(40)</code>'s output in hex as the salt. The <a href="https://cryptography.io/en/latest/hazmat/primitives/key-derivation-functions/?highlight=kdf" rel="nofollow noreferrer">kdf (cryptography.io)</a> is using <a href="https://cryptography.io/en/latest/hazmat/primitives/key-derivation-functions/?highlight=Scrypt" rel="nofollow noreferrer">Scrypt (cryptography.io)</a> password input is using <code>getpass.getpass</code>. It's on my GitHub: <a href="https://github.com/OfficialNoob/Python-Script-Locker/tree/2ed5d8cd6ba250767b41356f1adb9d37733aa002" rel="nofollow noreferrer">Python Script Locker (GitHub)</a>, and is required to work with both Python 2 and 3.</p> <pre><code>#!/usr/bin/env python import sys def exitmsg(msg): print(msg) input("Press ENTER to exit the script") sys.exit() if sys.version_info&lt;(3,0,0): def input(string): return raw_input(string) import base64 import binascii import os import getpass try: from cryptography.fernet import Fernet except ImportError: exitmsg("cryptography not installed install it with pip install cryptography via cmd or powershell (On Windows)") from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.kdf.scrypt import Scrypt print("PyLock beta v1.0.3 https://github.com/OfficialNoob/Python-Script-Locker") salt = binascii.hexlify(os.urandom(40)) kdf = Scrypt(salt=salt,length=32,n=2**14,r=8,p=1,backend=default_backend()) loc = input("Script to use: ") try: fscript = open(loc) except IOError: exitmsg("Unable to read file") script = fscript.read() fscript.close print("Can be used to overwrite your script") sloc = input("Save as: ") nc = '''#!/usr/bin/env python #Made using PyLock https://github.com/OfficialNoob/Python-Script-Locker import sys def exitmsg(msg): print(msg) input("Press ENTER to exit") sys.exit() if sys.version_info&lt;(3,0,0): def input(string): return raw_input(string) import getpass import base64 try: from cryptography.fernet import Fernet except ImportError: exitmsg("cryptography not installed install it with pip install cryptography via cmd or powershell (On Windows)") from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.kdf.scrypt import Scrypt kdf = Scrypt(salt=%s,length=32,n=2**14,r=8,p=1,backend=default_backend()) try: exec(Fernet(base64.urlsafe_b64encode(kdf.derive(getpass.getpass("Password to use: ").encode()))).decrypt(%s)) except Exception as ex: if(type(ex).__name__ == "InvalidToken"): exitmsg("Wrong password (-:") print(ex)''' % (salt, Fernet(base64.urlsafe_b64encode(kdf.derive(getpass.getpass("Password to use: ").encode()))).encrypt(script.encode())) try: f = open(sloc,"w+") f.write(nc) except IOError: exitmsg("Unable to write to file") f.close exitmsg("Your file has been created") </code></pre>
[]
[ { "body": "<p>The good news is that as far as I can tell, the cryptography is correct (password-based key derivation function, random salt). The bad news is that your code is hard to read, and so it's hard to make sure that it's correct.</p>\n\n<p>Please read <a href=\"https://www.python.org/dev/peps/pep-0008/\...
{ "AcceptedAnswerId": "197616", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-30T19:13:20.833", "Id": "197563", "Score": "1", "Tags": [ "python", "security", "cryptography", "meta-programming" ], "Title": "Encryption scripts using the module cryptography" }
197563
<p>Here is a class I wrote to provide a user a way to have a callback function executed at some defined frequency:</p> <p><strong>Task.hpp</strong></p> <pre><code>#pragma once #include &lt;memory&gt; #include &lt;functional&gt; class Task { public: Task(const double&amp; _hertz, const std::function&lt;void()&gt;&amp; _callback); ~Task(); void SetCallback(const std::function&lt;void()&gt;&amp; _callback); void Start(); void Pause(); void Exit(); void SetFrequency(const double&amp; _hertz); bool IsRunning() const; unsigned long GetOverrunCount() const; private: struct Internal; std::unique_ptr&lt;Internal&gt; impl; }; </code></pre> <p><strong>Task.cpp</strong></p> <pre><code>#include "Task.hpp" // misc #include "Chrono.hpp" // std #include &lt;thread&gt; #include &lt;mutex&gt; #include &lt;atomic&gt; struct Task::Internal { public: Internal(const double&amp; _m_freq, const std::function&lt;void()&gt;&amp; _callback): m_frequency(_m_freq), m_callback(_callback) { } ~Internal() { Exit(); } void SetCallback(const std::function&lt;void()&gt;&amp; _callback) { std::lock_guard&lt;std::mutex&gt; _lock(m_thread_mutex); m_callback = _callback; } void SetFrequency(const double&amp; _hertz) { m_frequency = _hertz; } void Start() { std::lock_guard&lt;std::mutex&gt; _lock(m_thread_mutex); // Already have a thread if (m_thread != nullptr) { return; } m_thread = std::make_unique&lt;std::thread&gt;(&amp;Internal::Task, this); m_pause = false; m_run = true; } void Pause() { m_run = false; m_pause = true; } void Exit() { std::lock_guard&lt;std::mutex&gt; _lock(m_thread_mutex); // We don't have a thread if (m_thread == nullptr) { return; } m_run = false; m_exit = true; // wait for exit m_thread-&gt;join(); // Destory thread object m_thread.reset(nullptr); } bool IsRunning() const { return m_run; } unsigned long GetOverrunCount() const { return m_overrun_count; } protected: private: std::atomic&lt;double&gt; m_frequency; std::atomic&lt;bool&gt; m_exit{ false }; std::atomic&lt;bool&gt; m_pause{ true }; std::atomic&lt;bool&gt; m_run{ false }; std::atomic&lt;unsigned long&gt; m_overrun_count{ 0 }; std::unique_ptr&lt;std::thread&gt; m_thread{ nullptr }; std::function&lt;void()&gt; m_callback; std::mutex m_thread_mutex; void Task() { // run until told to m_exit while (m_exit == false) { // Calculate the period from freq long long periodInUs = (long long)((1.0 / m_frequency) * 1000.0 * 1000.0); // start time of the task auto start = ChronoHelper::GetTimeNow(); // we are not paused if (m_pause == false) { std::lock_guard&lt;std::mutex&gt; _lock(m_thread_mutex); // the callback has been set if (m_callback != nullptr) { m_callback(); } } // get the amount of time left needed to sleep TimeVar end = ChronoHelper::GetTimeNow(); long long executionTime = ChronoHelper::DurationInMicroSeconds(start, end); long long toSleep = periodInUs - executionTime; if (toSleep &gt; 0) { std::this_thread::sleep_for(std::chrono::microseconds(toSleep)); } else { m_overrun_count++; } } }; }; Task::Task(const double&amp; _m_freq, const std::function&lt;void()&gt;&amp; _callback): impl(new Internal(_m_freq, _callback)) { } Task::~Task() { } void Task::Start() { impl-&gt;Start(); } void Task::Pause() { impl-&gt;Pause(); } void Task::Exit() { impl-&gt;Exit(); } bool Task::IsRunning() const { return impl-&gt;IsRunning(); } void Task::SetFrequency(const double&amp; _hertz) { impl-&gt;SetFrequency(_hertz); } void Task::SetCallback(const std::function&lt;void()&gt;&amp; _callback) { impl-&gt;SetCallback(_callback); } unsigned long Task::GetOverrunCount() const { return impl-&gt;GetOverrunCount(); } </code></pre> <p>I made <code>std::thread</code> dynamically allocated because I did not like that I can't control when <code>std::thread</code> starts executing. This way, I limit the thread from running unnecessarily until the user calls <code>Start()</code>. It will, however, still be ticking when the user calls <code>Pause()</code>, which is a little jarring.</p> <p>I was also considering having this class maintain a list of callbacks rather than a single callback.</p>
[]
[ { "body": "<p>Really nice use of an opaque type! (though I personally think it's overkill in this particular instance, but that's a matter of opinion).</p>\n\n<blockquote>\n <p>I made std::thread dynamically allocated because I did not like that I can't control when std::thread starts executing.</p>\n</blockqu...
{ "AcceptedAnswerId": "197571", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-30T21:12:57.583", "Id": "197570", "Score": "1", "Tags": [ "c++", "multithreading", "callback" ], "Title": "Class that provides callback execution at a specified rate" }
197570
<p>I wrote a program that, given a string of text, converts it to Title Case based on certain criteria. I would mainly like to know how I could improve readability and expressiveness, make a more clear API, and improve the efficiency of the algorithms, but any other feedback would also be appreciated. Here is an excerpt of the requirements from </p> <p><a href="https://www.fluentcpp.com/2018/06/29/7-more-ways-to-get-better-at-c-this-summer-2018-edition/" rel="noreferrer">https://www.fluentcpp.com/2018/06/29/7-more-ways-to-get-better-at-c-this-summer-2018-edition/</a> : </p> <blockquote> <p>Step 1: Basic Title Case For each word in a sentence, make all of its letters lower case, except the first one that would be in upper case.</p> <p>There is a list of “exceptions” words that need to be entirely in lower case, including their first letter. This lists includes “at” and “to”, along with another dozen words. For the sake of this project let’s say that the list of exceptions is: a, an, the, at, by, for, in, of, on, to, and, as and or.</p> <p>Note that in all cases, the first word of the string must start with a capital letter.</p> <p>Step 2: Title Case with customizations Make the list of exceptions customizable: the library user can add new exceptions, replace the list with their own, or add words that should not be changed by the library.</p> <p>An additional requirement is that words in all caps should be left as is (“STL” must remain “STL”, and not be changed into “Stl”), but the library user should be able to opt-out of this feature.</p> </blockquote> <h2>TitleCase.h</h2> <pre><code>#pragma once #include &lt;algorithm&gt; #include &lt;string&gt; #include &lt;string_view&gt; #include &lt;vector&gt; class TitleCase { //title case will not be applied to these words std::vector&lt;std::string&gt; m_exceptions = { "a", "an", "the", "at", "by", "for", "in", "of", "on", "to", "and", "as", "or" }; //acronyms like "STL" will optionally be ignored when applying title case bool m_ignore_acronyms = true; void apply_title_case(std::string::iterator begin_word, std::string::iterator end_word); std::string_view get_word(std::string::iterator begin_word, std::string::iterator end_word); template&lt;typename Pred&gt; void apply_case_if_pred_met(std::string::iterator begin_word, std::string::iterator end_word, Pred pred) { if (pred(get_word(begin_word, end_word))) { apply_title_case(begin_word, end_word); } } template&lt;typename Pred&gt; void convert_impl(std::string&amp; text, Pred pred) { auto begin_word = text.begin(); auto end_word = std::find(begin_word, text.end(), ' '); if (end_word == text.end()) //check if there's only one word in string or string is empty { if (text.empty()) return; apply_case_if_pred_met(begin_word, end_word, pred); return; } while (end_word != text.end()) { apply_case_if_pred_met(begin_word, end_word, pred); begin_word = end_word + 1; end_word = std::find(begin_word, text.end(), ' '); } } public: TitleCase() = default; TitleCase(bool ignore_acronyms) : m_ignore_acronyms{ ignore_acronyms } {} TitleCase(const std::vector&lt;std::string&gt;&amp; exceptions, bool ignore_acronyms = true) : m_exceptions(exceptions), m_ignore_acronyms(ignore_acronyms) {} void convert(std::string&amp; text); std::string converted_copy(const std::string&amp; text); bool is_exception(std::string_view str); bool is_acronym(std::string_view word); void ignore_acronyms(bool b) { m_ignore_acronyms = b; } template&lt;typename T&gt; void add_exception(T&amp;&amp; exception) { m_exceptions.emplace_back(std::forward&lt;T&gt;(exception)); } template&lt;typename T&gt; void remove_exception(T&amp;&amp; exception) { m_exceptions.erase(std::remove(m_exceptions.begin(), m_exceptions.end(), std::forward&lt;T&gt;(exception)), m_exceptions.end()); } void replace_exceptions(const std::vector&lt;std::string&gt;&amp; exceptions) { m_exceptions = exceptions; } const auto&amp; exceptions() { return m_exceptions; } }; </code></pre> <h2>TitleCase.cpp</h2> <pre><code>#include "TitleCase.h" #include &lt;algorithm&gt; #include &lt;cctype&gt; void TitleCase::apply_title_case(std::string::iterator begin_word, std::string::iterator end_word) { *begin_word = std::toupper(*begin_word); std::for_each(++begin_word, end_word, [](char&amp; c) { c = std::tolower(c); }); } void TitleCase::convert(std::string &amp; text) { if (m_ignore_acronyms) { convert_impl(text, [this](std::string_view word) { return !is_exception(word) &amp;&amp; !is_acronym(word); }); } else { convert_impl(text, [this](std::string_view word) { return !is_exception(word); }); } } std::string TitleCase::converted_copy(const std::string&amp; text) { auto text_copy = text; convert(text_copy); return text_copy; } bool TitleCase::is_exception(std::string_view word) { return std::find(m_exceptions.begin(), m_exceptions.end(), word) != m_exceptions.end(); } bool TitleCase::is_acronym(std::string_view word) { return std::all_of(word.begin(), word.end(), [](char c) { return std::isupper(c); }); } std::string_view TitleCase::get_word(std::string::iterator begin_word, std::string::iterator end_word) { const char* begin_word_ptr = &amp;(*begin_word); std::string_view::size_type word_size = std::distance(begin_word, end_word); auto word = std::string_view{ begin_word_ptr, word_size }; return word; } </code></pre>
[]
[ { "body": "<p>First, call it “English Title Case” so it is clear that it is hard-coded for this rule set. A function named <code>TitleCase</code> ought to use the current locale and/or have parameters specifying the language and culture.</p>\n\n<pre><code>void convert(std::string&amp; text);\n</code></pre>\n\n...
{ "AcceptedAnswerId": "197577", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-30T21:58:27.527", "Id": "197572", "Score": "10", "Tags": [ "c++", "strings" ], "Title": "Title Case Converter" }
197572
<p>I'm writing a simple wrapper for <code>std::unique_ptr</code>, which copies the pointed object when copied.</p> <p>Unlike <a href="https://codereview.stackexchange.com/questions/103744/deepptr-a-deep-copying-unique-ptr-wrapper-in-c">this wrapper</a>, it properly copies derived classes if <code>unique_ptr</code> points to a base class.</p> <p>Also it supports a feature similar to <code>std::visit</code>, which is described below.</p> <p><sub>(As noted by @Quuxplusone, deep-copying feature resembles that of <code>std::any</code>.)</sub></p> <hr> <p>Here's a short description of my class.<br> <strong>(The implementation is at the bottom of the question.)</strong></p> <ul> <li>It supports conventional <code>operator*</code>, <code>operator-&gt;</code>, <code>T* get()</code>, and <code>operator bool</code>.</li> <li>It doesn't have <code>.reset()</code>, but <code>my_obj = {};</code> can be used instead.</li> <li>Can be copy constructed/assigned. When copied, copies the underlying object.</li> <li>Can't aquire ownership of an external pointer, and can't release ownership of stored pointer.</li> <li><p><code>std::make_unique</code>-esque construction: <code>DynStorage&lt;T&gt; my_obj = DynStorage&lt;T&gt;::make(…);</code>.<br> Can be written as <code>DynStorage&lt;T&gt; my_obj(…);</code> if argument list is not empty.<br> Example usage:</p> <pre><code>auto x = DynStorage&lt;int&gt;::make(42); std::cout &lt;&lt; x.get() &lt;&lt; '\n'; // Prints 42 </code></pre></li> <li><p><code>DynStorage&lt;Derived&gt;</code> <em>can't</em> be converted to <code>DynStorage&lt;Base&gt;</code> (to simplify the implementation).<br> The only way to make a <code>DynStorage&lt;Base&gt;</code> that points to a derived class is to use <code>DynStorage&lt;Base&gt; my_obj = DynStorage&lt;Base&gt;::make&lt;Derived&gt;(…);</code></p></li> <li><code>const DynStorage&lt;T&gt;</code> doesn't allow you to modify the pointed object (unlike <code>unique_ptr</code>).</li> <li>Pointers to arrays aren't supported.</li> <li><p>Supports a feature similar to <code>std::visit</code>, but you have to specify every possible visitor function in advance in an (optional) template parameter of <code>DynStorage</code>:</p> <pre><code>// Assume we have some classes: struct A {virtual ~A() {}}; struct B : A {}; // Some overloaded (or template) function: void foo(A) {std::cout &lt;&lt; "foo(A)\n";} void foo(B) {std::cout &lt;&lt; "foo(B)\n";} // And we want to call a correct overload on a pointed object: int main() { auto x = DynStorage&lt;A&gt;::make(); // Makes an instance of A auto y = DynStorage&lt;A&gt;::make&lt;B&gt;(); // Makes an instance of B foo(*x); // Prints foo(A) foo(*y); // Prints foo(A), but we want foo(B) } // Here is how we do that: template &lt;typename BaseT&gt; struct MyFuncsBase : DynamicStorage::func_base&lt;BaseT&gt; { virtual void call_foo(BaseT *) = 0; using Base = MyFuncsBase; }; template &lt;typename BaseT, typename DerivedT&gt; struct MyFuncs : MyFuncsBase&lt;BaseT&gt; { void call_foo(BaseT *base) override { foo(*DynamicStorage::derived&lt;DerivedT&gt;(base)); } }; int main() { auto x = DynStorage&lt;A,MyFuncs&gt;::make(); auto y = DynStorage&lt;A,MyFuncs&gt;::make&lt;B&gt;(); x.functions().call_foo(x.get()); // prints foo(A) y.functions().call_foo(y.get()); // prints foo(B) } </code></pre></li> </ul> <hr> <h3>The implementation</h3> <p><strong><code>dynamic_storage.h</code></strong></p> <pre><code>#ifndef DYN_STORAGE_H_INCLUDED #define DYN_STORAGE_H_INCLUDED #include &lt;memory&gt; #include &lt;type_traits&gt; #include &lt;utility&gt; namespace DynamicStorage { namespace impl { // Type trait to check if A is static_cast'able to B. template &lt;typename A, typename B, typename = void&gt; struct can_static_cast_impl : std::false_type {}; template &lt;typename A, typename B&gt; struct can_static_cast_impl&lt;A, B, std::void_t&lt;decltype(static_cast&lt;B&gt;(std::declval&lt;A&gt;()))&gt;&gt; : std::true_type {}; template &lt;typename A, typename B&gt; inline constexpr bool can_static_cast_v = can_static_cast_impl&lt;A,B&gt;::value; // Type trait to check if A is dynamic_cast'able to B. template &lt;typename A, typename B, typename = void&gt; struct can_dynamic_cast_impl : std::false_type {}; template &lt;typename A, typename B&gt; struct can_dynamic_cast_impl&lt;A, B, std::void_t&lt;decltype(dynamic_cast&lt;B&gt;(std::declval&lt;A&gt;()))&gt;&gt; : std::true_type {}; template &lt;typename A, typename B&gt; inline constexpr bool can_dynamic_cast_v = can_dynamic_cast_impl&lt;A,B&gt;::value; template &lt;typename A, typename B&gt; inline constexpr bool can_static_or_dynamic_cast_v = can_static_cast_v&lt;A,B&gt; || can_dynamic_cast_v&lt;A,B&gt;; template &lt;typename T&gt; T *get_instance() { static T ret; return &amp;ret; } } // Downcasts a pointer. Attempts to use static_cast, falls back // to dynamic_cast. If none of them work, fails with a static_assert. template &lt;typename Derived, typename Base&gt; Derived *derived(Base *ptr) { static_assert(impl::can_static_or_dynamic_cast_v&lt;Base*, Derived*&gt;, "Pointer to derived can't be obtained from pointer to base."); if constexpr (impl::can_static_cast_v&lt;Base*, Derived*&gt;) return static_cast&lt;Derived *&gt;(ptr); // This doesn't work if base is virtual. else return dynamic_cast&lt;Derived *&gt;(ptr); } template &lt;typename B&gt; struct func_base { using Base = func_base; virtual std::unique_ptr&lt;B&gt; copy_(const B *) = 0; }; template &lt;typename B, typename D&gt; struct default_func_impl : func_base&lt;B&gt; {}; template &lt; typename T, template &lt;typename,typename&gt; typename Functions = default_func_impl &gt; class DynStorage { static_assert(!std::is_const_v&lt;T&gt;, "Template parameter can't be const."); static_assert(!std::is_array_v&lt;T&gt;, "Template parameter can't be an array."); template &lt;typename D&gt; struct Implementation : Functions&lt;T,D&gt; { static_assert(impl::can_static_or_dynamic_cast_v&lt;T*, D*&gt;, "Pointer to derived can't be obtained from pointer to base."); std::unique_ptr&lt;T&gt; copy_(const T *ptr) override { return ptr ? std::make_unique&lt;D&gt;(*derived&lt;const D&gt;(ptr)) : std::unique_ptr&lt;T&gt;(); } }; using Pointer = std::unique_ptr&lt;T&gt;; using FuncBase = typename Implementation&lt;T&gt;::Base; FuncBase *funcs = impl::get_instance&lt;Implementation&lt;T&gt;&gt;(); Pointer ptr; public: // Makes a null pointer. DynStorage() noexcept {} // Constructs an object of type T from a parameter pack. template &lt;typename ...P, typename = std::void_t&lt;decltype(T(std::declval&lt;P&gt;()...))&gt;&gt; DynStorage(P &amp;&amp;... p) : ptr(std::make_unique&lt;T&gt;(std::forward&lt;P&gt;(p)...)) {} DynStorage(const DynStorage &amp;other) : funcs(other.funcs), ptr(funcs-&gt;copy_(other.ptr.get())) {} DynStorage(DynStorage &amp;&amp;other) noexcept : funcs(other.funcs), ptr(std::move(other.ptr)) {} DynStorage &amp;operator=(const DynStorage &amp;other) { ptr = other.funcs-&gt;copy_(other.ptr.get()); funcs = other.funcs; return *this; } DynStorage &amp;operator=(DynStorage &amp;&amp;other) noexcept { ptr = std::move(other.ptr); funcs = other.funcs; return *this; } // Constructs an object of type T (by default) // or a derived type from a parameter pack. template &lt;typename D = T, typename ...P, typename = std::void_t&lt;decltype(D(std::declval&lt;P&gt;()...))&gt;&gt; [[nodiscard]] static DynStorage make(P &amp;&amp;... p) { static_assert(!std::is_const_v&lt;D&gt;, "Template parameter can't be const."); static_assert(!std::is_array_v&lt;D&gt;, "Template parameter can't be an array."); static_assert(std::is_same_v&lt;D,T&gt; || std::has_virtual_destructor_v&lt;T&gt;, "Base has to have a virtual destructor."); DynStorage ret; ret.ptr = std::make_unique&lt;D&gt;(std::forward&lt;P&gt;(p)...); ret.funcs = impl::get_instance&lt;Implementation&lt;D&gt;&gt;(); return ret; } [[nodiscard]] explicit operator bool() const {return bool(ptr);} [[nodiscard]] T *get() {return ptr.get();} [[nodiscard]] const T *get() const {return ptr.get();} [[nodiscard]] T &amp;operator*() {return *ptr;} [[nodiscard]] const T &amp;operator*() const {return *ptr;} [[nodiscard]] T *operator-&gt;() {return *ptr;} [[nodiscard]] const T *operator-&gt;() const {return *ptr;} FuncBase &amp;functions() const {return *funcs;} }; } using DynamicStorage::DynStorage; #endif </code></pre> <hr> <p>Some thoughts:</p> <ul> <li>It seems to work, but I'm not sure if I handle all possible exceptions correctly.</li> <li>I don't like the visiting syntax (especially visitor definitions), but I'm not sure how to improve it.</li> <li>It seems that copying (and visiting) could be optimized a bit by using function pointers instead of virtual functions, but I'm not sure how to do it elegantly.</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-01T00:03:04.270", "Id": "380900", "Score": "0", "body": "⟪It seems to work, but I'm not sure if I handle all possible exceptions correctly.⟫ Try multiple base classes and virtual base classes. Try non-public base classes, and multipl...
[ { "body": "<p>That's really neat! I really like the idea of provoking the on-demand instantiation of the polymorphic dispatcher by passing it as a template template parameter.</p>\n\n<p>That being said, I agree with you that the dispatching syntax can be improved quite a bit. </p>\n\n<pre><code>x.functions().ca...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-30T23:28:52.770", "Id": "197579", "Score": "2", "Tags": [ "c++", "memory-management", "c++17" ], "Title": "Deep-copyable unique_ptr wrapper with std::visit-like feature" }
197579
<p>I wrote an algorithm that solves this problem but I would love to get some feedback on it (especially since I'm not so confident in my Big \$O\$ skills).</p> <p>Do you think this is a good quality algorithm? Is it efficient? What would be your impression if you were an interviewer? I really want to improve as a programmer so any help is appreciated!</p> <pre><code>def lengthOfLongestSubstring(self, word): longest =0 currentLength = 0 if(len(word) &gt; 0): currentLength = 1 longest = 1 dict = {word[0] : 0} i = 1 while i &lt; len(word): if (dict.has_key(word[i])): i = dict[word[i]]+1 dict.clear() if (longest &lt; currentLength): longest= currentLength currentLength = 0 else: dict[word[i]] = i currentLength = currentLength + 1 i = i + 1 if (longest &lt; currentLength): longest= currentLength return longest </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-01T08:14:10.620", "Id": "380927", "Score": "0", "body": "Welcome to Code Review! What Python version is this written for?" } ]
[ { "body": "<p>The algorithmic complexity of your solution is \\$O(N*C)\\$ where \\$N\\$ is the number of characters in the string and \\$C\\$ is the size of the alphabet. Assuming lowercase ASCII characters, that's a linear algorithm and will probably be good enough for most things. That being said, it is possi...
{ "AcceptedAnswerId": "197594", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-01T07:11:47.050", "Id": "197589", "Score": "10", "Tags": [ "python", "strings", "programming-challenge", "python-2.x" ], "Title": "Given a string, find the length of the longest substring without repeating characters" }
197589
<p>I have a table with OHLCV values stored per symbol and I am trying to compute various technical indicators for the same. I am a newbie to Python and this type of application in general.</p> <p>There are 2 types of indicators from what I have worked on so far:</p> <ol> <li>The indicators that only require last N values to get an accurate result such as simple moving average</li> <li>The indicators that require all the values to get an accurate result such as exponential moving average</li> </ol> <p>I want to compute indicators on the symbols only if N values are present. For example a 20 period SMA has a valid value only if you have 20 values for that asset. Here's my attempt which is a lot of spaghetti code in my opinion. How do I structure this to make it better. Thanks</p> <pre><code>def refresh_indicators(table_name, indicator_key): """Compute indicators from the table""" hmset = {} #Connect to the database specified by file path with sqlite3.connect(file_path_15m) as conn: #Loop through each asset's symbol and internal id for 999 items for symbol, internal_id in zip(redis_connection.zrange('e3:symbols', 0, 999), redis_connection.zrange('e3:ids', 0, 999)): #Convert string integer id to integer id internal_id = int(internal_id) s = io.StringIO() #Fetch h,l,c for the current symbol using its internal id cur = conn.execute('select h,l,c from {} where symbol = ? order by ts'.format(table_name), (internal_id,)) #Convert the cursor into a structured np array ohlc = np.array(list(cur), dtype=dtype) h,l,c = ohlc['h'], ohlc['l'], ohlc['c'] #Add a check to exclude any symbol with nan values for its h,l,c missing = np.isnan(h).all() or np.isnan(l).all() or np.isnan(c).all() #This dict will store all the indicators for the current symbol indicators = {} if not missing: #Take the last 10 close values and compute the 10 period SMA if the current symbol has atleast 10 values indicators['sma10'] = func.SMA(c[-10:], 10)[-1] if len(c) &gt;= 10 else None #Take the last 20 close values and compute the 20 period SMA if the current symbol has atleast 20 values indicators['sma20'] = func.SMA(c[-20:], 20)[-1] if len(c) &gt;= 20 else None indicators['sma50'] = func.SMA(c[-50:], 50)[-1] if len(c) &gt;= 50 else None indicators['sma100'] = func.SMA(c[-100:], 100)[-1] if len(c) &gt;= 100 else None indicators['sma200'] = func.SMA(c[-200:], 200)[-1] if len(c) &gt;= 200 else None upper, middle, lower = func.BBANDS(c[-20:], 20, 2) indicators['lower'] = lower[-1] if len(lower) &gt;=20 else None indicators['middle'] = middle[-1] if len(middle) &gt;=20 else None indicators['upper'] = upper[-1] if len(upper) &gt;=20 else None indicators['trima'] = func.TRIMA(c[-20:], 20)[-1] if len(c) &gt;= 20 else None indicators['wma'] = func.WMA(c[-10:], 10)[-1] if len(c) &gt;= 10 else None aroonup, aroondown = func.AROON(h[-15:], l[-15:], 14) indicators['aroonup'] = aroonup[-1] if len(aroonup) &gt;= 15 else None indicators['aroondown'] = aroondown[-1] if len(aroondown) &gt;= 15 else None indicators['aroonosc'] = func.AROONOSC(h[-15:], l[-15:], 14)[-1] if len(h) &gt;= 15 and len(l) &gt;= 15 else None indicators['cci'] = func.CCI(h[-14:], l[-14:], c[-14:], 14)[-1] if len(h) &gt;= 14 and len(l) &gt;= 14 and len(c) &gt;=14 else None indicators['mom'] = func.MOM(c[-15:], 14)[-1] if len(c) &gt;= 14 else None indicators['roc'] = func.ROC(c[-11:], 10)[-1] if len(c) &gt;= 10 else None indicators['rocr'] = func.ROCR100(c[-11:], 10)[-1] if len(c) &gt;= 10 else None indicators['ultosc'] = func.ULTOSC(h[-29:], l[-29:], c[-29:], 7, 14, 28)[-1] if len(h) &gt;= 29 and len(l) &gt;= 29 and len(c) &gt;= 29 else None indicators['willr'] = func.WILLR(h[-14:], l[-14:], c[-14:], 14)[-1] if len(h) &gt;= 14 and len(l) &gt;= 14 and len(c) &gt;= 14 else None indicators['ema9'] = func.EMA(c, 9)[-1] if len(c) &gt;= 9 else None indicators['ema10'] = func.EMA(c, 10)[-1] if len(c) &gt;= 10 else None indicators['ema20'] = func.EMA(c, 20)[-1] if len(c) &gt;= 20 else None indicators['ema50'] = func.EMA(c, 50)[-1] if len(c) &gt;= 50 else None indicators['ema100'] = func.EMA(c, 100)[-1] if len(c) &gt;= 100 else None indicators['ema200'] = func.EMA(c, 200)[-1] if len(c) &gt;= 200 else None #minimum length needed 2 * period - 1 indicators['dema'] = func.DEMA(c, 9)[-1] if len(c) &gt;= 17 else None #minimum length needed 3 * period - 2 indicators['tema'] = func.TEMA(c, 9)[-1] if len(c) &gt;= 25 else None indicators['sar'] = func.SAR(h, l, 0.02, 0.2)[-1] indicators['kama'] = func.KAMA(c, 20)[-1] if len(c) &gt;= 21 else None #minimum length needed 2 * period indicators['adx'] = func.ADX(h, l, c, 14)[-1] if len(h) &gt;= 28 else None indicators['apo'] = func.APO(c, 10, 20, 1)[-1] if len(c) &gt;= 20 else None #Take all the values and compute 14 period RSI if the current symbol has atleast 15 values indicators['rsi'] = func.RSI(c, 14)[-1] if len(c) &gt;= 15 else None #Round all the computations to 8 digits indicators = {k:round(v,8) for k,v in indicators.items() if v is not None} #Convert the indicators from dict to csv format csv_writer = csv.DictWriter(s, fieldnames = fields, delimiter=',', lineterminator=':') csv_writer.writerow(indicators) hmset[symbol] = s.getvalue() return redis_connection.hmset(indicator_key, hmset) if hmset else None </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-01T11:51:27.237", "Id": "380937", "Score": "2", "body": "You can use a lamba to *hide* the condition, and add the required length parameter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-01T11:53:31.940",...
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-01T08:35:23.013", "Id": "197591", "Score": "1", "Tags": [ "python", "beginner", "python-3.x", "design-patterns" ], "Title": "Design code to compute technical indicators" }
197591
<p>I'm trying to learn Functional Programming and I picked <a href="https://www.erlang.org/" rel="nofollow noreferrer">Erlang</a> because I will have to use it eventually. In the meantime, I'm trying to build a simple lexer to stumble upon problems and solve them along the way.</p> <p>I'm aware that Erlang has <a href="http://erlang.org/doc/man/leex.html" rel="nofollow noreferrer">leex</a> and <a href="http://erlang.org/doc/man/yecc.html" rel="nofollow noreferrer">yeec</a> but this code is just for illustration purposes and teach me the "FP way".</p> <p>So I would appreciate if someone would give a cursory glance at my initial attempt and tell me their suggestions.</p> <p>The code below is a simple tokenizer that splits expressions in the form "<code>&lt;number&gt; + &lt;number&gt;</code>" into a list of tokens. The general direction I took to solve this problem is as follows:</p> <p>The <code>tokenize/2</code> funtion is called recursively on a successively shrinking portion of text. When the text is empty, it returns the <em>lexed</em> tokens.</p> <p>The <code>tokenize/2</code> function first builds a list of functions, each of which, when applied to a portion of text, returns an <code>{ok, {Type, Token}, Text}</code> tuple representing the outcome of the match, the token and the remaining, non matched, portion of the input string.</p> <p>The <code>tokenize/2</code> function then maps the list of functions, with the expectations that, at each stage, only one match will occur. A <code>HasMatched</code> predicate is built to extract the single match from the list, if any. If a match has indeed been found, the recursive call is made to the function, with arguments being the remaining potion of the text and the new token appended to the list of resulting tokens.</p> <pre><code>-module(tokenizer). -export([tokenize/1]). -include_lib("eunit/include/eunit.hrl"). % tokenize an input string tokenize(String) -&gt; tokenize_ignore_ws(String). tokenize_ignore_ws(String) -&gt; {R, Tokens} = tokenize(String, []), {R, lists:filter( fun ({ws, _}) -&gt; false ; (_) -&gt; true end , Tokens )} . tokenize([], Tokens) -&gt; {ok, Tokens}; tokenize(String, Tokens) -&gt; Patterns = [ fun(S) -&gt; match(number, "[0-9]+", S) end, fun(S) -&gt; match(op, "\\+", S) end, fun(S) -&gt; match(ws, "\\s+", S) end ], Matches = lists:map(fun(P) -&gt; P(String) end, Patterns), HasMatched = fun({error, _, _}) -&gt; false; (_) -&gt; true end, Match = lists_single_or_default(HasMatched, Matches), case Match of {ok, Token, Text} -&gt; tokenize(Text, Tokens ++ [Token]); null -&gt; {error, Tokens} end . % The match/3 function applies the specified Regex to the input String. % If the match is successful, the function returns the tuple: % {ok, {Type, Token}, Text} where % - Token is the matched portion of the input String and % - Text is the remaining portion of the input String. % % If the match fails, the function returns the tuple: % {error, null, String} % match(Type, Regex, String) -&gt; case re:run(String, Regex, [anchored]) of {match, Captures} -&gt; {0, Length } = lists:last(Captures), Token = string:left(String, Length), Text = string:substr(String, Length + 1), {ok, {Type, Token}, Text} ; nomatch -&gt; {error, null, String} end . %% Lists Helper Functions lists_single(Pred, L) -&gt; case lists_single_or_default(Pred, L) of null -&gt; error; X -&gt; X end . lists_single_or_default(Pred, L) -&gt; R = lists:filter(Pred, L), case length(R) of 0 -&gt; null; 1 -&gt; lists:nth(1, R); _ -&gt; error end . % EUnit tokenize_number_test() -&gt; {ok, [{Type, Token}]} = tokenize("123"), ?assert(Type =:= number), ?assert(Token =:= "123") . tokenize_op_plus_test() -&gt; {ok, [{Type, Token}]} = tokenize("+"), ?assert(Type =:= op), ?assert(Token =:= "+") . tokenize_empty_expression_test() -&gt; {ok, []} = tokenize("") . tokenize_expression_test() -&gt; {ok, Tokens} = tokenize("123+456"), [ {number, "123"}, {op, "+"}, {number, "456"} ] = Tokens </code></pre> <p>For instance, in the code above, I felt the need to declare a <code>lists_single_or_default/2</code> function. That's because I'm coming from a C# background. Is there some proper FP way to make the calling code more maintainable/readable with an alternative way?</p> <p>Another thing I'm interested about is to add <code>{Row, Column}</code> information to each token so as to give more meaningful error messages while tokenizing and, eventually, while parsing later on. For this, I think I will need to carry this information in the <code>{Type, Token, {Row, Column}}</code> <em>tuple</em> that represents a token. But I feel that adding more and more <em>state</em> to the Token will make the code more and more difficult to read and maintain.</p> <p>I'm aware that FP makes extensive use of recursion. For instance, the canonical way to implement the Fibbonacci suite is as follows:</p> <pre><code>fac(0) -&gt; 1; fac(1) -&gt; 1; fac(N) -&gt; N * fac(N - 1). </code></pre> <p>However, I have searched about potential for <em>stack overflows</em> while running recursive functions and I found that most functional programming languages make use of <em>Tail Call Optimization</em> in order to reuse the last stack frame while possible.</p> <p>It seems, unfortunately, that the canonical implementation of the Fibonaci suite shown above does not lend itself to being optimized that way. Is there a way to inspect the stack in Erlang and, in the context of my <code>tokenize/2</code> method, is is possible to use another algorithm that does not involve recursion ? Is there a way to adapt my algorithm so that is lends itself to being optimized ?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-01T10:34:39.273", "Id": "197592", "Score": "2", "Tags": [ "parsing", "functional-programming", "reinventing-the-wheel", "erlang" ], "Title": "A simple tokenizer in Erlang" }
197592
<p>This is a followup to a previous <a href="https://codereview.stackexchange.com/q/196628/146901">question</a> of mine on same subject.</p> <h3>Context</h3> <p>I want to have a tool that allows to simulate as much as possible a C++ standard container for a multidimensional contiguous array whose sizes are only known at run time. That immediately means that <code>std::arrays</code> are off (compile time sizes), as are vectors of vectors (not contiguous data). That also means that the common solution multi_array(i, j, k) is also off because of no natural iterators and direct members.</p> <p>Previous review have shown that is is impossible to build conformant containers and iterators over <em>views</em> of data (Refs: <a href="http://www.gotw.ca/publications/mill09.htm" rel="nofollow noreferrer">When Is a Container Not a Container?</a> and <a href="http://ericniebler.com/2015/01/28/to-be-or-not-to-be-an-iterator/" rel="nofollow noreferrer">To Be or Not to Be (an Iterator)</a>), so I have followed the given advice and tried to follow the proxy pattern. I have also tried to better explain in comments how the different classes are supposed to be used.</p> <h3>Code:</h3> <pre><code>#pragma once #include &lt;type_traits&gt; #include &lt;algorithm&gt; #include &lt;exception&gt; #include &lt;stdexcept&gt; #include &lt;memory&gt; #include &lt;utility&gt; #include &lt;iterator&gt; #include &lt;array&gt; #include &lt;vector&gt; /******************************** This intends to provide a general use multi dimensional view over a 1-D array. Public API classes: template &lt;class T, int dims, class Allocator = allocator&lt;T&gt; &gt; class Array: public ArrayBase&lt;T, dims, typename allocator_traits&lt;Allocator&gt;::size_type, typename allocator_traits&lt;Allocator&gt;::difference_type&gt; This is a quasi container in the sense that it holds the internal array in a member vector. But it is only a proxy container because it pretends that its elements are Row objects Array can be initialized from a raw array along with its dimensions, and it will hold a copy of the original data. It supports copy/move/swap semantics from another Array or copy semantics from any ArrayBase template &lt;class T, int dims, class size_type = size_t, class difference_type = ptrdiff_t&gt; class View : public ArrayBase&lt;T, dims, size_type, difference_type&gt; { This a a View over an external raw array which is expected to have a lifetime at least as long as the view. It will also pretends that its elements are Row objects. View can be initialized from a raw array and its dimensions, and will only keep a raw pointer over the original array. It supports copy semantics from any ArrayBase. Views are swappable, but this only change where each view points to template &lt;class T, int dims, class size_type, class difference_type&gt; class Row : public ArrayBase&lt;T, dims, size_type, difference_type&gt; This class represents a subarray of an Array, a View or another Row. It can only be created as an element of its parent. Rows can be copied, or moved from any ArrayBase. Rows are swappable. Operator &amp; on a row returns an iterator. template &lt;class T, int dims, class size_type, class difference_type&gt; class ArrayBase: ElementAccessor&lt;T, size_type, difference_type, size_type, dims&gt; ArrayBase is the base class of Array, View and ArrayBase. It contains all the logic of element access and iteration. Its iterators pretend to be random access iterators, but are only proxy iterators. That is quite enough for for loops with container syntax, and iterator arithmetics, but usage with standard algorithms (sort, shuffle, etc.) cannot be guaranteed template &lt;class T, class Allocator = std::allocator&lt;T&gt; &gt; class ArrayBuilder; This is only a utility class that knows how to build Array of View objects. It can save some boiler plate template declaration by declaring the types once at builder initialization, mainly when using not default allocators, size_type or difference_type. ********************************/ namespace DynArray { using std::allocator; using std::allocator_traits; //Forward declarations template &lt;class T, int dims, class size_type, class difference_type, bool cnst = false, bool rev=false&gt; class Iterator; template &lt;class T, int dims, class size_type, class difference_type&gt; class Row; namespace { /* private utility class to allow specialization of element access through operator[] or operator * */ template &lt;class T, class size_type, class difference_type, class index_type, int dims&gt; class ElementAccessor { protected: Row&lt;T, dims - 1, size_type, difference_type&gt; getElt(T* arr, size_type *sizes, size_type rowsize, index_type i) { Row&lt;T, dims - 1, size_type, difference_type&gt; child( arr + rowsize * i, sizes + 1, rowsize / sizes[1]); return child; } const Row&lt;T, dims - 1, size_type, difference_type&gt; getConstElt(T* arr, size_type *sizes, size_type rowsize, index_type i) { Row&lt;T, dims - 1, size_type, difference_type&gt; child( arr + rowsize * i, sizes + 1, rowsize / sizes[1]); return child; } }; // specialization for dims == 1: elements are actual T template &lt;class T, class size_type, class difference_type, class index_type&gt; class ElementAccessor&lt;T, size_type, difference_type, index_type, 1&gt; { protected: T&amp; getElt(T* arr, size_type *sizes, size_type rowsize, index_type i) { return arr[i]; } const T&amp; getConstElt(T* arr, size_type *sizes, size_type rowsize, index_type i) { return arr[i]; } }; } // Base: contains the data and types and manages access to elements // and sub arrays template &lt;class T, int dims, class size_type, class difference_type&gt; class ArrayBase: ElementAccessor&lt;T, size_type, difference_type, size_type, dims&gt; { public: using iterator = typename Iterator&lt;T, dims, size_type, difference_type, 0, 0&gt;; using const_iterator = typename Iterator&lt;T, dims, size_type, difference_type, 1, 0&gt;; typedef typename std::conditional&lt;dims == 1, T, Row&lt;T, dims - 1, size_type, difference_type&gt;&gt;::type value_type; typedef typename std::conditional&lt;dims == 1, T&amp;, value_type&gt;::type reference; // reference is indeed a proxy to real data when dims != 1 using reverse_iterator = typename Iterator&lt;T, dims, size_type, difference_type, 0, 1&gt;; using const_reverse_iterator = typename Iterator&lt;T, dims, size_type, difference_type, 1, 1&gt;; protected: T* arr; // underlying array for the data size_type *sizes; // array of dimensions of the nD array size_type rowsize; // cached size of a top level row // protected ctor called from subclasses ArrayBase(T* arr, size_type* sizes, size_type rowsize) : arr(arr), sizes(sizes), rowsize(rowsize) {} // pseudo-assignment from subclasses void load(T* arr, size_type *sizes, size_type rowsize) { this-&gt;arr = arr; this-&gt;sizes = sizes; this-&gt;rowsize = rowsize; } public: virtual ~ArrayBase() = default; // access to member reference operator[] (size_type i) noexcept { return getElt(arr, sizes, rowsize, i); } const reference operator[] (size_type i) const noexcept { return getConstElt(arr, sizes, rowsize, i); } // access to internal data, arr and sizes and number of dimensions size_type size(size_type i) const { if (i &gt;= dims) { throw std::out_of_range("Illegal dimension"); } return sizes[i]; } size_type size() const noexcept { return sizes[0]; } size_type tot_size() const noexcept { return sizes[0] * rowsize; } T* data() noexcept { return arr; } const T* data() const noexcept { return arr; } constexpr int getdims() const noexcept { return dims; } // iterators iterator begin() { return iterator(arr, sizes, rowsize); } iterator end() { iterator tmp = begin(); tmp += sizes[0]; return tmp; } const_iterator begin() const { return cbegin(); } const_iterator end() const { return cend(); } const_iterator cbegin() const { return const_iterator(arr, sizes, rowsize); } const_iterator cend() const { const_iterator tmp = cbegin(); tmp += sizes[0]; return tmp; } reverse_iterator rbegin() { reverse_iterator tmp = rend(); tmp -= sizes[0]; return tmp; } reverse_iterator rend() { return reverse_iterator(arr, sizes, rowsize); } const_reverse_iterator rbegin() const { return rcbegin(); } const_reverse_iterator rend() const { return rcend(); } const_reverse_iterator rcbegin() const { const_reverse_iterator tmp = rend(); tmp -= sizes[0]; return tmp; } const_reverse_iterator rcend() const { return const_reverse_iterator(arr, sizes, rowsize); } }; // Row represents a sub-array. Handles copying, moving and swapping rows // can only be created by an ElementAccessor template &lt;class T, int dims, class size_type, class difference_type&gt; class Row : public ArrayBase&lt;T, dims, size_type, difference_type&gt; { protected: using ArrayBase::arr; using ArrayBase::sizes; using ArrayBase::rowsize; Row(T* arr, size_type* sizes, size_type rowsize) : ArrayBase&lt;T, dims, size_type, difference_type&gt;(arr, sizes, rowsize) {} public: using base = ArrayBase&lt;T, dims, size_type, difference_type&gt;; /* copy/move assignment (construction can only be from an ElementAccessor) Programmers must use a view or a reference to point to a row, or an Array to get a copy. Swap operation is also possible */ Row&amp; operator = (const base&amp; src) { if (tot_size() != src.tot_size()) { throw std::logic_error("Wrong sizes"); } for (size_type i = 0; i &lt; tot_size(); i++) { arr[i] = src.data()[i]; } return *this; } Row&amp; operator = (base&amp;&amp; src) { if (tot_size() != src.tot_size()) { throw std::logic_error("Wrong sizes"); } for (size_type i = 0; i &lt; tot_size(); i++) { arr[i] = std::move(src.data()[i]); } return *this; } Iterator&lt;T, dims + 1, size_type, difference_type, 0, 0&gt; operator &amp; () { return Iterator&lt;T, dims + 1, size_type,difference_type, 0, 0&gt;(arr, sizes - 1, sizes[0] * rowsize); } Iterator&lt;T, dims + 1, size_type, difference_type, 1, 0&gt; operator &amp; () const { return Iterator&lt;T, dims + 1, size_type, difference_type, 1, 0&gt;(arr, sizes - 1, sizes[0] * rowsize); } // 1 argument swap allows the other member to be any ArrayBase void swap(ArrayBase&amp; other) { using std::swap; if (tot_size() != other.tot_size()) { throw std::logic_error("Wrong sizes"); } for (size_type i = 0; i &lt; tot_size(); i++) { swap(arr[i], other.data()[i]); } } friend class ElementAccessor&lt;T, size_type, difference_type, size_type, dims + 1&gt;; friend class ElementAccessor&lt;T, size_type, difference_type, difference_type, dims + 1&gt;; }; // 2 arguments swap between Rows template &lt;class T, int dims, class size_type, class difference_type&gt; void swap(Row&lt;T, dims, size_type, difference_type&gt;&amp; first, Row&lt;T, dims, size_type, difference_type&gt;&amp; second) { first.swap(second); } namespace { /* private auxilliary functions to build a sizes array and compute total sizes when given the dimensions */ template &lt;class size_type, class...U&gt; size_type calc_size(size_type *sizes, size_type first, U...others) { if (sizes != nullptr) *sizes = first; return first * calc_size&lt;size_type&gt;(sizes + 1, others...); } template&lt;class size_type&gt; size_type calc_size(size_type *sizes, size_type first) { if (sizes != nullptr) *sizes = first; return first; } } // View is a top-level nD array over an existing raw array - no ownership template &lt;class T, int dims, class size_type = size_t, class difference_type = ptrdiff_t&gt; class View : public ArrayBase&lt;T, dims, size_type, difference_type&gt; { public: using base = ArrayBase&lt;T, dims, size_type, difference_type&gt;; private: using ArrayBase::arr; using ArrayBase::sizes; using ArrayBase::rowsize; // private array to hold the actual dimensions // constraint: sizes shall point to _sizes size_type _sizes[dims]; public: /* public ctors, assignment operators and swap. Only copy semantics, because assignment only changes where the view points to, not the underlying data */ template &lt;class...U, typename = std::enable_if&lt;dims == sizeof...(U)&gt;::type&gt; View(T* arr, U...sz): base(arr, _sizes, 0) { size_t tot = calc_size&lt;size_type&gt;(sizes, sz...); rowsize = tot / sizes[0]; } View(const base&amp; other) : ArrayBase&lt;T, dims, size_type, difference_type&gt;(other) { std::copy(sizes, sizes + dims, _sizes); sizes = _sizes; } View(const View&amp; other) : ArrayBase&lt;T, dims, size_type, difference_type&gt;(other) { std::copy(sizes, sizes + dims, _sizes); sizes = _sizes; } View&amp; operator = (const base&amp; other) { ArrayBase.operator = (other); std::copy(sizes, sizes + dims, _sizes); sizes = _sizes; } void swap(View&amp; other) { using std::swap; swap(_sizes, other._sizes); T *tmparr = arr; size_type tmprs = rowsize; ArrayBase::operator = (other); other.load(tmparr, sizes, tmprs); sizes = _sizes; } }; template &lt;class T, int dims, class size_type = size_t, class difference_type = ptrdiff_t&gt; void swap(View&lt;T, dims, size_type, difference_type&gt;&amp; first, View&lt;T, dims, size_type, difference_type&gt;&amp; second) { first.swap(second); } // Full array, holds (a copy of) the underlying data template &lt;class T, int dims, class Allocator = allocator&lt;T&gt; &gt; class Array : public ArrayBase&lt;T, dims, typename allocator_traits&lt;Allocator&gt;::size_type, typename allocator_traits&lt;Allocator&gt;::difference_type&gt; { public: using size_type = typename allocator_traits&lt;Allocator&gt;::size_type; using difference_type = typename allocator_traits&lt;Allocator&gt;::difference_type; private: using base = ArrayBase&lt;T, dims, typename allocator_traits&lt;Allocator&gt;::size_type, typename allocator_traits&lt;Allocator&gt;::difference_type&gt;; using ArrayBase::arr; using ArrayBase::sizes; using ArrayBase::rowsize; Allocator alloc; // internal allocator size_type _sizes[dims]; std::vector&lt;T, Allocator&gt; _arr; template&lt;class...U&gt; void init(size_type first, U... others) { sizes = _sizes; size_t tot = calc_size&lt;size_type&gt;(sizes, first, others...); rowsize = tot / sizes[0]; if (arr == nullptr) { _arr.assign(tot, T()); } else { _arr.assign(arr, arr + tot); } this-&gt;arr = _arr.data(); } public: template&lt;class...U, typename = std::enable_if&lt;sizeof...(U)+1 == dims&gt;::type&gt; Array(T* arr, Allocator alloc, size_type first, U... others) : base(arr, nullptr, 0), alloc(alloc), _arr(this-&gt;alloc) { init(first, others...); } template&lt;class...U, typename = std::enable_if&lt;sizeof...(U)+1 == dims&gt;::type&gt; Array(T* arr, size_type first, U... others) : base(arr, nullptr, 0), _arr(this-&gt;alloc) { init(first, others...); } template&lt;class...U, typename = std::enable_if&lt;sizeof...(U)+1 == dims&gt;::type&gt; Array(Allocator alloc, size_type first, U... others) : base(nullptr, nullptr, 0), alloc(alloc), _arr(this-&gt;alloc) { init(first, others...); } template&lt;class...U, typename = std::enable_if&lt;sizeof...(U)+1 == dims&gt;::type&gt; Array(size_type first, U... others) : base(nullptr, nullptr, 0), _arr(this-&gt;alloc) { init(first, others...); } // copy/move ctors and assignment from another array // TODO: implement move semantics from an ArrayBase Array(const Array&amp; other) : ArrayBase(other), alloc(other.alloc), _arr(other._arr) { std::copy(sizes, sizes + dims, _sizes); arr = _arr.data(); sizes = _sizes; } Array(Array&amp;&amp; other) : ArrayBase(other), alloc(other.alloc), _arr(std::move(other._arr)) { std::copy(sizes, sizes + dims, _sizes); arr = _arr.data(); sizes = _sizes; } Array(const ArrayBase&amp; other) : ArrayBase(other), alloc(), _arr(arr, arr + rowsize * sizes[0]) { std::copy(sizes, sizes + dims, _sizes); arr = _arr.data(); sizes = _sizes; } Array&amp; operator = (const Array&amp; other) { load(other); if (std::allocator_traits( Allocator)::propagate_on_container_copy_assignment) { alloc = other.alloc; } std::copy(sizes, sizes + dims, _sizes); _arr.assign(other._arr); arr = _arr.data(); sizes = _sizes; return *this; } Array&amp; operator = (Array&amp;&amp; other) { ArrayBase::operator = (other); if (std::allocator_traits&lt; Allocator&gt;::propagate_on_container_move_assignment::value) { alloc = other.alloc; } std::copy(sizes, sizes + dims, _sizes); _arr = std::move(other._arr); arr = _arr.data(); sizes = _sizes; return *this; } Array&amp; operator = (const ArrayBase&amp; other) { ArrayBase::operator = (other); std::copy(sizes, sizes + dims, _sizes); _arr.assign(arr, arr + sizes[0] * rowsize); arr = _arr.data(); sizes = _sizes; return *this; } }; /* syntactic sugar to help template deduction and avoid some (re-)typing mainly usefull for non default allocators */ template &lt;class T, class Allocator = std::allocator&lt;T&gt; &gt; class ArrayBuilder { public: using size_type = typename allocator_traits&lt;Allocator&gt;::size_type; using difference_type = typename allocator_traits&lt;Allocator&gt;::difference_type; private: Allocator alloc; public: ArrayBuilder(const Allocator&amp; alloc = Allocator()) : alloc(alloc) {} template &lt;class ...U, int dims = sizeof...(U)+1&gt; View&lt;T, dims, size_type, difference_type&gt; dynUseArray(T* arr, size_type first, U...others) { return View&lt;T, dims, size_type, difference_type&gt;(arr, first, others...); } template &lt;class ...U, int dims = sizeof...(U)+1&gt; Array&lt;T, dims, Allocator&gt; dynCopyArray(T* arr, size_type first, U...others) { return Array&lt;T, dims, Allocator&gt;(arr, alloc, first, others...); } template &lt;class ...U, int dims = sizeof...(U)+1&gt; Array&lt;T, dims, Allocator&gt; dynBuildArray(size_type first, U...others) { return Array&lt;T, dims, Allocator&gt;(alloc, first, others...); } }; // iterator if cnst == 0 or const_iterator if cnst == 1, U is the value_type template &lt;class T, int dims, class size_type, class difference_type, bool cnst, bool rev&gt; class Iterator: public ElementAccessor&lt;T, size_type, difference_type, difference_type, dims&gt;{ public: using value_type = typename std::conditional&lt;cnst, typename std::conditional&lt;dims == 1, const T, const Row&lt;T, dims-1, size_type, difference_type&gt;&gt;::type, typename std::conditional&lt;dims == 1, T, Row&lt;T, dims - 1, size_type, difference_type&gt;&gt;::type&gt;::type; using reference = typename std::conditional &lt; dims == 1, value_type&amp;, value_type&gt;::type; using iterator_category = typename std::random_access_iterator_tag; private: struct Proxy { value_type elt; Proxy(value_type&amp;&amp; elt) : elt(elt) {} value_type* operator -&gt;() { return std::addressof(elt); } }; T* arr; size_type *sizes; size_type rowsize; Iterator(T* arr, size_type *sizes, size_type rowsize) : arr(arr), sizes(sizes), rowsize(rowsize) {} template&lt;bool x=false&gt; reference getXElt(difference_type i) { return getElt(arr - rowsize * (rev ? 1 : 0), sizes, rowsize, i); } template&lt;&gt; reference getXElt&lt;true&gt;(difference_type i) { return getConstElt(arr - rowsize * (rev ? 1 : 0), sizes, rowsize, i); } void add(difference_type i) { arr += (rev ? -i : i) * rowsize ; } using iterator = Iterator&lt;T, dims, size_type, difference_type, cnst, rev&gt;; public: using pointer = Proxy; // a default ctor (to mimic standard iterators) Iterator(): arr(nullptr), sizes(nullptr), rowsize(0) {} //convert an (non const) iterator to a const_iterator template &lt;class X = T, typename = std::enable_if&lt;cnst == 1&gt;::type&gt; Iterator(const Iterator&lt;T, dims, size_type, difference_type, 1 - cnst, rev&gt;&amp; other) : arr(other.arr), sizes(other.sizes), rowsize(other.rowsize) {} // all operations of an iterator reference operator * () { return getXElt(0) ; } pointer operator -&gt; () { return Proxy(getXElt(0)); } const reference operator * () const { return getConstElt(arr - rowsize * (rev ? 1 : 0), sizes, rowsize, 0); } const pointer operator -&gt; () const { return Proxy(getXElt(0)); } iterator&amp; operator ++() { this-&gt;add(1); return *this; } iterator&amp; operator --() { this-&gt;add(-1); return *this; } iterator operator ++(int) { iterator tmp = *this; this-&gt;add(1); return tmp; } iterator operator --(int) { iterator tmp = *this; this-&gt;add(-1); return tmp; } iterator&amp; operator += (difference_type i) { this-&gt;add(i); return *this; } iterator operator + (difference_type i) { iterator tmp = *this; tmp.add(i); return tmp; } iterator operator -= (difference_type i) { return operator += (-i); } iterator operator - (difference_type i) { return operator + (-i); } value_type operator [] (difference_type i) { return *(*this + i); } const value_type operator [] (difference_type i) const { return *(*this + i); } // comparisons are allowed between const and non const iterators template &lt;bool c&gt; bool operator ==(const Iterator&lt;T, dims, size_type, difference_type, c, rev&gt;&amp; other) const { return (arr == other.arr) &amp;&amp; (sizes == other.sizes) &amp;&amp; (rowsize == other.rowsize); } template &lt;bool c&gt; bool operator != (const Iterator&lt;T, dims, size_type, difference_type, c, rev&gt;&amp; other) const { return !operator ==(other); } template &lt;bool c&gt; bool operator &lt;(const Iterator&lt;T, dims, size_type, difference_type, rev, c&gt;&amp; other) const { return arr &lt; other.arr; } template &lt;bool c&gt; bool operator &gt;(const Iterator&lt;T, dims, size_type, difference_type, c, rev&gt;&amp; other) const { return arr &gt; other.arr; } template &lt;bool c&gt; bool operator &lt;=(const Iterator&lt;T, dims, size_type, difference_type, c, rev&gt;&amp; other) const { return !operator &gt;(other); } template &lt;bool c&gt; bool operator &gt;=(const Iterator&lt;T, dims, size_type, difference_type, c, rev&gt;&amp; other) const { return !operator &lt;(other); } friend class ArrayBase&lt;T, dims, size_type, difference_type&gt;; friend class Iterator&lt;T, dims, size_type, difference_type, !cnst, rev&gt;; friend class Row&lt;T, dims - 1, size_type, difference_type&gt;; }; } </code></pre> <p>For reference here are the unit test classes for MSCV 2017 test framework</p> <pre><code>#include "stdafx.h" #include "CppUnitTest.h" #include "../mdynarray/mdynarray.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace UnitTest1 { using namespace DynArray; TEST_CLASS(UnitTest1) { public: /* creation of a view shall point to original raw array */ TEST_METHOD(useArr) { ArrayBuilder&lt;int&gt; builder; int arr[60]; int l = 0; for (int&amp; i : arr) { i = l++; } auto dynarray = builder.dynUseArray(arr, 3, 4, 5); l = 0; for (int i = 0; i &lt; 3; i++) { for (int j = 0; j &lt; 4; j++) { for (int k = 0; k &lt; 5; k++) { Assert::AreSame(dynarray[i][j][k], arr[l++]); } } } } /* Assignment of a row from a second view */ TEST_METHOD(rowAssign) { int arr[60]; int l = 0; for (int&amp; i : arr) { i = l++; } View&lt;int, 3&gt; array {arr, 3, 4, 5}; int arr2[20]; l = 64; for (int&amp;i : arr) { i = l++; } View&lt;int, 2&gt; array2{ arr2, 4, 5 }; array[1] = array2; /* controls that: - values have been copied - indices still point to original raw array */ for (int i = 0; i &lt; 4; i++) { for (int j = 0; j &lt; 5; j++) { Assert::AreNotSame(array[1][i][j], array2[i][j]); Assert::AreEqual(array[1][i][j], array2[i][j]); Assert::AreSame(arr[20 + 5 * i + j], array[1][i][j]); } } } // swap Rows TEST_METHOD(rowSwap) { int arr[60]; int l = 0; for (int&amp; i : arr) { i = l++; } View&lt;int, 3&gt; array {arr, 3, 4, 5}; swap(array[0], array[2]); l = 40; int k = 0; for (int i = 0; i &lt; 4; i++) { for (int j = 0; j &lt; 5; j++) { Assert::AreSame(arr[k++], array[0][i][j]); Assert::AreEqual(l++, array[0][i][j]); } } } //Assignement of a view from a Row or another View TEST_METHOD(viewAssign) { int arr[60]; int l = 0; for (int&amp; i : arr) { i = l++; } View&lt;int, 3&gt; array {arr, 3, 4, 5}; View&lt;int, 2&gt; arr0{ array[0] }; l = 0; for (int i = 0; i &lt; 4; i++) { for (int j = 0; j &lt; 5; j++) { Assert::AreSame(arr[l++], arr0[i][j]); } } View&lt;int, 2&gt; arr2 = array[2]; arr0 = arr2; l = 40; for (int i = 0; i &lt; 4; i++) { for (int j = 0; j &lt; 5; j++) { Assert::AreSame(arr[l++], arr0[i][j]); } } } // swap views TEST_METHOD(viewSwap) { int arr[60]; int l = 0; for (int&amp; i : arr) { i = l++; } View&lt;int, 3&gt; array {arr, 3, 4, 5}; View&lt;int, 2&gt; arr0{ array[0] }; View&lt;int, 2&gt; arr2 = array[2]; swap(arr0, arr2); l = 40; int k = 0; for (int i = 0; i &lt; 4; i++) { for (int j = 0; j &lt; 5; j++) { Assert::AreSame(arr[l++], arr0[i][j]); Assert::AreSame(arr[k++], arr2[i][j]); } } } TEST_METHOD(copyArr) { ArrayBuilder&lt;int&gt; builder; int arr[60]; int l = 0; for (int&amp; i : arr) { i = l++; } auto dynarray = builder.dynCopyArray(arr, 3, 4, 5); l = 0; for (int i = 0; i &lt; 3; i++) { for (int j = 0; j &lt; 4; j++) { for (int k = 0; k &lt; 5; k++) { Assert::AreEqual(dynarray[i][j][k], arr[l]); Assert::AreNotSame(dynarray[i][j][k], arr[l]); l++; } } } } TEST_METHOD(buildArr) { ArrayBuilder&lt;int&gt; builder; auto dynarray = builder.dynBuildArray(3, 4, 5); for (int i = 0; i &lt; 3; i++) { for (int j = 0; j &lt; 4; j++) { for (int k = 0; k &lt; 5; k++) { Assert::AreEqual(dynarray[i][j][k], 0); } } } } TEST_METHOD(copyCtor) { ArrayBuilder&lt;int&gt; builder; int arr[60]; int l = 0; for (int&amp; i : arr) { i = l++; } auto dynarray = builder.dynUseArray(arr, 3, 4, 5); Array&lt;int, 3&gt; dyn2{ dynarray }; l = 0; for (int i = 0; i &lt; 3; i++) { for (int j = 0; j &lt; 4; j++) { for (int k = 0; k &lt; 5; k++) { Assert::AreEqual(dyn2[i][j][k], arr[l]); Assert::AreNotSame(dyn2[i][j][k], arr[l]); l++; } } } } TEST_METHOD(moveCtor) { ArrayBuilder&lt;int&gt; builder; int arr[60]; int l = 0; for (int&amp; i : arr) { i = l++; } auto dynarray = builder.dynCopyArray(arr, 3, 4, 5); int *ix = dynarray.data(); auto dyn2 = std::move(dynarray); Assert::AreEqual(ix, dyn2.data()); l = 0; for (int i = 0; i &lt; 3; i++) { for (int j = 0; j &lt; 4; j++) { for (int k = 0; k &lt; 5; k++) { Assert::AreEqual(dyn2[i][j][k], arr[l]); l++; } } } } TEST_METHOD(copyAssign) { ArrayBuilder&lt;int&gt; builder; int arr[60]; int l = 0; for (int&amp; i : arr) { i = l++; } auto dynarray = builder.dynUseArray(arr, 3, 4, 5); auto dyn2 = builder.dynBuildArray(3, 4, 5); dyn2 = dynarray; l = 0; for (int i = 0; i &lt; 3; i++) { for (int j = 0; j &lt; 4; j++) { for (int k = 0; k &lt; 5; k++) { Assert::AreEqual(dyn2[i][j][k], arr[l]); Assert::AreNotSame(dyn2[i][j][k], arr[l]); l++; } } } } TEST_METHOD(moveAssign) { ArrayBuilder&lt;int&gt; builder; int arr[60]; int l = 0; for (int&amp; i : arr) { i = l++; } auto dynarray = builder.dynCopyArray(arr, 3, 4, 5); int *ix = dynarray.data(); auto dyn2 = builder.dynBuildArray(3, 4, 5); dyn2 = std::move(dynarray); l = 0; for (int i = 0; i &lt; 3; i++) { for (int j = 0; j &lt; 4; j++) { for (int k = 0; k &lt; 5; k++) { Assert::AreEqual(dyn2[i][j][k], arr[l]); l++; } } } Assert::AreEqual(ix, dyn2.data()); } TEST_METHOD(nonConstIter) { ArrayBuilder&lt;int&gt; builder; int arr[60]; int l = 0; for (int&amp; i : arr) { i = l++; } auto dynarray = builder.dynUseArray(arr, 3, 4, 5); l = 0; for (auto&amp; it1 : dynarray) { for (auto&amp; it2 : it1) { for (auto&amp; it3 : it2) { Assert::AreSame(it3, arr[l]); l++; it3 = l; // control it is not const... } } } } TEST_METHOD(constIter) { ArrayBuilder&lt;int&gt; builder; int arr[60]; int l = 0; for (int&amp; i : arr) { i = l++; } auto dynarray = builder.dynUseArray(arr, 3, 4, 5); l = 0; for (auto it1 = dynarray.cbegin(); it1 != dynarray.cend(); it1++) { for (auto it2 = it1-&gt;cbegin(); it2 != it1-&gt;cend(); it2++) { for (auto it3 = it2-&gt;cbegin(); it3 != it2-&gt;cend(); it3++) { Assert::AreSame(*it3, arr[l]); l++; // *it3 = l; // does not compile } } } } TEST_METHOD(convConstIterator) { ArrayBuilder&lt;int&gt; builder; int arr[60]; int l = 0; for (int&amp; i : arr) { i = l++; } auto dynarray = builder.dynUseArray(arr, 3, 4, 5); auto it = dynarray.begin(); Array&lt;int, 3&gt;::const_iterator cit = it; //it = (MDynArray&lt;int, 3&gt;::iterator) cit; // does not compile it += 1; cit += 1; Assert::IsTrue(it &gt; dynarray.begin()); Assert::IsTrue(it == cit); Assert::IsTrue(cit == it); } TEST_METHOD(revIterator) { ArrayBuilder&lt;int&gt; builder; int arr[60]; int l = 0; for (int&amp; i : arr) { i = l++; } auto dynarray = builder.dynUseArray(arr, 3, 4, 5); l = 0; for (auto it1 = dynarray.rbegin(); it1 != dynarray.rend(); it1++) { for (auto it2 = it1-&gt;rbegin(); it2 != it1-&gt;rend(); it2++) { for (auto it3 = it2-&gt;rbegin(); it3 != it2-&gt;rend(); it3++) { Assert::AreSame(*it3, arr[59 - l]); l++; *it3 = l; // control non constness } } } } TEST_METHOD(rowToIter) { ArrayBuilder&lt;int&gt; builder; int arr[60]; int l = 0; for (int&amp; i : arr) { i = l++; } auto dynarray = builder.dynUseArray(arr, 3, 4, 5); l = 0; auto row = dynarray[1]; auto it = &amp;row - 1; Assert::AreSame(arr[0], it[0][0][0]); } }; } </code></pre> <p>I admit it is a rather large piece of code...</p>
[]
[ { "body": "<p>I found a number of compilation issues using GCC 8 (with <code>-std=c++2a</code>). I'm guessing you're using an older or less-conformant compiler. Here's what I had to change.</p>\n\n<hr>\n\n<p>The <code>typename</code> keyword isn't wanted here (where it knows that <code>Iterator&lt;&gt;</code>...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-01T11:18:54.707", "Id": "197595", "Score": "4", "Tags": [ "c++", "array", "iterator", "collections" ], "Title": "General use multi-dimensional container using operator[]" }
197595
<p>The McCabe code complexity of the following function is 19 as found by <code>pytest --mccabe test.py</code> (from my toy-project <a href="https://github.com/MartinThoma/mpu/tree/15e749184605f6235ed772453bdfb717e87bb1f2" rel="nofollow noreferrer"><code>mpu</code></a>). While I agree that this function is length and likely will become longer in future, I don't know how to improve the situation.</p> <h2>What it does</h2> <p>The code <code>mpu.io.write(filepath)</code> is a convenience function for writing a few common file formats.</p> <h2>Code</h2> <p>This code should work in Python 2 and 3.</p> <pre><code>def write(filepath, data, **kwargs): """ Write a file. Supported formats: * CSV * JSON, JSONL * pickle Parameters ---------- filepath : str Path to the file that should be read. This methods action depends mainly on the file extension. data : dict or list Content that should be written kwargs : dict Any keywords for the specific file format. Returns ------- data : str or bytes """ if filepath.lower().endswith('.csv'): kwargs_open = {'newline': ''} mode = 'w' if sys.version_info &lt; (3, 0): kwargs_open.pop('newline', None) mode = 'wb' with open(filepath, mode, **kwargs_open) as fp: if 'delimiter' not in kwargs: kwargs['delimiter'] = ',' if 'quotechar' not in kwargs: kwargs['quotechar'] = '"' with open(filepath, 'w') as fp: writer = csv.writer(fp, **kwargs) writer.writerows(data) return data elif filepath.lower().endswith('.json'): with io_stl.open(filepath, 'w', encoding='utf8') as outfile: if 'indent' not in kwargs: kwargs['indent'] = 4 if 'sort_keys' not in kwargs: kwargs['sort_keys'] = True if 'separators' not in kwargs: kwargs['separators'] = (',', ': ') if 'ensure_ascii' not in kwargs: kwargs['ensure_ascii'] = False str_ = json.dumps(data, **kwargs) outfile.write(to_unicode(str_)) elif filepath.lower().endswith('.jsonl'): print(filepath) with io_stl.open(filepath, 'w', encoding='utf8') as outfile: kwargs['indent'] = None # JSON has to be on one line! if 'sort_keys' not in kwargs: kwargs['sort_keys'] = True if 'separators' not in kwargs: kwargs['separators'] = (',', ': ') if 'ensure_ascii' not in kwargs: kwargs['ensure_ascii'] = False for line in data: str_ = json.dumps(line, **kwargs) outfile.write(to_unicode(str_)) outfile.write(u'\n') elif filepath.lower().endswith('.pickle'): if 'protocol' not in kwargs: kwargs['protocol'] = pickle.HIGHEST_PROTOCOL with open(filepath, 'wb') as handle: pickle.dump(data, handle, **kwargs) elif (filepath.lower().endswith('.yml') or filepath.lower().endswith('.yaml')): raise NotImplementedError('YAML is not supported, because you need ' 'PyYAML in Python3. ' 'See ' 'https://stackoverflow.com/a/42054860/562769' ' as a guide how to use it.') elif (filepath.lower().endswith('.h5') or filepath.lower().endswith('.hdf5')): raise NotImplementedError('HDF5 is not supported. See ' 'https://stackoverflow.com/a/41586571/562769' ' as a guide how to use it.') else: raise NotImplementedError('File \'{}\' is not known.'.format(filepath)) </code></pre>
[]
[ { "body": "<p>You’ve got your code split into various sections; why not make the sections their own methods?</p>\n\n<pre><code>if filepath.lower().endswith('.csv'):\n return _write_csv(filepath, data, kwargs)\nelif filepath.lower().endswith('.json'):\n return _write_json(filepath, data, kwargs)\nelif filepa...
{ "AcceptedAnswerId": "197632", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-01T11:47:37.170", "Id": "197597", "Score": "2", "Tags": [ "python", "json", "file", "csv", "cyclomatic-complexity" ], "Title": "Convenience function for writing files in CSV, JSON, etc" }
197597
<p>I'm visiting a functional programming course at my university which has a small project for examination. The language we are using is clojure and the contents of the lecture have mostly been about it's syntax, rather than the benefits and paradigms of functional programming. Our lecturer doesn't seem to be too harsh when it comes to grading but we are still very unsure if our program fully matches the requirements of functional programming. Here are some of our questions:</p> <ol> <li>Can you mess up that badly when it comes to functional programming or are some things already ensured when using clojure?</li> <li>We have some functions with random numbers to randomize the output (e.g. "create-star"). This makes them "unpure" because output with the same input is different every time. If we would pass the random numbers via the parameters instead it would make the code much less readable and clear. Is sticking to the parameters of functional programming more important than visibility? <em>(If we would follow that train of thought we would even have to create and pass all random values in the "update-state" functions parameters as it is the outer-most function to be called and would be unpure aswell if it contained randomness.)</em></li> <li>The framework internally uses an atom for the state variable which we modify in some methods. But we always pass it as parameter and return it, so we don't use global variables. Does this violate the principle of immutable objects?</li> <li>Is there anything else in our code below that violates functional programming principles?</li> </ol> <p>Below is the main part of our code. The full project can be found at <a href="https://github.com/Niggls/rocket_game/tree/3efd103c924aa544cbd577d7d568bf6888912b7b" rel="noreferrer">https://github.com/Niggls/rocket_game</a>. It's a small game where you have to control a rocket to avoid incoming meteors. We are using the "quil" library to draw the contents of the game screen. It works with a "state" variable that handles all data of objects on the screen. The main parts are the "draw" function which creates the output and the "update-state" function which evaluates all of our functions for every frame. Both of these are at the bottom.</p> <pre><code>(ns rocket-game.core (:require [quil.core :as q] [quil.middleware :as m])) (defn star-color-index [x] (if (&lt; x 12) 0 (if (&lt; x 15) 2 3))) (defn create-star [y] {:x (rand-int (q/width)) :y (rand-int y) :size (+ (rand-int 5) 1) :speed (+ (rand-int 3) 1) :color (star-color-index (rand-int 20))}) ;; function for reset state (defn reset-state-variable [state] {:rocket {:image (q/load-image "images/rocket.png") :x 260 :y 340 :dir 0} :background (q/load-image "images/stars.jpg") :fires [] :smoke [] :score 0 :stars (:stars state) :highscore (if ( &gt; (:score state) (:highscore state)) (:score state) (:highscore state)) :gameOver true :meteors [] :bonus []}) ;; setup: here we define our global state variable ;; # --&gt; anonymous function (defn setup [] ;; these two lines, a map (data structure) is added in step 1-6 {:rocket {:image (q/load-image "images/rocket.png") :x 260 :y 340 :dir -1} :background (q/load-image "images/stars.jpg") :fires [] :score 0 :smoke [] :highscore 0 :stars (take 150 (repeatedly #(create-star (q/height)))) :gameOver false :meteors [] :bonus []}) ;;;; helper methods;;;;;;;;;;;;;;;;;;;;;;;; (defn inside? [x y] (or (&lt; x -12) (&gt; (+ x 33) (q/width)) (&lt; y 0) (&gt; (+ y 40) (q/height)))) (defn item-inside? [item] (let [x (:x item) y (:y item)] (&gt; y (q/height)))) (defn remove-stars [stars] (remove item-inside? stars)) (defn meteor-out [state] (let [old (-&gt; state :meteors (count)) new-meteor (remove item-inside? (:meteors state)) new (count new-meteor)] {:rocket (:rocket state) :background (q/load-image "images/stars.jpg") :fires (:fires state) :score (+ (:score state) (- old new)) :highscore (:highscore state) :gameOver false :smoke (:smoke state) :stars (:stars state) :meteors new-meteor :bonus (:bonus state)})) (defn meteor-hit [state] (let [rocket-x (-&gt; state :rocket :x) rocket-y (-&gt; state :rocket :y) meteors (:meteors state)] (if (empty? meteors) state (if (loop [[m1 &amp; rest] meteors] (if (or (and (&lt;= (:x m1) rocket-x (+ (:x m1) 45)) (&lt;= (:y m1) rocket-y (+ (:y m1) 45))) (and (&lt;= (:x m1) (+ rocket-x 45) (+ (:x m1) 45)) (&lt;= (:y m1) (+ rocket-y 45) (+ (:y m1) 45)))) true (if (empty? rest) false (recur rest)))) (reset-state-variable state) state)))) (defn bonus-out [state] (if (item-inside? (:bonus state)) state {:rocket (:rocket state) :background (q/load-image "images/stars.jpg") :fires (:fires state) :score (:score state) :highscore (:highscore state) :gameOver false :smoke (:smoke state) :stars (:stars state) :meteors (:meteors state) :bonus []})) (defn bonus-hit [state] (let [rocket-x (-&gt; state :rocket :x) rocket-y (-&gt; state :rocket :y) bonus (get (:bonus state) 0)] (if (empty? bonus) state (if (or (and (&lt;= (:x bonus) rocket-x (+ (:x bonus) 40)) (&lt;= (:y bonus) rocket-y (+ (:y bonus) 40))) (and (&lt;= (:x bonus) rocket-x (+ (:x bonus) 40)) (&lt;= (:y bonus) (+ rocket-y 45) (+ (:y bonus) 40))) (and (&lt;= (:x bonus) (+ rocket-x 45) (+ (:x bonus) 40)) (&lt;= (:y bonus) rocket-y (+ (:y bonus) 40))) (and (&lt;= (:x bonus) (+ rocket-x 45) (+ (:x bonus) 40)) (&lt;= (:y bonus) (+ rocket-y 45) (+ (:y bonus) 40)))) {:rocket (:rocket state) :background (q/load-image "images/stars.jpg") :fires (:fires state) :score (+ (:score state) (:points bonus)) :highscore (:highscore state) :gameOver false :smoke (:smoke state) :stars (:stars state) :meteors (:meteors state) :bonus []} state)))) ;; # defines a function --&gt; (fn [oldAge] (+ oldAge 0.3)) (defn age-smoke [smoke] (update-in smoke [:age] #(+ % 0.3))) (defn old? [smoke] (&lt; 2.0 (:age smoke))) (defn remove-old-smokes [smokes] (remove old? smokes)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; creation methods ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn create-meteor [state] (if (= (rand-int 10) 1) (if-not (or (-&gt; state :rocket :dir (= 0)) (-&gt; state :rocket :dir (= -1))) (update-in state [:meteors] conj {:x (rand-int (+ (q/width) -40)) :y -40 :speed (+ (rand-int 30) 5)}) ;(update-in state [:meteors] conj {:x (rand-int (+ (q/width) -40)) :y -40 :speed 1}) state) state)) (defn create-smoke [x y] {:pos [(+ x 25 (- (rand-int 10) 5)) (+ y 50 (- (rand-int 10) 5))] :dir 0.0 :age 0.0 :col [(+ (rand-int 105) 150) (+ (rand-int 100) 100) (rand-int 100)]}) (defn emit-smoke [state] (let [x (-&gt; state :rocket :x) y (-&gt; state :rocket :y)] (update-in state [:smoke] conj (create-smoke x y)))) (defn create-new-star [state] (if(= (rand-int 7) 1) (if-not (or (-&gt; state :rocket :dir (= 0)) (-&gt; state :rocket :dir (= -1))) {:rocket (:rocket state) :background (q/load-image "images/stars.jpg") :fires (:fires state) :score (:score state) :highscore (:highscore state) :gameOver true :smoke (:smoke state) :stars (conj (:stars state) (create-star 1)) :meteors (:meteors state) :bonus (:bonus state)} state) state)) (defn create-bonus [state] (if (and (empty? (:bonus state)) (= (rand-int 100) 1)) (if-not (or (-&gt; state :rocket :dir (= 0)) (-&gt; state :rocket :dir (= -1))) (if (= (rand-int 5) 1) (update-in state [:bonus] conj {:x (rand-int (+ (q/width) -40)) :y (rand-int (+ (q/height) -40)) :points 25 :speed 3 :image "images/bonus2.png"}) (update-in state [:bonus] conj {:x (rand-int (+ (q/width) -40)) :y (rand-int (+ (q/height) -40)) :points 10 :speed 2 :image "images/bonus.png"})) state) state)) (defn fly-backwards [smoke state] (if (-&gt; state :rocket :dir (= 2)) [] smoke)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;; reset methods;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn reset-game [state] (if (inside? (:x (:rocket state )) (:y (:rocket state))) (reset-state-variable state) state)) (defn reset-game-over [gameOver state] (if (-&gt; state :rocket :dir (not= 0)) false true)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;, ;;;;;;;; move methods;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn move [state event] (case (:key event) (:w :up) (assoc-in state [:rocket :dir] 1) (:s :down) (assoc-in state [:rocket :dir] 2) (:a :left) (assoc-in state [:rocket :dir] 3) (:d :right) (assoc-in state [:rocket :dir] 4) state)) (defn move-meteors [meteor] (let [speed (:speed meteor)] (update-in meteor [:y] #(+ % speed)))) (defn move-star [star] (update-in star [:y] #(+ % (:speed star)))) (defn move-stars [state] (if-not (or (= (:dir (:rocket state)) 0) (= (:dir (:rocket state)) -1)) {:rocket (:rocket state) :background (q/load-image "images/stars.jpg") :fires (:fires state) :score (:score state) :highscore (:highscore state) :gameOver true :smoke (:smoke state) :stars (doall (map move-star (:stars state))) :meteors (:meteors state) :bonus (:bonus state)} state)) (defn move-bonus [state] (if (empty? (:bonus state)) state (update-in (:bonus state) [:y] + 4))) (defn move-rocket [rocket] (case (:dir rocket) (1) (update-in rocket [:y] - 10) (2) (update-in rocket [:y] + 10) (3) (update-in rocket [:x] - 10) (4) (update-in rocket [:x] + 10) (0) (update-in rocket [:x] + 0) (-1) (update-in rocket [:x] + 0))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; draw method (defn draw [state] ;; q/background-image and q/image functions are added in step 1-6 ;(q/background-image (:background state)) (q/background 0) (q/fill 250 250 250) (q/stroke 250 250 250) (doseq [star (:stars state)] (if (= (:color star) 0) (do (q/fill 250 250 250) (q/stroke 250 250 250) (q/ellipse (:x star) (:y star) (:size star) (:size star))) (if (= (:color star) 1) (do (q/fill 255 255 26) (q/stroke 255 255 26) (q/ellipse (:x star) (:y star) (:size star) (:size star))) (do (q/fill 255 77 77) (q/stroke 255 77 77) (q/ellipse (:x star) (:y star) (:size star) (:size star)))))) (doseq [bonus (:bonus state)] (q/image (q/load-image (:image bonus)) (:x bonus) (:y bonus) 45 45)) (q/image (:image (:rocket state)) (:x (:rocket state)) (:y (:rocket state))) (q/fill 0 0 255) (q/text-align :left) (q/stroke 0 0 255) (doseq [meteor (:meteors state)] (q/image (q/load-image "images/meteor.png") (:x meteor) (:y meteor))) (doseq [smoke (:smoke state)] (let [age (:age smoke) size (max 0.0 (- 10.0 (* 5.0 age))) [r g b] (:col smoke) [x y] (:pos smoke)] (q/fill 0 0 250 150) (q/stroke 0 0 250 150) (q/ellipse x y size size))) (q/fill 255 255 255) (q/text-size 20) (q/text (str "Score: " (:score state)) 10 30) (q/text (str "Highscore: " (:highscore state)) (- (q/width) 140) 30) (q/fill 200 0 0) (q/text-font (q/create-font "DejaVu Sans" 40 true)) (q/text-align :center) (when (:gameOver state) (q/text (str "Game Over...\nMove to try again") (/ (q/width) 2) 500))) ; update method (defn update-state [state] (-&gt; state (update-in [:meteors] (fn [meteors] (doall (map move-meteors meteors)))) (update-in [:rocket] move-rocket) ; (update-in [:bonus] (fn [bonus] (doall (map move-bonus bonus)))) move-stars create-new-star (update-in [:stars] remove-stars) emit-smoke (update-in [:smoke] (fn [smokes] (map age-smoke smokes))) (update-in [:smoke] remove-old-smokes) meteor-out create-meteor ; bonus-out create-bonus bonus-hit meteor-hit reset-game (update-in [:smoke] fly-backwards state) (update-in [:gameOver] reset-game-over state))) ;; defsketch (q/defsketch rocket_game :host "host" :title "rocket game" :size [600 700] :setup setup :draw draw :key-pressed move :update update-state :middleware [m/fun-mode]) </code></pre>
[]
[ { "body": "<p>For code written by students new to the language, this is quite good. You haven't made any of the major mistakes that most newbies to the language make, like abuse of <code>def</code>, or use of unnecessary side effects.</p>\n\n<p>For your main questions:</p>\n\n<ol>\n<li><p>It's very possible to ...
{ "AcceptedAnswerId": "197619", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-01T13:39:30.400", "Id": "197600", "Score": "7", "Tags": [ "game", "functional-programming", "homework", "clojure" ], "Title": "Avoid incoming meteors" }
197600
<p>As a C programming exercise, I implemented a minimal <code>tac</code> program that prints the input line by line starting from the last line.</p> <p>I'm looking for feedback on my code. Did I overlook anything? Can the style be improved? Did I miss a major issue?</p> <p>The code is available here or on <a href="https://github.com/thk2b/ex/tree/master/c" rel="nofollow noreferrer">GitHub</a>.</p> <pre><code>/* ** tac [ infd [ outfd ]] ** ** output each line from infd to oufile, starting from the last line. ** infd and outfd default to stdin and stdout, respectively. ** */ #include &lt;stdio.h&gt; #include &lt;fcntl.h&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; #include &lt;sys/types.h&gt; #include &lt;errno.h&gt; void err_exit(char *msg) { perror(msg); exit(errno); } /* ** write each line starting from the end of the buffer. ** ** if flush is falsy, don't output characters unless they are preceded by a newline. ** if flush is truthy, write all characters to the output. ** ** return the number of charaters not outputed. */ int rev_write_lines(int outfd, const char *buf, size_t len, int flush) { int i, prev_eol; size_t line_len; for(i = prev_eol = len; i &gt;= 0; i--) if(buf[i] == '\n') { line_len = prev_eol - i; if(write(outfd, buf+i+1, line_len) != line_len) err_exit("write"); prev_eol = i; } if(flush) { if(write(outfd, buf, prev_eol+1) != prev_eol+1) err_exit("write"); return 0; } return prev_eol+1; } #define BUF_SIZE 512 /* ** read size characters from stdin into buffer. ** return the number of characters read. ** stop reading when buffer is full or when EOF is encountered. */ size_t read_in_buf(char *buf, size_t size) { char *p = buf; size_t num_read; int c; if(size == 0) return 0; while((c = getchar()) != EOF) { *p++ = c; if(++num_read == size) break; } return num_read; } int stdin_tac(int outfd) { size_t buf_size = BUF_SIZE; char *buf; ssize_t num_read; size_t total_read, read_n; if((buf = (char *) malloc(buf_size)) == NULL) err_exit("malloc"); total_read = 0; read_n = buf_size; while((total_read += num_read = read_in_buf(buf+total_read, read_n)) , num_read == read_n) { if((buf = (char *) realloc(buf, buf_size *= 2)) == NULL) err_exit("realloc"); read_n = buf_size - total_read; } if(num_read == -1) err_exit("read(stdin)"); return rev_write_lines(outfd, buf, total_read, 1); } int tac(int infd, int outfd) { char *buf; size_t buf_size = BUF_SIZE, bytes_left; off_t offset, seek_by; ssize_t num_read = 0; int chars_left_in_line = 0; if((buf = (char *) malloc(buf_size)) == NULL) err_exit("malloc"); offset = lseek(infd, 0, SEEK_END); seek_by = -buf_size; /* loop until we try to seek before the start of file */ while(offset + seek_by &gt;= 0) { if((offset = lseek(infd, seek_by, SEEK_CUR)) == -1) err_exit("lseek(SEEK_CUR)"); if((num_read = read(infd, buf, buf_size)) != buf_size) if(num_read == -1) err_exit("read(infd)"); chars_left_in_line = rev_write_lines( outfd, buf, num_read, 0); if( chars_left_in_line == num_read) { /* ** buffer is too small to hold this entire line. ** realloc a larger buffer, and (inneficiently) re-read ** the current chunk that we just read in the next iteration. */ if((buf = (char *) realloc(buf, buf_size *= 2 )) == NULL) err_exit("realloc"); seek_by = -buf_size; } else seek_by = -2*buf_size + chars_left_in_line; } bytes_left = offset + chars_left_in_line; if((offset = lseek(infd, 0, SEEK_SET)) == -1) err_exit("lseek(SEEK_START)"); if((num_read = read(infd, buf, bytes_left)) != bytes_left) err_exit("read"); return rev_write_lines( outfd, buf, num_read, 1); } int main(int argc, char **argv) { int infd, outfd; if(argc == 1) return stdin_tac(STDOUT_FILENO); if((infd = open(argv[1], O_RDONLY)) == -1) err_exit("open infd"); if(argc == 2) return tac(infd, STDOUT_FILENO); if((outfd = open(argv[2], O_CREAT | O_WRONLY, S_IRWXU)) == -1) err_exit("open outfd"); return tac(infd, outfd); } </code></pre> <p>A concession I made is that, on occasion, it is acceptable (though inefficient) to re-read characters that have already been read. For instance, when the buffer overflows in the middle of a line, we re-read the end of the line into a larger buffer as we attempt to read the rest of the line. An alternative would be to copy the incomplete line to the end of the buffer, and read this many less characters. I found that this solution was significantly more complicated to implement, for a negligible performance gain.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-01T16:12:14.430", "Id": "380959", "Score": "2", "body": "You are forcing the read of the whole file into memory. You could quite easily get the size of the whole file and pre-allocate the buffer. Or you can use some of the file system ...
[ { "body": "<p>Well, let's make a start with reviewing:</p>\n\n<ol>\n<li><p>You are assuming that all files the user might name are seekable, even though he might name the console, a socket, a pipe or just about anything else. Also, you assume <code>STDIN</code> is never a normal file.<br>\nSo, open files as req...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-01T14:13:26.750", "Id": "197601", "Score": "5", "Tags": [ "c", "file", "io" ], "Title": "Implementation of the `tac` command" }
197601
<p>Simple game where you control space shuttle with mouse click and try to avoid meteors moving in random speed toward you. There are some things I am still developing like rotation and menus, but wanted to get some tips/recommendations on what I have so far. </p> <p>Thank you in advance! </p> <pre><code># Import pygame and random import pygame import random # Initialize the game engine pygame.init() #Define colors WHITE = (255, 255, 255) # Define done done = False # Define function to create new meteor def create_meteor(): meteor = Meteor(WHITE, width, height) meteor_sprites_list.add(meteor) # Define player class class Player(pygame.sprite.Sprite): def __init__(self, filename, color, HW, HH): super().__init__() # Set height, width self.image = pygame.image.load("player.png").convert_alpha() # Set background color to transparent self.image.set_colorkey(color) # Make top-left corner the passed in locatin self.rect = pygame.rect.Rect((HW, HH), self.image.get_size()) # Gravity self.dy = 0 def ignite(self): self.dy = -400 def update(self, dt, screen): # Apply gravity self.dy = min(400, self.dy + 40) self.rect.y += self.dy * dt # What happens if go to border of screen if(self.rect.top &lt;= 0): #top self.rect.y = 0 self.dy = -4 elif(self.rect.bottom &gt;= height): #ground self.rect.y = (526-self.rect.height) #blit image to screen screen.blit(self.image, self.rect) # Define new clas for meteor class Meteor(pygame.sprite.Sprite): def __init__(self, color, width, height): # Takes in parameters for color, width (x position) , and height (y postion) # Call the parent class super().__init__() # Make list of image file location self.meteor_list = ["meteors/meteor1.png"] # Randomly select meteor from above list self.new_meteor = random.choice(self.meteor_list) # Load graphic that is in file folder self.image = pygame.image.load(self.new_meteor).convert_alpha() # Set background to transparent self.image.set_colorkey(color) # Fetch the rectangle object that has the dimensions of the image self.rect = self.image.get_rect() # Random starting location self.rect.x = random.randrange(width, (width + 300)) self.rect.y = random.randrange(0, height) # Random movement to the left self.change_x = random.randrange(-10,-5) self.change_y = random.randrange(-4,3) # Set angle for rotate attribute # ---- Attributes def reset_pos(self, screen): # List of meteors self.meteor_list = ["meteors/meteor1.png"] # Pick random meteor from above list self.new_meteor = random.choice(self.meteor_list) # Load graphic that is in file folder self.image = pygame.image.load(self.new_meteor).convert_alpha() # Set background to transparent self.image.set_colorkey(WHITE) # Fetch the rectangle object that has the dimensions of the image self.rect = self.image.get_rect() # Reset postion of bad block when they reach the bottom of the screen self.rect.x = random.randrange(width, (width +100)) self.rect.y = random.randrange(0, height) # Random movement to the left self.change_x = random.randrange(-10,-5) self.change_y = random.randrange(-4,3) # What meteor does each cycle through def update(self): # Add rotation #pygame.transform.rotate(self.image, 115) # Move bad block down 3 at a time self.rect.x += self.change_x self.rect.y += self.change_y #blit image to screen screen.blit(self.image, self.rect) # Reset if falls off screen if self.rect.right &lt; 0: self.reset_pos(screen) if self.rect.top &gt; height: self.reset_pos(screen) if self.rect.bottom &lt; 0: self.reset_pos(screen) # Class to show the how far rocketship has travelled class Distance(pygame.sprite.Sprite): def __init__(self): # Call the parent class super().__init__() # Get time since init was called time = pygame.time.get_ticks() # Convert milliseconds to seconds, 1 second = 1 km travel_distance = round(time/1000, 2) # Format the font to be used font = pygame.font.SysFont ("transistor", 25, True, False) # Create text to be displayed text = font.render("You've travelled " + str(travel_distance) + " kms", True, WHITE) # Center text text_rect = text.get_rect(center=(HW, HH)) # Blit text to the screen screen.blit(text, text_rect) # Used to manage how fast the screen updates clock = pygame.time.Clock() background_size = pygame.image.load("background.png") # Get dimensions of background width = background_size.get_width() height = background_size.get_height() HW, HH = width/2, height/2 size = (width, height) screen = pygame.display.set_mode(size) x = 0 # Load image for star background background = pygame.image.load("background.png").convert() # Seperate becuase error when placed before screen #Set caption pygame.display.set_caption("") # Creates a list of sprites. Each object in program is added to list. Managed by a class called "group" meteor_sprites_list = pygame.sprite.Group() # Create spaceship player = Player("player.png", WHITE, HW, HH) # Create meteor sprites on the screen for i in range(4): create_meteor() #-----Main Program Loop while not done: dt = clock.tick(30) # Main event Loop for event in pygame.event.get(): if event.type == pygame.QUIT: done = True if event.type == pygame.MOUSEBUTTONDOWN: player.ignite() #-----Game Logic # Draw background and move to the left rel_x = x % width screen.blit(background, (rel_x - width, 0)) if rel_x &lt; width: screen.blit(background, (rel_x, 0)) x -= 2 # Display text on screen Distance() # Update Sprites # Update meteor sprite meteor_sprites_list.update() # Update player sprite player.update(dt/1000. , screen) # Check to see if player has collided with meteor meteor_hit_list = pygame.sprite.spritecollide(player, meteor_sprites_list, True, pygame.sprite.collide_circle) # Event if player collides with meteor for item in meteor_hit_list: print("Shuttle hit") create_meteor() meteor_hit_list.remove(item) # Make into game over screen and display distance # Update the screen with what we've drawn. pygame.display.flip() # Make sure to quit pygame.quit() </code></pre>
[]
[ { "body": "<p>Good job! Here are my suggestions (roughly ordered from important to less important):</p>\n\n<p>Separate the game logic from the drawing/blitting code. That will make your main loop cleaner and the code will probably be easier to extend. So don't blit the sprite images in their <code>update</code>...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-01T15:27:09.867", "Id": "197603", "Score": "6", "Tags": [ "python", "pygame" ], "Title": "Flappy Bird Style Game in Space Setting" }
197603
<p>I tried to literally convert recursive algorithm taught <a href="https://www.geeksforgeeks.org/depth-first-search-or-dfs-for-a-graph/" rel="nofollow noreferrer">here</a> to iterative, by simulating the recursive stack exactly as much as possible.</p> <p>I have tested my code and it passed all test cases. </p> <p>Please let me know if any more improvements are possible.</p> <p>Here is my code:</p> <pre><code>public class Graph { private int tv; //total vertices private int te; //total edges private ArrayList&lt;ArrayList&lt;Integer&gt;&gt; adjacencyList; public Graph(int tv) { this.tv = tv; adjacencyList = new ArrayList&lt;ArrayList&lt;Integer&gt;&gt;(tv); for (int i = 0; i &lt; tv; i++) { adjacencyList.add(i, new ArrayList&lt;Integer&gt;()); } } //adds edge for undirected graph //s - source, d - destination public void addEdge(int s, int d) { //need to check s &amp; d are with in bounds adjacencyList.get(s).add(d); adjacencyList.get(d).add(s); te++; } public void dfsIterative() { boolean[] isVisited = new boolean[tv]; for (int v = 0; v &lt; tv; v++) { if (!isVisited[v]) { dfsIterativeUtil(v, isVisited); } } } //sv - start vertex private void dfsIterativeUtil(int sv, boolean[] isVisited) { class Node { int v; //vertex in a graph int i; //current index of v's adjacency list Node(int v, int i) { this.v = v; this.i = i; } } Deque&lt;Node&gt; stack = new LinkedList&lt;&gt;(); stack.push(new Node(sv, -1)); while (!stack.isEmpty()) { int cv = stack.peek().v; //cv - current vertex if (!isVisited[cv]) { System.out.print(cv + " "); isVisited[cv] = true; } ArrayList&lt;Integer&gt; cvAdjList = adjacencyList.get(cv); int ci = ++stack.peek().i; //ci - current index in cvAdjList if (ci&gt;=cvAdjList.size()) { stack.pop(); } else { int vtx = cvAdjList.get(ci); if (!isVisited[vtx]) { stack.push(new Node(vtx, -1)); } } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-01T18:16:56.487", "Id": "380976", "Score": "0", "body": "\"I tried few test cases and they passed. But I am unsure whether my algorithm is correct.\" Why? And what test cases did you try?" }, { "ContentLicense": "CC BY-SA 4.0",...
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-01T17:07:51.907", "Id": "197605", "Score": "2", "Tags": [ "java", "graph", "depth-first-search" ], "Title": "DFS logic to traverse a graph" }
197605
<p>I am a mathematician attempting to become proficient with C++. At the moment I am learning about data structures. I am now writing a queue data structure using linked list from scratch.</p> <p>I have tested my class that I wrote and everything seems to be working fine but I want to see if there are any bugs or some areas of the code I could improve on.</p> <p>Here is the class:</p> <pre><code>#ifndef Queue_h #define Queue_h template &lt;class T&gt; class Queue { private: struct Node { T data; Node* next = nullptr; }; Node* first = nullptr; Node* last = nullptr; // Used for destructor to delete elements void do_unchecked_pop(); // Use for debugging purposes and for overloading the &lt;&lt; operator void show(std::ostream &amp;str) const; public: // Constructors Queue() = default; // empty constructor Queue(Queue const&amp; value); // copy constructor // Rule of 5 Queue(Queue&amp;&amp; move) noexcept; // move constuctor Queue&amp; operator=(Queue&amp;&amp; move) noexcept; // move assignment operator ~Queue(); // destructor // Overload operators Queue&amp; operator=(Queue const&amp; rhs); friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; str, Queue&lt;T&gt; const&amp; data) { data.show(str); return str; } // Member functions bool empty() const {return first == nullptr;} int size() const; T&amp; front() const; T&amp; back() const; void push(const T&amp; theData); void push(T&amp;&amp; theData); void pop(); void swap(Queue&amp; other) noexcept; }; template &lt;class T&gt; Queue&lt;T&gt;::Queue(Queue&lt;T&gt; const&amp; value) { try { for(auto loop = value.first; loop != nullptr; loop = loop-&gt;next) push(loop-&gt;data); } catch (...) { while(first != nullptr) do_unchecked_pop(); throw; } } template &lt;class T&gt; Queue&lt;T&gt;::Queue(Queue&amp;&amp; move) noexcept { move.swap(*this); } template &lt;class T&gt; Queue&lt;T&gt;&amp; Queue&lt;T&gt;::operator=(Queue&lt;T&gt; &amp;&amp;move) noexcept { move.swap(*this); return *this; } template &lt;class T&gt; Queue&lt;T&gt;::~Queue() { while(first != nullptr) { do_unchecked_pop(); } } template &lt;class T&gt; int Queue&lt;T&gt;::size() const { int size = 0; for (auto current = first; current != nullptr; current = current-&gt;next) size++; return size; } template &lt;class T&gt; T&amp; Queue&lt;T&gt;::front() const { if(first == nullptr) { throw std::out_of_range("the Queue is empty!"); } return first-&gt;data; } template &lt;class T&gt; T&amp; Queue&lt;T&gt;::back() const { return last-&gt;data; } template &lt;class T&gt; void Queue&lt;T&gt;::push(const T&amp; theData) { Node* newNode = new Node; newNode-&gt;data = theData; newNode-&gt;next = nullptr; if(first == nullptr) { first = last = newNode; } else { last-&gt;next = newNode; last = newNode; } } template &lt;class T&gt; void Queue&lt;T&gt;::push(T&amp;&amp; theData) { Node* newNode = new Node; newNode-&gt;data = std::move(theData); newNode-&gt;next = nullptr; if(first == nullptr) { first = last = newNode; } else { last-&gt;next = newNode; last = newNode; } } template &lt;class T&gt; void Queue&lt;T&gt;::pop() { if(first == nullptr) { throw std::invalid_argument("the Queue is empty!"); } do_unchecked_pop(); } template &lt;class T&gt; void Queue&lt;T&gt;::do_unchecked_pop() { Node* tmp = first-&gt;next; delete tmp; first = tmp; } template &lt;class T&gt; void Queue&lt;T&gt;::show(std::ostream &amp;str) const { for(Node* loop = first; loop != nullptr; loop = loop-&gt;next) { str &lt;&lt; loop-&gt;data &lt;&lt; "\t"; } str &lt;&lt; "\n"; } template &lt;class T&gt; void Queue&lt;T&gt;::swap(Queue&lt;T&gt; &amp;other) noexcept { using std::swap; swap(first, other.first); swap(last, other.last); } // Free function template &lt;typename T&gt; void swap(Queue&lt;T&gt;&amp; a, Queue&lt;T&gt;&amp; b) noexcept { a.swap(b); } #endif /* Queue_h */ </code></pre> <p>Here is the main.cpp that tests the latter class:</p> <pre><code>#include &lt;algorithm&gt; #include &lt;cassert&gt; #include &lt;iostream&gt; #include &lt;ostream&gt; #include &lt;iosfwd&gt; #include "Queue.h" int main(int argc, const char * argv[]) { /////////////////////////////////////////////////////////////////////////////////// ///////////////////////////// Queue Using Linked List ////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// Queue&lt;int&gt; obj; obj.push(2); obj.push(4); obj.push(6); obj.push(8); obj.push(10); std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout&lt;&lt;"---------------Displaying Queue Contents---------------"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout &lt;&lt; obj &lt;&lt; std::endl; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout&lt;&lt;"---------------Pop Queue Element -------------------"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; obj.pop(); std::cout &lt;&lt; obj &lt;&lt; std::endl; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout&lt;&lt;"---------------Get the size of Queue -------------------"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout &lt;&lt; obj.size() &lt;&lt; std::endl; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout&lt;&lt;"---------------Print top element --------------------"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout &lt;&lt; obj.front() &lt;&lt; std::endl; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout&lt;&lt;"---------------Print last element --------------------"; std::cout&lt;&lt;"\n--------------------------------------------------\n"; std::cout &lt;&lt; obj.back() &lt;&lt; std::endl; return 0; } </code></pre>
[]
[ { "body": "<p>There is a check missing in your <code>back()</code> function (If the queue is empty you have an error). </p>\n\n<p>It would increase readability if you would use <code>empty()</code> instead of repeated <code>top == nullptr</code> checks. The intent is more obvious that way.</p>\n\n<p>Your <code...
{ "AcceptedAnswerId": "197615", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-01T18:07:39.017", "Id": "197607", "Score": "1", "Tags": [ "c++", "queue" ], "Title": "Generic Queue data structure in C++" }
197607
<p>I made a simple Hearthstone fatigue calculator. For those who don't know, <a href="https://en.wikipedia.org/wiki/Hearthstone" rel="nofollow noreferrer">Hearthstone</a> is a card game in which every turn you draw a card from your deck. Once you're out of cards, you start taking <em>fatigue damage</em>, getting 1 more damage each turn. The total damage dealt in X turns is known as the Triangular Number Sequence: 1 (1), 3 (1+2), 6 (1+2+3), 10 (1+2+3+4). For example, at turn 4 the fatigue damage has already dealt 10 dmg (1+2+3+4). This could be used for some decks that make you run out of cards, to calculate how much damage they need to kill the opponent or to just calculate how much damage X fatigue turns will do.</p> <p>I just wanted to know how my code looks. I know it's a very simple program but I might be doing something wrong and I guess it's better to know as early as possible. Besides, code reviewing a long project is just too boring for everyone. I've been learning by myself and as nobody ever reads my code I might be doing terrible things without knowing it haha</p> <pre><code>def error(): print("Whoops, something went wrong. Please try again.") def calc_mode(t, s): d = 0 for i in range(s, t+s): d = d + i return d def lethal_mode(d_input, s): d_calc = 0 i = 1 t = 0 while d_calc &lt; d_input: d_calc = d_calc + i i += 1 t += 1 return t while True: # Checks if the mode input is valid try: mode = int(input("\nMODES: " "\n* '1' to get the turns needed for X damage " "\n* '2' to get the damage dealt in X turns " "\nPlease type to select your mode: ")) except ValueError: error() continue else: while True: if mode == 1: # Checks if the input after the mode is valid while True: try: damageInput = int(input("\nPlease input the damage needed for lethal: ")) startInput = int(input("Starting at how much damage? (default is 1): ")) except ValueError: error() continue else: print("\n&gt;&gt; You will need %d fatigue turns for that sweet lethal" % lethal_mode(damageInput, startInput)) continue if mode == 2: while True: try: turnsInput = int(input("\nPlease input how many fatigue turns: ")) startInput = int(input("Starting at how much damage? (default is 1): ")) except ValueError: error() continue else: print("\n&gt;&gt; It will deal %d damage" % calc_mode(turnsInput, startInput)) continue else: error() break </code></pre> <p>What do you think overall? Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-01T20:14:04.973", "Id": "380983", "Score": "2", "body": "What's your Python version?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-01T21:33:03.700", "Id": "380987", "Score": "1", "body": "It's...
[ { "body": "<h1>The math</h1>\n\n<p>There is a useful formula for <a href=\"https://en.wikipedia.org/wiki/Triangular_number\" rel=\"nofollow noreferrer\">triangle numbers</a> that vastly simplifies a lot of the code here:</p>\n\n<p>$$\\sum_{k=1}^n k = \\frac{n(n+1)}{2}$$</p>\n\n<p>So for instance, the first tria...
{ "AcceptedAnswerId": "197618", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-01T18:20:35.727", "Id": "197608", "Score": "5", "Tags": [ "python", "python-3.x" ], "Title": "Hearthstone fatigue calculator" }
197608
<p>In my Spring MVC app I have <code>User</code> and <code>Role</code> entities.</p> <p><code>User</code>:</p> <pre><code>public class User { private Long id; private Set&lt;Role&gt; roles; // other fields, getters and setters } </code></pre> <p><code>Role</code>:</p> <pre><code>public class Role { private Long id; // other fields, getters and setters } </code></pre> <p>I have a service method with the following signature:</p> <pre><code>@Transactional void setRolesByUserId(Map&lt;Long, Set&lt;Long&gt;&gt; rolesByUserId) </code></pre> <p>The key of the <code>Map</code> is a <code>User</code> ID and the corresponding value is a <code>Set</code> of <code>Role</code> IDs that needs to be assigned to the user.</p> <p>My implementation:</p> <pre><code>public void setRolesByUserId(Map&lt;Long, Set&lt;Long&gt;&gt; rolesByUserId) { // 1. Map&lt;Long, Role&gt; roles = roleRepository.findAll() .stream().collect(Collectors.toMap(Role::getId, Function.identity())); // 2. userRepository.findAllById(rolesByUserId.keySet()) // 3. .forEach(user -&gt; user.setRoles(rolesByUserId.get(user.getId()) .stream().map(roles::get).collect(Collectors.toSet()))); } </code></pre> <p>So basically the flow is the following:</p> <ol> <li>fetch all the <code>Role</code> entities from the DB into a <code>Map&lt;Long, Role&gt;</code> (where the key is the <code>Role</code> ID and the value is the <code>Role</code> entity itself)</li> <li>fetch the <code>User</code> entities from the DB that needs to be modified</li> <li>for each <code>User</code>, iterate through the <code>Role</code> IDs to be assigned, fetch the corresponding <code>Role</code> entities from the <code>Map</code>, collect them into a <code>Set</code> and assign it to the <code>User</code></li> </ol> <p>Can this method be optimized?</p>
[]
[ { "body": "<p>Well, you created a good code so far. Your lamda is OK. But there are some things about naming which could be improved</p>\n\n<ol>\n<li>About the API <code>setRolesByUserId</code>, it is OK to accept userId as long. But about role, it could be better to change the Set to Set, and i think you're ab...
{ "AcceptedAnswerId": "197633", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-01T19:05:42.047", "Id": "197610", "Score": "2", "Tags": [ "java", "hibernate", "authorization", "jpa" ], "Title": "JPA method to update roles for users" }
197610
<p>I am trying to solve a puzzle in a performant way. This is <a href="https://www.codewars.com/kata/insane-coloured-triangles" rel="nofollow noreferrer">the puzzle</a>.</p> <p>Simply explained: you have a String and you must reduce it to one character with the given rules. This is the solution to the <a href="https://www.codewars.com/kata/coloured-triangles" rel="nofollow noreferrer">simple</a> variant. </p> <pre><code>COLORS = set("RGB") def triangle(row): while len(row) &gt; 1: row = ''.join(a if a == b else (COLORS-{a, b}).pop() for a, b in zip(row, row[1:])) return row </code></pre> <p>In the harder variant the task is to do the same, but performance is asked. I thought adding a dictionary and "remembering" already solved words would boost the performance. But actualy it is not performing faster than the simple variation. Is there a way to boost one of my codes? Do I have an efficiency lack in my code? Is there maybe a efficiency lack in the algorithm?</p> <pre><code>COLORS = set("RGB") mapping_simple = {} def triangle_simple(row): result = [''] while True: if len(row) == 1: result[0] = row return result[0] if row in mapping_simple: result[0] = mapping_simple[row][0] return result[0] mapping_simple[row] = result row = ''.join(a if a == b else (COLORS-{a, b}).pop() for a, b in zip(row, row[1:])) return result[0] </code></pre>
[]
[ { "body": "<h1>string conversion</h1>\n\n<p>You convert the row to a string at each iteration, there is no need for that. You can shave off a few µs by using a tuple</p>\n\n<pre><code>def triangle_tuple(row):\n while len(row) &gt; 1:\n row = tuple(a if a == b else (COLORS-{a, b}).pop() for a, b in zip...
{ "AcceptedAnswerId": "197642", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-01T20:58:51.683", "Id": "197612", "Score": "12", "Tags": [ "python", "performance", "strings", "programming-challenge", "hash-map" ], "Title": "Codewars: Reduce strings to one character" }
197612
<p>I was told my QT Project file is a hot mess. I'm returning to C++ after many years of doing Java and I'm really new to QT. I would like someone familiar with QT Project files to give my code a once over and provide a critique with suggestions for improvement. I have to use <code>install_name_tool</code> to set <code>@rpath</code> after I build in QT Creator. That was not fun finding a solution there but that's when I was told my project file is a mess. I started modifying a file from another altcoin to be by own new coin. It seems that no one has kept up with the os-x builds, core or QT (GUI). Please do a code review of my project file.</p> <pre><code># QT Project File TEMPLATE = app TARGET = cybill-wallet macx:TARGET = "cybill-wallet" VERSION = 0.1.0 INCLUDEPATH += src src/json src/qt DEFINES += QT_GUI BOOST_THREAD_USE_LIB BOOST_SPIRIT_THREADSAFE CONFIG += no_include_pwd CONFIG += thread CONFIG += static QT += core gui network greaterThan(QT_MAJOR_VERSION, 4) { QT += widgets } # for boost &gt; 1.37, add -mt to the boost libraries # use: qmake BOOST_LIB_SUFFIX=-mt # for boost thread win32 with _win32 sufix # use: BOOST_THREAD_LIB_SUFFIX=_win32-... # when linking against a specific BerkelyDB version: BDB_LIB_SUFFIX=-4.8 # Dependency library locations can be customized using following settings # winbuild dependencies win32 { # BOOST_LIB_SUFFIX=-mgw49-mt-s-1_58 BOOST_INCLUDE_PATH=$$DEPSDIR/boost_1_58_0 BOOST_LIB_PATH=$$DEPSDIR/boost_1_58_0/stage/lib BDB_INCLUDE_PATH=$$DEPSDIR/db-4.8.30.NC/build_unix BDB_LIB_PATH=$$DEPSDIR/db-4.8.30.NC/build_unix OPENSSL_INCLUDE_PATH=$$DEPSDIR/openssl-1.0.2j/include OPENSSL_LIB_PATH=$$DEPSDIR/openssl-1.0.2j MINIUPNPC_INCLUDE_PATH=$$DEPSDIR/miniupnpc MINIUPNPC_LIB_PATH=$$DEPSDIR/miniupnpc QRENCODE_INCLUDE_PATH=$$DEPSDIR/qrencode-3.4.3 QRENCODE_LIB_PATH=$$DEPSDIR/qrencode-3.4.3/.libs GMP_INCLUDE_PATH=$$DEPSDIR/gmp-6.0.0 GMP_LIB_PATH=$$DEPSDIR/gmp-6.0.0/.libs } OBJECTS_DIR = build MOC_DIR = build UI_DIR = build # use: qmake "RELEASE=1" contains(RELEASE, 1) { # Mac: compile for maximum compatibility (10.5, 64-bit) macx:QMAKE_CXXFLAGS += -mmacosx-version-min=10.5 -arch x86_64 - isysroot $(xcode-select --print-path)/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.5.sdk !windows:!macx { # Linux: static link LIBS += -Wl,-Bstatic } } !win32 { # for extra security against potential buffer overflows: enable GCCs Stack Smashing Protection QMAKE_CXXFLAGS *= -fstack-protector-all --param ssp-buffer-size=1 QMAKE_LFLAGS *= -fstack-protector-all --param ssp-buffer-size=1 # We need to exclude this for Windows cross compile with MinGW 4.2.x, as it will result in a non-working executable! # This can be enabled for Windows, when we switch to MinGW &gt;= 4.4.x. } # for extra security on Windows: enable ASLR and DEP via GCC linker flags #win32:QMAKE_LFLAGS *= -Wl,--dynamicbase -Wl,--nxcompat -Wl,--large- address-aware -static win32:QMAKE_LFLAGS *= -Wl,--dynamicbase -Wl,--nxcompat -static win32:QMAKE_LFLAGS += -static-libgcc -static-libstdc++ # use: qmake "USE_QRCODE=1" # libqrencode (http://fukuchi.org/works/qrencode/index.en.html) must be installed for support contains(USE_QRCODE, 1) { message(Building with QRCode support) DEFINES += USE_QRCODE LIBS += -lqrencode } # use: qmake "USE_UPNP=1" ( enabled by default; default) # or: qmake "USE_UPNP=0" (disabled by default) # or: qmake "USE_UPNP=-" (not supported) # miniupnpc (http://miniupnp.free.fr/files/) must be installed for support contains(USE_UPNP, -) { message(Building without UPNP support) } else { message(Building with UPNP support) count(USE_UPNP, 0) { USE_UPNP=1 } DEFINES += USE_UPNP=$$USE_UPNP STATICLIB INCLUDEPATH += $$MINIUPNPC_INCLUDE_PATH LIBS += $$join(MINIUPNPC_LIB_PATH,,-L,) -lminiupnpc win32:LIBS += -liphlpapi } # use: qmake "USE_DBUS=1" contains(USE_DBUS, 1) { message(Building with DBUS (Freedesktop notifications) support) DEFINES += USE_DBUS QT += dbus } # use: qmake "USE_IPV6=1" ( enabled by default; default) # or: qmake "USE_IPV6=0" (disabled by default) # or: qmake "USE_IPV6=-" (not supported) contains(USE_IPV6, -) { message(Building without IPv6 support) } else { message(Building with IPv6 support) count(USE_IPV6, 0) { USE_IPV6=1 } DEFINES += USE_IPV6=$$USE_IPV6 } contains(BITCOIN_NEED_QT_PLUGINS, 1) { DEFINES += BITCOIN_NEED_QT_PLUGINS QTPLUGIN += qcncodecs qjpcodecs qtwcodecs qkrcodecs qtaccessiblewidgets } INCLUDEPATH += src/leveldb/include src/leveldb/helpers LIBS += $$PWD/src/leveldb/libleveldb.a $$PWD/src/leveldb/libmemenv.a SOURCES += src/txdb.cpp \ src/qt/magi.cpp \ src/qt/magiaddressvalidator.cpp \ src/qt/magiamountfield.cpp \ src/qt/magigui.cpp \ src/qt/magistrings.cpp \ src/qt/magiunits.cpp \ src/magirpc.cpp \ src/clientversion.cpp \ src/qt/utilitydialog.cpp !win32 { # we use QMAKE_CXXFLAGS_RELEASE even without RELEASE=1 because we use RELEASE to indicate linking preferences not -O preferences genleveldb.commands = cd $$PWD/src/leveldb &amp;&amp; CC=$$QMAKE_CC CXX=$$QMAKE_CXX $(MAKE) OPT=\"$$QMAKE_CXXFLAGS $$QMAKE_CXXFLAGS_RELEASE\" libleveldb.a libmemenv.a } else { # make an educated guess about what the ranlib command is called isEmpty(QMAKE_RANLIB) { QMAKE_RANLIB = $$replace(QMAKE_STRIP, strip, ranlib) } LIBS += -lshlwapi genleveldb.commands = cd $$PWD/src/leveldb &amp;&amp; CC=$$QMAKE_CC CXX=$$QMAKE_CXX TARGET_OS=OS_WINDOWS_CROSSCOMPILE $(MAKE) OPT=\"$$QMAKE_CXXFLAGS $$QMAKE_CXXFLAGS_RELEASE\" libleveldb.a libmemenv.a &amp;&amp; $$QMAKE_RANLIB $$PWD/src/leveldb/libleveldb.a &amp;&amp; $$QMAKE_RANLIB $$PWD/src/leveldb/libmemenv.a } genleveldb.target = $$PWD/src/leveldb/libleveldb.a genleveldb.depends = FORCE PRE_TARGETDEPS += $$PWD/src/leveldb/libleveldb.a QMAKE_EXTRA_TARGETS += genleveldb # Gross ugly hack that depends on qmake internals, unfortunately there is no other way to do it. QMAKE_CLEAN += $$PWD/src/leveldb/libleveldb.a; cd $$PWD/src/leveldb ; $(MAKE) clean # regenerate src/build.h !windows|contains(USE_BUILD_INFO, 1) { genbuild.depends = FORCE genbuild.commands = cd $$PWD; /bin/sh share/genbuild.sh $$OUT_PWD/build/build.h genbuild.target = $$OUT_PWD/build/build.h PRE_TARGETDEPS += $$OUT_PWD/build/build.h QMAKE_EXTRA_TARGETS += genbuild DEFINES += HAVE_BUILD_INFO } # If we have an ARM device, we can't use SSE2 instructions, so don't try to use them QMAKE_XCPUARCH = $$QMAKE_HOST.arch equals(QMAKE_XCPUARCH, armv7l) { message(Building without SSE2 support) } else:equals(QMAKE_XCPUARCH, armv6l) { message(Building without SSE2 support) } else { message(Building with SSE2 support) QMAKE_CXXFLAGS += -msse2 QMAKE_CFLAGS += -msse2 } #endif QMAKE_CXXFLAGS_WARN_ON = -fdiagnostics-show-option -Wall -Wextra - Wformat -Wformat-security -Wno-unused-parameter -Wstack-protector # Input DEPENDPATH += src src/json src/qt HEADERS += \ src/qt/transactiontablemodel.h \ src/qt/addresstablemodel.h \ src/qt/optionsdialog.h \ src/qt/coincontroldialog.h \ src/qt/coincontroltreewidget.h \ src/qt/sendcoinsdialog.h \ src/qt/addressbookpage.h \ src/qt/signverifymessagedialog.h \ src/qt/editaddressdialog.h \ src/alert.h \ src/addrman.h \ src/base58.h \ src/bignum.h \ src/checkpoints.h \ src/compat.h \ src/coincontrol.h \ src/sync.h \ src/util.h \ src/hash.h \ src/uint256.h \ src/kernel.h \ src/scrypt_mine.h \ src/pbkdf2.h \ src/serialize.h \ src/strlcpy.h \ src/main.h \ src/net.h \ src/key.h \ src/db.h \ src/txdb.h \ src/walletdb.h \ src/script.h \ src/init.h \ src/mruset.h \ src/magimath.h \ src/json/json_spirit_writer_template.h \ src/json/json_spirit_writer.h \ src/json/json_spirit_value.h \ src/json/json_spirit_utils.h \ src/json/json_spirit_stream_reader.h \ src/json/json_spirit_reader_template.h \ src/json/json_spirit_reader.h \ src/json/json_spirit_error_position.h \ src/json/json_spirit.h \ src/qt/clientmodel.h \ src/qt/guiutil.h \ src/qt/transactionrecord.h \ src/qt/guiconstants.h \ src/qt/optionsmodel.h \ src/qt/monitoreddatamapper.h \ src/qt/transactiondesc.h \ src/qt/transactiondescdialog.h \ src/qt/updatecheck.h \ src/wallet.h \ src/keystore.h \ src/qt/transactionfilterproxy.h \ src/qt/transactionview.h \ src/qt/walletmodel.h \ src/qt/overviewpage.h \ src/qt/csvmodelwriter.h \ src/crypter.h \ src/qt/sendcoinsentry.h \ src/qt/qvalidatedlineedit.h \ src/qt/qvaluecombobox.h \ src/qt/askpassphrasedialog.h \ src/protocol.h \ src/qt/notificator.h \ src/qt/qtipcserver.h \ src/allocators.h \ src/ui_interface.h \ src/qt/console.h \ src/qt/rpcconsole.h \ src/version.h \ src/netbase.h \ src/clientversion.h \ src/hash_magi.h \ src/hash/sph_types.h \ src/hash/sph_keccak.h \ src/hash/sph_haval.h \ src/hash/sph_ripemd.h \ src/hash/sph_sha2.h \ src/hash/sph_tiger.h \ src/hash/sph_whirlpool.h \ src/qt/magiaddressvalidator.h \ src/qt/magiamountfield.h \ src/qt/magigui.h \ src/qt/magiunits.h \ src/magirpc.h \ src/qt/utilitydialog.h SOURCES += \ src/qt/transactiontablemodel.cpp \ src/qt/addresstablemodel.cpp \ src/qt/optionsdialog.cpp \ src/qt/sendcoinsdialog.cpp \ src/qt/coincontroldialog.cpp \ src/qt/coincontroltreewidget.cpp \ src/qt/addressbookpage.cpp \ src/qt/signverifymessagedialog.cpp \ src/qt/editaddressdialog.cpp \ src/alert.cpp \ src/sync.cpp \ src/util.cpp \ src/hash.cpp \ src/netbase.cpp \ src/key.cpp \ src/script.cpp \ src/main.cpp \ src/init.cpp \ src/net.cpp \ src/checkpoints.cpp \ src/addrman.cpp \ src/db.cpp \ src/walletdb.cpp \ src/magimath.cpp \ src/qt/clientmodel.cpp \ src/qt/guiutil.cpp \ src/qt/transactionrecord.cpp \ src/qt/optionsmodel.cpp \ src/qt/monitoreddatamapper.cpp \ src/qt/transactiondesc.cpp \ src/qt/transactiondescdialog.cpp \ src/qt/updatecheck.cpp \ src/wallet.cpp \ src/keystore.cpp \ src/qt/transactionfilterproxy.cpp \ src/qt/transactionview.cpp \ src/qt/walletmodel.cpp \ src/rpcdump.cpp \ src/rpcnet.cpp \ src/rpcmining.cpp \ src/rpcwallet.cpp \ src/rpcblockchain.cpp \ src/rpcrawtransaction.cpp \ src/qt/overviewpage.cpp \ src/qt/csvmodelwriter.cpp \ src/crypter.cpp \ src/qt/sendcoinsentry.cpp \ src/qt/qvalidatedlineedit.cpp \ src/qt/qvaluecombobox.cpp \ src/qt/askpassphrasedialog.cpp \ src/protocol.cpp \ src/qt/notificator.cpp \ src/qt/qtipcserver.cpp \ src/qt/console.cpp \ src/qt/rpcconsole.cpp \ src/noui.cpp \ src/kernel.cpp \ src/pbkdf2.cpp \ src/hash/keccak.cpp \ src/hash/haval.cpp \ src/hash/ripemd.cpp \ src/hash/sha2.cpp \ src/hash/sha2big.cpp \ src/hash/tiger.cpp \ src/hash/whirlpool.cpp RESOURCES += \ src/qt/magi.qrc FORMS += \ src/qt/forms/coincontroldialog.ui \ src/qt/forms/sendcoinsdialog.ui \ src/qt/forms/addressbookpage.ui \ src/qt/forms/signverifymessagedialog.ui \ src/qt/forms/editaddressdialog.ui \ src/qt/forms/transactiondescdialog.ui \ src/qt/forms/overviewpage.ui \ src/qt/forms/sendcoinsentry.ui \ src/qt/forms/askpassphrasedialog.ui \ src/qt/forms/rpcconsole.ui \ src/qt/forms/optionsdialog.ui \ src/qt/forms/console.ui \ src/qt/forms/helpmessagedialog.ui contains(USE_QRCODE, 1) { HEADERS += src/qt/qrcodedialog.h SOURCES += src/qt/qrcodedialog.cpp FORMS += src/qt/forms/qrcodedialog.ui } contains(BITCOIN_QT_TEST, 1) { SOURCES += src/qt/test/test_main.cpp \ src/qt/test/uritests.cpp HEADERS += src/qt/test/uritests.h DEPENDPATH += src/qt/test QT += testlib TARGET = m-wallet_test DEFINES += BITCOIN_QT_TEST } CODECFORTR = UTF-8 # for lrelease/lupdate # also add new translations to src/qt/magi.qrc under translations/ TRANSLATIONS = $$files(src/qt/locale/bitcoin_*.ts) isEmpty(QMAKE_LRELEASE) { win32:QMAKE_LRELEASE = $$[QT_INSTALL_BINS]\\lrelease.exe else:QMAKE_LRELEASE = $$[QT_INSTALL_BINS]/lrelease } isEmpty(QM_DIR):QM_DIR = $$PWD/src/qt/locale # automatically build translations, so they can be included in resource file TSQM.name = lrelease ${QMAKE_FILE_IN} TSQM.input = TRANSLATIONS TSQM.output = $$QM_DIR/${QMAKE_FILE_BASE}.qm TSQM.commands = $$QMAKE_LRELEASE ${QMAKE_FILE_IN} -qm ${QMAKE_FILE_OUT} TSQM.CONFIG = no_link QMAKE_EXTRA_COMPILERS += TSQM # "Other files" to show in Qt Creator OTHER_FILES += README.md \ doc/*.rst \ doc/*.txt doc/README \ src/qt/res/magi-qt.rc \ src/test/*.cpp \ src/test/*.h \ src/qt/test/*.cpp \ src/qt/test/*.h # platform specific defaults, if not overridden on command line isEmpty(BOOST_LIB_SUFFIX) { macx:BOOST_LIB_SUFFIX = -mt windows:BOOST_LIB_SUFFIX = -mgw49-mt-s-1_58 } isEmpty(BOOST_THREAD_LIB_SUFFIX) { BOOST_THREAD_LIB_SUFFIX = $$BOOST_LIB_SUFFIX } isEmpty(BDB_LIB_PATH) { macx:BDB_LIB_PATH = /opt/local/lib/db48 } isEmpty(BDB_LIB_SUFFIX) { macx:BDB_LIB_SUFFIX = -4.8 } isEmpty(BDB_INCLUDE_PATH) { macx:BDB_INCLUDE_PATH = /opt/local/include/db48 } isEmpty(BOOST_LIB_PATH) { macx:BOOST_LIB_PATH = /usr/local/Cellar/boost@1.57/1.57.0/lib } isEmpty(BOOST_INCLUDE_PATH) { macx:BOOST_INCLUDE_PATH = /opt/local/include } windows:DEFINES += WIN32 windows:RC_FILE = src/qt/res/magi-qt.rc windows:!contains(MINGW_THREAD_BUGFIX, 0) { # At least qmake's win32-g++-cross profile is missing the -lmingwthrd # thread-safety flag. GCC has -mthreads to enable this, but it doesn't # work with static linking. -lmingwthrd must come BEFORE -lmingw, so # it is prepended to QMAKE_LIBS_QT_ENTRY. # It can be turned off with MINGW_THREAD_BUGFIX=0, just in case it causes # any problems on some untested qmake profile now or in the future. DEFINES += _MT QMAKE_LIBS_QT_ENTRY = -lmingwthrd $$QMAKE_LIBS_QT_ENTRY } !windows:!macx { DEFINES += LINUX LIBS += -lrt } ############################################ # MAC OS-X Specific ############################################ macx:CFLAGS += -stdlib=libc++ - rpath=/usr/local/Cellar/qt/5.11.1/lib/QtWidgets.framework/Versions/5/QtWidgets macx:INCLUDEPATH += /usr/local/Cellar/miniupnpc/2.1/include /usr/local/Cellar/boost@1.57/1.57.0/include /usr/local/Cellar/openssl/1.0.2o_2/include /usr/local/Cellar/gmp/6.1.2_2/include /usr/local/Cellar/leveldb/1.20_2/include /usr/local/Cellar/berkeley- db@4/4.8.30/include macx:HEADERS += src/qt/macdockiconhandler.h src/qt/macnotificationhandler.h macx:OBJECTIVE_SOURCES += src/qt/macdockiconhandler.mm src/qt/macnotificationhandler.mm macx:LIBS += -framework Foundation -framework ApplicationServices -framework AppKit -framework CoreServices macx:DEFINES += MAC_OSX MSG_NOSIGNAL=0 macx:ICON = src/qt/res/icons/cybill.icns macx:CONFIG += -std=c++11 macx:QMAKE_CFLAGS_THREAD += -pthread -stdlib=libc++ macx:QMAKE_LFLAGS_THREAD += -pthread macx:QMAKE_CXXFLAGS_THREAD += -pthread -stdlib=libc++ -std=c++11 macx:MINIUPNPC_LIB_PATH = /usr/local/Cellar/miniupnpc/2.1/lib macx:LIBS += $$join(MINIUPNPC_LIB_PATH,,-L,) -lminiupnpc macx:GMP_LIB_PATH = /usr/local/Cellar/gmp/6.1.2_2/lib macx:LIBS += $$join(GMP_LIB_PATH,,-L,) -lgmp macx:OPENSSL_LIB_PATH = /usr/local/Cellar/openssl/1.0.2o_2/lib macx:LIBS += $$join(OPENSSL_LIB_PATH,,-L,) -lssl macx:BOOST_LIB_PATH = /usr/local/Cellar/boost@1.57/1.57.0/lib macx:LIBS += $$join(BOOST_LIB_PATH,,-L,) -lboost_system-mt macx:LIBS += $$join(BOOST_LIB_PATH,,-L,) -lboost_thread-mt # Set libraries and includes at end, to use platform-defined defaults if not overridden INCLUDEPATH += $$OPT_INCLUDE_PATH $$BOOST_INCLUDE_PATH $$BDB_INCLUDE_PATH $$OPENSSL_INCLUDE_PATH $$QRENCODE_INCLUDE_PATH $$GMP_INCLUDE_PATH LIBS += $$join(OPT_LIB_PATH,,-L,) $$join(BOOST_LIB_PATH,,-L,) $$join(BDB_LIB_PATH,,-L,) $$join(OPENSSL_LIB_PATH,,-L,) $$join(QRENCODE_LIB_PATH,,-L,) $$join(GMP_LIB_PATH,,-L,) LIBS += -lssl -lgmp -lcrypto -ldb_cxx$$BDB_LIB_SUFFIX LIBS += $$OPT_LIBS # -lgdi32 has to happen after -lcrypto (see #681) windows:LIBS += -lws2_32 -lshlwapi -lmswsock -lole32 -loleaut32 -luuid - lgdi32 LIBS += -lboost_system$$BOOST_LIB_SUFFIX - lboost_filesystem$$BOOST_LIB_SUFFIX - lboost_program_options$$BOOST_LIB_SUFFIX - lboost_thread$$BOOST_THREAD_LIB_SUFFIX windows:LIBS += -lboost_chrono$$BOOST_LIB_SUFFIX contains(RELEASE, 1) { !windows:!macx { # Linux: turn dynamic linking back on for c/c++ runtime libraries LIBS += -Wl,-Bdynamic } } system($$QMAKE_LRELEASE -silent $$TRANSLATIONS) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-04T14:11:00.090", "Id": "385007", "Score": "0", "body": "Since no one has attempted to do a code review, I'll do a quick review. The project file is messy, however it's because the focus has been to build the application for Mac OS-X. ...
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-01T20:59:22.560", "Id": "197613", "Score": "1", "Tags": [ "qt", "makefile", "macos" ], "Title": "Alt-Coin Wallet QT Project for Mac OS-X" }
197613
<blockquote> <p>Write a factorial function that takes a positive integer, N as a parameter and prints the result of N! (N factorial).</p> <p>Note: If you fail to use recursion or fail to name your recursive function factorial or Factorial, you will get a score of 0 .</p> </blockquote> <p>Here's my solution in C++:</p> <pre><code>#include &lt;iostream&gt; int factorial( int n ) { if(n&lt;=1) return 1 ; else{ return n * factorial (n-1) ; } } int main() { int n; std::cin &gt;&gt; n; std::cout &lt;&lt; factorial (n) ; } </code></pre> <p>Is there a more efficient solution to this problem?</p>
[]
[ { "body": "<p>Yes, there is a more efficient solution that still uses recursion; specifically, using <a href=\"https://en.m.wikipedia.org/wiki/Tail_call\" rel=\"nofollow noreferrer\">Tail Recursion</a>.</p>\n\n<p>When you <code>return n * factorial(n-1);</code>, the compiler can’t optimize the call away because...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-01T23:12:36.687", "Id": "197621", "Score": "1", "Tags": [ "c++", "programming-challenge", "recursion", "functional-programming" ], "Title": "Hackerrank Day 9: Recursion" }
197621
<p>I wrote an algorithm to solve this challenge but would love some feedback on its efficiency and, if you were an interviewer, what your opinion would be on my solution. I believe my time complexity is \$O(N)\$. Is this correct?</p> <p><strong>The Task:</strong></p> <blockquote> <p>Given a sorted array <em>nums</em>, remove the duplicates in-place such that each element appear only once and return the new length.</p> <p>Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.</p> <blockquote> <p><strong>Example:</strong> Given <em>nums</em> = [0,0,1,1,1,2,2,3,3,4]</p> <p>Your function should return length = 5, with the first five elements of <em>nums</em> being modified to 0, 1, 2, 3, and 4 respectively.</p> <p>It doesn't matter what values are set in the array beyond the returned length.</p> </blockquote> </blockquote> <p><strong>My Solution:</strong></p> <pre><code>def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ if(nums): IndFirstKind = IndCompare = 0 lengthArray = len(nums) while(IndCompare &lt; lengthArray): if nums[IndFirstKind] == nums[IndCompare]: IndCompare = IndCompare + 1 else: if(IndFirstKind + 1 != IndCompare): temp = nums[IndCompare] nums[IndCompare] = nums[IndFirstKind + 1] nums[IndFirstKind + 1]= temp IndFirstKind = IndFirstKind +1 IndCompare = IndCompare + 1 return IndFirstKind + 1 return 0 </code></pre>
[]
[ { "body": "<ul>\n<li><p>Flat is better than nested. Consider reverting the first <code>if</code> condition:</p>\n\n<pre><code>if not nums:\n return 0\n\n# main logic goes here, less one indentation level\n</code></pre></li>\n<li><p>An <code>if-else</code> as a body of the loop is always a red flag. In this c...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-01T23:17:54.380", "Id": "197622", "Score": "2", "Tags": [ "python", "performance", "programming-challenge", "python-2.x", "interview-questions" ], "Title": "Given a sorted array nums, remove the duplicates in-place" }
197622
<p>I had written code in C++ to create transformation filters to get input, sort (custom_sorting and existing sorting routine) and write the output to stdin and file. When I presented it to my teacher, he ran it on a considerably huge file and observed that my custom sorting routine took over 5 minutes to complete. He mentioned that instead of using hash maps to store the input and do the sorting, if I re-wrote the entire code using structs/classes in a more structured oriented way, I could get it to finish sorting within 10 seconds instead of 5 minutes. I am rusty when it comes to following a structured oriented approach. Can anyone help with re-writing the following code in a more structured oriented way using objects and classes/structs in C++?</p> <pre><code>#include &lt;sstream&gt; #include &lt;iostream&gt; #include &lt;algorithm&gt; #include &lt;string&gt; #include &lt;unistd.h&gt; #include &lt;sys/time.h&gt; #include &lt;getopt.h&gt; #include &lt;cstdlib&gt; #include &lt;cctype&gt; #include &lt;cstring&gt; #include &lt;vector&gt; #include &lt;fstream&gt; #include &lt;map&gt; #include &lt;iterator&gt; #include &lt;tr1/unordered_map&gt; using namespace std::tr1; using namespace std; vector &lt;string&gt; str; void custom_sort (vector &lt;string&gt; str, int num) { int round, r, i; for (round = 0; round &lt; num; round++) { for (i = 0; i &lt; num-1; i++) { r = str[i].compare(str[i+1]); if (r &gt; 0) { string s = ""; s = str[i]; str[i] = str[i+1]; str[i+1] = s; } } } } string getField (string input_str, char ch, int fieldNum) { istringstream ss(input_str); string temp; string field; int count = 0; vector &lt;string&gt; input; while(getline(ss,temp,ch)) { if(count &lt; fieldNum) { input.push_back(temp); count++; } } field = input.back(); //cout &lt;&lt; "Hey this is the field : " &lt;&lt; field &lt;&lt; endl; return field; } int main(int argc, char** argv) { int c; int items = 0; unordered_map&lt;string, vector&lt;string&gt; &gt; output; unordered_map&lt;string, vector&lt;string&gt; &gt; custom_output; string action_variable = ""; string input_variable = ""; string output_variable = ""; string separation_variable = ""; int field_variable = 0; while(1) { int option_index = 0; struct option long_options[] = { {"action", required_argument, 0, 'a'}, {"input", required_argument, 0, 'i'}, {"output", required_argument, 0, 'o'}, {"separator", required_argument, 0, 's'}, {"field", required_argument, 0, 'f'}, }; c = getopt_long(argc, argv, "a:i:o:s:f:",long_options, &amp;option_index); if (c == -1) { break; } switch (c) { case 'a': action_variable = optarg; cout &lt;&lt; "action :" &lt;&lt; action_variable &lt;&lt; endl; break; case 'i': input_variable = optarg; cout &lt;&lt; "input :" &lt;&lt; input_variable &lt;&lt; endl; break; case 'o': output_variable = optarg; cout &lt;&lt; "output :" &lt;&lt; output_variable &lt;&lt; endl; break; case 's': separation_variable = optarg; cout &lt;&lt; "Separation variable :" &lt;&lt; separation_variable &lt;&lt; endl; break; case 'f': field_variable = atoi(optarg); cout &lt;&lt; "Field variable :" &lt;&lt; field_variable &lt;&lt; endl; break; default: cout &lt;&lt; "Usage: myfilter --input arg --action arg --output arg" &lt;&lt; action_variable &lt;&lt; endl; exit(0); } } string name = ""; char ch = separation_variable[0]; ifstream myfile; myfile.open (input_variable.c_str()); if (myfile.is_open()) { while(getline(myfile,name)) { string field = getField(name,ch,field_variable); output[field].push_back(name); custom_output[field].push_back(name); str.push_back(field); items++; } myfile.close(); } else { cout &lt;&lt; "Unable to open file. Enter values in the standard input" &lt;&lt; endl; while (getline(cin,name)) { string field = getField(name,ch,field_variable); output[field].push_back(name); custom_output[field].push_back(name); str.push_back(field); items++; } } struct timeval tv1, tv2; struct timeval qtv1, qtv2; double start_time = gettimeofday(&amp;tv1, NULL); vector &lt;string&gt; custom_sort_output; //sorting = custom sorting routine custom_sort(str,items); int strLength = str.size(); for(int i = 0; i &lt; strLength; i++) { if(output.find(str[i]) != output.end()) { vector &lt;string&gt; temp = output[str[i]]; int sz = temp.size(); for(int j = 0; j &lt; sz; j++) { custom_sort_output.push_back(temp[j]); } } } double end_time = gettimeofday(&amp;tv2, NULL); double q_start_time = gettimeofday(&amp;qtv1, NULL); //sorting using an ordered_map map &lt;string,vector&lt;string&gt; &gt; sorted_output(output.begin(), output.end()); double q_end_time = gettimeofday(&amp;qtv2, NULL); printf ("Total time to read, sort and display from standard input using my sorting routine = %f seconds\n",(double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec)); printf ("Total time to read, sort and display from standard input using my sorting routine = %f seconds\n",(double) (qtv2.tv_usec - qtv1.tv_usec) / 1000000 + (double) (qtv2.tv_sec - qtv1.tv_sec)); //printing the output ofstream outputfile; outputfile.open(output_variable.c_str()); if (outputfile.is_open()) { for( map&lt;string, vector&lt;string&gt; &gt;::iterator it = sorted_output.begin(); it != sorted_output.end(); ++it) { int length = it-&gt;second.size(); for(int i = 0; i &lt; length; i++) { outputfile &lt;&lt; it-&gt;second[i] &lt;&lt; endl; } } outputfile.close(); } else { for( map&lt;string,vector&lt;string&gt; &gt;::iterator it = sorted_output.begin(); it != sorted_output.end(); ++it) { int length = it-&gt;second.size(); for(int i = 0; i &lt; length; i++) { outputfile &lt;&lt; it-&gt;second[i] &lt;&lt; endl; } } } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-02T13:01:57.650", "Id": "381051", "Score": "0", "body": "What is `getopt.h`? it seems instrumental, but I don't get where it comes from. More generally, could you explain us how the input data is structured, and what you need to do wit...
[ { "body": "<p>Your code doesn't seem to work. However, let's break down just the sort routine, since that's what you seem to think is the bottleneck.</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>Get in the habit of <strong>not</strong> <code>using namespace</code> anything. Then you won't have to...
{ "AcceptedAnswerId": "197628", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-01T23:48:58.500", "Id": "197625", "Score": "6", "Tags": [ "c++", "object-oriented", "sorting", "time-limit-exceeded", "homework" ], "Title": "C++ code to read, sort, and write data" }
197625
<p>I created an MVC router based on knowledge of an MVC design pattern.</p> <p>It will simply take a URL as a string (class/method/params...), then it will instantiate a requested class controller and call its method.</p> <p>In my class, I call a controller method and then include the view at the same time to display data.</p> <p>My questions are:</p> <ul> <li>Is this a valid MVC router?</li> <li>Is it good practice to make this class call include views for our application?</li> </ul> <p></p> <pre><code>class FrontController { //default view private $view = 'index'; //default methode private $method = 'indexMethode'; //default controller private $controller = 'Page'; //this attribute to store data returned private $data; //to store methode parameters from url. private $param; public function __construct() { //getting user url request $url = $this-&gt;getUrl(); //checking user input if (isset($url[0])) { //getting class name from user input $this-&gt;controller = ucwords($url[0]); unset($url[0]); } //checking if class file exsiste if yes we include it if(file_exists('controllers/'.$this-&gt;controller.'.php')){ require 'controllers/'.$this-&gt;controller.'.php'; } //instantiating the demanded class $this-&gt;controller = new $this-&gt;controller; //getting demanded class method if it is demanded by user if (isset($url[1])) { if(method_exists($this-&gt;controller, $url[1])) $this-&gt;method = $url[1]; } //checking if there is a view for our request if(file_exists('view/'.$url[1].'.php')){ //setting the sutable template for the methode $this-&gt;view = $url[1]; unset($url[1]); } //Getting methode parameters from user input if exsist $this-&gt;param = $url ? array_values($url) : []; //Calling the methode and getting the result $this-&gt;data = call_user_func_array([$this-&gt;controller, $this-&gt;method], $this-&gt;param); //Getting the sutable page for the responde to display it. include 'view/' . $this-&gt;view . '.php'; } //To get any private var in our class public function __get($name) { return $this-&gt;$name; } //Here we are gona take user input and devide it as array element public function getUrl() { //checking user input and filtring it for unwanted charecters if (!empty($_GET['url'])) { // remove / char from url $url = rtrim($_GET['url'], '/'); //Checking url for unwanted chars $url = filter_var($url, FILTER_SANITIZE_URL); //forming array from url $url = explode('/', $url); //Sending back url array return $url; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-02T08:09:48.903", "Id": "381020", "Score": "0", "body": "One problem I can see is that of security. Given this code anybody can call any of your public controller methods with any arguments. You will have to be very dissiplined and pro...
[ { "body": "<h2>Dependency Injection</h2>\n\n<p>You instantiate all the controllers with <code>new $this-&gt;controller</code> what if my controller has dependencies ? Instead of your controllers looking like this; </p>\n\n<pre><code>public function __construct() {\n $this-&gt;xyz = new xyz();\n}\n</code></pre...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-02T00:49:35.597", "Id": "197627", "Score": "1", "Tags": [ "php", "mvc" ], "Title": "Creating an MVC router" }
197627
<p>I have to convert a JsonArray to an ArrayList but unfortunately the code below is used very often during the execution of the program! How can I speed it up?</p> <p><strong>Java:</strong></p> <pre><code>public static ArrayList CastJsonObject(JSONArray object) { ArrayList&lt;Cantiere&gt; tm = new ArrayList&lt;Cantiere&gt;(); Cantiere cant; Cliente c; try { for (int i = 0; i &lt; object.length(); i++) { JSONObject value = object.getJSONObject(i); int IdCantiere = Integer.parseInt(value.getString("IdCantiere").toString()); int IdCliente = Integer.parseInt(value.getString("IdCliente").toString()); String Filiale = value.getString("Filiale").toString(); String RagioneSociale = value.getString("RagioneSociale").toString(); String NomeCantiere = value.getString("NomeCantiere").toString(); String DataCreazioneCantiere = value.getString("DataCreazioneCantiere").toString(); String Tipologia = value.getString("Tipologia").toString(); String StatoCantiere = value.getString("StatoCantiere").toString(); int StatoFatturazione = Integer.parseInt(value.getString("StatoFatturazione").toString()); c = new Cliente(IdCliente, RagioneSociale, Filiale); cant = new Cantiere(c, IdCantiere, NomeCantiere, DataCreazioneCantiere, Tipologia, StatoCantiere, StatoFatturazione); tm.add(cant); } } catch (Exception ex) { System.out.println("\n Error: " + ex); } return tm; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-02T07:04:12.983", "Id": "381012", "Score": "0", "body": "It would help us a lot if you added an example of the data you're parsing. `JSONObject` also looks like this is about adroid..." }, { "ContentLicense": "CC BY-SA 4.0", ...
[ { "body": "<p>If there really is a performance problem with that code, please back this up with some measurements. Otherwise, read some articles concerning premature optimization and don't bother.</p>\n\n<p>Nevertheless, on micro-level there are a few calls that you don't need:</p>\n\n<p>Get rid of superfluous ...
{ "AcceptedAnswerId": "197645", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-02T06:55:03.803", "Id": "197635", "Score": "1", "Tags": [ "java", "performance", "json" ], "Title": "Slow Converting from JsonArray to ArrayList" }
197635
<p>I have a class that handles interactions with a custom rest/json webserver, for the purposes of handling online game matchmaking etc. I want the class to have very simple public functions like <code>Server.Login()</code> and <code>Server.JoinMatch()</code>, so they can be connected up at the UI layer easily. As you will see from the code fairly quickly, there is a lot of repeated code in each function, which I want to refactor out.</p> <p>The first part of each function ensures only one operation at once. The next bit defines a callback delegate for when the request is finished (async). And the last part starts the actual request operation.</p> <pre class="lang-cs prettyprint-override"><code>public class Server { #region Fields public string playerName { get; private set; } public string playerID { get; private set; } public string playerToken { get; private set; } public string currentMatchID { get; private set; } private Patterns.State&lt;ServerState&gt; state = new Patterns.State&lt;ServerState&gt;(); #endregion public Server() { state.Add(ServerState.Idle); } public void Login(string playerName, Action&lt;TcpRequest&gt; onSuccess = null, Action&lt;TcpRequest&gt; onError = null) { // Throw exception already busy with an operation if (!state.Has(ServerState.Idle)) { throw new OperationInProgress(); } // Define login callback action Action&lt;TcpRequest&gt; loginCallback = delegate (TcpRequest request) { // Add idle state back in state.Add(ServerState.Idle); // Check if the request succeeded if (request.OK) { // Store player data in class playerName = (string)request.requestJson["player_name"]; playerID = (string)request.responseJson["player_id"]; playerToken = (string)request.responseJson["player_token"]; // Add the logged in state state.Add(ServerState.LoggedIn); // Call the onSuccess callback if provided onSuccess?.Invoke(request); } // Login failed, call the onError callback if provided else { onError?.Invoke(request); } }; // Remove idle state state.Remove(ServerState.Idle); // Perform request Request("login", callback: loginCallback, requestJson: new Dictionary&lt;string, object&gt; { { "player_name", playerName }, { "client_version", "test1" } }); } public void CreateMatch(string matchName, Action&lt;TcpRequest&gt; onSuccess = null, Action&lt;TcpRequest&gt; onError = null) { // Throw exception already busy with an operation if (!state.Has(ServerState.Idle)) { throw new OperationInProgress(); } // Define callback action Action&lt;TcpRequest&gt; callback = delegate (TcpRequest request) { // Add idle state back in state.Add(ServerState.Idle); // Check if the request succeeded if (request.OK) { // Add the inLobby state state.Add(ServerState.InLobby); // Call the onSuccess callback if provided onSuccess?.Invoke(request); } // Request failed. Call the onError callback if provided else { onError?.Invoke(request); } }; // Remove idle state state.Remove(ServerState.Idle); // Perform request AuthenticatedRequest("match/create", callback: callback, requestJson: new Dictionary&lt;string, object&gt; { { "match_name", matchName } }); } public void JoinMatch(string matchID, Action&lt;TcpRequest&gt; onSuccess = null, Action&lt;TcpRequest&gt; onError = null) { // Throw exception already busy with an operation if (!state.Has(ServerState.Idle)) { throw new OperationInProgress(); } // Define callback action Action&lt;TcpRequest&gt; callback = delegate (TcpRequest request) { // Add idle state back in state.Add(ServerState.Idle); // Check if the request succeeded if (request.OK) { // Add the inLobby state state.Add(ServerState.InLobby); // Set currentMatchID in class currentMatchID = (string)request.responseJson["match_id"]; // Call the onSuccess callback if provided onSuccess?.Invoke(request); } // Request failed. Call the onError callback if provided else { onError?.Invoke(request); } }; // Perform request AuthenticatedRequest("match/join", callback: callback, requestJson: new Dictionary&lt;string, object&gt; { { "match_id", matchID } }); } private void Request(string resource, Action&lt;TcpRequest&gt; callback = null, Dictionary&lt;string, object&gt; requestJson = null) { // Start async request, invoke callback when done } private void AuthenticatedRequest(string resource, Action&lt;TcpRequest&gt; callback = null, Dictionary&lt;string, object&gt; requestJson = null) { // Add login auth data into the requestJson dict or throw exception if we aren't logged in // Call Request() } } </code></pre> <p>Notes:</p> <ul> <li>Patterns.State class is basically a hashset that keeps track of what states an object has. When a server transaction is in progress, I remove the Idle state, and add it back in when its done. To prevent concurrent transactions, I check for the presence of the Idle state.</li> <li>I am restricted to c#6, .net 4.7 (Unity)</li> </ul> <p>EDIT1: I tweaked the callbacks, so that instead of having one callback in the TcpRequest and having it call other things, I added a callback list for onSuccess and onError. This means I just add extra callbacks as required, instead of redefining a master one each time.</p> <pre><code>public void Login(string playerName, Action&lt;TcpRequest&gt; onSuccess=null, Action&lt;TcpRequest&gt; onError=null) { // Throw exception already busy with an operation if (!state.Has(ServerState.Idle)) { throw new OperationInProgress(); } // Prepare callback lists List&lt;Action&lt;TcpRequest&gt;&gt; onSuccessCallbacks = new List&lt;Action&lt;TcpRequest&gt;&gt;(); List&lt;Action&lt;TcpRequest&gt;&gt; onErrorCallbacks = new List&lt;Action&lt;TcpRequest&gt;&gt;(); // Add login callback action onSuccessCallbacks.Add(delegate (TcpRequest request) { // Add idle state back in state.Add(MakoState.Idle); // Store player data in class playerName = (string)request.requestJson["player_name"]; playerID = (string)request.responseJson["player_id"]; playerToken = (string)request.responseJson["player_token"]; // Add the logged in state state.Add(MakoState.LoggedIn); }); // Add onSuccess/onError callback args if not null if (onSuccess != null) { onSuccessCallbacks.Add(onSuccess); } if (onError != null) { onErrorCallbacks.Add(onError); } // Remove idle state state.Remove(MakoState.Idle); // Perform request (using NoAuth method as we aren't logged in yet) Request("login", onSuccess=onSuccessCallbacks, onError=onErrorCallbacks, requestJson: new Dictionary&lt;string, object&gt;{ {"player_name", playerName }, {"client_version", "test1" } }); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-02T08:41:05.050", "Id": "381022", "Score": "0", "body": "Is the class itself meant to be thread-safe, or are you just worried about asynchronous call-backs? (i.e. are you intending to address the concern of these methods being called c...
[ { "body": "<p>I'm answering instead of just editing the original with updates, as these changes solve my initial problem. I'm still interested to see if anyone comes up with anything else or has any other feedback. </p>\n\n<ul>\n<li>Moved the idle state check <code>if(!state.Has(ServerState.Idle))</code> into <...
{ "AcceptedAnswerId": "197654", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-02T07:28:22.897", "Id": "197638", "Score": "1", "Tags": [ "c#" ], "Title": "Server Request Class, Async Callbacks" }
197638
<p>I have written a simple JavaScript function to make an array reactive (i.e. observable). Is there anything I could improve? What the code does is take an array, a callback and a <code>this</code> value as arguments, then whenever the array gets updated or a value gets added to it, it runs the callback with the specified <code>this</code> value. It works similar to the obsolete <code>Array.observe()</code>.</p> <pre><code>function arrayObserve(array, callback, thisArg){ var result = []; result.push.apply(result, array); function getterAndSetter() { if (Array.isArray(array)) var currentArray = result; else var currentArray = Object.keys(result); console.log(result); currentArray.forEach( function(prop){ if (Array.isArray(result)) var currentProp = result.lastIndexOf(prop); else var currentProp = prop; Object.defineProperty(array, currentProp, { configurable: true, enumerable: true, set: function(val) { result[currentProp] = val; callback.call(thisArg, result); }, get: function() { return result[currentProp]; } }); //} if (typeof result[currentProp] == 'object') { arrayObserve(result[currentProp], callback, result); } }); } getterAndSetter(); ['pop','push','reverse','shift','unshift','splice','sort','map','filter'].forEach( function(method){ Object.defineProperty(array, method, { configurable: false, enumerable: false, writable: true, value: function () { var noReturnMethods = ['push', 'pop', 'reverse', 'shift', 'unshift']; if (noReturnMethods.indexOf(method) &gt; -1) { Array.prototype[method].apply(result, arguments); } else { var results = Array.prototype[method].apply(result, arguments); result = results; } callback.call(thisArg, result); getterAndSetter(); return result; } }); }); return result; } </code></pre>
[]
[ { "body": "<p>Some minor nit-picks about your code.</p>\n\n<blockquote>\n<pre><code>Object.defineProperty(array, method, {\n configurable: false,\n enumerable: false,\n writable: true,\n value: function () {\n // ...\n</code></pre>\n</blockquote>\n\n<p>Here, <code>configurable</code> and <cod...
{ "AcceptedAnswerId": "198178", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-02T09:32:39.773", "Id": "197647", "Score": "4", "Tags": [ "javascript", "array", "observer-pattern" ], "Title": "Make an Array Reactive (Observable)" }
197647
<p>My new mobile phone is capable of importing contact information from a renamed *.VCF file stored on an SD memory card (<a href="https://www.quora.com/How-do-I-sync-contacts-on-Nokia-130" rel="nofollow noreferrer">https://www.quora.com/How-do-I-sync-contacts-on-Nokia-130</a>). Annoyingly, it does not work very well for contacts with multiple phone numbers or anything not tagged as <code>TEL:</code> or <code>TEL;TYPE=CELL:</code>.</p> <p>The following script takes an *.vcf file, parses the stored contact information as needed - first name, last name and phone numbers - and outputs the information in a way that the phone imports it correctly. Therefore, each contact may only contain one number. For multiple numbers, a contact will be duplicated for each phone number. The resulting string is simply printet out.</p> <pre><code>#!/usr/bin/python import re class Contact(object): """ Contains the contact infromation, including a list of phone numbers. Arguments: object {[type]} -- [description] """ def __init__(self): self.FirstName = "" self.LastName = "" self.Phonenumbers = [] def extract_number(line): """ Extracts the phone number from a vCard-file line, by removing everything but numbers and '+' Arguments: line {string} -- the line to extract the phone number from Returns: string -- the phone number """ line = line[line.index(":")+1:].rstrip() line = re.sub('[^0-9+]', '', line) return line def generate_vcard_contact_string(contact): """ Generates the vCard string for this contact. Will generate a sperate vCard for each phone number of the contact. Arguments: contact {Contact} -- the contact to generate the vCard string from Returns: string -- the generated vCard string """ base = f"BEGIN:VCARD\n" base += f"N:{contact.LastName};{contact.FirstName}\n" base += f"TEL:{{phone_number}}\n" # use '{phone_number}' as a placeholder. # Will be replaced by actual number. base += f"END:VCARD\n" result = "" for number in contact.Phonenumbers: # Add the base string for this contact, # replace {phone_number} with actual number result += base.replace("{phone_number}", number) return result contacts = [] with open(r'contacts.vcf') as f: current_contact = Contact() for line in f: # Some lines are build like "item1.TEL;...", # remove "item1.", "item2.", to ease parsing if line.startswith("item"): line = line[line.index(".")+1:] if "BEGIN:VCARD" in line: # Marks the start of a vCard, # create a blank contact to work with current_contact = Contact() elif line.startswith("N:"): # Line contains a name in the format N:LastName;FirstName;...;...; # Only LastName and FirstName will be used line = line.replace("N:", "") # remove "N:" from line chunks = line.split(';') current_contact.LastName = chunks[0].strip() current_contact.FirstName = chunks[1].strip() elif line.startswith("TEL"): # Line contains a phone number # phone number type may be specified by "TYPE=...", # currently, TYPE will ne omitted # One contact may contain multiple phone numbers. number = extract_number(line) current_contact.Phonenumbers.append(number) elif "END:VCARD" in line: # Marks the end of a vCard, # append contact to list contacts.append(current_contact) result = "" for contact in contacts: # Generate a string containing a vCard for each of the contacts phone # numbers, append those string to create one big text containing everything result += generate_vcard_contact_string(contact) print(result) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T08:34:54.780", "Id": "381140", "Score": "1", "body": "Did you consider using one of the [Python packages handling the VCF format](https://pypi.org/search/?q=vcf)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "...
[ { "body": "<p>Your function <code>generate_vcard_contact_string</code> obviously belongs to the <code>Contact</code> class. It even takes a <code>Contact</code> instance as the first argument.</p>\n\n<p>I would actually elevate this to be the magic <code>__str__</code> method, which is for example called when y...
{ "AcceptedAnswerId": "197865", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-02T11:19:41.437", "Id": "197652", "Score": "3", "Tags": [ "python", "parsing", "reinventing-the-wheel", "converting" ], "Title": "Convert *.VCF contact file for cellphone import" }
197652
<p>Could you please correct me if I'm not following best practices or code optimizations? It is working fine in test environment planning to deploy.</p> <p>Trigger does two tasks:</p> <ol> <li><p>Gives an error when trying to change case owner from</p> <ol> <li>DS Service Queue</li> <li>Data Services</li> <li>RFP, Data Services and Case fields <code>Categiry__c</code> or <code>Sub_Department__c</code> is null (should not allow to change case owner if Category and Sub Department is null on queues mentioned)</li> </ol></li> <li><p>When case owner changes to Queues</p> <ol> <li>Marketing Queue</li> <li>G&amp;T Service Queue</li> <li>CCSC Queue</li> <li>E-Commerce</li> <li>Guest Assistance Queue respective case fields <code>RecordTypeId</code>, <code>Department__c</code>, <code>Sub_Department__c</code>, <code>Category__c</code> should update with respective values</li> </ol></li> </ol> <p></p> <pre><code>trigger updateCase on Case (before update) { Set&lt;Id&gt; QIds = new Set&lt;Id&gt;(); list&lt;RecordType&gt; rc= new list&lt;RecordType&gt;(); list &lt;Group&gt; gc=new list&lt;group&gt;(); list &lt;id&gt; caseid=new list&lt;id&gt;(); list &lt;Group&gt; g=new list&lt;group&gt;(); //Get the Ids of the different Queues Id MarkeRecoTyId = Schema.SObjectType.case.getRecordTypeInfosByName().get('Marketing').getRecordTypeId(); Id GTGrLRecoTyId = Schema.SObjectType.case.getRecordTypeInfosByName().get('G&amp;T Group Leads').getRecordTypeId(); Id CCSCRecoTyId = Schema.SObjectType.case.getRecordTypeInfosByName().get('CCSC').getRecordTypeId(); Id EcomRecoTyId = Schema.SObjectType.case.getRecordTypeInfosByName().get('E-Commerce').getRecordTypeId(); Case oldC = new Case(); for (Case c:trigger.new) { oldC = trigger.oldMap.get(c.Id); } rc=[Select ID, Name From RecordType Where sObjectType = 'case' and id=:oldc.RecordTypeId limit 1 ]; gc=[select id, Name from Group where id =:Trigger.new[0].ownerid and Type = 'Queue']; g=[select Id, Name from Group where Type = 'Queue']; for( Group qu :g){ if(qu.Name == 'DS Service Queue' || qu.Name == 'Data Services RFP' || qu.Name == 'Data Services') QIds.add(qu.Id); } //Loop through all Cases and check owner change system.debug('oldrecord type==&gt;+' + oldc.RecordTypeId ); for (Case c:trigger.new) { oldC = trigger.oldMap.get(c.Id); System.debug('Oldc'+ oldc); System.debug('RecordTypename' + oldc.RecordType.name); // Guest Assistance Project Requirments - Auto stamp Department and Sub-Department when a GA case is re-assigned to other Queues if (oldC.OwnerId != c.OwnerId &amp;&amp; QIds.contains(oldC.OwnerId)) { c.Status = 'Open'; if (c.Category__c == null || c.Sub_Department__c == null) c.addError('You must provide a value for Category and Sub Department before changing the Case Owner'); } for(RecordType rt : rc) { system.debug('Record Type name ==&gt;' + rt.Name); if(rt.Name == 'Guest Assistance') { System.debug('RecordTypeIds ==&gt;'+ 'Marketing==&gt;' + MarkeRecoTyId + ' ' + 'G&amp;T Group Leads==&gt;'+ GTGrLRecoTyId + ' ' + 'CCSC==&gt;' + CCSCRecoTyId + ' ' + 'E-Commerce ==&gt;' + EcomRecoTyId ); for( Group qu :gc){ if (qu.name == 'Marketing Queue') { c.RecordTypeId = MarkeRecoTyId; c.Department__c = 'Marketing'; c.Sub_Department__c = 'Marketing'; c.Category__c = 'Website Feature'; } if (qu.name == 'G&amp;T Service Queue' || Test.isRunningTest() ) { c.RecordTypeId = GTGrLRecoTyId; c.Department__c = 'Group &amp; Tour'; c.Sub_Department__c = 'Group &amp; Tour'; c.Category__c = 'Group Event'; } if (qu.name == 'CCSC Queue'||Test.isRunningTest()) { c.RecordTypeId = CCSCRecoTyId; c.Department__c = 'Guest Assistance'; c.Sub_Department__c = 'Guest Assistance'; c.Category__c = null ; } if (qu.name == 'E-Commerce'||Test.isRunningTest()) { c.RecordTypeId = EcomRecoTyId; c.Department__c = 'E-Commerce'; c.Sub_Department__c = 'E-Commerce'; c.Category__c = 'Other'; } } } else if ((rt.Name == 'Marketing') || (rt.Name == 'G&amp;T Group Leads') || (rt.Name == 'CCSC') || (rt.Name == 'E-Commerce'|| Test.isRunningTest())) { Id GuesRecoTyId = Schema.SObjectType.case.getRecordTypeInfosByName().get('Guest Assistance').getRecordTypeId(); for( Group qu :gc){ if (qu.name == 'Guest Assistance Queue') { c.RecordTypeId = GuesRecoTyId; c.Department__c = 'Guest Assistance'; c.Sub_Department__c = 'Guest Assistance'; c.Category__c = null; } } } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-02T15:17:12.053", "Id": "381068", "Score": "0", "body": "Hey welcome to Code Review! So, what does your code actually do, besides being a trigger? Some explanation goes a long way for reviewers to understand your code." }, { "C...
[ { "body": "<p>I'm no Apex expert, nor coding expert in general. I do deal with Apex triggers quite a bit, both my own and those written by others.</p>\n\n<p>Ultimately, I don't see any practices which break any of the <a href=\"https://developer.salesforce.com/blogs/developer-relations/2015/01/apex-best-practic...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-02T11:58:56.437", "Id": "197655", "Score": "1", "Tags": [ "salesforce-apex" ], "Title": "Trigger corrections" }
197655
<p>The question is from <a href="https://www.hackerearth.com/zh/practice/data-structures/linked-list/singly-linked-list/practice-problems/algorithm/remove-friends-5/" rel="nofollow noreferrer">here</a>.</p> <blockquote> <p>Given two numbers N and K where N is the number of nodes and K is the number of nodes to be deleted, delete K nodes whose data is less than their next node's data. If no such nodes exist, delete the last node.</p> </blockquote> <p>But it is still giving me TLE. I tried all the optimisations that could occur to me. I know this can be done with stacks but I would like to know if it can't done in the allocated time with linked lists.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; struct Node { int value; struct Node *next; }; void addnode(struct Node** head, struct Node** tail, int data) { struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); temp-&gt;value = data; temp-&gt;next = nullptr; if( *head == nullptr) { *head = temp; *tail = *head; return; } (*tail)-&gt;next = temp; *tail = temp; } void deleteNode(struct Node** head, struct Node** prev, struct Node** temp) { if( (*prev)-&gt;next == *head) { *head = (*prev)-&gt;next-&gt;next; return; } (*prev)-&gt;next = (*temp)-&gt;next; } void deletenodeatlast(struct Node** prev) { (*prev)-&gt;next = (*prev)-&gt;next-&gt;next; } void display(struct Node* head) { struct Node* p = head; while(p != nullptr) { printf("%d ", p-&gt;value); p = p-&gt;next; } printf("\n"); } int main() { int T; scanf("%d", &amp;T); while(T--) { struct Node* head = nullptr; struct Node* tail = head; int N, K; scanf("%d %d", &amp;N, &amp;K); for(int i = 0; i &lt; N; i++) { int data; scanf("%d", &amp;data); addnode(&amp;head, &amp;tail, data); } for(int i = 0; i &lt; K; i++) { bool isGreater = false; struct Node* p = head; struct Node* prev = (struct Node*)malloc(sizeof(struct Node)); prev-&gt;value = 1000000; prev-&gt;next = p; while( p-&gt;next != nullptr) { if( p-&gt;value &lt; p-&gt;next-&gt;value) { deleteNode(&amp;head, &amp;prev, &amp;p); isGreater = true; } else { prev = p; p = p-&gt;next; } if( isGreater ) { break; } } if( !isGreater) { deletenodeatlast(&amp;prev); } } display(head); } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-02T13:50:51.047", "Id": "381057", "Score": "0", "body": "Do you want this reviewed as pure C (which is how you wrote the code), or C++ (which is how you tagged it)? Because, as C++, a review amounts to a full re-write." }, { "C...
[ { "body": "<h2>Initialize your variables:</h2>\n\n<p>Leaving variables in uninitialized states is generally a bad idea, get into the habit of always giving them a value:</p>\n\n<pre><code>int T = 0;\n</code></pre>\n\n<p>The small additional amount of work required will soon become second nature, and in the long...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-02T13:06:34.063", "Id": "197656", "Score": "0", "Tags": [ "c++", "linked-list" ], "Title": "Delete K nodes in a linked list having their data less than the next node's" }
197656
<p>After implementing suggestions from my previous questions about <a href="https://codereview.stackexchange.com/questions/197076/shortest-job-first-preemptive/197177#197177">SJF</a>, <a href="https://codereview.stackexchange.com/questions/197269/priority-scheduling-algorithm-preemptive/197325?noredirect=1#comment380390_197325">priority</a> and <a href="https://codereview.stackexchange.com/questions/197498/round-robin-scheduling-algorithm/197554?noredirect=1#comment380947_197554">round robin</a>.</p> <p>Here I have <code>scheduling.h</code> which contains a struct <code>Data</code> and <code>virtual</code> member functions. Then I have derived class for each scheduling algorithm. Only <code>calcEndTime()</code> is defined for each scheduling algorithm. I have asked to enter priority in each algortihm because it must be in <code>Data</code> so it is bounded to <code>arrivalTime</code> and <code>burstTime</code>. This is first time I have written program related to inheritance. Suggest me improvements.</p> <p>scheduling.h</p> <pre><code>#ifndef SCHEDULING_H_ #define SCHEDULING_H_ #include &lt;vector&gt; class Scheduler { public: double avgWaitingTime; double avgTurnAroundTime; struct Data { unsigned arrivalTime; //When process start to execute unsigned burstTime; //only for priority Scheduling unsigned priority; Data(unsigned arrivalTime, unsigned burstTime, unsigned priority): arrivalTime(std::move(arrivalTime)), burstTime(std::move(burstTime)), priority(std::move(priority)) {} Data() = default; }; std::vector&lt;Data&gt; data; //process wait to execute after they have arrived std::vector&lt;unsigned&gt; waitingTime; //total time taken by processes std::vector&lt;unsigned&gt; turnAroundTime; //time when a process end std::vector&lt;unsigned&gt; endTime; Scheduler(unsigned num = 0); Scheduler(const Scheduler&amp;) = delete; Scheduler &amp;operator=(const Scheduler&amp;) = delete; Scheduler(Scheduler&amp;&amp;) = delete; Scheduler &amp;operator=(Scheduler&amp;&amp;) = delete; ~Scheduler() = default; void calcWaitingTime(); void calcTurnAroundTime(); virtual void calcEndTime() = 0; void printInfo() const; }; #endif </code></pre> <p>scheduling.cpp</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include "scheduling.h" Scheduler::Scheduler(unsigned num): endTime(num, 0) { unsigned arrivalVal, burstVal, priorityVal; data.reserve(num); endTime.reserve(num); waitingTime.reserve(num); turnAroundTime.reserve(num); std::cout &lt;&lt; "\nEnter arrival time and burst time and priority eg(5 18 2)\n"; std::cout &lt;&lt; "If it is not priority scheduling enter 0 for priority\n"; std::cout &lt;&lt; "Lower integer has higher priority\n"; for (unsigned i = 0; i &lt; num; i++) { std::cout &lt;&lt; "\nProcess" &lt;&lt; i+1 &lt;&lt; ": "; std::cin &gt;&gt; arrivalVal &gt;&gt; burstVal &gt;&gt; priorityVal; data.push_back( Data(arrivalVal, burstVal, priorityVal) ); } } void Scheduler::calcTurnAroundTime() { double sum = 0.00; for (std::size_t i = 0; i &lt; data.size(); i++) { unsigned val = endTime[i] - data[i].arrivalTime; turnAroundTime.push_back(val); sum += (double)val; } avgTurnAroundTime = sum / turnAroundTime.size(); } void Scheduler::calcWaitingTime() { double sum = 0.00; for (std::size_t i = 0; i &lt; data.size(); i++) { unsigned val = turnAroundTime[i] - data[i].burstTime; waitingTime.push_back(val); sum += (double)val; } avgWaitingTime = sum / waitingTime.size(); } void Scheduler::printInfo() const { std::cout &lt;&lt; "ProcessID\tArrival Time\tBurst Time\tPriority\tEnd Time\tWaiting Time"; std::cout &lt;&lt; "\tTurnaround Time\n"; for (std::size_t i = 0; i &lt; data.size(); i++) { std::cout &lt;&lt; i+1 &lt;&lt; "\t\t" &lt;&lt; data[i].arrivalTime &lt;&lt; "\t\t"; std::cout &lt;&lt; data[i].burstTime &lt;&lt; "\t\t" &lt;&lt;data[i].priority &lt;&lt; "\t\t"; std::cout &lt;&lt; endTime[i] &lt;&lt; "\t\t"; std::cout &lt;&lt; waitingTime[i] &lt;&lt;"\t\t" &lt;&lt; turnAroundTime[i] &lt;&lt;'\n'; } std::cout &lt;&lt; "Average Waiting Time : " &lt;&lt; avgWaitingTime &lt;&lt; '\n'; std::cout &lt;&lt; "Average Turn Around Time : " &lt;&lt; avgTurnAroundTime &lt;&lt; '\n'; } </code></pre> <p>shortestjobfirst.h</p> <pre><code>#ifndef SHORTESTJOBFIRST_H_ #define SHORTESTJOBFIRST_H_ #include "scheduling.h" class ShortestJobFirst : public Scheduler { public: ShortestJobFirst(unsigned num); ShortestJobFirst() = default; ShortestJobFirst(const ShortestJobFirst&amp;) = delete; ShortestJobFirst &amp;operator=(const ShortestJobFirst&amp;) = delete; ShortestJobFirst(ShortestJobFirst&amp;&amp;) = delete; ShortestJobFirst &amp;operator=(ShortestJobFirst&amp;&amp;) = delete; ~ShortestJobFirst() = default; void calcEndTime(); }; #endif </code></pre> <p>shortestjobfirst.cpp</p> <pre><code>#include &lt;iostream&gt; #include &lt;array&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; // std::find #include &lt;iterator&gt; // std::begin, std::end #include &lt;limits&gt; //std::numeric_limits #include "scheduling.h" #include "shortestjobfirst.h" ShortestJobFirst::ShortestJobFirst(unsigned num) :Scheduler(num) {} void ShortestJobFirst::calcEndTime() { //If arrival time is not sorted //sort burst time according to arrival time static const auto byArrival = [](const Data &amp;a, const Data &amp;b) { return a.arrivalTime &lt; b.arrivalTime; }; std::sort(data.begin(), data.end(), byArrival); //copy values of burst time in new vector std::vector&lt;unsigned&gt; burstTimeCopy; for (auto it = data.begin(); it != data.end(); ++it) { unsigned val = (*it).burstTime; burstTimeCopy.push_back(val); } unsigned timeCounter = 0; unsigned currActiveProcessID = 0; while (!(std::all_of(burstTimeCopy.begin(), burstTimeCopy.end(), [] (unsigned e) { return e == 0; }))) { std::size_t dataSize = data.size(); //All processes are not arrived if (timeCounter &lt;= data[dataSize -1].arrivalTime) { unsigned minBurstTime = std::numeric_limits&lt;uint&gt;::max(); //Find index with minimum burst Time remaining for (std::size_t i = 0; i &lt; burstTimeCopy.size(); i++) { if (burstTimeCopy[i] != 0 &amp;&amp; burstTimeCopy[i] &lt; minBurstTime &amp;&amp; data[i].arrivalTime &lt;= timeCounter) { minBurstTime = burstTimeCopy[i]; currActiveProcessID = i; } } burstTimeCopy[currActiveProcessID] -= 1; timeCounter++; if (burstTimeCopy[currActiveProcessID] == 0) { endTime[currActiveProcessID] = timeCounter; } } else //When all processes are arrived { unsigned minBurstTime = std::numeric_limits&lt;uint&gt;::max(); //Find index with minimum burst Time remaining for (std::size_t i = 0; i &lt; burstTimeCopy.size(); i++) { if (burstTimeCopy[i] != 0 &amp;&amp; burstTimeCopy[i] &lt; minBurstTime) { minBurstTime = burstTimeCopy[i]; currActiveProcessID = i; } } timeCounter += minBurstTime; endTime[currActiveProcessID] = timeCounter; burstTimeCopy[currActiveProcessID] = 0; } } } int main() { int num; std::cout &lt;&lt; "Enter the number of processes\n"; std::cin &gt;&gt; num; ShortestJobFirst batch(num); batch.calcEndTime(); batch.calcTurnAroundTime(); batch.calcWaitingTime(); batch.printInfo(); } </code></pre> <p><code>Priority</code>, <code>ShortestJobFirst</code> are nearly smae and in <code>RoundRobin</code> we have member function <code>timeQuantum</code> which is entered through constructor.</p> <p>priorit.cpp</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; // std::find #include &lt;iterator&gt; // std::begin, std::end #include &lt;limits&gt; //std::numeric_limits #include "scheduling.h" #include "priority.h" Priority::Priority(unsigned num): Scheduler(num) {} void Priority::calcEndTime() { //If arrival time is not sorted //sort burst time according to arrival time static const auto byArrival = [](const Data &amp;a, const Data &amp;b) { return a.arrivalTime &lt; b.arrivalTime; }; std::sort(data.begin(), data.end(), byArrival); //copy values of burst time in new vector std::vector&lt;unsigned&gt; burstTimeCopy; for (auto it = data.begin(); it != data.end(); ++it) { unsigned val = (*it).burstTime; burstTimeCopy.push_back(val); } unsigned timeCounter = 0; unsigned currActiveProcessID = 0; while (!(std::all_of(burstTimeCopy.begin(), burstTimeCopy.end(), [] (unsigned e) { return e == 0; }))) { std::size_t dataSize = data.size(); //All processes are not arrived if (timeCounter &lt;= data[dataSize - 1].arrivalTime) { unsigned maxPriority = std::numeric_limits&lt;uint&gt;::max(); for (std::size_t i = 0; i &lt; burstTimeCopy.size(); i++) { if (burstTimeCopy[i] != 0 &amp;&amp; data[i].priority &lt; maxPriority &amp;&amp; data[i].arrivalTime &lt;= timeCounter) { maxPriority = data[i].priority; currActiveProcessID = i; } } burstTimeCopy[currActiveProcessID] -= 1; timeCounter++; if (burstTimeCopy[currActiveProcessID] == 0) { endTime[currActiveProcessID] = timeCounter; } } else //When all processes are arrived { unsigned maxPriority = std::numeric_limits&lt;uint&gt;::max(); for (std::size_t i = 0 ; i &lt; burstTimeCopy.size(); i++) { if (burstTimeCopy[i] != 0 &amp;&amp; data[i].priority &lt; maxPriority) { maxPriority = data[i].priority; currActiveProcessID = i; } } timeCounter += burstTimeCopy[currActiveProcessID]; burstTimeCopy[currActiveProcessID] = 0; endTime[currActiveProcessID] = timeCounter; } } } int main() { int num; std::cout &lt;&lt; "Enter the number of processes\n"; std::cin &gt;&gt; num; Priority prioritySchedule(num); prioritySchedule.calcEndTime(); prioritySchedule.calcTurnAroundTime(); prioritySchedule.calcWaitingTime(); prioritySchedule.printInfo(); } </code></pre> <p>roundrobin.cpp</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; // std::find #include &lt;iterator&gt; // std::begin, std::end #include &lt;limits&gt; //std::numeric_limits #include "scheduling.h" #include "roundrobin.h" RoundRobin::RoundRobin(unsigned num, unsigned quantum): Scheduler(num) { timeQuantum = quantum; } void RoundRobin::calcEndTime() { //If arrival time is not sorted //sort burst time according to arrival time static const auto byArrival = [](const Data &amp;a, const Data &amp;b) { return a.arrivalTime &lt; b.arrivalTime; }; std::sort(data.begin(), data.end(), byArrival); //copy values of burst time in new vector std::vector&lt;unsigned&gt; burstTimeCopy; for (auto it = data.begin(); it != data.end(); ++it) { unsigned val = (*it).burstTime; burstTimeCopy.push_back(val); } unsigned timeCounter = 0; while (!(std::all_of(burstTimeCopy.begin(), burstTimeCopy.end(), [] (unsigned e) { return e == 0; }))) { unsigned currActiveProcessID = 0; auto it = burstTimeCopy.begin(); while (it != burstTimeCopy.end()) { if (burstTimeCopy[currActiveProcessID] &gt; timeQuantum) { burstTimeCopy[currActiveProcessID] -= timeQuantum; timeCounter += timeQuantum; } else if (burstTimeCopy[currActiveProcessID] &gt; 0) { timeCounter += burstTimeCopy[currActiveProcessID]; burstTimeCopy[currActiveProcessID] = 0; endTime[currActiveProcessID] = timeCounter; } currActiveProcessID++; it++; } } } int main() { unsigned num, timeQuantum; std::cout &lt;&lt; "Enter number of process: "; std::cin &gt;&gt; num; std::cout &lt;&lt; "\nEnter time quantum : "; std::cin &gt;&gt; timeQuantum; RoundRobin roundRobin(num, timeQuantum); roundRobin.calcEndTime(); roundRobin.calcTurnAroundTime(); roundRobin.calcWaitingTime(); roundRobin.printInfo(); } </code></pre>
[]
[ { "body": "<p>At first glance, in <code>Scheduler</code>, I would replace</p>\n\n<pre><code>std::vector&lt;Data&gt; data;\nstd::vector&lt;unsigned&gt; waitingTime;\nstd::vector&lt;unsigned&gt; turnAroundTime;\nstd::vector&lt;unsigned&gt; endTime;\n</code></pre>\n\n<p>by</p>\n\n<pre><code>struct Process {\n D...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-02T13:36:38.350", "Id": "197659", "Score": "5", "Tags": [ "c++", "c++11" ], "Title": "Follow up: CPU Scheduling Algorithm (SJF, priority & Round Robin)" }
197659
<p>I apologize for that title, lol.</p> <p>I have a Java method that I'm writing where I want to be able to pass in an array of Objects and two interfaces that will be used for lambda expressions that specify a particular value to use for calculation.</p> <p>It's part of a larger class that I want to use for all kinds of Statistics calculations, but I started with calculating correlation because it's most relevant to the specific problem I want to solve.</p> <pre><code>import java.lang.IllegalArgumentException; import java.util.Arrays; import java.util.stream.Stream; import java.util.stream.Collectors; import java.util.List; public class Statistics { //1. This method is really unreadable public static &lt;O&gt; double getCorrelation(O[] a, Fetchable&lt;O, Double&gt; dataPointA, Fetchable&lt;O, Double&gt; dataPointB) { Double[] temp = Arrays.stream(a).map(x -&gt; dataPointA.fetch(x)).collect(Collectors.toList()).toArray(new Double[0]); Double[] temp2 = Arrays.stream(a).map(x -&gt; dataPointB.fetch(x)).collect(Collectors.toList()).toArray(new Double[0]); return getCorrelation(temp, temp2); } public static double getCorrelation(double[] a, double[] b) { if (a.length != b.length) { //2. Is this the best Exception for this case? throw new IllegalArgumentException(); } double sumA = 0.0; double sumB = 0.0; double sumSquareA = 0.0; double sumSquareB = 0.0; double sumAB = 0.0; for(int i = 0; i &lt; a.length; i++) { sumA += a[i]; sumB += b[i]; sumSquareA += a[i] * a[i]; sumSquareB += b[i] * b[i]; sumAB += a[i] * b[i]; } int n = a.length; return (n * sumAB - sumA * sumB) / (Math.sqrt(n * sumSquareA - sumA * sumA) * Math.sqrt(n * sumSquareB - sumB * sumB)); } private static double getCorrelation(Double[] a, Double[] b) { if (a.length != b.length) { //2. Is this the best Exception for this case? throw new IllegalArgumentException(); } //3. Is there a better way to do this conversion from Double[] to double[]? double doubleArrA[] = new double[a.length]; double doubleArrB[] = new double[a.length]; for (int i = 0; i &lt; a.length; i++) { doubleArrA[i] = (double)a[i]; doubleArrB[i] = (double)b[i]; } return getCorrelation(doubleArrA, doubleArrB); } interface Fetchable&lt;T1, T2&gt; { public T2 fetch(T1 a); } //main function for testing public static void main(String[] args) { //this class is defined in another file; it's a simple class with four public doubles I made just to test TestDataPoint a[] = new TestDataPoint[5]; a[0] = new TestDataPoint(); a[0].w = 3; a[0].x = 0; a[0].y = 4; a[0].z = 9; a[1] = new TestDataPoint(); a[1].w = 1; a[1].x = 8; a[1].y = 3; a[1].z = 2; a[2] = new TestDataPoint(); a[2].w = 7; a[2].x = 4; a[2].y = 4; a[2].z = 0; a[3] = new TestDataPoint(); a[3].w = 3; a[3].x = 1; a[3].y = 0; a[3].z = 1; a[4] = new TestDataPoint(); a[4].w = 6; a[4].x = 3; a[4].y = 9; a[4].z = 8; a[1] = new TestDataPoint(); System.out.println(getCorrelation(a, p -&gt; p.w, q -&gt; q.z)); System.out.println(getCorrelation(a, p -&gt; p.x, q -&gt; q.z)); System.out.println(getCorrelation(a, p -&gt; p.y, q -&gt; q.z)); System.out.println(getCorrelation(a, p -&gt; p.z, q -&gt; q.z)); } } </code></pre> <p>It works pretty well; I've tried it and it seems to do exactly what I want. There are a few things I want to look at, though:</p> <ol> <li>That crazy method is absurdly unreadable.</li> <li>Is IllegalArgumentException the best Exception for the case where the method cannot execute properly because arrays of differing lengths are provided?</li> <li>Is there any easily readable way to convert Double[] to double[] without the loop I used in getCorrelation(Double[] a, Double[] b)?</li> </ol> <p>Thanks in advance.</p>
[]
[ { "body": "<p><strong>To focus on your initial questions</strong></p>\n\n<blockquote>\n <p>1) That crazy method is absurdly unreadable.</p>\n</blockquote>\n\n<p>I don't think it's too bad. You can improve it by using method references rather than lambdas and the <a href=\"https://docs.oracle.com/javase/8/docs/...
{ "AcceptedAnswerId": "197669", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-02T13:57:40.333", "Id": "197660", "Score": "0", "Tags": [ "java", "generics", "interface", "lambda", "exception" ], "Title": "Using a wrapper on a primitive as a generic for an interface used for Java lambda" }
197660
<p>I was recently playing around with some code, and someone mentioned that my code uses too many classes. I didn't realize I've been doing ES6 incorrectly for so long. </p> <p>I'm having a hard time finding a way to organize my code in a way that reads nicely. I say this coming from a C# background. </p> <p>Thanks for your time, everyone.</p> <pre><code>class Producer { constructor(starterString) { this.rules = []; this.createRules(); this.producedString = starterString; } createRules() { this.rules.add(new RuleAddE()); this.rules.add(new RuleAddNumberOne()); } produce() { for(var i = 0, len = this.rules.length; i &lt; len; i++) { this.producedString = this.rules[i].run(this.producedString); } return this.producedString; } } class Rule { constructor() { this.applied = false; } run() { } } class RuleAddE extends Rule { constructor() { super(); } run(stringToChange) { this.applied = true; return stringToChange + "e"; } } class RuleAddNumberOne extends Rule { constructor() { super(); } run(stringToChange) { this.applied = true; return stringToChange + "1"; } } var producer = new Producer("aa 1hdheb"); console.log(producer.produce()); </code></pre> <p>How could I improve this code with more proper structure?</p>
[]
[ { "body": "<p><strong>1</strong>. You have classes but you do not effectively <em>need</em> them because they do not keep any state (even the <code>applied</code> field is actually unused). In C# you do not have much options (unless they're local) but in JavaScript you can use functions anywhere:</p>\n\n<pre><c...
{ "AcceptedAnswerId": "197670", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-02T14:07:13.427", "Id": "197664", "Score": "3", "Tags": [ "javascript", "ecmascript-6" ], "Title": "Produces a string based on rules" }
197664
<p>Please help me improving this existing, working code. I am not asking you to change what it does, as it handles connections already perfectly as designed by my own specs. I just want the code to be reviewed to be sure.</p> <pre><code>#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os, ssl from socketserver import ThreadingMixIn from http.server import SimpleHTTPRequestHandler, HTTPServer global sslcontext sslcontext = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH) sslcontext.options |= ssl.OP_NO_TLSv1 sslcontext.options |= ssl.OP_NO_TLSv1_1 sslcontext.protocol = ssl.PROTOCOL_TLSv1_2 sslcontext.set_ciphers("ECDHE-ECDSA-AES256-GCM-SHA384 ECDHE-ECDSA-CHACHA20-POLY1305") sslcontext.set_ecdh_curve("secp384r1") sslcontext.load_cert_chain("/home/pi/keys/fullchain.pem", "/home/pi/keys/privkey.pem") class HSTSHandler(SimpleHTTPRequestHandler): def end_headers(self): self.send_header("Strict-Transport-Security", "max-age=63072000; includeSubDomains; preload") SimpleHTTPRequestHandler.end_headers(self) class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): daemon_threads = True def main(): try: os.chdir("/media/external")#auto-change working directory SimpleHTTPRequestHandler.sys_version = "0.1"#display custom Python system version SimpleHTTPRequestHandler.server_version = "0.2"#display custom server software version my_server = ThreadedHTTPServer(('', 443), HSTSHandler) my_server.socket = sslcontext.wrap_socket(my_server.socket, server_side=True) print('Starting server, use &lt;Ctrl-C&gt; to stop') my_server.serve_forever() except KeyboardInterrupt: print(' received, shutting down server') my_server.shutdown() if __name__ == '__main__': main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-02T15:00:47.713", "Id": "381067", "Score": "1", "body": "What does this *actually* do? How is /media/external significant?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T11:03:19.143", "Id": "381163...
[ { "body": "<ol>\n<li><p>When importing names from a location (module, package, dynamic library, ...), don't mix multiple locations on a single line. That is, this:</p>\n\n<pre><code>import os, ssl\n</code></pre>\n\n<p>... should be:</p>\n\n<pre><code>import os\nimport ssl\n</code></pre>\n\n<p>This is purely a s...
{ "AcceptedAnswerId": "197961", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-02T14:46:09.820", "Id": "197666", "Score": "2", "Tags": [ "python", "python-3.x", "socket", "https" ], "Title": "Actively writing an HTTPS webserver in Python 3" }
197666
<p>I have a dict with a series of <code>bools</code> to specify if a particular aspect of my program will be run (e.g. <code>settings['A']</code> and <code>settings['B']</code>). </p> <p>If they are run the results need to go into an aptly named directory. The directory names (not the entire path) are also stored in the dict (e.g. <code>settings['outputDirNameOut1']</code> and <code>settings['outputDirNameA']</code>) </p> <p>In order to create the directories I'm using the following code.</p> <pre><code>for each in filePathList: path = os.path.dirname(each) if not os.path.exists(os.path.join(path, settings['outputDirNameOut1'])): os.makedirs(os.path.join(path, settings['outputDirNameOut1'])) if settings['A'] is True and not os.path.exists(os.path.join(path, settings['outputDirNameA'])): os.makedirs(os.path.join(path, settings['outputDirNameA'])) if settings['B'] is True and not os.path.exists(os.path.join(path, settings['outputDirNameB'])): os.makedirs(os.path.join(path, settings['outputDirNameThreshold'])) if settings['C'] is True and not os.path.exists(os.path.join(path, settings['outputDirNameC'])): os.makedirs(os.path.join(path, settings['outputDirNameC'])) os.makedirs(os.path.join(path, settings['outputDirNameOut2'])) if settings['D'] is True and not os.path.exists(os.path.join(path, settings['outputDirNameOut2'])): os.makedirs(os.path.join(path, settings['outputDirNameOut2'])) </code></pre> <p>I'm wondering if there's a simpler, easier to read way to accomplish this.</p>
[]
[ { "body": "<p>Any time there's a repeating pattern that's very obvious like this you\nmight consider using another loop, or a function, or some other\nabstraction mechanism available. To me this also looks like example\ncode - please post the actual code you're using!</p>\n\n<p>So first a few comments:</p>\n\n...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-02T17:54:44.387", "Id": "197673", "Score": "1", "Tags": [ "python", "python-2.x", "file-system" ], "Title": "Create directories for outputs based on setting" }
197673
<p>I am trying to make a stored procedure and pass some parameters for filtering. As soon as filtering is in horizon, code has to be as generic as possible with as few as possible <code>if</code>, <code>else</code>, etc.</p> <p>How could I make this more readable? Can I use functions for this?</p> <pre><code>ALTER PROCEDURE [dbo].[Stats] @network VARCHAR(9) = NULL, @name VARCHAR(100) = NULL, @version VARCHAR(15) = NULL, @year INT = NULL, @month INT = NULL, @day INT = NULL, @from DATE = null, @to DATE = null AS BEGIN SET nocount ON; DECLARE @fromYear INT = NULL; SET @fromYear = CASE WHEN @from IS NOT NULL THEN Datepart(year, @from) END DECLARE @fromMonth INT = NULL; SET @fromMonth = CASE WHEN @from IS NOT NULL THEN Datepart(month, @from) END DECLARE @fromDay INT = NULL; SET @fromDay = CASE WHEN @from IS NOT NULL THEN Datepart(day, @from) END DECLARE @toYear INT = NULL; SET @toYear = CASE WHEN @to IS NOT NULL THEN Datepart(year, @to) ELSE @fromYear END DECLARE @toMonth INT = NULL; SET @toMonth = CASE WHEN @to IS NOT NULL THEN Datepart(month, @to) ELSE @fromMonth END DECLARE @toDay INT = NULL; SET @toDay = CASE WHEN @to IS NOT NULL THEN Datepart(day, @to) ELSE @fromDay END SELECT GS.[contractaddress], GS.[network], GS.[rounds], GS.[sessions], GS.[handle], GS.[hold], GS.[year], GS.[month], GS.[day], G.[name], G.[version], DATEFROMPARTS(GS.[Year], GS.[Month], GS.[Day]) as [Date] FROM [dbo].[gamestatsdaily] AS GS INNER JOIN [dbo].[game] AS G ON GS.contractaddress = G.[contractaddress] WHERE ( @network IS NULL OR ( GS.network = Upper(@network) ) ) AND ( @name IS NULL OR ( GS.[contractaddress] IN (SELECT [contractaddress] FROM [dbo].[game] WHERE [name] = @name AND [version] = @version AND [network] = @network) ) ) AND ( @year IS NULL OR GS.[Year] = @year ) AND ( @month IS NULL OR GS.[Month] = @month ) AND ( @day IS NULL OR GS.[Day] = @day ) AND ( @from IS NULL OR ( GS.[Year] &lt;= @fromYear AND @toYear &gt;= GS.[Year] AND GS.[Month] &lt;= @fromMonth AND @toMonth &gt;= GS.[Month] AND GS.[Day] &lt;= @fromMonth AND @toMonth &gt;= GS.[Day])) ORDER BY GS.[year] ASC, GS.[month] ASC, GS.[day] ASC END </code></pre>
[]
[ { "body": "<h3>Here is the revised SQL I came up with</h3>\n\n<p>Below this code is a list of tips for writing better SQL. </p>\n\n<hr>\n\n<pre><code>ALTER PROCEDURE [dbo].[Stats] \n @network VARCHAR(9) = NULL\n , @name VARCHAR(100) = NULL\n , @version VARCHAR(15) = NULL\n , @year INT = NULL\n ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-02T18:01:32.850", "Id": "197674", "Score": "0", "Tags": [ "sql", "t-sql", "stored-procedure" ], "Title": "Filtering query by date built from integers" }
197674
<p>I've implemented a card game called Macau. This is a follow-up from this <a href="https://softwareengineering.stackexchange.com/questions/373133/designing-a-card-game">topic</a>, where I tried to get the game's design right before actually implementing it. </p> <p>Even if the game is presented on that topic, I will give a brief explanation as it follows. The game consists of a standard-deck that contains 52 cards. At the very beginning, every player receives 5 cards from the deck. (The first player that runs out of cards is the winner). Then, a card is put on the top of the pile. A player can put on the pile any card that is compatible with the top one. Two cards are compatible if they have the same suit or the same rank. There also exist several special cards:</p> <ul> <li>Rank: 2 or 3. This will require the next player to receive 2/3 cards from the deck if he doesn't have a 4 card with the same suit.</li> <li>Rank: A (Ace). This will simply skip the next player's turn.</li> </ul> <p>Please note that, even if I mentioned 7 and the Joker as special cards in that topic, in the current state of the game they are not implemented. More precisely, the Jokers are disabled and the 7 is considered a normal card.</p> <p>Here is the diagram of my classes. <a href="https://i.stack.imgur.com/NMbJo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NMbJo.png" alt="diagram"></a></p> <p>And here is the code:</p> <p><strong>CardProperties.hpp</strong></p> <pre><code>#pragma once #include &lt;array&gt; #include &lt;string&gt; constexpr unsigned int numberOfSuits{ 6 }; constexpr unsigned int numberOfRanks{ 14 }; const std::array&lt;std::string, numberOfSuits&gt; suits{"Diamonds","Clubs" , "Hearts","Spades" , "Red", "Black"}; const std::array&lt;std::string, numberOfRanks&gt; ranks{ "A", "2","3","4","5","6","7","8","9","10", "J","Q","K","Joker" }; enum class Suit { Diamonds, Clubs, Hearts, Spades, Red, Black, }; enum class Rank { Ace = 0, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Joker, }; </code></pre> <p><strong>Card.hpp</strong></p> <pre><code>#pragma once #include &lt;ostream&gt; #include "CardProperties.hpp" class Game; class Card { public: Card(const Suit&amp; suit, const Rank&amp; rank); Card(const Rank&amp; rank, const Suit&amp; suit); bool isCompatibleWith(const Card&amp; other) const; bool operator != (const Card&amp; other) const; friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const Card&amp; card); //needed for std::set bool operator == (const Card&amp; other) const; bool operator &lt; (const Card&amp; other) const; friend class Game; private: bool invalidCardProperties(const Suit&amp; suit, const Rank&amp; rank) const; Suit _suit; Rank _rank; }; </code></pre> <p><strong>Exceptions.hpp</strong></p> <pre><code>#pragma once #include &lt;exception&gt; #include &lt;string&gt; class InvalidCardException : public std::exception { public: InvalidCardException(const std::string&amp; errorMessage); const char* what() const override; private: std::string _errorMessage; }; class EmptyDeckException : public std::exception { public: EmptyDeckException(const std::string&amp; errorMessage); const char* what() const override; private: std::string _errorMessage; }; class NotEnoughCardsException : public std::exception { public: NotEnoughCardsException(const std::string&amp; errorMessage); const char* what() const override; private: std::string _errorMessage; }; class InvalidNumberOfPlayersException : public std::exception { public: InvalidNumberOfPlayersException(const std::string&amp; errorMessage); const char* what() const override; private: std::string _errorMessage; }; </code></pre> <p><strong>Card.cpp</strong></p> <pre><code>#include "Card.hpp" #include "Exceptions.hpp" bool Card::invalidCardProperties(const Suit&amp; suit, const Rank&amp; rank) const { if (rank == Rank::Joker &amp;&amp; (suit != Suit::Black &amp;&amp; suit != Suit::Red)) return true; if (rank != Rank::Joker &amp;&amp; (suit == Suit::Black || suit == Suit::Red)) return true; return false; } Card::Card(const Suit&amp; suit, const Rank&amp; rank) : _suit(suit), _rank(rank) { if (invalidCardProperties(suit, rank)) throw InvalidCardException("The Joker can only be red or black.\n"); } Card::Card(const Rank&amp; rank, const Suit&amp; suit) : Card(suit,rank) {} bool Card::isCompatibleWith(const Card&amp; other) const { return _suit == other._suit || _rank == other._rank; } bool Card::operator&lt; (const Card&amp; other) const { return (static_cast&lt;int&gt;(_rank) &lt; static_cast&lt;int&gt;(other._rank)); } bool Card::operator == (const Card&amp; other) const { return _rank == other._rank &amp;&amp; _suit == other._suit; } bool Card::operator!= (const Card&amp; other) const { return !((*this) == other); } std::ostream&amp; operator &lt;&lt; (std::ostream&amp; os, const Card&amp; card) { return os &lt;&lt; '[' &lt;&lt; suits[static_cast&lt;int&gt;(card._suit)] &lt;&lt; " " &lt;&lt; ranks[static_cast&lt;int&gt;(card._rank)] &lt;&lt; ']'; } </code></pre> <p><strong>Deck.hpp</strong></p> <pre><code>#pragma once #include &lt;vector&gt; #include "Card.hpp" class Deck { public: Deck(); const Card&amp; dealCard(); std::vector&lt;Card&gt; dealCards(const unsigned int&amp; numberOfCards); void refill(const std::vector&lt;Card&gt;&amp; cards); void refill(const Card&amp; card); private: void fill(); void shuffle(); std::vector&lt;Card&gt; _cards; }; </code></pre> <p><strong>Deck.cpp</strong></p> <pre><code>#include "Deck.hpp" #include "Exceptions.hpp" #include &lt;random&gt; Deck::Deck() { fill(); shuffle(); } const Card&amp; Deck::dealCard() { if (_cards.empty()) throw EmptyDeckException(""); Card&amp; topCard(_cards.back()); _cards.pop_back(); return topCard; } std::vector&lt;Card&gt; Deck::dealCards(const unsigned int&amp; numberOfCards) { if (_cards.size() &lt; numberOfCards) throw NotEnoughCardsException(""); std::vector&lt;Card&gt; requestedCards; auto it{ std::prev(_cards.end(), numberOfCards) }; std::move(it, _cards.end(), std::back_inserter(requestedCards)); _cards.erase(it, _cards.end()); return requestedCards; } void Deck::fill() { constexpr unsigned int numberOfSuitsWithoutJokerSpecificOnes{ 4 }; constexpr unsigned int numberOfRanksWithoutJokers{ 13 }; for (unsigned int index1 = 0; index1 &lt; numberOfRanksWithoutJokers; ++index1) { for (unsigned int index2 = 0; index2 &lt; numberOfSuitsWithoutJokerSpecificOnes; ++index2) { Card card(static_cast&lt;Suit&gt;(index2), static_cast&lt;Rank&gt;(index1)); _cards.push_back(card); } } /*Card redJoker(Suit::Red, Rank::Joker); _cards.push_back(redJoker); Card blackJoker(Suit::Black, Rank::Joker); _cards.push_back(blackJoker);*/ } void Deck::shuffle() { std::mt19937 randomNumberGenerator{ std::random_device{}() }; std::shuffle(_cards.begin(), _cards.end(), randomNumberGenerator); } void Deck::refill(const std::vector&lt;Card&gt;&amp; cards) { _cards.insert(_cards.end(), cards.begin(), cards.end()); shuffle(); } void Deck::refill(const Card&amp; card) { _cards.push_back(card); shuffle(); } </code></pre> <p><strong>Pile.hpp</strong></p> <pre><code>#pragma once #include "Card.hpp" #include &lt;vector&gt; class Pile { public: void addCard(const Card&amp; card); const Card&amp; eraseTopCard(); const Card&amp; getTopCard(); friend std::ostream&amp; operator &lt;&lt; (std::ostream&amp; os, const Pile&amp; pile); std::vector&lt;Card&gt; releaseAllCardsButFirst(); private: std::vector&lt;Card&gt; _alreadyPlayedCards; }; </code></pre> <p><strong>Pile.cpp</strong></p> <pre><code>#include "Pile.hpp" #include "Exceptions.hpp" #include &lt;algorithm&gt; constexpr unsigned int minimumValueOfPlayedCards{ 1 }; constexpr unsigned int lastElementOffset{ 1 }; void Pile::addCard(const Card&amp; card) { _alreadyPlayedCards.push_back(card); } std::vector&lt;Card&gt; Pile::releaseAllCardsButFirst() { std::vector&lt;Card&gt; releasedCards; auto it{ std::next(_alreadyPlayedCards.begin(), _alreadyPlayedCards.size() - lastElementOffset) }; std::move(_alreadyPlayedCards.begin(), it, std::back_inserter(releasedCards)); _alreadyPlayedCards.erase(_alreadyPlayedCards.begin(), it); return releasedCards; } const Card&amp; Pile::getTopCard() { return _alreadyPlayedCards.back(); } const Card&amp; Pile::eraseTopCard() { const Card&amp; requestedCard{ _alreadyPlayedCards.back() }; _alreadyPlayedCards.pop_back(); return requestedCard; } std::ostream &amp; operator&lt;&lt;(std::ostream &amp; os, const Pile &amp; pile) { return os &lt;&lt; pile._alreadyPlayedCards.back(); } </code></pre> <p><strong>Hand.hpp</strong></p> <pre><code>#pragma once #include &lt;vector&gt; #include "Card.hpp" class Hand { public: void addCard(const Card&amp; card); void addCards(const std::vector&lt;Card&gt;&amp; cards); void removeCard(const Card&amp; card); void removeCard(const unsigned int&amp; cardNumber); std::vector&lt;Card&gt;::iterator findCard(const Card&amp; card); const Card&amp; getCard(const Card&amp; card); const Card&amp; getCard(const unsigned int&amp; cardNumber); const unsigned int numberOfCards() const; friend std::ostream&amp; operator &lt;&lt; (std::ostream&amp; os, const Hand&amp; hand); private: std::vector&lt;Card&gt; _cards; }; </code></pre> <p><strong>Hand.cpp</strong></p> <pre><code>#include "Hand.hpp" #include &lt;algorithm&gt; constexpr unsigned int indexOffset{ 1 }; void Hand::addCard(const Card&amp; card) { _cards.push_back(card); } void Hand::removeCard(const Card&amp; card) { auto it{ findCard(card) }; _cards.erase(it); } void Hand::addCards(const std::vector&lt;Card&gt;&amp; cards) { _cards.insert(_cards.end(), cards.begin(), cards.end()); } void Hand::removeCard(const unsigned int&amp; cardNumber) { _cards.erase(std::next(_cards.begin(), cardNumber - indexOffset)); } std::vector&lt;Card&gt;::iterator Hand::findCard(const Card&amp; card) { return std::find(_cards.begin(), _cards.end(), card); } const Card&amp; Hand::getCard(const Card&amp; card) { auto it{ findCard(card) }; return *it; } const Card&amp; Hand::getCard(const unsigned int&amp; cardNumber) { return _cards[cardNumber - indexOffset]; } const unsigned int Hand::numberOfCards() const { return _cards.size(); } std::ostream&amp; operator &lt;&lt; (std::ostream&amp; os, const Hand&amp; hand) { for (unsigned int index = 0; index &lt; hand._cards.size(); ++index) os &lt;&lt; "Card number: " &lt;&lt; index + indexOffset &lt;&lt;" "&lt;&lt; hand._cards[index] &lt;&lt; '\n'; return os &lt;&lt; '\n'; } </code></pre> <p><strong>Player.hpp</strong></p> <pre><code>#pragma once #include "Hand.hpp" #include &lt;vector&gt; class Player { public: Player(const std::string&amp; name = "undefined_name"); const Card&amp; putCard(const Card&amp; card); Card putCard(const unsigned int&amp; cardNumber); const Card&amp; getCard(const unsigned int&amp; cardNumber); void receive(const Card&amp; card); void receive(const std::vector&lt;Card&gt;&amp; cards); const unsigned int numberOfCards() const; friend std::ostream&amp; operator &lt;&lt; (std::ostream&amp; os, const Player&amp; player); const std::string name() const; private: Hand _handOfCards; std::string _name; }; </code></pre> <p><strong>Player.cpp</strong></p> <pre><code>#include "Player.hpp" Player::Player(const std::string&amp; name) : _name(name) {} const Card&amp; Player::putCard(const Card&amp; card) { const Card&amp; requestedCard{ _handOfCards.getCard(card) }; _handOfCards.removeCard(card); return requestedCard; } Card Player::putCard(const unsigned int&amp; cardNumber) { Card requestedCard{ _handOfCards.getCard(cardNumber) }; _handOfCards.removeCard(cardNumber); return requestedCard; } const Card&amp; Player::getCard(const unsigned int&amp; cardNumber) { return _handOfCards.getCard(cardNumber); } void Player::receive(const Card&amp; card) { _handOfCards.addCard(card); } void Player::receive(const std::vector&lt;Card&gt;&amp; cards) { _handOfCards.addCards(cards); } std::ostream&amp; operator &lt;&lt; (std::ostream&amp; os, const Player&amp; player) { return os &lt;&lt; player._name &lt;&lt; "'s cards.\n" &lt;&lt; player._handOfCards; } const unsigned int Player::numberOfCards() const { return _handOfCards.numberOfCards(); } const std::string Player::name() const { return _name; } </code></pre> <p><strong>Game.hpp</strong></p> <pre><code>#pragma once #include "Deck.hpp" #include "Pile.hpp" #include "Exceptions.hpp" #include "Player.hpp" #include &lt;set&gt; class Game { public: Game(const unsigned int&amp; numberOfPlayers = 2); void run(); private: void dealInitialCardsToEachPlayer(); void initializePlayerNames(); void receiveCardsFromDeck(Player&amp; player, const unsigned int&amp; numberOfCards); void putCardToPile(Player&amp; player, unsigned int&amp; cardNumber); void normalCardPlayerTurn(Player&amp; player); void specialCardPlayerTurn(Player&amp; player); void printInformationAboutThePlayerAndTheTopCardFromPile(const Player&amp; player) const; void printInformationAboutThePlayerAndTheTopCardFromPile(const Player&amp; player, const Rank&amp; rank) const; const Player&amp; findWinner(); bool isSpecialCard(const Card&amp; card) const; void validatePlayerCardCompatibilityWithPileTopCard(Player&amp; player, unsigned int&amp; cardNumber); std::vector&lt;Player&gt; _players; unsigned int _numberOfPlayers; Deck _deck; Pile _pile; bool _isRunning; const std::set&lt;Card&gt; _specialCards{ { Suit::Clubs, Rank::Two },{ Suit::Diamonds, Rank::Two },{ Suit::Hearts, Rank::Two },{ Suit::Spades, Rank::Two } ,{ Suit::Clubs, Rank::Three },{ Suit::Diamonds, Rank::Three },{ Suit::Hearts, Rank::Three },{ Suit::Spades, Rank::Three }, /*,{ Suit::Clubs, Rank::Seven },{ Suit::Diamonds, Rank::Seven },{ Suit::Hearts, Rank::Seven },{ Suit::Spades, Rank::Seven },*/ { Suit::Clubs, Rank::Ace },{ Suit::Diamonds, Rank::Ace },{ Suit::Hearts, Rank::Ace },{ Suit::Spades, Rank::Ace } }; }; </code></pre> <p><strong>Game.cpp</strong></p> <pre><code>#include "Game.hpp" #include "GameConstants.hpp" #include &lt;set&gt; #include &lt;iostream&gt; #include &lt;algorithm&gt; void Game::initializePlayerNames() { std::string currentPlayerName; for (unsigned int index = 0; index &lt; _numberOfPlayers; ++index) { std::cout &lt;&lt; "Name: "; std::getline(std::cin, currentPlayerName); Player player(currentPlayerName); _players.push_back(player); } } Game::Game(const unsigned int&amp; numberOfPlayers) : _numberOfPlayers(numberOfPlayers), _isRunning(true) { if (numberOfPlayers &gt; maximumNumberOfPlayers || numberOfPlayers &lt; minimumNumberOfPlayers) throw InvalidNumberOfPlayersException("The minimum number of players is 2, while the maximum number of players is 9."); initializePlayerNames(); } void Game::printInformationAboutThePlayerAndTheTopCardFromPile(const Player&amp; player) const { std::cout &lt;&lt; "\nTop card from pile: " &lt;&lt; _pile &lt;&lt; "\n"; std::cout &lt;&lt; player &lt;&lt; "\n"; std::cout &lt;&lt; "What card would you like to put? If you don't have any compatible card or you wish to skip the turn, enter 0.\n"; } void Game::printInformationAboutThePlayerAndTheTopCardFromPile(const Player&amp; player, const Rank&amp; rank) const { switch (rank) { case Rank::Two: { std::cout &lt;&lt; "\nTop card from pile: " &lt;&lt; _pile &lt;&lt; "\nThis is 2 card and you will need to receive 2 cards from the deck.\n" &lt;&lt; "If you have a 4 card that has the same suit, then you can stop it.\n"; std::cout &lt;&lt; "What card would you like to put? If don't have a compatible 4 card, then enter 0.\n" &lt;&lt; player &lt;&lt; "\n"; break; } case Rank::Three: { std::cout &lt;&lt; "\nTop card from pile: " &lt;&lt; _pile &lt;&lt; "\nThis is 3 card and you will need to receive 3 cards from the deck.\n" &lt;&lt; "If you have a 4 card that has the same suit, then you can stop it.\n"; std::cout &lt;&lt; "What card would you like to put? If don't have a compatible 4 card, then enter 0.\n" &lt;&lt; player &lt;&lt; "\n"; break; } case Rank::Seven: { std::cout &lt;&lt; "\nTop card from pile: " &lt;&lt; _pile &lt;&lt; "\nThis is a 7 card and you will need to put down a card that has the specified suit. If you have a Joker, then" &lt;&lt; " you can put it. Enter 0 if you don't have such a compatible card.\n" &lt;&lt; player &lt;&lt; "\n"; break; } case Rank::Ace: { std::cout &lt;&lt; "\nTop card from pile: " &lt;&lt; _pile &lt;&lt; "\nThis is an A card."&lt;&lt; player.name() &lt;&lt;"'s turn was skipped.\n"; break; } } } void Game::receiveCardsFromDeck(Player&amp; player, const unsigned int&amp; numberOfCards) { try { player.receive(_deck.dealCards(numberOfCards)); } catch (const NotEnoughCardsException&amp; error) { _deck.refill(_pile.releaseAllCardsButFirst()); player.receive(_deck.dealCards(numberOfCards)); } catch (const EmptyDeckException&amp; error) { _deck.refill(_pile.releaseAllCardsButFirst()); player.receive(_deck.dealCards(numberOfCards)); } } void Game::putCardToPile(Player&amp; player, unsigned int&amp; cardNumber) { _pile.addCard(player.putCard(cardNumber)); } bool Game::isSpecialCard(const Card&amp; card) const { return (_specialCards.find(card) != _specialCards.end()); } const Player&amp; Game::findWinner() { auto it{ std::find_if(_players.begin(), _players.end(), [&amp;](const Player&amp; player) { return !player.numberOfCards(); }) }; return *it; } void Game::dealInitialCardsToEachPlayer() { std::for_each(_players.begin(), _players.end(), [this](Player&amp; player) {player.receive(_deck.dealCards(initialNumberOfCardsPerPlayer)); }); } void Game::validatePlayerCardCompatibilityWithPileTopCard(Player&amp; player, unsigned int&amp; cardNumber) { while (!player.getCard(cardNumber).isCompatibleWith(_pile.getTopCard())) { std::cout &lt;&lt; "This card is incompatible.\nEnter another card or enter 0 to skip your turn.\n"; std::cin &gt;&gt; cardNumber; if (!cardNumber) break; } } void Game::normalCardPlayerTurn(Player&amp; player) { unsigned int cardNumber{ 0 }; printInformationAboutThePlayerAndTheTopCardFromPile(player); std::cin &gt;&gt; cardNumber; if (!cardNumber) receiveCardsFromDeck(player, defaultNumberOfCardsToPick); else { validatePlayerCardCompatibilityWithPileTopCard(player, cardNumber); if (!cardNumber) receiveCardsFromDeck(player, defaultNumberOfCardsToPick); else putCardToPile(player, cardNumber); } if (!player.numberOfCards()) _isRunning = false; } void Game::specialCardPlayerTurn(Player&amp; player) { unsigned int cardNumber{ 0 }; switch (_pile.getTopCard()._rank) { case Rank::Two: { printInformationAboutThePlayerAndTheTopCardFromPile(player, Rank::Two); std::cin &gt;&gt; cardNumber; if (!cardNumber) receiveCardsFromDeck(player, neededCardsToPickForTwo); else if (player.getCard(cardNumber)._rank == Rank::Four &amp;&amp; player.getCard(cardNumber).isCompatibleWith(_pile.getTopCard())) putCardToPile(player, cardNumber); else { validatePlayerCardCompatibilityWithPileTopCard(player, cardNumber); if (!cardNumber) receiveCardsFromDeck(player, neededCardsToPickForTwo); else putCardToPile(player, cardNumber); } break; } case Rank::Three: { printInformationAboutThePlayerAndTheTopCardFromPile(player, Rank::Three); std::cin &gt;&gt; cardNumber; if (!cardNumber) receiveCardsFromDeck(player, neededCardsToPickForThree); else if (player.getCard(cardNumber)._rank == Rank::Four &amp;&amp; player.getCard(cardNumber).isCompatibleWith(_pile.getTopCard())) putCardToPile(player, cardNumber); else { validatePlayerCardCompatibilityWithPileTopCard(player, cardNumber); if (!cardNumber) receiveCardsFromDeck(player, neededCardsToPickForThree); else putCardToPile(player, cardNumber); } break; } case Rank::Ace: { printInformationAboutThePlayerAndTheTopCardFromPile(player, Rank::Ace); break; } } if (!player.numberOfCards()) _isRunning = false; } void Game::run() { dealInitialCardsToEachPlayer(); _pile.addCard(_deck.dealCard()); while (isSpecialCard(_pile.getTopCard())) { _deck.refill(_pile.eraseTopCard()); _pile.addCard(_deck.dealCard()); } Card lastCard{ _pile.getTopCard() }; bool specialCardHadEffect{ false }; while (_isRunning) { for (auto&amp; currentPlayer : _players) { if (!isSpecialCard(_pile.getTopCard())) normalCardPlayerTurn(currentPlayer); else { if (isSpecialCard(_pile.getTopCard()) &amp;&amp; !specialCardHadEffect) { specialCardPlayerTurn(currentPlayer); specialCardHadEffect = true; } else normalCardPlayerTurn(currentPlayer); } if (_pile.getTopCard() != lastCard) { specialCardHadEffect = false; lastCard = _pile.getTopCard(); } if (!_isRunning) break; } } std::cout &lt;&lt; "\tThe winner is " &lt;&lt; findWinner().name() &lt;&lt; ".\n"; } </code></pre> <p><strong>main.cpp</strong></p> <pre><code>#include "Game.hpp" #include &lt;iostream&gt; int main() { unsigned int numberOfPlayers{ 0 }; std::cout &lt;&lt; "Number of players.\n"; std::cin &gt;&gt; numberOfPlayers; std::cin.ignore(); try { Game game(numberOfPlayers); game.run(); } catch (const InvalidNumberOfPlayersException&amp; error) { std::cerr &lt;&lt; error.what() &lt;&lt; "\n"; std::cin &gt;&gt; numberOfPlayers; Game game(numberOfPlayers); game.run(); } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-02T19:44:04.010", "Id": "381097", "Score": "0", "body": "BTW, what are you using to draw your class diagrams?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T07:49:35.000", "Id": "381134", "Score...
[ { "body": "<p>Writing identifiers with a leading underscore is a bad idea, and is generally dissuaded as a style. Note that it is legal for member names if (and only if) the next character is not a capital letter or another underscore. </p>\n\n<hr>\n\n<p>You used old-style syntax for some member initializers. ...
{ "AcceptedAnswerId": "197688", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-02T18:21:39.377", "Id": "197675", "Score": "8", "Tags": [ "c++", "object-oriented", "game", "playing-cards" ], "Title": "Macau Card Game" }
197675
<p>Finished my first lone project and I'm wondering if the execution is passable. This is a basic lbs to tons converter. The customer drives on the scale loaded, then dumps the load and returns unloaded to the scale again. We need to convert the leftover lbs to tons. I am wondering if this is a concise way to perform this task.</p> <p>loaded weight - unloaded weight = Total lbs in scrap</p> <p>total lbs * 0.0005 = weight in tons</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 calc() { let loadedAmount = document.getElementById("loaded").value; let unloadedAmount = document.getElementById("unloaded").value; let final = document.getElementById("result").value = Math.round(`${(loadedAmount - unloadedAmount) * 0.0005}` * 100)/100; let resultInPounds = document.getElementById("result").value = Math.round(`${(loadedAmount - unloadedAmount)}`); if (!loadedAmount) { document.getElementById("loaded").value=alert("waiting for an initial value for loaded"); } else { loadedAmount = parseInt(loadedAmount); } if (!unloadedAmount) { document.getElementById("unloaded").value = alert("waiting for an initial value for unloaded"); } else { unloadedAmount = parseInt(unloadedAmount); } if (loadedAmount &lt; unloadedAmount) { alert("loaded amount must be greater than unloaded amount"); } console.log(`loadedAmount: ${loadedAmount}`); console.log(`unloadedAmount: ${unloadedAmount}`); document.getElementById("result").innerHTML=final + " Tons or " + resultInPounds + " lbs"; console.log(result); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;&lt;/title&gt; &lt;style&gt; &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;header&gt;Negaunee Iron and Metal&lt;/header&gt; &lt;script src="app.js"&gt;&lt;/script&gt; &lt;div &gt;input loaded pounds &lt;input type="number" id="loaded" placeholder="Loaded..."&gt; &lt;/div&gt; &lt;div &gt; input unloaded pounds &lt;input type="number" id="unloaded" placeholder="Unloaded" &gt; &lt;/div&gt; &lt;div&gt;&lt;label type="number" id="result" &gt;&lt;/label&gt;&lt;/div&gt; &lt;button type="submit" id="button" onclick="calc()"&gt;Click To Convert&lt;/button&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-02T21:21:25.377", "Id": "381105", "Score": "1", "body": "\"total lbs * 0.0005 = weight in tons\" That's quite a rounding error you produce there, almost 10% just with one action. Are you sure you want to do this?" }, { "Content...
[ { "body": "<p>The <a href=\"https://www.w3.org/TR/2017/REC-html52-20171214/sec-forms.html#the-label-element\" rel=\"nofollow noreferrer\"><code>label</code> element</a> can be used for the labels of the <code>input</code> fields.</p>\n\n<p>The <a href=\"https://www.w3.org/TR/2017/REC-html52-20171214/sec-forms.h...
{ "AcceptedAnswerId": "197737", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-02T19:47:15.293", "Id": "197681", "Score": "2", "Tags": [ "javascript", "html", "unit-conversion" ], "Title": "Pounds-to-tons converter" }
197681
<p>Test data passes the test, so why does Codility keep failing it? Am I perhaps misunderstanding the requirement?</p> <pre><code>using System; class Solution { public int solution(int[] A) { int max = 0; for (var i = 0; i &lt; A.Length; i++) { for (var j = i + 1; j &lt; A.Length; j++) { for (var k = j + 1; k &lt; A.Length; k++) { var product = A[i] * A[j] * A[k]; var zeros = trailingZeros(product); //Console.WriteLine($"{product} - {zeros}"); if (zeros &gt; max) { max = zeros; } } } } return max; } private int trailingZeros(int N) { if (N == 0) { return 0; } int count = 0; while (!(N &lt;= 0 || N % 10 != 0)) { count++; N /= 10; } return count; } } </code></pre> <p>Test data:</p> <pre><code>A = [7, 15, 6, 20, 5, 10] A = [25, 10, 25, 10, 32] A = [1, 1, 110] A = [90, 76, 300, 10, 3, 5, 9, 1000000000] A = [100090, 10030, 1000, 90, 87655, 676345] A = [85, 65, 20, 50, 1, 0] A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] A = [10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 3, 90] A = [101, 307, 890, 208, 406, 701, 222, 445, 5432] A = [7, 15, 6, 20, 5, 10] A = [90, 70, 80] A = [900, 800, 700, 600, 500, 551, 662, 773, 884, 995] </code></pre> <p>Full description of the problem:</p> <blockquote> <p>Write a function:</p> <p>class Solution { public int solution(int[] A); }</p> <p>that, given an array of N positive integers, returns the maximum number of trailing zeros of the number obtained by multiplying three <strong>different</strong> elements from the array. Numbers are considered different if they are at different positions in the array.</p> <p>For example, given A = [7, 15, 6, 20, 5, 10], the function should return 3 (you can obtain three trailing zeros by taking the product of numbers 15, 20 and 10 or 20, 5 and 10).</p> <p>For another example, given A = [25, 10, 25, 10, 32], the function should return 4 (you can obtain four trailing zeros by taking the product of numbers 25, 25 and 32).</p> <p>Assume that:</p> <p>N is an integer within the range [3..100,000]; each element of array A is an integer within the range [1..1,000,000,000]. Complexity:</p> <p>expected worst-case time complexity is O(N*log(max(A))) expected worst-case space complexity is O(N) (not counting the storage required for input arguments).</p> </blockquote>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T15:05:12.227", "Id": "381193", "Score": "0", "body": "_so why does Codility keep failing it_ - I don't think Code Review is the right place for this question. We're reviewing code and not explain requirements." }, { "Content...
[ { "body": "<p>You must consider domain boundaries: <code>A</code> can contain integers in the range <code>[1..1,000,000,000]</code> so the largest possible product would be <code>1,000,000,000^3</code> which is way beyond <code>int.MaxValue</code> (and even <code>ulong.MaxValue</code>). One way to overcome this...
{ "AcceptedAnswerId": "197714", "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-02T21:14:59.300", "Id": "197686", "Score": "0", "Tags": [ "c#" ], "Title": "Codility: MaxZeroProduct challenge and solution" }
197686
<p>This is a <strong>follow-up post of my previous question: <a href="https://codereview.stackexchange.com/questions/197135/displaying-javascript-objects-structure-on-page-with-html#">Displaying JavaScript object's structure on page with HTML</a></strong> which looked at how to display all properties of a JavaScript object on a page similar to how the console behaves in browsers. In this first question, I had figured out how to render object that had cycles.</p> <p>Receiving valuable advice from <a href="https://codereview.stackexchange.com/users/142650/gerrit0">Gerrit0</a>, I changed a couple of things:</p> <ul> <li><p>used <code>template</code> to prepare the HTML elements with JavaScript this allows to safely parse string as strings, not HTML (using <code>textContent</code> instead of <code>innerHTML</code>)</p></li> <li><p>used the <code>details</code> element to make the foldable containers</p></li> <li><p>added some CSS styling</p></li> </ul> <p>Here's how it looks like:</p> <p><a href="https://i.stack.imgur.com/Bww1i.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Bww1i.gif" alt="enter image description here"></a></p> <hr> <p><strong>HTML templates</strong></p> <pre><code>&lt;template id="keyValue"&gt; &lt;div class="csle-property"&gt; &lt;span class="csle-key"&gt;&lt;/span&gt;: &lt;span class="csle-value"&gt;&lt;/span&gt; &lt;/div&gt; &lt;/template&gt; &lt;template id="folder"&gt; &lt;summary&gt; &lt;div&gt; &lt;div class="csle-key"&gt;&lt;/div&gt;: &lt;div class="csle-preview"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/summary&gt; &lt;/template&gt; </code></pre> <p><strong>JavaScript code:</strong></p> <pre><code>/** * Shows all the object's properties with a depth of 1 * @params {Object} object, its first level properties are shown * {HTMLElement} parent the element in which are displayed the properties * @return {undefined} */ const showObject = (object, parent = document.body) =&gt; { const template = { keyValue: document.querySelector('template#keyValue'), folder: document.querySelector('template#folder') } Object.entries(object).forEach(([key, value]) =&gt; { const objectClass = (value &amp;&amp; value.constructor) ? value.constructor : undefined; const isContainer = (objectClass == Object) || (objectClass == Array); if (isContainer) { // !better naming for (objects, arrays, maps, sets)? const element = document.importNode(template.folder.content, true); const children = { key: element.querySelector('.csle-key'), preview: element.querySelector('.csle-preview') } children.key.textContent = key; children.preview.classList.add('csle-' + objectClass.name); // show four properties maximum per preview Object.entries(value).some(([k, v], i) =&gt; { type = (v &amp;&amp; v.constructor) ? v.constructor : undefined; const keyValue = document.importNode(template.keyValue.content, true); const keyValueElement = { key: keyValue.querySelector('.csle-key'), value: keyValue.querySelector('.csle-value') } // all types need different formatting switch (type) { case Object: keyValueElement.value.textContent = `{...}`; break; case Array: keyValueElement.value.textContent = `Array(${v.length})`; break default: keyValueElement.value.textContent = `${v}`; } keyValueElement.key.textContent = k; keyValueElement.value.setAttribute('class', 'csle-' + typeof v); children.preview.appendChild(keyValue); return i == 4; }); const wrapper = document.createElement('details'); // !couldn't add event listener on &lt;details&gt; wrapper.appendChild(element) wrapper.addEventListener('toggle', () =&gt; { showObject(value, wrapper) }, { once: true }); parent.appendChild(wrapper); } else { const element = document.importNode(template.keyValue.content, true); const children = { key: element.querySelector('.csle-key'), value: element.querySelector('.csle-value') } children.key.textContent = key; children.value.textContent = value; // !undefined and null won't be parsed children.value.setAttribute('class', 'csle-' + typeof value); parent.appendChild(element); } }); }; </code></pre> <hr> <p><strong>Full code:</strong></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>/** * Shows all the object's properties with a depth of 1 * @params {Object} object, its first level properties are shown * {HTMLElement} parent the element in which are displayed the properties * @return {undefined} */ const showObject = (object, parent = document.body) =&gt; { const template = { keyValue: document.querySelector('template#keyValue'), folder: document.querySelector('template#folder') } Object.entries(object).forEach(([key, value]) =&gt; { const objectClass = (value &amp;&amp; value.constructor) ? value.constructor : undefined; const isContainer = (objectClass == Object) || (objectClass == Array); if (isContainer) { // !better naming for (objects, arrays, maps, sets)? const element = document.importNode(template.folder.content, true); const children = { key: element.querySelector('.csle-key'), preview: element.querySelector('.csle-preview') } children.key.textContent = key; children.preview.classList.add('csle-' + objectClass.name); // show four properties maximum per preview Object.entries(value).some(([k, v], i) =&gt; { type = (v &amp;&amp; v.constructor) ? v.constructor : undefined; const keyValue = document.importNode(template.keyValue.content, true); const keyValueElement = { key: keyValue.querySelector('.csle-key'), value: keyValue.querySelector('.csle-value') } switch (type) { case Object: keyValueElement.value.textContent = `{...}`; break; case Array: keyValueElement.value.textContent = `Array(${v.length})`; break default: keyValueElement.value.textContent = `${v}`; } keyValueElement.key.textContent = k; keyValueElement.value.setAttribute('class', 'csle-' + typeof v); children.preview.appendChild(keyValue); return i == 4; }); const wrapper = document.createElement('details'); // !couldn't add event listener on &lt;details&gt; wrapper.appendChild(element) wrapper.addEventListener('toggle', () =&gt; { showObject(value, wrapper) }, { once: true }); parent.appendChild(wrapper); } else { const element = document.importNode(template.keyValue.content, true); const children = { key: element.querySelector('.csle-key'), value: element.querySelector('.csle-value') } children.key.textContent = key; children.value.textContent = value; // !undefined and null won't be parsed children.value.setAttribute('class', 'csle-' + typeof value); parent.appendChild(element); } }); }; /** * For demonstration purposes */ const obj = { integer: 12, string: 'Hello World', boolean: true, htmlString: '&lt;b&gt;Nope, not bold&lt;/b&gt;', object: { innerArray: ['first', 'second'], innerString: 'yes', innerInteger: 12, innerObject: { first: 1, second: 2 } }, array: ['&lt;b&gt;bold text&lt;/b&gt;', 'two'], function: function() {} }; obj['cycle'] = obj; showObject(obj, document.querySelector('.container'))</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>/** * // all properties for the console get the prefix "csle-" */ /** * Console frame */ .container { background: #242424; padding: 8px 15px; } /** * Property value's styling * csle-{boolean, undefined, string, Array, Object} */ .csle-boolean, .csle-undefined { color: #9283d1; } .csle-string { color: #ca3b38; /*#e93f3b;*/ } .csle-string:before, .csle-string:after { content: '"'; } .csle-Array:before { content: '['; } .csle-Array:after { content: ']'; } .csle-Object:before { content: '{'; } .csle-Object:after { content: '}'; } /** * &lt;summary&gt; styling */ summary { margin-left: 18px; padding-left: 0px; font-size: 20px; display: flex; align-items: center; margin-bottom: 2px; } summary::-webkit-details-marker { color: #8d8d8d; text-shadow: 1em 0.1em #242424; } /** * properties styling */ details &gt; *:not(:first-child) { margin-left: 22px; } summary &gt; div { display: inline-block; width: 100%; } .csle-property, summary { font-family: "Lucida Grande", sans-serif; font-size: 17px; padding: 1px; overflow: hidden; padding-left: 17px; color: #acabab; } .csle-property { line-height: 23px; margin-bottom: 2px; font-size: 18px; } .csle-property &gt; span { font-size: 17px; } .csle-preview &gt; .csle-property { display: inline; margin: 0px; padding: 0px; margin: -2px; color: #acabab; font-size: 18px; } .csle-preview &gt; .csle-property &gt; span { font-size: 17px; } .csle-preview &gt; .csle-property:not(:first-child) &gt; .csle-key:before { content: ', '; } .csle-key, summary { color: #a545ac; font-size: 17px } .csle-key, .csle-preview { display: inline; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="container"&gt;&lt;/div&gt; &lt;template id="keyValue"&gt; &lt;div class="csle-property"&gt; &lt;span class="csle-key"&gt;&lt;/span&gt;: &lt;span class="csle-value"&gt;&lt;/span&gt; &lt;/div&gt; &lt;/template&gt; &lt;template id="folder"&gt; &lt;summary&gt; &lt;div&gt; &lt;div class="csle-key"&gt;&lt;/div&gt;: &lt;div class="csle-preview"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/summary&gt; &lt;/template&gt;</code></pre> </div> </div> </p> <hr> <p><strong>Issues:</strong></p> <ul> <li><p>my function <code>showObject</code> seems to big.</p></li> <li><p>Unsure if I'm using ECMAScript 6 properly</p></li> <li><p>some of the variable names bother me (<code>element</code>, <code>childrenPreview</code>, <code>isContainer</code>) as they aren't very clear.</p></li> <li><p>I can't attach an event listener on the imported template <code>&lt;details&gt;</code> because it is a <code>DocumentFragment</code>. To fix that I had to (<code>line 62</code> of the snippet):</p> <ol> <li>only import <code>&lt;summary&gt;</code> as a <code>template</code></li> <li>create the <code>&lt;details&gt;</code> element manually</li> <li>append <code>&lt;summary&gt;</code> inside <code>&lt;details&gt;</code></li> <li>attach the event listener to <code>&lt;details&gt;</code></li> </ol> <p><br /> Any workaround?</p></li> </ul> <p><strong>I'm looking forward to reading your comments.</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T11:29:28.620", "Id": "381167", "Score": "0", "body": "Very nice! I see a few small things, but I'll hold off on reviewing as I believe it would be more valuable for you to receive a review from someone with a slightly different pers...
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-02T22:07:22.543", "Id": "197690", "Score": "3", "Tags": [ "javascript", "ecmascript-6" ], "Title": "Replicating Chrome console's JavaScript object explorer" }
197690
<p>This is my second attempt after I started to learn about STL. I am oblivious and need suggestions/advices on if there can be improvements made on this code.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;sstream&gt; #include &lt;algorithm&gt; #include &lt;iterator&gt; #include &lt;vector&gt; using namespace std; string LongestWord(string sen) { vector&lt;string&gt; coll; //initialize vector istringstream iss(sen); //read the string "sen" copy(istream_iterator&lt;string&gt;(iss), //copy from beginning of iss istream_iterator&lt;string&gt;(), //to the end of iss back_inserter(coll)); //and insert string to vector //istream_iterator by default separates word by whitespace string longestWord = coll.at(0); int longestCount = longestWord.length(); for(auto element : coll) { if(element.length() &gt; longestCount) { longestWord = element; } } return longestWord; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T03:37:24.063", "Id": "381117", "Score": "1", "body": "This doesn't appear to work. When I run it, it always returns the last word rather than the longest word. I'm passing it a sentence like \"This is a sentence with a long word\" a...
[ { "body": "<p>As @user1118321 points out: just using your implementation, I believe you're missing a crucial line (inside your for loop and if-statement):</p>\n\n<pre><code>longestCount = element.length();\n</code></pre>\n\n<p>Which becomes:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n...
{ "AcceptedAnswerId": "197696", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T02:59:57.343", "Id": "197694", "Score": "0", "Tags": [ "c++", "algorithm", "strings" ], "Title": "Find the longest word in a sentence" }
197694
<p>I have this kind of instance method:</p> <pre><code>def list_records(self,race_type,year=0): yearnow= datetime.now().year yearlist = [yearnow - i for i in range(4)] if not year: for y in yearlist: if self.records: yield self.records[utils.dateracetype_to_DBcolumn(y,str(race_type))] else: yield None else: if self.records: yield self.records[utils.dateracetype_to_DBcolumn(year,str(race_type))] else: yield None </code></pre> <ol> <li>I am calling it mainly through list comprehension, but I could return it simply as a list, what is the most pythonic way to do this? What would be the reasons to chose one method or the other? </li> <li>let's say I'll go with a generator, should I turn the 2 last 'yield' into return values as there will be only one value to be returned?</li> <li>Is there a more optimized way to code this method, as I have the feeling there's too much nested conditions/loop in there?</li> <li>Is there a Python convention to name generators? something like 'gen...'</li> </ol> <p>Thanks</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T07:50:50.357", "Id": "381135", "Score": "2", "body": "1) Depends on the context, which is missing in this question. Please take a look at the [help/on-topic]. 3) I've seen much worse. I'd probably create 2 sub-functions for `list_re...
[ { "body": "<ol>\n<li><p>If you are going to need the whole list for some reason, then make a list. But if you only need one item at a time, use a generator. The reasons for preferring generators are (i) you only need the memory for one item at a time; (ii) if the items are coming from a file or network connecti...
{ "AcceptedAnswerId": "197701", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T06:30:48.523", "Id": "197698", "Score": "-1", "Tags": [ "python", "generator" ], "Title": "When to create a generator or return simply a list in Python?" }
197698
<p>I have a table in Lua, which contains two 1-dimensional arrays in which each array contains approximately 800,000 elements. I want to serialize this Lua table to file efficiently. Hence, I planned to use Lua C bindings.</p> <pre><code>#include "lua.h" #include "lauxlib.h" #include &lt;stdio.h&gt; #include &lt;assert.h&gt; static int do_it(lua_State *L) { assert(L &amp;&amp; lua_type(L, -1) == LUA_TTABLE); int len, idx; void *ptr; FILE *f; size_t r; lua_pushstring(L, "p"); lua_gettable(L, -2); len = lua_objlen(L, -1); // instead of using lua_rawlen, i used lua_objlen. see below // len = lua_rawlen(L, -1); // it throws the following error // lua: error loading module 'savetable' from file './savetable.so': // ./savetable.so: undefined symbol: lua_rawlen int p_values[len]; for (idx = 1; idx &lt;= len; idx++) { lua_rawgeti(L, -1, idx); p_values[idx - 1] = (int)lua_tonumber(L, -1); lua_pop(L, 1); } f = fopen("p.bin", "wb"); assert(f); r = fwrite(p_values, sizeof(int), len, f); printf("[p] wrote %zu elements out of %d requested\n", r, len); fclose(f); lua_pop(L, 1); lua_pushstring(L, "q"); lua_gettable(L, -2); len = lua_objlen(L, -1); double q_values[len]; for (idx = 1; idx &lt;= len; idx++) { lua_rawgeti(L, -1, idx); q_values[idx - 1] = (double)lua_tonumber(L, -1); lua_pop(L, 1); } f = fopen("q.bin", "wb"); assert(f); r = fwrite(q_values, sizeof(double), len, f); printf("[q] wrote %zu elements out of %d requested\n", r, len); fclose(f); lua_pop(L, 1); return 1; } int luaopen_savetable(lua_State *L) { static const luaL_reg Map[] = {{"do_it", do_it}, {NULL, NULL}}; luaL_register(L, "mytask", Map); return 1; } </code></pre> <p>Please note that for debugging purpose, I have defined two very small 1-dimensional arrays:</p> <pre><code>my_table = {p = {11, 22, 33, 44}, q = {0.12, 0.23, 0.34, 0.45, 0.56}} require "savetable" mytask.do_it(my_table) </code></pre> <p>I used the following commands to compile and run it:</p> <pre><code>&gt; gcc -I/usr/include/lua5.1 -o savetable.so -shared savetable.c -fPIC &gt; lua wrapper.lua </code></pre> <p>The code works, however, I am looking for suggestions to make table serialization to file much faster than current.</p> <p>Please note that I am using Lua 5.1 on a 64-bit Ubuntu PC.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T09:54:59.143", "Id": "381156", "Score": "0", "body": "Tip: you may write your array implementation in C and push it into Lua as a light userdata with custom metatable (with insert/remove methods). If you make your array continuous y...
[ { "body": "<pre><code>// undefined symbol: lua_rawlen\n</code></pre>\n\n<p>This happens because there is no such function in Lua 5.1 C API. As stated by documentation <code>lua_objlen</code> is preffered way to get table length.</p>\n\n<p>FYI <code>lua_rawlen</code> function first appeared in Lua 5.2.</p>\n\n<p...
{ "AcceptedAnswerId": "197754", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T07:44:21.117", "Id": "197700", "Score": "3", "Tags": [ "performance", "c", "serialization", "lua", "lua-table" ], "Title": "Serializing a table for filing" }
197700
<p>In order to learn haskell, I wrote a solver for the <a href="https://code.google.com/codejam/contest/6224486/dashboard#s=p1" rel="nofollow noreferrer">Infinite House of Pancakes</a> problem. </p> <pre><code>-- Solve the 'Infinite House of Pancakes' problem. -- https://code.google.com/codejam/contest/6224486/dashboard#s=p1 import Text.Printf import Control.Monad -- Generic solver code readInt :: IO Int readInt = readLn readIntList :: IO [Int] readIntList = getLine &gt;&gt;= return . map read . words main :: IO [()] main = do n &lt;- readInt forM [1..n] (\i -&gt; parse &gt;&gt;= putStr . printf "Case #%d: %d\n" i . solve) -- Problem-specific code parse :: IO [Int] parse = getLine &gt;&gt; readIntList cost :: Int -&gt; Int -&gt; Int cost l n = if r == 0 then q - 1 else q where (q, r) = n `quotRem` l test :: Int -&gt; [Int] -&gt; Int test l = (+l) . sum . map (cost l) solve :: [Int] -&gt; Int solve s = minimum . map (\l -&gt; test l s) $ [1 .. maximum s] </code></pre> <p>I used <a href="https://github.com/vxgmichel/codejam-solver/blob/master/example/pancake.py" rel="nofollow noreferrer">this python solution</a> as a reference, which is based on the <a href="https://code.google.com/codejam/contest/6224486/dashboard#s=a&amp;a=1" rel="nofollow noreferrer">following problem analysis</a>. I tested my program using those <a href="https://github.com/vxgmichel/codejam-solver/blob/master/example/B-large-practice.in" rel="nofollow noreferrer">input</a> and <a href="https://github.com/vxgmichel/codejam-solver/blob/master/example/B-large-practice.out.expected" rel="nofollow noreferrer">output</a> files, and it seems to work fine:</p> <pre><code>$ stack ghc pancake.hs -- -O2 $ \time -f "%e s" ./pancake &lt; B-large-practice.in | diff - B-large-practice.out 0.28 s </code></pre> <p>I'm looking for comments about the following points:</p> <ul> <li>coding style</li> <li>performance (currently runs in 0.28 seconds using <code>-O2</code>, against 5.5 seconds for python 3)</li> <li>bind operators vs do syntax (I used both here, but it was mostly for educational purposes)</li> <li>tools and ecosystem (code analysis, better compilation flags, etc.)</li> </ul> <hr> <p><strong>EDIT -</strong> Thanks to @Gurkenglas answer, I've been able to improve this program quite a lot. Here's a <a href="https://gist.github.com/vxgmichel/5f3cfc69e06dd149d6bc188a58f949cd" rel="nofollow noreferrer">link to the corresponding gist</a>.</p>
[]
[ { "body": "<p>I'll refactor so every line tells the reader something about the program.</p>\n\n<pre><code>{-# LANGUAGE ScopedTypeVariables #-}\nimport Text.Printf\nimport Control.Monad\nimport Data.List.Split (splitPlaces)\nimport Safe (headNote)\n\nmain :: IO ()\nmain = interact ...
{ "AcceptedAnswerId": "197864", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T08:47:52.913", "Id": "197703", "Score": "1", "Tags": [ "haskell" ], "Title": "Infinite House of Pancakes in Haskell" }
197703
<p>I tried implementing a queue using <code>std::vector</code>, using some properties of vector class. Is there scope for further improvement in my code, to make it more efficient?</p> <pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; vector&lt;int&gt; q; void push(int d){ q.insert(q.end(),d); } void pop(){ q.erase(q.begin()); } int front(){ return *q.begin(); } int main(){ push(1); push(2); push(3); push(4); pop(); cout&lt;&lt;front()&lt;&lt;endl; for(int i=0;i&lt;q.size();i++) cout&lt;&lt;q[i]&lt;&lt;" "; } </code></pre>
[]
[ { "body": "<p>There are a number of things that could be improved here, and none of them have to do with the efficiency of the program. The problems with this code are more fundamental.</p>\n\n<h2>Don't abuse <code>using namespace std</code></h2>\n\n<p>Putting <code>using namespace std</code> at the top of eve...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T08:55:42.213", "Id": "197706", "Score": "3", "Tags": [ "c++", "beginner", "reinventing-the-wheel", "queue" ], "Title": "implementing a queue using std::vector" }
197706
<p>I write this session helper class to use it inside my projects for managing the <code>$_SESSION</code> variables setup after an user login or logout. It's very simple and after some tests it seems to work smoothly and fine. </p> <p>The class doesn't have a constructor, this because the needed parameters that are the username and the user id are passed directly to the <code>setSession</code> method. </p> <p>The <code>sessionCode</code> method is instead only a code who is used to check if the user is logged in or not, this to limit the access to certain pages if needed. </p> <pre><code>&lt;?php namespace library; class SessionHelper{ private $username; private $id; private $ip; public function setSession(string $email,int $id){ session_regenerate_id(); $_SESSION['session_code'] = $this-&gt;sessionCode(); $_SESSION['user_ip'] = $_SERVER['REMOTE_ADDR']; $_SESSION['user_id'] = $id; $_SESSION['username'] = $email; return true; } public function sessionStatus(){ if(isset($_SESSION['session_code'])){ if(hash_equals($_SESSION['session_code'], $this-&gt;sessionCode())){ return true; } else { return false; } } } public function unsetSession(){ session_unset(); session_destroy(); return true; } private function sessionCode(){ return hash('sha256', session_id()); } } ?&gt; </code></pre> <p>USAGE EXAMPLE AFTER A LOGIN SCRIPT:</p> <pre><code>&lt;?php require_once 'SessionHelper.php'; use library\SessionHelper as SessionHelper; $session = new SessionHelper; $session-&gt;setSession('user1', '4'); ?&gt; </code></pre> <p>USAGE ON RESTRICTED ACCESS PAGES</p> <pre><code>&lt;?php session_start(); require_once 'library/Autoloader.php'; use library\SessionHelper as SessionHelper; $session = new SessionHelper; if($session-&gt;sessionStatus() != true){ header('Location: index'); die(); } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T12:28:11.193", "Id": "381172", "Score": "1", "body": "What's the point of `session_regenerate_id()` here? I also can't see how you're using the session code in a safe manner. You must be accessing `$_SESSION` outside this helper cla...
[ { "body": "<p>This is not a SessionHelper but a UserSessionHelper in the first place. A session is a container that could contain anything, not only user credentials. A shopping cart items for example. Therefore you have to either extend its functionality or at least rename a class. </p>\n\n<p>In 2018 you are o...
{ "AcceptedAnswerId": "197713", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T10:46:23.707", "Id": "197711", "Score": "1", "Tags": [ "php", "object-oriented", "session" ], "Title": "User session helper class" }
197711
<p>I've built a VBA Excel macro that works on a spreadsheet of duplicated files, and displays only groups in which at least one duplication is owned by the current user.</p> <p>The spreadsheet lists file metadata, one file per row, grouped with other files whose content is identical, i.e. "duplicated". Each such duplication group is preceded by a title row in bold.</p> <p>The macro uses text boldness to determine duplication groups, and checks within each group whether any file's owner (represented in column 7) is the currently logged user. All groups with no file owned by the user get hidden. (auto-filtering would not solve this problem because I want the user to see the other files in the duplication group, i.e. see files from other owners with the same content as theirs) </p> <p>It works exactly as intended, but too slowly. It takes one or two minutes to run through a spreadsheet about 80 thousand lines long. Anyone can see a way to speed it up?</p> <p>I had the idea of maybe hiding every row first (which I assume can be done much faster) and then de-hide what should be shown. But I couldn't find a command to mass-hide.</p> <p>Also, since we're here, what best practices am I missing? I'm a complete novice to VBA, though I'm an experienced programmer in other languages.</p> <p>Grateful for any help.</p> <pre><code>'Operates on .xslx report of network file duplication, as output by TreeSize tool. 'Hides all Duplication Groups not involving the currently logged user as a file Owner '(regular filtering does not work because it hides the other duplicates which have a different owner) 'TODO: speed it up. It currently takes ~1min to run. Probably hide-all then unhide-selected will be faster. Private Sub My_duplicates_Click() Dim hidIt As Boolean Dim foundInGroup As Boolean Application.ScreenUpdating = False Application.EnableEvents = False login = Environ("Username") ownerCol = 7 rowNum = 3 'skip header Do While Not IsEmpty(Cells(rowNum, 1)) If Cells(rowNum, ownerCol).Font.Bold = True Then 'bold text indicates the beginning of a duplication group foundInGroup = False groupMemberRow = rowNum + 1 Do While Not IsEmpty(Cells(groupMemberRow, 1)) And Not Cells(groupMemberRow, ownerCol).Font.Bold = True If Cells(groupMemberRow, ownerCol).Value2 = login Then foundInGroup = True End If groupMemberRow = groupMemberRow + 1 Loop If foundInGroup = False Then hidIt = True Else hidIt = False End If Cells(rowNum, ownerCol).EntireRow.Hidden = hidIt groupMemberRow = rowNum + 1 Do While Not IsEmpty(Cells(groupMemberRow, 1)) And Not Cells(groupMemberRow, ownerCol).Font.Bold = True Cells(groupMemberRow, ownerCol).EntireRow.Hidden = hidIt groupMemberRow = groupMemberRow + 1 Loop rowNum = groupMemberRow - 1 'counting on next increment to place it back on the next group header End If rowNum = rowNum + 1 Loop End Sub </code></pre>
[]
[ { "body": "<p>First off, regarding </p>\n\n<blockquote>\n <p>But I couldn't find a command to mass-hide.</p>\n</blockquote>\n\n<p>For me, the snippet <code>WhateverSheet.Range(\"A3:A80000\").Rows.Hidden = True</code> seems to do the trick.</p>\n\n<hr>\n\n<p>I see a lot of not fully qualified <code>Range()</cod...
{ "AcceptedAnswerId": "197728", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T11:17:24.603", "Id": "197712", "Score": "5", "Tags": [ "performance", "vba", "excel" ], "Title": "Hide Excel Rows faster" }
197712
<p>I used an opportunity to learn about Dependency Injection and DDD, therefore, althought any feedback is welcome, I am interested in feedback about those software design principles.</p> <p>I have a small project where I have to display some information queried from several similar databases (= DB that have the same purpose, but are assigned to different plants).</p> <p>The back-end is coding using C#/Web API 2.</p> <p>I have organized it in 3 projects (plus one test project per actual project), organized as follows (Only showing the file I believe are relevant to the review).</p> <p>I am submitting for review the very first step of the program, reading the different servers that exist from configuration, and serve them to the front-end.</p> <pre><code>Backend.sln |-&gt; Backend.API (WebApi2 project) |-&gt; Controllers/ServersController.cs |-&gt; App_Start/UnityConfig.cs |-&gt; Settings/Servers (a string, JSON-formatted) |-&gt; Backend.Domain (Class Library) |-&gt; Server/AServer.cs |-&gt; Server/SettingsServerRepository.cs |-&gt; Backend.Infra (Class Library) |-&gt; Server/IServer.cs |-&gt; Server/IServerRepository.cs </code></pre> <p><strong>Backend.API</strong></p> <p><em>Controllers/ServersController.cs</em></p> <pre><code>namespace Backend.API.Controllers { [EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*", SupportsCredentials = true)] public class ServersController : ApiController { Infra.Server.IServerRepository serverRepository; public ServersController(Infra.Server.IServerRepository serverRepo) { serverRepository = serverRepo; } public HttpResponseMessage Get() { IEnumerable&lt;Infra.Server.IServer&gt; servers = serverRepository.Servers; return Request.CreateResponse(HttpStatusCode.OK, servers); } } } </code></pre> <p><em>App_Start/UnityConfig.cs</em></p> <pre><code>namespace Backend.API { public static class UnityConfig { public static void RegisterComponents() { var servers = Properties.Settings.Default.Servers; var container = new UnityContainer(); container.RegisterType&lt;Infra.Server.IServerRepository, Domain.Server.SettingsServerRepository&gt;(new InjectionConstructor(servers)); GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container); } } } </code></pre> <p><em>Settings/Servers</em></p> <pre><code>[ { "$type": "Backend.Domain.Server.AServer, Backend.Domain", "HostName": "foo", }, { "$type": "Backend.Domain.Server.AServer, Backend.Domain", "HostName": "bar", } ] </code></pre> <p><strong>Backend.Domain</strong></p> <p><em>Server/AServer.cs</em></p> <pre><code>namespace Backend.Domain.Server { public class AServer: Infra.Server.IServer { public string HostName { get; } public AServer (string HostName) { this.HostName = HostName; } } } </code></pre> <p><em>Server/SettingsServerRepository.cs</em></p> <pre><code>namespace Backend.Domain.Server { public class SettingsServerRepository : Infra.Server.IServerRepository { public IEnumerable&lt;Infra.Server.IServer&gt; Servers {get;} public SettingsServerRepository(string jsonSettings) { Servers = JsonConvert.DeserializeObject&lt;IEnumerable&lt;Infra.Server.IServer&gt;&gt;( jsonSettings, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }); } } } </code></pre> <p><strong>Backend.Infra</strong></p> <p><em>Server/IServer.cs</em></p> <pre><code>namespace Backend.Infra.Server { public interface IServer { string HostName { get; } } } </code></pre> <p><em>Server/IServerRepository.cs</em></p> <pre><code>namespace Backend.Infra.Server { public interface IServerRepository { IEnumerable&lt;IServer&gt; Servers { get; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T14:57:56.667", "Id": "381191", "Score": "0", "body": "Please post your real code, do not edit it for the sake of the question. Some variables in your question don't match. Either this is not working or you have edited it." }, { ...
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T11:41:56.213", "Id": "197716", "Score": "0", "Tags": [ "c#", "dependency-injection", "asp.net-web-api", "ddd" ], "Title": "Inject settings as a dependency, and serve them using a Web API" }
197716
<p>The small bit of code below blits and image to the screen within a class. I call this 4 times to display the image 4 times, each image has a different y coordinate and doesn't need different x but when they are blitted they make the code MUCH slower. I know it is the blitting as well due to the fact that if i just draw rects instead, the program moves smoothly.</p> <pre><code>tableTex = pygame.transform.scale(pygame.image.load('./Sources/Table.png'), (270, 240)) def display(self): if not self.occupied: screen.blit(tableTex, (self.x, self.y)) else: pygame.draw.rect(screen, (127, 0, 0), self.rect, 0) </code></pre> <p>A link to the full code can be found <a href="https://github.com/tomayling7/restaurant-game/" rel="nofollow noreferrer">here</a> if needed. I just want to know if there is any reason this is so slow and if there are any other methods I could use that are faster?</p> <p>Thanks</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T15:49:53.690", "Id": "381213", "Score": "0", "body": "You should add the definition of `tableTex` to the code, since it is actually quite relevant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T15:5...
[ { "body": "<p>As noted in the <a href=\"https://www.pygame.org/docs/tut/newbieguide.html\" rel=\"nofollow noreferrer\">beginners guide</a>, you should convert your image right after loading it. So instead of</p>\n\n<pre><code>tableTex = pygame.transform.scale(pygame.image.load('./Sources/Table.png'), (270, 240)...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T12:08:36.690", "Id": "197718", "Score": "2", "Tags": [ "python", "object-oriented", "pygame" ], "Title": "The start of a game in pygame, blitting images to the screen" }
197718
<p>I have the following code I'm using to show/hide multiple shape groups in Excel 2016 using VBA and macros:</p> <pre><code> Sub Pic_1_SA_click() ActiveSheet.Shapes("Group 23").Visible = True ActiveSheet.Shapes("Group 71").Visible = False ActiveSheet.Shapes("Group 19").Visible = False ActiveSheet.Shapes("Group 20").Visible = False End Sub Sub Pic_1_SB_click() ActiveSheet.Shapes("Group 23").Visible = False ActiveSheet.Shapes("Group 71").Visible = True ActiveSheet.Shapes("Group 19").Visible = False ActiveSheet.Shapes("Group 20").Visible = False End Sub Sub Pic_2_SA_click() ActiveSheet.Shapes("Group 23").Visible = False ActiveSheet.Shapes("Group 71").Visible = False ActiveSheet.Shapes("Group 19").Visible = True ActiveSheet.Shapes("Group 20").Visible = False End Sub Sub Pic_2_SB_click() ActiveSheet.Shapes("Group 23").Visible = False ActiveSheet.Shapes("Group 71").Visible = False ActiveSheet.Shapes("Group 19").Visible = False ActiveSheet.Shapes("Group 20").Visible = True End Sub </code></pre> <p>Now the above is somewhat tedious if I plan to add more buttons. Is there any way to do this more efficiently? </p>
[]
[ { "body": "<p>The simple answer is to use pass an array of names to the <code>Shapes.Range</code>, hide all 4 Groups, and then make the one Group visible. </p>\n\n<blockquote>\n<pre><code>ActiveSheet.Shapes.Range(Array(\"Group 19\", \"Group 20\", \"Group 23\", \"Group 71\")).Visible = msoTrue\nActiveSheet.Shap...
{ "AcceptedAnswerId": "197727", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T13:05:33.823", "Id": "197721", "Score": "4", "Tags": [ "vba", "excel" ], "Title": "Excel 2016 VBA - Show/Hide multiple shape groups" }
197721
<p>This is a functional component that I have developed in React Native for creating a circular progress view.</p> <p>The code does not use any external libraries, just pure CSS. Article that I wrote while creating this code is <a href="https://medium.com/@0saurabhgour/react-native-percentage-based-progress-circle-no-external-library-e25b43e83888" rel="nofollow noreferrer">here</a>. <a href="https://github.com/saurabhgour/react-native-progress-circle-without-library/tree/5bd395eae76f42cf9fa184816555401895de9ebc" rel="nofollow noreferrer">Github repo</a>. <a href="https://www.npmjs.com/package/react-native-circular-progress-no-ext-library" rel="nofollow noreferrer">npm package</a>.</p> <pre><code>import React from 'react'; import {Text, View, StyleSheet} from 'react-native'; /** * Function that calculates rotation of the semicircle for firstProgressLayer * ( when percent is less than equal to 50 ) or for the secondProgressLayer * when percent is greater than 50. **/ rotateByStyle = (percent, base_degrees, clockwise) =&gt; { let rotateBy = base_degrees; if(clockwise){ rotateBy = base_degrees + (percent * 3.6); }else{ //anti clockwise progress rotateBy = base_degrees - (percent * 3.6); } return { transform:[{rotateZ: `${rotateBy}deg`}] }; } renderThirdLayer = (percent, commonStyles, ringColorStyle, ringBgColorStyle, clockwise, bgRingWidth, progressRingWidth, innerRingStyle, startDegrees) =&gt; { let rotation = 45 + startDegrees; let offsetLayerRotation = -135 + startDegrees; if(!clockwise){ rotation += 180; offsetLayerRotation += 180; } if(percent &gt; 50){ /** * Third layer circles default rotation is kept 45 degrees for clockwise rotation, so by default it occupies the right half semicircle. * Since first 50 percent is already taken care by second layer circle, hence we subtract it * before passing to the rotateByStyle function **/ return &lt;View style={[styles.secondProgressLayer,rotateByStyle((percent - 50), rotation, clockwise), commonStyles, ringColorStyle, {borderWidth: progressRingWidth} ]}&gt;&lt;/View&gt; }else{ return &lt;View style={[styles.offsetLayer, innerRingStyle, ringBgColorStyle, {transform:[{rotateZ: `${offsetLayerRotation}deg`}], borderWidth: bgRingWidth}]}&gt;&lt;/View&gt; } } const CircularProgress = ({percent, radius, bgRingWidth, progressRingWidth, ringColor, ringBgColor, textFontSize, textFontWeight, clockwise, bgColor, startDegrees}) =&gt; { const commonStyles = { width: radius * 2, height: radius * 2, borderRadius: radius }; /** * Calculate radius for base layer and offset layer. * If progressRingWidth == bgRingWidth, innerRadius is equal to radius **/ const widthDiff = progressRingWidth - bgRingWidth; const innerRadius = (radius - progressRingWidth) + bgRingWidth + widthDiff/2; const innerRingStyle = { width: innerRadius * 2, height: innerRadius * 2, borderRadius: innerRadius }; const ringColorStyle = { borderRightColor: ringColor, borderTopColor: ringColor, }; const ringBgColorStyle = { borderRightColor: ringBgColor, borderTopColor: ringBgColor, }; const thickOffsetRingStyle = { borderRightColor: bgColor, borderTopColor: bgColor, }; let rotation = -135 + startDegrees; /** * If we want our ring progress to be displayed in anti-clockwise direction **/ if(!clockwise){ rotation += 180; } let firstProgressLayerStyle; /* when ther ring's border widths are different and percent is less than 50, then we need an offsetLayer * before the original offser layer to avoid ring color of the thick portion to be visible in the background. */ let displayThickOffsetLayer = false; if(percent &gt; 50){ firstProgressLayerStyle = rotateByStyle(50, rotation, clockwise); }else { firstProgressLayerStyle = rotateByStyle(percent, rotation, clockwise); if(progressRingWidth &gt; bgRingWidth){ displayThickOffsetLayer = true; } } let offsetLayerRotation = -135 + startDegrees; if(!clockwise){ offsetLayerRotation += 180; } return( &lt;View style={[styles.container, {width: radius * 2, height: radius * 2}]}&gt; &lt;View style={[styles.baselayer, innerRingStyle, {borderColor: ringBgColor, borderWidth: bgRingWidth}]}&gt; &lt;/View&gt; &lt;View style={[styles.firstProgressLayer, firstProgressLayerStyle, commonStyles, ringColorStyle, {borderWidth: progressRingWidth}]}&gt; &lt;/View&gt; { displayThickOffsetLayer &amp;&amp; &lt;View style={[styles.offsetLayer, commonStyles, thickOffsetRingStyle, {transform:[{rotateZ: `${offsetLayerRotation}deg`}], borderWidth: progressRingWidth}]}&gt;&lt;/View&gt; } { renderThirdLayer(percent, commonStyles, ringColorStyle, ringBgColorStyle, clockwise, bgRingWidth, progressRingWidth, innerRingStyle, startDegrees) } &lt;Text style={[styles.display, {fontSize: textFontSize,fontWeight: textFontWeight}]}&gt;{percent}%&lt;/Text&gt; &lt;/View&gt; ); } // default values for props CircularProgress.defaultProps = { percent: 0, radius: 100, bgRingWidth: 10, progressRingWidth: 20, ringColor: '#3498db', ringBgColor: 'grey', textFontSize: 40, textFontWeight: 'bold', clockwise: true, bgColor: 'white', startDegrees: 0 } /** * offsetLayer has transform:[{rotateZ: '-135deg'}] since * the offsetLayer rotation is fixed by us. **/ const styles = StyleSheet.create({ container: { justifyContent: 'center', alignItems: 'center' }, baselayer: { position: 'absolute' }, firstProgressLayer: { position: 'absolute', borderLeftColor: 'transparent', borderBottomColor: 'transparent' }, secondProgressLayer:{ position: 'absolute', borderLeftColor: 'transparent', borderBottomColor: 'transparent' }, offsetLayer: { position: 'absolute', borderLeftColor: 'transparent', borderBottomColor: 'transparent' }, display: { position: 'absolute' } }); export default CircularProgress; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T13:36:58.480", "Id": "197723", "Score": "3", "Tags": [ "css", "animation", "react.js", "jsx", "react-native" ], "Title": "React native circular progress view" }
197723
<p>Merged cells are a PITA in Excel. They prevent doing a lot of actions and make copying columns impossible. So I wrote this little code to change all the merged cells in a given sheet into 'Center across selection'.<br> I did NOT test against vertically merged cells, but it should not trigger an error (just unmerge them).</p> <pre><code>Sub fixMergedCells(sh As Worksheet) 'replace merged cells by Center Acroos Selection 'high perf version using a hack: https://stackoverflow.com/a/9452164/78522 Dim c As Range, used As Range Dim m As Range, i As Long Dim constFla: constFla = Array(xlConstants, xlFormulas) Set used = sh.UsedRange For i = 0 To 1 '1 run for constants, 1 for formulas Err.Clear On Error Resume Next Set m = Intersect(used.Cells.SpecialCells(constFla(i)), used.Cells.SpecialCells(xlBlanks)) On Error GoTo 0 If Not m Is Nothing Then For Each c In m.Cells If c.MergeCells Then With c.MergeArea 'Debug.Print .Address .UnMerge .HorizontalAlignment = xlCenterAcrossSelection End With End If Next c End If Next i End Sub Sub test_fixMergedCells() fixMergedCells ActiveSheet End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T16:46:11.747", "Id": "381232", "Score": "0", "body": "Nice work. I am sure that there are a lot of people search for code to get rid of the PITA Merged Cells. Thank you for sharing." }, { "ContentLicense": "CC BY-SA 4.0", ...
[ { "body": "<h2>Vertically Merged Cells</h2>\n<blockquote>\n<p>I did NOT test against vertically merged cells, but it should not trigger an error (just unmerge them).</p>\n</blockquote>\n<p>You code will unmerge the cells and set each cells <code>.HorizontalAlignment = xlCenterAcrossSelection</code>.</p>\n<h2>Ta...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T14:02:40.723", "Id": "197726", "Score": "2", "Tags": [ "vba", "excel" ], "Title": "Getting rid of Merged cells" }
197726
<p>I have written low quality php code, I'm not a good coder ;) Help me, please, to optimise it ;)</p> <p>This simple code check bitstamp.net exchange rate, compare it with previous rate and print the result.</p> <pre><code>&lt;?php function getPrice($url) { $decode = @file_get_contents($url); return json_decode($decode, true); } $btc = getPrice('https://api.binance.com/api/v1/ticker/24hr?symbol=BTCUSDT'); $btcusdlast = round($btc["lastPrice"], 1); $rbtc = ($btc["priceChange"]&gt;0) ? 'up' : ' down'; $ltc = getPrice('https://api.binance.com/api/v1/ticker/24hr?symbol=LTCUSDT'); $ltcusdlast = round($ltc["lastPrice"], 1); $rltc = ($ltc["priceChange"]&gt;0) ? 'up' : ' down'; ?&gt; &lt;h2&gt;BTC $ &lt;?=$btcusdlast, ' ', $rbtc;?&gt;&lt;/h2&gt; &lt;h2&gt;LTC $ &lt;?=$ltcusdlast, ' ', $rltc;?&gt;&lt;/h2&gt; </code></pre> <p>But it's low quality and work <strong>very slowly</strong>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T14:45:36.673", "Id": "381189", "Score": "1", "body": "_\"and work very slowly.\"_ Since you’re calling an external site, it can't work faster than your internet connection speed…" }, { "ContentLicense": "CC BY-SA 4.0", "...
[ { "body": "<p>Id make your code more functional (if your not going to use OOP) the fact that this code is slow is probably your internet connection (as mentioned in the comments) </p>\n\n<p>First as the api is returning common keys I would just make the rounding &amp; ternary operator as one function you can pa...
{ "AcceptedAnswerId": "197740", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T14:39:36.397", "Id": "197729", "Score": "2", "Tags": [ "php" ], "Title": "Check bitstamp.net exchange rate, compare it with previous rate" }
197729
<p>I come from a C background and am trying to learn Rust. I wrote my first Rust program, to check the battery level on my laptop and warn me if it's low/critical. </p> <p>It works fine, but I wrote it in a way I'm familiar with and was wondering if I'm missing out on some features of the Rust language that could make this more portable, more optimal, or safer.</p> <pre><code>extern crate notify_rust; use notify_rust::Notification; use notify_rust::NotificationUrgency; use std::fs::File; use std::io::prelude::*; static CHARGE_NOW: &amp;str = "/sys/class/power_supply/BAT0/charge_now"; static CHARGE_FULL: &amp;str = "/sys/class/power_supply/BAT0/charge_full"; static STATUS: &amp;str = "/sys/class/power_supply/BAT0/status"; static CHARGING_STR: &amp;str = "Charging"; const CHARGE_WARN: f32 = 15.0; const CHARGE_CRIT: f32 = 5.0; const NOTIFICATION_TIMEOUT: i32 = 4000; fn main() { /* If we're charging, just exit */ if get_str_from_file(STATUS).trim() == CHARGING_STR { std::process::exit(0); } let charge_level: f32 = (get_float_from_file(CHARGE_NOW) / get_float_from_file(CHARGE_FULL)) * 100.0; if charge_level &lt; CHARGE_WARN { Notification::new() .summary("Battery level low!") .body(&amp;format!("Battery level: {0:.1$}%", charge_level, 2)) .icon("dialog-information") .urgency( if charge_level &lt; CHARGE_CRIT { NotificationUrgency::Critical } else { NotificationUrgency::Normal } ) .timeout(NOTIFICATION_TIMEOUT) .show().unwrap(); } } fn get_str_from_file(file_path: &amp;str) -&gt; String { let mut file = File::open(file_path) .expect("file not found"); let mut ret = String::new(); file.read_to_string(&amp;mut ret) .expect("failed to read file"); ret } fn get_float_from_file(file_path: &amp;str) -&gt; f32 { get_str_from_file(file_path).trim().parse::&lt;f32&gt;().unwrap() } </code></pre> <p>Used crate: <a href="https://docs.rs/notify-rust/3.4.2/x86_64-unknown-linux-gnu/notify_rust/" rel="nofollow noreferrer">notify_rust</a>.</p>
[]
[ { "body": "<p>Unwrapping options is probably fine for this simple little app that only you’re using, but it dumps out a panic if the result is <code>None</code>. I like your use of <code>expect</code> better. That can give a nicer error message to the user. Either way, it’d be good to learn the more idiomatic w...
{ "AcceptedAnswerId": "197771", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T16:41:08.617", "Id": "197742", "Score": "10", "Tags": [ "beginner", "linux", "rust", "status-monitoring" ], "Title": "Laptop battery level monitor for Linux" }
197742