body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I am new to building with design patterns. I have been working on implementing the builder design pattern in PHP. I just want to make sure I am doing it correctly. I have been following along with this tutorial on jakowicz: <a href="https://www.jakowicz.com/builder-pattern-in-php/" rel="nofollow noreferrer">https://www.jakowicz.com/builder-pattern-in-php/</a></p> <p>I have made a few minor changes to the way I'm implementing the pattern but nothing too major. I just hope I am doing it correctly.</p> <p>User.php</p> <pre><code>class User { public $user; public $firstName; public $lastName; public $company; public $address; public $city; public $state; public $zip; } </code></pre> <p>UserBuilderInterface.php</p> <pre><code>interface UserBuilderInterface { public function setFirstName($firstName); public function setLastName($lastName); public function setCompany($company); public function setAddress($address); public function setCity($city); public function setState($state); public function setZip($zip); public function storeUser(); public function getUser(); } </code></pre> <p>UserBuilder.php</p> <pre><code>class UserBuilder extends User implements UserBuilderInterface { public function __construct(){ $this-&gt;user = new User(); } public function setFirstName($firstName){ $this-&gt;user-&gt;firstName = $firstName; } public function setLastName($lastName){ $this-&gt;user-&gt;lastName = $lastName; } public function setCompany($company){ $this-&gt;user-&gt;company = $company; } public function setAddress($address){ $this-&gt;user-&gt;address = $address; } public function setCity($city){ $this-&gt;user-&gt;city = $city; } public function setState($state){ $this-&gt;user-&gt;state = $state; } public function setZip($zip){ $this-&gt;user-&gt;zip = $zip; } public function getUser(){ return $this-&gt;user; } } </code></pre> <p>UserDirector.php</p> <pre><code>class UserDirector{ public static function create(UserBuilderInterface $set, $first, $last, $company, $address, $city, $state, $zip){ $set-&gt;setFirstName($first); $set-&gt;setLastName($last); $set-&gt;setCompany($company); $set-&gt;setAddress($address); $set-&gt;setCity($city); $set-&gt;setState($state); $set-&gt;setZip($zip); return $set-&gt;getUser(); } } </code></pre> <p>index.php</p> <pre><code>$user = UserDirector::create(new UserBuilder,'John', 'Doe', 'Foo', '1444 Foo Bar Ave', 'Fo', 'FO', '11111'); echo 'First Name:' . $user-&gt;firstName; echo 'Last Name:' . $user-&gt;lastName; </code></pre> <p>BTW everything runs as expected. Just want to know if Im doing it right? Any feedback is greatly appreciated.</p> <p>edit: My code will be used to store User information into a database. It is not for production use it is just to learn how to implement a design pattern</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-05T18:45:52.883", "Id": "399346", "Score": "4", "body": "Please tell us what your builder is for and put this also in the title. It should describe the purpose of your code, not your concerns about it." }, { "ContentLicense": "...
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-05T18:28:27.360", "Id": "207010", "Score": "2", "Tags": [ "php", "design-patterns" ], "Title": "Builder Design Pattern To Store User Information" }
207010
<p>I am writing a piece of software that aims at streaming the modified lines of an external file located at given uri (and retrieved as a QueryString parameter).</p> <p>I am trying to minimize the impact of big files so that I can maximize the use of asynchronous calls (i.e. <code>async</code> / <code>await</code>). I am using <code>AsyncEnumerable</code> (<a href="https://github.com/Dasync/AsyncEnumerable" rel="nofollow noreferrer">https://github.com/Dasync/AsyncEnumerable</a>) to have at the same time the feature of enumerable and and <code>async</code> / <code>await</code>, in order to free up threads and memory (I am not going to keep the whole file in memory before sending the modified version back).</p> <p>I created an extension method that can fetch the lines of a remote file.</p> <pre><code>public static class StringExtensions { public static AsyncEnumerable&lt;string&gt; ReadLinesAsyncViaHttpClient(this string uri) { return new AsyncEnumerable&lt;string&gt;(async yield =&gt; { using (var httpClient = new HttpClient()) { using (var responseStream = await httpClient.GetStreamAsync(uri)) { using (var streamReader = new StreamReader(responseStream)) { while(true) { var line = await streamReader.ReadLineAsync(); if (line != null) { await yield.ReturnAsync(line); } else { return; } } } } } }); } } </code></pre> <p>And used that extension method in a Controller action:</p> <pre><code>using System; using System.Collections.Async; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace WebApplicationTest.Controllers { [Route("api/[controller]")] [ApiController] public class LinesController : ControllerBase { private static readonly Random Random = new Random(); // GET api/lines // POST api/lines [HttpGet] [HttpPost] public async Task&lt;IActionResult&gt; GetAsync([FromQuery] string fileUri) { using (var streamWriter = new StreamWriter(HttpContext.Response.Body)) { await fileUri.ReadLinesAsyncViaHttpClient().ForEachAsync(async line =&gt; { // Some dumb process on each (maybe big line) line += Random.Next(0, 100 + 1); await streamWriter.WriteLineAsync(line); }); } return Ok(); } } } </code></pre> <p>I used the <code>HttpContext.Response.Body</code> stream instead of the <code>PushStreamContent</code> cause according to this answer: <a href="https://stackoverflow.com/a/48115434/4636721">https://stackoverflow.com/a/48115434/4636721</a> (in .NET Core we don't need to use the <code>PushStreamContent</code> if no need of HttpMessage)</p> <p>It seems to work I mean, I get a payload with the lines of the initial file passed in the query string and with some random numbers at the end of each line. It seems there is no increase in memory but I would like to have another pair of eyes to check what I have done.</p> <p>[EDIT 2] Turns out there is already an issue on the ASP.NET MVC Github about that: <a href="https://github.com/aspnet/Mvc/issues/6224" rel="nofollow noreferrer">https://github.com/aspnet/Mvc/issues/6224</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-05T19:24:50.550", "Id": "399351", "Score": "4", "body": "`yield` - this is a really, really, really! terrible variable name. I had to look ten times at your code to actually understand that it's not an enumerator :-o" }, { "Con...
[ { "body": "<p>A small improvement you can do to avoid the pretty deep nesting is, stacking all usings without extra brackets.</p>\n\n<pre><code>public static AsyncEnumerable&lt;string&gt; ReadLinesAsyncViaHttpClient(this string uri)\n{\n return new AsyncEnumerable&lt;string&gt;(async yield =&gt;\n { \n ...
{ "AcceptedAnswerId": "208560", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-05T19:08:50.333", "Id": "207012", "Score": "4", "Tags": [ "c#", "beginner", "stream", "async-await", "asp.net-core-webapi" ], "Title": "Streaming modified lines of a file from a Controller" }
207012
<p>I am trying to find a way to optimize the code runtime. Improvements I have implemented include using dictionaries, removing redundancies and using <code>str.translate</code>.</p> <pre><code>from collections import namedtuple import string import jellyfish as jf import Levenshtein as l #conda install -c conda-forge python-levenshtein #instantitiate trans table words2numbers = { '1' : 'one ', '2' : 'two ', '3' : 'three ', '4' : 'four ', '5' : 'five ', '6' : 'six ', '7' : 'seven ', '8' : 'eight ', '9' : 'nine ', '0' : 'zero ' } string_punc = {key: None for key in string.punctuation} replace_with = str.maketrans({**words2numbers, **string_punc}) String = namedtuple('String','encode lev ori') def norm_func(s): ''' Normalize number characters and punctuations '123' -- &gt; 'one two three' '.?1 12 gray' --&gt; 'one two gray' ''' s = s.translate(replace_with) return s.lower() def encode_phonetic(s): #should return normalize string here ''' Tag sentence by tokenizing string and returns soundex via jellyfish. Creates a dictionary that stores the normalized string and key value pairs for each tokenized string. '123 washington blvd' --&gt; '{'T000': 'two', 'B413': 'blvd', 'T600': 'three', 'W252': 'washington', 'O500': 'one', 'KEY': 'one two three washington blvd'}' ''' norm = norm_func(s) norm_set = set(norm.split()) norm_dict = {jf.soundex(i):i for i in norm_set} norm_dict['KEY'] = norm return norm_dict def bstring(s,o): ''' Compares both 2 strings based on soundex differences and string distance in a namedtuple. encode: difference in soundex encoding lev: difference in string distance ori: holds original string bstring('123 washington blvd','123 washington boulevard') --&gt; String(encode={'B413': 'blvd'}, lev=5, ori=('123 washington blvd', '123 washington boulevard')) ''' s_dict = encode_phonetic(s) o_dict = encode_phonetic(o) e_d = {**s_dict, **o_dict} e_diff = {k:e_d[k] for k in set(s_dict) - set(o_dict)} dist = l.distance(s_dict['KEY'], o_dict['KEY']) return String(e_diff, dist, (s,o)) </code></pre> <p>I also tried timing the functions and I understand that a big part of the runtime depends on the string length, which I am leaving out at the moment.</p> <pre><code>import timeit print(bstring('123 washington blvrd','123 washington boulevard')) print(timeit.timeit(lambda: bstring('123 washington blvd','123 washington boulevard'), number= 1000000)) &gt;&gt;String(encode={}, lev=4, ori=('123 washington blvrd', '123 washington boulevard')) &gt;&gt;47.34113038036594 </code></pre> <p>Is there anything I to improve the code runtime from the data model perspective?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-05T19:52:21.047", "Id": "207014", "Score": "3", "Tags": [ "python", "strings", "edit-distance" ], "Title": "Finding differences in strings with Levenshtein distance and soundex" }
207014
<p>first time using Code Review, although I have been active on StackOverflow, hope I'm in the right place.</p> <p>I am putting together Excel VBA code that using information from various columns on a worksheet to search for a document on a company intranet site, and save the document as a PDF, then move on to the next line and repeat.</p> <p>My issue is that the code works well for the first 80-100 lines or so, then Excel stops responding. I'm pretty sure this is because I have room to increase efficiency in my code, but I'm a VBA beginner, especially when it comes to using VBA with IE. I may be in a bit over my head.</p> <p>In short, my question is, is there a noticeable error I am making that would cause Excel to regularly "Stop Responding" after looping through so many lines?</p> <p>I have been searching for advice on StackOverflow, but have not come across a solution that works for me yet. I saw that an array could help? Not sure how to put 5 or so columns of data into a single array for my loop.</p> <p>The code:</p> <pre><code>Option Explicit Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Public Const BM_CLICK = &amp;HF5 Public Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As LongPtr Public Declare PtrSafe Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As LongPtr, ByVal hWnd2 As LongPtr, ByVal lpsz1 As String, ByVal lpsz2 As String) As LongPtr Public Declare PtrSafe Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As LongPtr, ByVal wMsg As Long, ByVal wParam As LongPtr, lParam As Any) As LongPtr #If VBA7 Then Private Declare PtrSafe Sub keybd_event Lib "user32.dll" (ByVal bVk As Byte, ByVal bScan As Byte, _ ByVal dwFlags As LongPtr, ByVal dwExtraInfo As LongPtr) Private Declare PtrSafe Function GetKeyboardState Lib "user32.dll" (ByVal lpKeyState As LongPtr) As Boolean #Else Private Declare PtrSafe Sub keybd_event Lib "user32.dll" (ByVal bVk As Byte, ByVal bScan As Byte, _ ByVal dwFlags As Long, ByVal dwExtraInfo As Long) Private Declare PtrSafe Function GetKeyboardState Lib "user32.dll" (ByVal lpKeyState As Long) As Boolean #End If Private Const KEYEVENTF_EXTENDEDKEY As Long = &amp;H1 Private Const KEYEVENTF_KEYUP As Long = &amp;H2 Private Const VK_NUMLOCK As Byte = &amp;H90 Private Const NumLockScanCode As Byte = &amp;H45 Public Sub Papervision() Dim ieApp As InternetExplorerMedium Dim ee As Variant, htmldoc Dim wb As Workbook Dim FilePath As String Dim oShell As Object Dim oShellWindows As Object Dim oShellWindow As Object Dim sPartialURL As String Dim F As Range '***** Setting variables for Windows API. Will be used to find the proper windows box by name ***** Dim windowHWND As LongPtr Dim WinHwnd As LongPtr Dim buttonHWND As LongPtr Dim hwnd As String Dim hwindow2 As String '***** Declaring our Loop variables ***** Dim wsSheet As Worksheet, Rows1 As Long, Invoices As Range, Invoice As Range '***** Setting the workbook and worksheet ***** Set wb = ThisWorkbook Set wsSheet = wb.Sheets("Email Check Pull") '***** Finding the last used rows ***** Rows1 = wsSheet.Cells(wsSheet.Rows.Count, "G").End(xlUp).Row '***** Set range for the loop ***** Set Invoices = wsSheet.Range("G2:G" &amp; Rows1) '***** Set the browser ***** Set ieApp = New InternetExplorerMedium FilePath = "C:\Users\username\Documents\Downloads\" Dim inCounter As Integer '***** Navigating to our Papervision link and setting the size of the IE window ***** With ieApp .Navigate "http://ctdayppv02/PVE.aspx" .Visible = True .AddressBar = 0 .StatusBar = 0 .Toolbar = 0 .MenuBar = 0 .Height = 700 .Width = 950 '***** Waiting for IE to load the page ***** Do While ieApp.Busy: DoEvents: Loop Do Until ieApp.ReadyState = READYSTATE_COMPLETE: DoEvents: Loop '***** Setting an additional variant to be used to click the Login button ***** Set htmldoc = ieApp.Document '***** Using the HTML elements to enter the username and password ***** ieApp.Document.all.Item("txtUserName").Value = "name" ieApp.Document.all.Item("txtPassword").Value = "pass" '***** The login button was not simply defined as a login button, so we search for relevant buttons by the HTML tag name ***** '***** When we find a clickable button, we click it and then sleep for 1 second ***** For Each ee In htmldoc.getElementsByTagName("span") If ee.ClassName = "dijitReset dijitInline dijitButtonNode" And InStr(ee.innerHTML, "btnLogin") &gt; 0 Then ee.Click: DoEvents: Sleep 2000 Exit For End If Next ee '***** This finds the project HTML element in the navigation sidebar and clicks it, then sleeps for 1 second ***** ieApp.Document.all.Item("project118").Click: DoEvents: Sleep 1000 '***** This finds the Search Type dropdown box from the Project Search Options and selects the "AND" option, then sleeps for 1 second ***** ieApp.Document.getElementById("lstSearchType").Value = "And": DoEvents: Sleep 1000 End With '***** Setting the Loop to do the following steps and then repeat for the next item ***** For Each Invoice In Invoices.Cells If Invoice.Offset(0, 1).Value &lt;&gt; "" Then GoTo NxtInv With ieApp '***** Inputting the Invoice # from Column G into the INV# input box ***** ieApp.Document.all.Item("txtFrom4").Value = Invoice '***** Inputting the Vendor # from Column A into the VEN# input box ***** ieApp.Document.all.Item("txtFrom1").Value = "*" &amp; Invoice.Offset(0, -6).Value '***** Clearing the VEN LOC input box ***** ieApp.Document.all.Item("txtFrom2").Value = "" '***** Inputting the Amount into the input box ***** ieApp.Document.all.Item("txtFrom6").Value = Invoice.Offset(0, 2).Value Application.Wait Now + TimeValue("0:00:01") '***** Click the Search button ***** ieApp.Document.all.Item("btnSubmitProjectSearch").Click: DoEvents: Sleep 1000 On Error GoTo Handler '***** Click the Print button ***** ieApp.Document.all.Item("printLink").Click On Error GoTo 0 Do While ieApp.Busy Or ieApp.ReadyState &lt;&gt; READYSTATE_COMPLETE Sleep 250 Loop ''***** Will click the Print button. MUST HAVE MICROSOFT PDF AS DEFAULT PRINTER ***** If getWindowPointer("Print", "#32770") = 0 Then Do While ieApp.Busy Or ieApp.ReadyState &lt;&gt; READYSTATE_COMPLETE Sleep 250 Loop End If windowHWND = getWindowPointer("Print", "#32770") If windowHWND &gt; 0 Then '***** Add a small delay to allow the window to finish rendering if needed ***** Sleep 250 buttonHWND = FindWindowEx(windowHWND, 0, "Button", "&amp;Print") If buttonHWND &gt; 0 Then SendMessage buttonHWND, BM_CLICK, 0, 0 Else Debug.Print "didn't find button!" End If End If '***** Locate the "Save Print Output As" window, enter the filepath/filename and press ENTER ***** hwnd = FindWindow(vbNullString, "Save Print Output As") Do DoEvents hwindow2 = FindWindow(vbNullString, "Save Print Output As") Loop Until hwindow2 &gt; 0 SendKeys FilePath &amp; Invoice DoEvents SendKeys "{Enter}" DoEvents '***** Locate the Viewer Control box that appears after saving and press ENTER to advance ***** hwnd = FindWindow(vbNullString, "PaperVision Document Viewer Control") Do DoEvents hwindow2 = FindWindow(vbNullString, "PaperVision Document Viewer Control") Loop Until hwindow2 &gt; 0 SendKeys "{Enter}" DoEvents '***** Here we locate any IE instance that includes the partial URL provided, and will close those IE instances ***** sPartialURL = "http://ctdayppv02/PVEShowDocPopup.aspx?" Set oShell = CreateObject("Shell.Application") Set oShellWindows = oShell.Windows For Each oShellWindow In oShellWindows If oShellWindow.Name = "Internet Explorer" Then If InStr(oShellWindow.Document.URL, sPartialURL) &gt; 0 Then Exit For End If End If Next oShellWindow If Not oShellWindow Is Nothing Then oShellWindow.Quit DoEvents Else End If Set oShell = Nothing Set oShellWindows = Nothing Set oShellWindow = Nothing '***** This will click the link to go back to the search screen in Papervision ieApp.Document.all.Item("btnSearchResults").Click: DoEvents: Sleep 1000 '***** Finding the last used row in the Final Email List worksheet and putting the PDF file path and Invoice number on that sheet ***** '***** This will later be used to send the appropriate PDF to its corresponding email address ***** Set F = ThisWorkbook.Worksheets("Final Email List").Cells(Rows.Count, 1).End(xlUp) 'last cell in Column A with data If Len(F.Value) &gt; 0 Then Set F = F.Offset(1) F.Value = Invoice DoEvents Set F = F.Offset(0, 1) F.Value = FilePath &amp; Invoice DoEvents inCounter = inCounter + 1 End With DoEvents '***** Repeat with the next item in the loop ***** GoTo NxtInv '***** This is used to resume the For Each loop and begin the process for the next invoice ***** NxtInv: If Invoice.Offset(1, 0) Is Nothing Then GoTo Finished Next Invoice '***** This is the start of the Error Handler. We use it to move to the next invoice and to ensure the error handling is properly ended ***** Handler: Resume NxtInv '***** Notify user when downloads are complete ***** Finished: ieApp.Quit Set ieApp = Nothing ToggleNumlock True MsgBox ("Papervison search completed!") End Sub Private Function getWindowPointer(WindowName As String, Optional ClassName As String = vbNullString) As LongPtr '***** This function is used to find the named window in the above sub ***** Dim i As Byte Dim hwnd As LongPtr 'Wait for the window to exist then return the pointer For i = 1 To 100 hwnd = FindWindow(ClassName, WindowName) If hwnd &gt; 0 Then getWindowPointer = hwnd Exit For End If DoEvents Sleep 200 Next End Function Private Sub ToggleNumlock(enabled As Boolean) Dim keystate(255) As Byte 'Test current keyboard state. GetKeyboardState (VarPtr(keystate(0))) If (Not keystate(VK_NUMLOCK) And enabled) Or (keystate(VK_NUMLOCK) And Not enabled) Then 'Send a keydown keybd_event VK_NUMLOCK, NumLockScanCode, KEYEVENTF_EXTENDEDKEY, 0&amp; 'Send a keyup keybd_event VK_NUMLOCK, NumLockScanCode, KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, 0&amp; End If End Sub </code></pre> <p>Any advice or guidance on what may be causing Excel to work for the first bunch of rows and then stop responding would be greatly appreciated, thank you!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-05T21:02:09.823", "Id": "399384", "Score": "1", "body": "With all the `DoEvents` in there, _anything_ else happening on your PC while this is running will steal the CPU from it. Using sleep with a very small period may be more effectiv...
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-05T20:31:27.703", "Id": "207015", "Score": "3", "Tags": [ "performance", "vba", "excel" ], "Title": "Excel VBA to download from IE Database Stops Responding" }
207015
<p>I've needed a couple of very special comparers recenty and didn't want to implement each one of them every time so I created a builder and a couple of supporting classes that do that for me.</p> <h3>Example</h3> <p>I'll start with an example. Given a collection of <code>Product</code>s:</p> <blockquote> <pre><code>var products = new[] { new Product {Name = "Car", Price = 7 }, new Product {Name = "Table", Price = 3 }, new Product {Name = "Orange", Price = 1 }, }; private class Product { public int Id { get; set; } public string Name { get; set; } public int Price { get; set; } } </code></pre> </blockquote> <p>I'd like to sort them either by the length of their name or price. Instead of implementig this type of unusual sorting with a new comparer I can use my new builder that allows me to create a comparer for that on the fly:</p> <pre><code>var comparer = ComparerFactory&lt;Product&gt;.Create( x =&gt; new { x.Name.Length, x.Price }, (builder, x, y) =&gt; { builder .LessThen(() =&gt; x.Length &lt; y.Length || x.Price &lt; y.Price) .Equal(() =&gt; x.Length == y.Length || x.Price == y.Price) .GreaterThan(() =&gt; x.Length &gt; y.Length || x.Price &gt; y.Price); }); var sorted = products.OrderByDescending(p =&gt; p, comparer).ToList(); </code></pre> <h3>Implementation</h3> <p>On top of everything else I use the <code>ComparerFactory&lt;T&gt;</code> that implements the tedious null checks and comparisons. No magic here.</p> <pre><code>internal static class ComparerFactory&lt;T&gt; { private class Comparer : IComparer&lt;T&gt; { private readonly IDictionary&lt;CompareOperator, Func&lt;T, T, bool&gt;&gt; _comparers; internal Comparer([NotNull] IDictionary&lt;CompareOperator, Func&lt;T, T, bool&gt;&gt; comparers) { _comparers = comparers; } public int Compare(T x, T y) { if (ReferenceEquals(x, y)) return 0; if (ReferenceEquals(x, null)) return -1; if (ReferenceEquals(y, null)) return 1; if (_comparers[CompareOperator.LessThan](x, y)) return -1; if (_comparers[CompareOperator.Equal](x, y)) return 0; if (_comparers[CompareOperator.GreaterThan](x, y)) return 1; // Makes the compiler very happy. return 0; } } public static IComparer&lt;T&gt; Create&lt;TComparable&gt;(Expression&lt;Func&lt;T, TComparable&gt;&gt; selectComparable, Action&lt;ComparerBuilder&lt;T, TComparable&gt;, TComparable, TComparable&gt; create) { var builder = new ComparerBuilder&lt;T, TComparable&gt;(selectComparable); create(builder, default, default); var funcs = builder.Build(); return new Comparer(funcs); } } </code></pre> <p>The interesing part begins with the <code>ComparerBuilder&lt;T, TComparable&gt;</code>. An instance of this class passed to the <code>Create</code> call just after the expression that selects the relevant value or properties as an anonymous object:</p> <blockquote> <pre><code>var comparer = ComparerFactory&lt;Product&gt;.Create( x =&gt; new { x.Name.Length, x.Price }, (builder, x, y) =&gt; { ... }); </code></pre> </blockquote> <p>The user also receives the two arguments that should be compared <code>x</code> and <code>y</code>. I'm doing this to not have to repeat myself when defining each comparison like I did before. </p> <p>This was the first version but I didn't like it. Too much redundancy so I moved the two repeating variables to the top.</p> <blockquote> <pre><code>( isLessThan: (x, y) =&gt; x.Ordinal &lt; y.Ordinal, areEqual: (x, y) =&gt; x.Ordinal == y.Ordinal, isGreaterThan: (x, y) =&gt; x.Ordinal &gt; y.Ordinal ); </code></pre> </blockquote> <p>The builder collects a couple of expressions. One for selecting the value or the properties that should be compared and one expression for each operation. </p> <p>Finally the <code>Build</code> method turns each three operation expressions into three <code>Func&lt;T, T, bool&gt;</code>:</p> <pre><code>internal class ComparerBuilder&lt;T, TComparable&gt; { private readonly Expression&lt;Func&lt;T, TComparable&gt;&gt; _getComparable; private readonly IDictionary&lt;CompareOperator, Expression&lt;Func&lt;bool&gt;&gt;&gt; _expressions = new Dictionary&lt;CompareOperator, Expression&lt;Func&lt;bool&gt;&gt;&gt;(); public ComparerBuilder(Expression&lt;Func&lt;T, TComparable&gt;&gt; getComparable) { _getComparable = getComparable; } public ComparerBuilder&lt;T, TComparable&gt; LessThen(Expression&lt;Func&lt;bool&gt;&gt; expression) { _expressions[CompareOperator.LessThan] = expression; return this; } public ComparerBuilder&lt;T, TComparable&gt; Equal(Expression&lt;Func&lt;bool&gt;&gt; expression) { _expressions[CompareOperator.Equal] = expression; return this; } public ComparerBuilder&lt;T, TComparable&gt; GreaterThan(Expression&lt;Func&lt;bool&gt;&gt; expression) { _expressions[CompareOperator.GreaterThan] = expression; return this; } internal IDictionary&lt;CompareOperator, Func&lt;T, T, bool&gt;&gt; Build() { var left = Expression.Parameter(typeof(T), "left"); var right = Expression.Parameter(typeof(T), "right"); return _expressions.ToDictionary(x =&gt; x.Key, x =&gt; CompileComparer(x.Value, new[] { left, right })); } private Func&lt;T, T, bool&gt; CompileComparer(Expression compare, ParameterExpression[] parameters) { var rewritten = CompareRewriter.Rewrite(_getComparable, parameters, compare); var lambda = Expression.Lambda&lt;Func&lt;T, T, bool&gt;&gt;(Expression.Invoke(rewritten), parameters); return lambda.Compile(); } } </code></pre> <p>But since the original operation expressions are incompatible with the <code>Func&lt;T, T, bool&gt;</code> signature:</p> <blockquote> <pre><code>() =&gt; x &lt; y </code></pre> </blockquote> <p>I cannot call them from the comparer yet. I need something else that wold accept parameters:</p> <blockquote> <pre><code>(x, y) =&gt; x &lt; y </code></pre> </blockquote> <p>In order to achieve this I created the <code>CompareRewriter</code> that is a <code>ExpressionVisitor</code> and replaces closures with calls to the selector for the comparable type or value. In case it's an anonymous type an additional conversion is necessary. Here a property access needs to be done to get the result of the type selector and not the closure which is useless later.</p> <p>This means that on the left and right side of each <code>&lt;</code>, <code>&gt;</code> and <code>==</code> operator I inject the selector specified as the first argument:</p> <blockquote> <pre><code>x =&gt; new { x.Name.Length, x.Price } </code></pre> </blockquote> <p>Rewriting the expressions was the trickiest part but I managed to create the correct expressions and it behaves just as I expect it to.</p> <pre><code>internal class CompareRewriter : ExpressionVisitor { private readonly Expression _getComparable; private readonly ParameterExpression[] _parameters; private int _param; public CompareRewriter(Expression getComparable, ParameterExpression[] parameters) { _getComparable = getComparable; _parameters = parameters; } public static Expression Rewrite(Expression getComparable, ParameterExpression[] parameters, Expression compare) { var visitor = new CompareRewriter(getComparable, parameters); return visitor.Visit(compare); } protected override Expression VisitLambda&lt;T&gt;(Expression&lt;T&gt; node) { var binary = Visit((BinaryExpression)node.Body); return Expression.Lambda&lt;Func&lt;bool&gt;&gt;(binary); } protected override Expression VisitBinary(BinaryExpression node) { if (node.NodeType == ExpressionType.Equal) return base.VisitBinary(node); // Rewrite // () =&gt; ClosureT1.x &lt; ClosureT2.y // to // () =&gt; getComparable(T2).x &lt; getComparable(T2).y var getLeft = Expression.Invoke(_getComparable, _parameters[0]); var getRight = Expression.Invoke(_getComparable, _parameters[1]); _param = 0; var left = Visit(node.Left); _param++; var right = Visit(node.Right); // Determine whether a member-access is necessary or are we using pure values? left = left == node.Left ? getLeft : left; right = right == node.Right ? getRight : right; switch (node.NodeType) { case ExpressionType.LessThan: return Expression.LessThan(left, right); case ExpressionType.Equal: return Expression.Equal(left, right); case ExpressionType.GreaterThan: return Expression.GreaterThan(left, right); } return base.VisitBinary(node); } protected override Expression VisitMember(MemberExpression node) { return node.Member.MemberType == MemberTypes.Property ? Expression.MakeMemberAccess(Expression.Invoke(_getComparable, _parameters[_param]), node.Member) : base.VisitMember(node); } } internal enum CompareOperator { LessThan, Equal, GreaterThan } </code></pre> <hr> <p>What do you think of this kind of a builder where you need to rewrite the expressions afterwards? What do you say about the expression-visitor?</p> <hr> <p>The same code but as a single file can be found <a href="https://github.com/he-dev/Reusable/blob/master/Reusable.Core/src/ComparerFactory.cs" rel="noreferrer">here</a> and my two tests <a href="https://github.com/he-dev/Reusable/blob/master/Reusable.Tests/src/Core/ComparerTest.cs" rel="noreferrer">here</a>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T01:42:49.937", "Id": "399409", "Score": "0", "body": "What will the array look like after it's sorted?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T06:57:24.493", "Id": "399428", "Score": "...
[ { "body": "<blockquote>\n<pre><code> builder\n .LessThen(() =&gt; x.Length &lt; y.Length || x.Price &lt; y.Price)\n .Equal(() =&gt; x.Length == y.Length || x.Price == y.Price)\n .GreaterThan(() =&gt; x.Length &gt; y.Length || x.Price &gt; y.Price);\n</code></pre>\n</block...
{ "AcceptedAnswerId": "207043", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-05T21:08:51.077", "Id": "207020", "Score": "14", "Tags": [ "c#", "design-patterns", "sorting", "expression-trees" ], "Title": "Building unusual IComparer<T> from expressions" }
207020
<p>I wrote a simple tic tac toe game in python. (I wrote the game logic and implementation separately) (in this case, it's a command line interface, I may do a Tkinter version) Can you review the code and give me tips for the future ?</p> <p><b>logic.py</b></p> <pre><code>from itertools import product TIC = 0 TAC = 1 BLANK = -1 WINNERS = ( ((0, 0), (0, 1), (0, 2)), ((1, 0), (1, 1), (1, 2)), ((2, 0), (2, 1), (2, 2)), ((0, 0), (1, 0), (2, 0)), ((0, 1), (1, 1), (2, 1)), ((0, 2), (1, 2), (2, 2)), ((0, 0), (1, 1), (2, 2)), ((2, 0), (1, 1), (0, 2)), ) INDICES = list(product(range(3), range(3))) # keep track of the game using a dictionary # keys are the indices (i, j) where 0 &lt;= i, j &lt;=2 # where i represents the row &amp; j the column def init_state(): """returns a blank state dictionary""" state = dict() for tup in INDICES: state[tup] = BLANK return state def is_valid_move(state, tup): """returns a boolean, true if the move is valid""" return state[tup] == BLANK def tic_turn(state, tup): """[TIC] assumes the move is valid, and returns a new state dictionary with updated values""" state = dict(state) state[tup] = TIC return state def tac_turn(state, tup): """[TAC] assumes the move is valid, and returns a new state dictionary with updated values""" state = dict(state) state[tup] = TAC return state def is_won(state): """returns a boolean, true if the game is won""" for winner in WINNERS: vals = set(state[tup] for tup in winner) if len(vals) == 1 and BLANK not in vals: return True return False def state_generator(get_input): """yields successive states takes a function with optional string argument that returns a tuple of numbers in range(3)""" state = init_state() yield state for level in range(5): human_input = get_input('TIC') machine_input = human_input[0] - 1, human_input[1] - 1 state = tic_turn(state, machine_input) yield state if is_won(state): print("tic won!") break if level == 4: print("Tie!") break human_input = get_input('TAC') machine_input = human_input[0] - 1, human_input[1] - 1 state = tac_turn(state, machine_input) yield state if is_won(state): print("tac won!") break </code></pre> <p><b>main.py</b></p> <pre><code>from logic import TIC, TAC, BLANK, INDICES, state_generator def get_int(info, kind): """prompts the user with prompt=info for a numerical value of type=kind return integer or quits program""" try: data = input("\t\t[%s] %-6s: " % (info, kind)) data = data.strip() if data.capitalize() == 'Q': exit() data = int(data) if data not in range(1, 4): raise Exception() return data except Exception as e: print("\t\t[%s] Invalid input." % info) print("\t\t[%s] Try again\n" % info) return get_int(info, kind) def get_input(info=""): """return tuple of numbers in range: 1,2,3 from user input""" return get_int(info, "Row"), get_int(info, "Column") def display_grid(): """creates display grid where to show the game steps""" ws = 5 * " " lm = 5 * "_" ds = " %s " cl_line = 2 * "\t" + " " + 17 * "_" + " " + "\n" ws_line = 2 * "\t" + "|" + ws + "|" + ws + "|" + ws + "|" + "\n" lm_line = 2 * "\t" + "|" + lm + "|" + lm + "|" + lm + "|" + "\n" ds_line = 2 * "\t" + "|" + ds + "|" + ds + "|" + ds + "|" + "\n" bloc = ws_line + ds_line + lm_line return "\n" + cl_line + 3 * bloc def draw(state): """draws the state of the game using a display_grid""" to_str = {TIC: 'X', TAC: 'O', BLANK: ' '} grid = display_grid() _list = [] for tup in INDICES: _list.append(to_str[state[tup]]) params = tuple(_list) print(grid % params) print("\n\n\t\t My Tic Tac Toe game") print("\n\n\t\t Press q to exit.") for state in state_generator(get_input): draw(state) </code></pre> <p><b>Snapshot</b> <a href="https://i.stack.imgur.com/gpaBJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gpaBJ.png" alt="enter image description here"></a></p>
[]
[ { "body": "<p>I would create a TTTBoard class with the logic to draw it as text, fill positions and check if the game is won as methods of it. Then the main program would create an instance and process input like it already does but not worry about much else.</p>\n", "comments": [], "meta_data": { ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-05T21:25:13.290", "Id": "207021", "Score": "1", "Tags": [ "python", "tic-tac-toe" ], "Title": "Tic Tac Toe Python" }
207021
<blockquote> <p><strong>The Problem</strong></p> <p>Sam Morose served for many years as communications officer aboard the U.S.S. Dahdit, a U.S. Coast Guard frigate deployed in the South Pacific. Sam never quite got over the 1995 decision to abandon Morse code as the primary ship-to shore communication scheme, and was forced to retire soon after because of the undue mental anguish that it was causing. After leaving the Coast Guard, Sam landed a job at the local post office, and became a model U.S. Postal worker… That said, it isn’t surprising that Sam is now holding President Clinton hostage in a McDonald’s just outside the beltway. The FBI and Secret Service have been trying to bargain with Sam for the release of the president, but they find it very difficult since Sam refuses to communicate in anything other than Morse code. Janet Reno has just called you to write a program that will interpret Sam’s demands in Morse code as English. Morse code represents characters of an alphabet as sequences of dits (short key closures) and dahs (longer key closures). If we let a period (.) represent a dit and a dash (-) represent a dah, then the Morse code version of the English alphabet is:</p> <p><a href="https://i.stack.imgur.com/zHaJH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zHaJH.png" alt="morse table"></a></p> <p><strong>Sample Input</strong></p> <p>Your program must takes its input from the ASCII text file <code>morse.in</code>. The file contains periods and dashes representing a message composed only of the English alphabet as specified above. One blank space is used to separate letters and three blanks are used to separate words. Sample contents of the file could appear as follows:</p> <pre><code>.... . .-.. .-.. --- -- -.-- -. .- -- . .. ... ... .- -- </code></pre> <p><strong>Sample Output</strong></p> <p>Your program must direct its output to the screen and must be the English interpretation of the Morse code found in the input file. There must be no blanks between letters in the output and only one blank between words. You must use all capital letters in the output. The output corresponding to the input file above is:</p> <pre><code>HELLO MY NAME IS SAM </code></pre> </blockquote> <p><strong>code.py</strong></p> <pre><code>import re codes = { '.-':'A', '-...':'B', '-.-.':'C', '-..':'D', '.':'E', '..-.':'F', '--.':'G', '....':'H', '..':'I', '.---':'J', '-.-':'K', '.-..':'L', '--':'M', '-.':'N', '---':'O', '...':'S', '-':'T', '..-':'U', '...-':'V', '.--':'W', '-..-':'X', '-.--':'Y', '--..':'Z' } with open('morse.in') as f: for line in f: t = [] for s in line.strip().split(' '): t.append(codes.get(s) if s else ' ') print(re.sub(' +', ' ', ''.join(t))) </code></pre> <p>Any advice on performance enhancement and solution simplification is appreciated, as are topical comments!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T03:07:11.803", "Id": "399415", "Score": "0", "body": "I always wondered why jslint dislikes single quotes, now I know." } ]
[ { "body": "<p>I realize this is just puzzle code, but treating this as a merge request for a production system:</p>\n\n<ol>\n<li>Replacing unknown codes with a space character seems counter to requirements. I would instead just <code>t.append(codes[s])</code> and let the script exit with an error when given inv...
{ "AcceptedAnswerId": "207027", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-05T22:15:53.367", "Id": "207025", "Score": "3", "Tags": [ "python", "python-3.x", "programming-challenge", "morse-code" ], "Title": "Contest Solution: Remorseful Sam" }
207025
<p><a href="https://codereview.stackexchange.com/questions/206983/mixed-duo-string-generator">Mixed Duo String Generator</a> Hello again;</p> <p>Previously my code was critique and I applied this feedback to form my new revised code for the Mixed Duo String Generator. In the code below I revised it to the best of my ability. I removed un-needed comments, keep variables in as small a scope as I could think of, removed un-needed functions, replaced manually typed values with constants, stuck with a consistent indexation, renamed variables with meaningful names, removed camel casing from variables name, nothing is unused, and finally attempted to remove all unnecessary usage of "!= or ==". </p> <p>I am somewhat nervous but I humbly await judgement of the quality of my code. </p> <pre><code>#include &lt;map&gt; #include &lt;string&gt; #include &lt;fstream&gt; #include &lt;sstream&gt; #include &lt;iostream&gt; std::string findPair2(std::string input){ if (input.size() &lt;= 4u) { return (input.size() == 4u &amp;&amp; input[0] == input[2] &amp;&amp; input[1] == input[3]) ? input : ""; } const std::string ELEM_1 = "ELEMENT_1"; const std::string ELEM_2 = "ELEMENT_2"; const std::string FAILED = "FAILED"; std::map&lt;char,std::string&gt; potential_second_element_status; /*The key value of the map represents the status of the character being compared to the first element of the string*/ std::string unique_charaters; std::string saved_failures = ""; for(int i=0; i&lt;input.size(); i++){ //get all the unique characters as they appear in chroniclogical order except the first character if((potential_second_element_status.find(input[i]) == potential_second_element_status.end())&amp;&amp;(input[i] != input[0])){ potential_second_element_status[input[i]] = ELEM_1; unique_charaters += input[i]; } } for(int i=0; i&lt;input.size(); i++){ if(saved_failures.size() == unique_charaters.size()){ break; } if(input[i] == input[0]){ for(int a=0; a&lt;unique_charaters.size(); a++){ if(potential_second_element_status.find(unique_charaters[a])-&gt;second == ELEM_2){ saved_failures += unique_charaters[a]; potential_second_element_status[unique_charaters[a]] = FAILED; } if(potential_second_element_status.find(unique_charaters[a])-&gt;second == ELEM_1){ potential_second_element_status[unique_charaters[a]] = ELEM_2; } } } else if(potential_second_element_status.find(input[i])-&gt;second == ELEM_2){ potential_second_element_status[input[i]] = ELEM_1; } else if(potential_second_element_status.find(input[i])-&gt;second == ELEM_1){ saved_failures += input[i]; potential_second_element_status[input[i]] = FAILED; } } if(saved_failures.size() == unique_charaters.size()){ char temp = input[0]; input.erase(std::remove(input.begin(), input.end(), temp), input.end()); input = findPair2(input); } else{ for(int i=0; i&lt;saved_failures.size(); i++){ input.erase(std::remove(input.begin(), input.end(), saved_failures[i]), input.end()); } } return input; } void autoStringRead2(){ std::ifstream inputs( "pairs-in.txt" ); std::string line; std::string output; std::string filename = "pairs-in.txt"; std::fstream fs(filename, std::ios::in); std::ofstream results; results.open ("results.txt"); if(!fs.is_open()){ return; } while (inputs &gt;&gt; line) { output = findPair(line); results &lt;&lt; output &lt;&lt;"\n"; std::cout&lt;&lt; line &lt;&lt; "\n"; std::cout&lt;&lt; output &lt;&lt; "\n"; } //inputs.close(); //results.close(); } int main(){ autoStringRead2(); int read; std::cin &gt;&gt; read; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T03:12:58.790", "Id": "399416", "Score": "0", "body": "What's the relation to \"*[Mixed Duo String Generator 2](https://codereview.stackexchange.com/questions/206987/mixed-duo-string-generator-2)*\"?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T01:43:13.607", "Id": "207028", "Score": "1", "Tags": [ "c++", "performance", "object-oriented", "strings", "complexity" ], "Title": "Mixed Duo String Generator Part 2" }
207028
<p>I have the following code in my Django template. It's a bit repetitive. I wonder if that's good the way I wrote it, or if you would combine these two 'if'-statements into one somehow?</p> <pre><code>{% elif discount.no_more_left %} &lt;div class="modal fade" id="no-more-left-modal" tabindex="-1" role="dialog" aria-hidden="true"&gt; &lt;div class="modal-dialog" role="document"&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-header"&gt; &lt;h3 class="modal-title"&gt;{{ discount.code }}&lt;/h3&gt; &lt;button type="button" class="close" data-dismiss="modal" aria-label="Close"&gt; &lt;span aria-hidden="true"&gt;&amp;times;&lt;/span&gt; &lt;/button&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;p&gt;{% trans "There are no more discount codes available. If you want to offer more, you can edit it and increase the available quantity." %}&lt;/p&gt; &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;button type="button" class="btn btn-secondary" data-dismiss="modal"&gt;{% trans "Close" %}&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; {% elif discount.is_expired %} &lt;div class="modal fade" id="expired-modal" tabindex="-1" role="dialog" aria-hidden="true"&gt; &lt;div class="modal-dialog" role="document"&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-header"&gt; &lt;h3 class="modal-title"&gt;{{ discount.code }}&lt;/h3&gt; &lt;button type="button" class="close" data-dismiss="modal" aria-label="Close"&gt; &lt;span aria-hidden="true"&gt;&amp;times;&lt;/span&gt; &lt;/button&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;p&gt;{% trans "This discount code is expired. If you want to extend it, you can edit it and change the expiration date." %}&lt;/p&gt; &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;button type="button" class="btn btn-secondary" data-dismiss="modal"&gt;{% trans "Close" %}&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; {% endif %} </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T07:09:18.940", "Id": "207034", "Score": "1", "Tags": [ "django" ], "Title": "Django template for \"no more discount codes\" and \"expired discount code\" situations" }
207034
<p>I'm afraid just about everybody who read this question has misunderstood it. I'm not trying to find the best way of printing a vector. I'm trying to find the best way of excluding part of an operation from the last iteration in a loop. I'm seeking advice about a <strong>pattern</strong> that is repeated is many <strong>different contexts</strong>. For this reason, I cannot provide a concrete example.</p> <p><strong>This question is off-topic</strong></p> <hr> <p>A well-formed comma-separated list has commas after all but the last element. This means that when dealing with these lists, the comma has to be dealt with on all but the last iteration. This is how I do things currently:</p> <pre><code>for (auto e = vec.cbegin(); e != vec.cend(); ++e) { // code that has to be executed for every element std::cout &lt;&lt; *e; if (e != vec.cend() - 1) { // code that must not be executed for the last element std::cout &lt;&lt; ", "; } } </code></pre> <p>There are five instances of the above pattern in the project that I'm working on. I feel like there might be a more elegant way of doing this. An alternative that I've come up with is this:</p> <pre><code>// infinite loop if vec is empty if (!vec.empty()) { for (auto e = vec.cbegin(); e != vec.cend() - 1; ++e) { // code that has to be executed for every element std::cout &lt;&lt; *e; // code that must not be executed for the last element std::cout &lt;&lt; ", "; } // code that has to be executed for every element std::cout &lt;&lt; vec.back(); } </code></pre> <p>This alternative is slightly faster because there isn't an <code>if</code> in the body but that's not a big deal. The <code>if</code> is true for all but the last iteration so the branch predictor will probably only miss on the last iteration. I also have to repeat <code>code that has to be executed for every element</code> which means that I need to hoist that into a function. </p> <p>The first snippet is the best that I can come up with but I feel like this could be done better. Note that writing to <code>std::cout</code> is just an example.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T11:27:29.930", "Id": "399473", "Score": "2", "body": "You're implementing an [`ostream_joiner`](https://en.cppreference.com/w/cpp/experimental/ostream_joiner) - is this [tag:reinventing-the-wheel], or do you need something for strai...
[ { "body": "<p>I'm not sure that elegance should be your first concern here, because the algorithm should be very simple and the code short however you write them. </p>\n\n<p>I/O operations will have a much greater impact on performance than the lay-out of your loop, so you shouldn't worry too much about speed e...
{ "AcceptedAnswerId": "207046", "CommentCount": "15", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T07:15:46.187", "Id": "207035", "Score": "2", "Tags": [ "c++", "c++17", "iteration" ], "Title": "Elegantly exclude part of an operation for the last iteration in a loop" }
207035
<p>In my opinion, Vectorization operation with numpy should be much faster than use for in pure python. I write two function to get and process data in a csv file, one in numpy and another in pure python, but numpy one takes nearly four times time of the other. Why? Is this the "wrong" way to numpy? Any suggestion would be greatly appreciated!</p> <p>The python code is below, while csv file in rather long, and I put it to <a href="https://gist.github.com/jjwt/de4e75b81ced840183b7c8cbea3e1644" rel="nofollow noreferrer">enter link description here</a></p> <p>The csv file includes some info about an engine, in which, the first column means crankshaft angle in degrees, and the 8th column means (header "PCYL_1") means the first cylinder pressure in bar.</p> <p>what I want to do:</p> <ol> <li>get angle-pressure data pairs with only integer angle,</li> <li>group the data by angle, and get the max pressure of each angle</li> <li>get new angle-max_pressure data pairs</li> <li>shift angle range from -360~359 to 0~719</li> <li>sort data-pairs by angle</li> <li>because angle range must be 0~720, and first pressure equals last pressure, add a [720.0, first angle] to data pairs</li> <li>output data pairs to a dat file</li> </ol> <p>my run eviroment is </p> <ol> <li>python3.6.4 MSC v.1900 32 bit (Intel)</li> <li>win8.1 64 bit</li> </ol> <p>I i run ipython in the script file direcotry and input below:</p> <pre><code>from gen_cylinder_pressure_data_from_csv import * In [5]: %timeit main_pure_python() 153 ms ± 1.11 ms per loop (mean ± std. dev. of 7 runs, 10 loops each In [6]: %timeit main_with_numpy() 627 ms ± 3.51 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) </code></pre> <p>python code is below:</p> <pre><code>from glob import glob import numpy def get_data(filename): with open(filename, 'r', encoding='utf-8-sig') as f: headers = None for line_number, line in enumerate(f.readlines()): if line_number == 0: headers = line.strip().split(',') angle_index = headers.index('曲轴转角') # cylinder_pressure_indexes = [i for i in range(len(headers)) if headers[i].startswith('PCYL_1')] cylinder_pressure_indexes = [i for i in range(len(headers)) if headers[i].startswith('PCYL_1')] elif line_number == 1: continue else: data = line.strip() if data != '': datas = data.split(',') angle = datas[angle_index] if '.' not in angle: # cylinder_pressure = max(datas[i] for i in cylinder_pressure_indexes) cylinder_pressure = datas[cylinder_pressure_indexes[0]] # if angle == '17': # print(angle, cylinder_pressure) yield angle, cylinder_pressure def write_data(filename): data_dic = {} for angle, cylinder_pressure in get_data(filename): k = int(angle) v = float(cylinder_pressure) if k in data_dic: data_dic[k].append(v) else: data_dic[k] = [v] for k, v in data_dic.items(): # datas_dic[k] = sum(v) / len(v) data_dic[k] = max(v) angles = sorted(data_dic.keys()) if angles[-1] - angles[0] != 720: data_dic[angles[0] + 720] = data_dic[angles[0]] angles.append(angles[0] + 720) else: print(angles[0], angles[-1]) with open('%srpm.dat' % filename[-8:-4], 'w', encoding='utf-8') as f: for k in angles: # print('%s,%s\n' % (k,datas_dic[k])) f.write('%s,%s\n' % (k, data_dic[k])) def main_with_numpy(): # rather slow than main_pure_python for filename in glob('Ten*.csv'): with open(filename, mode='r', encoding='utf-8-sig') as f: data_array = numpy.loadtxt(f, delimiter=',', usecols=(0, 7), skiprows=2)[::10] pressure_array = data_array[:, 1] pressure_array = pressure_array.reshape(720, pressure_array.shape[0] // 720) pressure_array = numpy.amax(pressure_array, axis=1, keepdims=True) data_output = numpy.zeros((721, 2), ) data_output[:-1, 0] = data_array[:720, 0] data_output[:-1, 1] = pressure_array.reshape(720) data_output[:, 0] = (data_output[:, 0] + 720) % 720 data_output[-1, 0] = 721 data_output = data_output[data_output[:, 0].argsort()] data_output[-1] = data_output[0] data_output[-1, 0] = 720.0 with open('%srpm.dat' % filename[-8:-4], 'w', encoding='utf-8') as f: numpy.savetxt(f, data_output, fmt='%f', delimiter=',') pass def main_pure_python(): for filename in glob('Ten*.csv'): write_data(filename) pass if __name__ == '__main__': main_pure_python() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T08:38:07.450", "Id": "399440", "Score": "0", "body": "We need to know what your program is doing. Could you explain these calculations etc?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T09:12:47.890...
[ { "body": "<p>Well I am also newbie on numpy, but your question interested me, so I did some profile check on your code also google some about numpy. Here is what I found</p>\n\n<p><strong>The main reason why you numpy solution is so slow is because of <code>numpy.loadtxt</code></strong></p>\n\n<hr>\n\n<h2>Prof...
{ "AcceptedAnswerId": "207057", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T07:27:06.370", "Id": "207036", "Score": "5", "Tags": [ "python", "performance", "python-3.x", "comparative-review", "numpy" ], "Title": "process data with numpy seems rather slow than pure python?" }
207036
<p>The AI I'm making is really simple, however it might be a bit too inefficient for what it is doing. The chart below shows speed differences between various arithmetic and math operations. <code>sin</code>, <code>cos</code> and especially <code>atan</code> are really inefficient. It's tested in C++ but should still hold true to JavaScript.</p> <p>Is it possible to achieve the same result with more efficient math?</p> <p><a href="https://i.stack.imgur.com/uGjcH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uGjcH.png" alt="Math efficiency"></a> <a href="http://www.latkin.org/blog/2014/11/09/a-simple-benchmark-of-various-math-operations/" rel="nofollow noreferrer">Chart Source</a></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>const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); let targetX = 50; let targetY = 50; let obstacleX = 150; let obstacleY = 50; let aiX = 250; let aiY = 51; function loop() { // Distance between the vector points let disTargetX = targetX - aiX; let disTargetY = targetY - aiY; let disObstacleX = obstacleX - aiX; let disObstacleY = obstacleY - aiY; // Moves to target by default const angleTarget = Math.atan2(disTargetY, disTargetX); let moveAngle = angleTarget; // If near obstacle, adjust course and try to avoid it if (Math.sqrt(disObstacleX * disObstacleX + disObstacleY * disObstacleY) &lt; 60) { const angleObstacle = Math.atan2(disObstacleY, disObstacleX); moveAngle += angleTarget - angleObstacle; } // Move the vector to desired location aiX += Math.cos(moveAngle); aiY += Math.sin(moveAngle); //Drawing ctx.clearRect(0, 0, 600, 200); ctx.beginPath(); ctx.fillStyle = "teal"; ctx.arc(aiX, aiY, 10, 0, Math.PI * 2, true); ctx.fill(); ctx.beginPath(); ctx.fillStyle = "purple"; ctx.arc(obstacleX, obstacleY, 10, 0, Math.PI * 2, true); ctx.fill(); ctx.rect(targetX - 20, targetY - 20,40,40); ctx.stroke(); requestAnimationFrame(loop); } requestAnimationFrame(loop);</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;canvas id="canvas" width="600" height="200"&gt;&lt;/canvas&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T07:40:42.600", "Id": "399437", "Score": "2", "body": "If you don't need the actual Euclidean distance, you can leave the Math.sqrt out and just do distance squared." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate":...
[ { "body": "<p>AFAIK, trigonometric functions are pretty much unavoidable in (non-graph-based) dynamic movement. Depending on what you're trying to accomplish, grid- or graph-based movement might be an option, though graph traversal and pathfinding can be its own can of worms.</p>\n\n<p>A simpler solution might ...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T07:32:35.647", "Id": "207037", "Score": "5", "Tags": [ "javascript", "performance", "animation", "computational-geometry", "pathfinding" ], "Title": "AI to avoid obstacle" }
207037
<p>-> Already Asked at StackOverFlow, but was adviced to post question here! &lt;-</p> <p>I want to compare two lists, which both can be null, both can contain <code>0</code> or more entries. </p> <p>If the amount matches, there should be some handling for that.<br> If not, it should be checked if the difference of the amount is covered by the tolerance given. </p> <p>Here's what I did. Is there a more elegant way to do that? </p> <p>Note: Null-Check not included in current snipplet. Currently is done earlier in code, but could be part of the asked solution. </p> <pre><code>int tolerableDifference = 5; //example. Result success = Result.Valid; if (listA.Count == listB.Count) { // do whatever is to be done when counts match. } else { // Lists have different length. No match. var absDifference = Math.Abs(listA.Count - listB.Count); if ((listA.Count - listB.Count) &gt; 0) { if (absDifference &lt; tolerableDifference) { Console.WriteLine($"Difference below Tolerance threshold. Difference: {absDifference}."); } else { //Outside tolerance, too less items in listB success = Result.Invalid | Result.TooFewItems; } } else if ((listA.Count - listB.Count) &lt; 0) { if (absDifference &lt; tolerableDifference) { Console.WriteLine($"Difference below Tolerance threshold. Difference: {absDifference}."); } else { //Outside tolerance, too many items in listB success = Result.Invalid | Result.TooManyItems; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T10:47:12.957", "Id": "399464", "Score": "2", "body": "Welcome to Code Review.To help us reviewing your code it would be better if you at least post the entire method. Giving as much code and context as possible will lead to better a...
[ { "body": "<p>A rather obvious improvement is implementing the <code>absDifference &lt; tolerableDifference</code> check <em>once instead of twice</em>.</p>\n\n<p>Furthermore, using the ternary <code>?:</code> operator will make the remainder of the code shorter and easier to read.</p>\n\n<p>The result:</p>\n\n...
{ "AcceptedAnswerId": "207058", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T10:42:20.900", "Id": "207053", "Score": "-1", "Tags": [ "c#" ], "Title": "Compare quantity of two lists - with a given tolerance" }
207053
<p>I have written code to count the continuous ones in an array or you can use binary string for convenience. Any solution using the binary string is acceptable.</p> <p>My Solution is:</p> <pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; #define MAX 100000 int main() { int n,q,k,count; string str; cin&gt;&gt;n&gt;&gt;q&gt;&gt;k; bitset&lt;MAX&gt;s,c; //inserting bits in array for(int i=0;i&lt;n;i++) { int temp; cin&gt;&gt;temp; s[i]=temp; } cin&gt;&gt;str; for(int i=0;i&lt;q;i++) { //making duplicate bitset c=s; if(str[i]=='?') { count=0; while(c!=0) { //using bitmask to count maximum no of continuous 1's-O(1's bit) c=(c&amp;(c&lt;&lt;1)); count++; } if(count&gt;k) cout&lt;&lt;k&lt;&lt;"\n"; else cout&lt;&lt;count&lt;&lt;"\n"; } else { //shifting each bit to right and updating first bit with previous last // bit bool lb=s[n-1]; s=s&gt;&gt;1; s[n-1]=lb; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T14:52:16.543", "Id": "399525", "Score": "4", "body": "Try to give an example with possible value and invalid inputs and expected outputs. it will help people to figure out the way and the purpose of your programme." } ]
[ { "body": "<p><code>&lt;bits/stdc++.h&gt;</code> (like everything in your compiler's <code>bits/</code> subtree) is not a standard header and therefore not portable. Even if you're willing to sacrifice portability, it's a poor choice, as it will slow compilation down compared to simply including what you use.<...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T13:23:59.713", "Id": "207063", "Score": "3", "Tags": [ "c++", "programming-challenge", "bitset" ], "Title": "Bitmasking and searching consecutive 1's" }
207063
<p>I completed a coding challenge recently in which my function was to be given two parameters: N, the number of counters to be used (numbered 1 through N) - and A, an array of integers. Iterating through the array A, when the index of a counter occurs, that counter is incremented by 1. When an index of N+1 occurs, all of the counters are reset to the maximum counter at that point.</p> <pre><code>def solution(N, A): li = [0] * N #print('A is %s' % A) #print('N is %s' % N) max_val = 0 for i in A: i = i-1 #print('i is %s' % i) #print('li is %s' % li) if i == N: #print(' in if') li = [max_val] * N else: #print(' in else') li[i] = li[i] + 1 if li[i] &gt; max_val: max_val = li[i] return li </code></pre> <p>[Using Python 3.6]<br> (See related <a href="https://codereview.stackexchange.com/questions/204534/maxcounters-codility-challenge">question</a>.)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T16:12:47.657", "Id": "399537", "Score": "1", "body": "Yes; I missed some code. Updated post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T16:19:16.760", "Id": "399538", "Score": "1", "b...
[ { "body": "<ul>\n<li><code>li</code> is the name of your list of counters. The fact they are counters matters more than the fact it's a list, so, I'd call it <code>counters</code>.</li>\n<li>I like the clever way you updated all elements in the counters list by creating a new one, but it may be slower than loop...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T13:34:03.153", "Id": "207064", "Score": "0", "Tags": [ "python", "python-3.x", "programming-challenge", "time-limit-exceeded", "complexity" ], "Title": "Incrementing specified list values, with \"catch-up\"" }
207064
<p>I'm reading range/distance sensor data from one Serial Port, decoding it and then transmitting it to a secondary device in ASCII format. The sensor uses a 2-byte header with each byte containing the following hex values: 0x59 0x59. Additional data from the sensor is also sent in a 7-byte message, subsequent to the header.</p> <p>The code works but I'm not convinced that I'm reading the data correctly in DataReceived event handler. How can I improve this code?</p> <pre><code>internal static class Program { private static long _validMessageCount; private static SerialPort _distanceOutputSerialPort; private const int FrameHeader = 0x59; public static void Main() { SerialPort lidarSensorSerialPort = null; try { lidarSensorSerialPort = new SerialPort(AppSettings.InputPort) { BaudRate = AppSettings.InputBaudRate, DataBits = AppSettings.InputDataBits, Handshake = Handshake.None, Parity = Parity.None, StopBits = StopBits.One }; _distanceOutputSerialPort = new SerialPort(AppSettings.OutputPort) { BaudRate = AppSettings.OutputBaudRate, DataBits = AppSettings.OutputDataBits, Handshake = Handshake.None, Parity = Parity.None, StopBits = StopBits.One, NewLine = "\r", Encoding = Encoding.ASCII }; _distanceOutputSerialPort.Open(); lidarSensorSerialPort.DataReceived += DataReceivedHandler; lidarSensorSerialPort.Open(); Console.Write("Waiting for data..."); Console.ReadKey(); } catch (IOException e) { Console.WriteLine(e.Message); } catch (Exception e) { Console.WriteLine(e.Message); } finally { lidarSensorSerialPort?.Close(); _distanceOutputSerialPort?.Close(); Console.Write("Press any key to exit..."); Console.ReadKey(); } } private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) { var headerBytes = new byte[2]; var measuredRangeBytes = new byte[7]; var serialPort = (SerialPort) sender; if (serialPort.BytesToRead &lt; 9) return; while (true) { if (headerBytes[0] == FrameHeader &amp;&amp; headerBytes[1] == FrameHeader) break; serialPort.Read(headerBytes, 0, headerBytes.Length); } var bytesRead = serialPort.Read(measuredRangeBytes, 0, measuredRangeBytes.Length); if (bytesRead &lt; measuredRangeBytes.Length) { Console.WriteLine($"Invalid data Received. [{bytesRead}]"); return; } var completeBytes = headerBytes.Concat(measuredRangeBytes).ToArray(); var checksum = Helpers.CalculateChecksum(completeBytes); var check = measuredRangeBytes[6]; if (checksum != check) { Console.WriteLine("Invalid Checksum"); return; } CalculateDistance(measuredRangeBytes); } private static void CalculateDistance(IList&lt;byte&gt; distanceBytes) { var distanceLow = distanceBytes[0]; var distanceHigh = distanceBytes[1]; var strengthLow = distanceBytes[2]; var strengthHigh = distanceBytes[3]; var realibilityLevel = distanceBytes[4]; var exposureTime = distanceBytes[5]; var distance = Math.Round(distanceHigh * 256d + distanceLow, 2); var strength = strengthHigh * 256 + strengthLow; var time = $"{DateTime.Now:HH:mm:ss.fff}"; _validMessageCount++; Console.WriteLine( $"{_validMessageCount}. {time} | {distance} | {strength} | {realibilityLevel} | {exposureTime}"); ConvertOuput(distance); } private static void ConvertOuput(double distance) { var distanceInMeters = Math.Round(distance / 100d, 2); var mdlLmSensorOutput = $"{distanceInMeters.ToString("F").PadLeft(6, '0')}m"; _distanceOutputSerialPort.WriteLine(mdlLmSensorOutput); Console.WriteLine($"Output: {mdlLmSensorOutput}"); } } </code></pre>
[]
[ { "body": "<p>The main problem I see is that you could miss the frame header if it was preceeded by odd number of different bytes (0xAA 0x59 0x59 ... you will try to match AA59 and then 59XX missing 5959). I would therefore rewrite it like this:</p>\n\n<pre><code>static int headerBytes; // counter to help us fi...
{ "AcceptedAnswerId": "207579", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T15:38:32.913", "Id": "207078", "Score": "2", "Tags": [ "c#", "console", "serial-port" ], "Title": "Reading range sensor data from one Serial Port and writing output to another" }
207078
<p>When sections are ignored and no writing capability is needed, an <a href="https://en.wikipedia.org/wiki/INI_file" rel="nofollow noreferrer">INI</a> reader becomes quite simple to implement. Here is my attempt at reading a sectionless INI file without any non-<code>std</code> dependencies.</p> <p>The general idea is to store all <code>key</code>-<code>value</code> pairs in a <code>&lt;string, string&gt;</code> <code>map</code>, and use getters to convert the <code>value</code> string to desired type on demand.</p> <pre><code>#include &lt;fstream&gt; #include &lt;iostream&gt; #include &lt;map&gt; #include &lt;string&gt; class SectionlessINIReader { private: std::map&lt;std::string, std::string&gt; dict; public: // https://stackoverflow.com/a/1798170/3516684 static std::string trim(const std::string&amp; str, const std::string&amp; whitespace = " \t") { const auto strBegin = str.find_first_not_of(whitespace); if (strBegin == std::string::npos) return ""; // no content const auto strEnd = str.find_last_not_of(whitespace); const auto strRange = strEnd - strBegin + 1; return str.substr(strBegin, strRange); } SectionlessINIReader(const std::string&amp; filename) { std::ifstream file(filename); std::string line; int idxEq; while (std::getline(file, line)) { if ((line.find_first_not_of(";#")==0) &amp;&amp; ((idxEq = line.find("=")) != std::string::npos)) { std::string key = trim(line.substr(0,idxEq)); std::string value = trim(line.substr(idxEq+1)); dict[key] = value; } } file.close(); } std::string get(std::string key) { return dict[key]; } bool getLong(std::string key, long* p_value) { std::string value = dict[key]; if (value=="") { return false; } else { *p_value = std::stol(dict[key]); return true; } } // bool getDouble(...) }; </code></pre> <p>The intended usage is:</p> <pre><code>SectionlessINIReader ini("config.ini"); long age; if (ini.getLong("age", &amp;age)) std::cout &lt;&lt; "Name: " &lt;&lt; ini.get("name") &lt;&lt; "; age: " &lt;&lt; age &lt;&lt; std::endl; </code></pre>
[]
[ { "body": "<h2>Code Review</h2>\n\n<p>There is no need to close the file manually, it will be closed as part of the <code>std::ifstream</code>'s destructor.</p>\n\n<p>Checking if line is comment could be simplified into checking the first character and <code>or</code>ing the result.</p>\n\n<p>There is a <a href...
{ "AcceptedAnswerId": "207130", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T16:49:43.003", "Id": "207086", "Score": "6", "Tags": [ "c++", "parsing", "file", "io", "configuration" ], "Title": "Minimalistic, self-contained class for reading a sectionless INI file" }
207086
<p>I have this code with nested foreach loops that is getting out of hand.</p> <p>Is there a better and/or cleaner way of doing this?</p> <p>Basically, what it's doing, is take the results from an API call, and then looping through each layer.</p> <p>I check to make sure that each layers Results.Length is greater than zero before I start the next loop.</p> <p>Anyway, here's my crazy ugly mess of code:</p> <pre><code>parentFolderResponse = GetFolders(parentFolder, sessionMgr, SessionManagementAuth, pagination); if (parentFolderResponse.Results.Length &gt; 0) { foreach (Folder folder in parentFolderResponse.Results) { Console.WriteLine("\n + Class Of = " + folder.Name); ListFoldersResponse childFolderResponse = GetFolders(folder.Id, sessionMgr, SessionManagementAuth, pagination); if (childFolderResponse.Results.Length &gt; 0) { foreach (Folder childFolder in childFolderResponse.Results) { Console.WriteLine("\n \t Course Name = " + childFolder.Name); ListSessionsResponse courseSessionResponse = GetPresentations(sessionMgr, SessionManagementAuth, pagination, childFolder.Id); if (courseSessionResponse.Results.Length &gt; 0) { foreach (Session session in courseSessionResponse.Results) { Console.WriteLine("n \t \t Session Name = " + session.Name); } } else { Console.WriteLine("\n No sessions found!"); } } } else { Console.WriteLine("\n No course folder(s) found!"); } } } else { Console.WriteLine("\n No class of folder(s) found!"); } </code></pre> <p>If anyone has any suggestions, I'd love to hear them.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T18:06:02.163", "Id": "399558", "Score": "0", "body": "Heard about `Linq`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T18:11:03.637", "Id": "399559", "Score": "1", "body": "@kara This c...
[ { "body": "<p>There's no reason to check if there are any items in a collection before iterating over it. If there are no items, iterating over it <em>won't do anything</em>. So that alone removes half of the indentation, which makes the code fairly manageable.</p>\n\n<pre><code>parentFolderResponse = GetFold...
{ "AcceptedAnswerId": "207092", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T18:00:22.673", "Id": "207091", "Score": "0", "Tags": [ "c#" ], "Title": "Listing sessions within folders in API results" }
207091
<p>In this small bit of JavaScript, a date is passed in as <code>YYYY-MM-DD</code>. It's formatted like this to be passed to the backend system. On the front end, we need to display it as <code>MM/DD/YYYY</code>. </p> <p>I split the string, and put the each array index in the correct position. However, I feel like there could be a a better way to do this. </p> <p>This is the code I have at the moment.</p> <pre><code>static formatCourseDate(date: string): string { const _date = date.split('-'); const dateObj = {month: _date[1], day: _date[2], year: _date[0]}; return dateObj.month + '/' + dateObj.day + '/' + dateObj.year; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-23T01:31:26.077", "Id": "454868", "Score": "0", "body": "From a high level, are you sure you want to? https://en.wikipedia.org/wiki/ISO_8601#Calendar_dates" } ]
[ { "body": "<p>One cleaner, simpler and more obvious way is:</p>\n\n<pre><code>const _date = new Date(date); // yyyy-MM-dd\nreturn (_date.getMonth()+1) + '/' + _date.getDate() + '/' + _date.getFullYear();\n</code></pre>\n\n<p><code>getMonth()</code> - Returns month based on 0 index. So we added 1 to it.</p>\n\n<...
{ "AcceptedAnswerId": "207100", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T18:58:55.697", "Id": "207095", "Score": "6", "Tags": [ "javascript", "strings", "datetime", "ecmascript-6", "formatting" ], "Title": "Reformatting a date from YYYY-MM-DD to MM/DD/YYYY" }
207095
<p>I have a CSV file that I would like to split up by row, do some whitespace processing on the string data in each row of the document column, and then output the processed data into separate TXT files in a new directory. The whitespace processing is to standardize the documents by removing newlines, carriage returns, and replacing all empty strings with <code>" "</code>.</p> <p>The thing is, I will be doing this on corpora of 3+ million documents, so was wondering if there is a better way to do this instead of iterating through each one.</p> <pre><code>with open(csv_file) as file: reader = csv.reader(file, delimiter=',') count = -1 for row in reader: row[1] = str(row[1]).replace(r'\n', '') row[1] = str(row[1]).replace(r'\r', '') if not row[1]: row[1] = ' ' with open('corpus' + str(count) + '.txt', 'w') as output: output.write(str(row[1])) count += 1 </code></pre> <p>Input CSV data:</p> <pre><code>document_id,document 0,"Bacon ipsum dolor amet kevin jerky sausage filet mignon landjaeger, turducken drumstick burgdoggen kielbasa frankfurter doner tongue meatloaf." 1,"Beef ribs jerky biltong fatback." 2,"Short loin capicola pastrami meatball. Brisket meatloaf jowl salami porchetta jerky hamburger t-bone meatball turkey." 3,"Cow ham strip steak pastrami venison." 4,"Landjaeger fatback pork loin pig sausage." </code></pre> <p>Output individual TXT files with contents of processed <code>document</code> column:</p> <pre><code>corpus_0 "Bacon ipsum dolor amet kevin jerky sausage filet mignon landjaeger, turducken drumstick burgdoggen kielbasa frankfurter doner tongue meatloaf." corpus_1 "Beef ribs jerky biltong fatback." corpus_2 "Short loin capicola pastrami meatball. Brisket meatloaf jowl salami porchetta jerky hamburger t-bone meatball turkey." corpus_3 "Cow ham strip steak pastrami venison." corpus_4 "Landjaeger fatback pork loin pig sausage." </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-07T09:38:03.697", "Id": "404303", "Score": "0", "body": "I don't see any newlines in the sample data. Since this has a tendency to complicate things, can you include sample data with newlines and the expected outcome, if they are reall...
[ { "body": "<p>Since you don't actually use the first column or row you should preprocess the files to remove them: <code>sed -i -e '1d;s/[0-9]\\+,//' *</code>. You can then use <code>split --lines=1 --suffix-length=7</code> to put each line in its own file. This <em>should</em> be faster than your Python script...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T19:31:22.907", "Id": "207097", "Score": "2", "Tags": [ "python", "csv" ], "Title": "Split CSV file into a text file per row, with whitespace normalization" }
207097
<p>This is how I configure the utility SSMTP that allows me to send mail via <code>smtp</code> protocol through a Google-Gmail proxy instead I'll have to manually configure an "heavier" Postfix bi-directional email server on my environment. I configure it in my own server environment that only I uses.</p> <pre><code>#!/bin/bash myHostName="$HOSTNAME" read -sp "Please paste your Gmail proxy email address (due to pasting, no verfication needed): " gmail_proxy_email_address &amp;&amp; echo read -sp "Please paste your Gmail proxy email password (due to pasting, no verfication needed):" gmail_proxy_email_password &amp;&amp; echo cat &lt;&lt;-EOF &gt; /etc/ssmtp/ssmtp.conf root=${gmail_proxy_email_address} AuthUser=${gmail_proxy_email_address} AuthPass=${gmail_proxy_email_password} hostname=${myHostName} mailhub=smtp.gmail.com:587 rewriteDomain=gmail.com FromLineOverride=YES UseTLS=YES UseSTARTTLS=YES EOF </code></pre> <p>Would you do this even otherwise? Something to shorten? Some alternative utility maybe?</p>
[]
[ { "body": "<p>First, I recommend <code>set -eu</code> early in the script to abort on errors and to make any use of unset variables be an error.</p>\n\n<p>Second, If <code>HOSTNAME</code> is unset, we probably want to fallback to running the <code>hostname</code> command. There seems little point in assigning ...
{ "AcceptedAnswerId": "207132", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T19:40:30.153", "Id": "207098", "Score": "1", "Tags": [ "bash", "linux", "email", "configuration" ], "Title": "SSMTP configuration in Ubuntu 18.04 with Bash in my own system (one user)" }
207098
<p>This code is for a ROS (<a href="http://www.ros.org/" rel="nofollow noreferrer">http://www.ros.org/</a>) node that controls a pair of servo motors (referred to in the code as grippers) that can be controlled individually or together. When they are controlled together they move in opposite directions to create a gripping motion.</p> <p>Running this code requires both ROS and the Dynamixel SDK which is a tall order so I'm mostly looking for general advice on best practice, efficiency, or any potential issues that can be spotted.</p> <p>Most of the code for directly interacting with the port was taken from the SDK examples. This is pretty long, I don't know if that's an issue.</p> <p>The node file, manipulator.cpp:</p> <pre><code>#include "../include/manipulator/manipulator.h" Grippers grippers; //actuator callbacks void grDirLeftCallback(const std_msgs::Float32::ConstPtr &amp;msg) { grippers.setDesired(LEFT_GRIPPER, msg-&gt;data); } void grDirRightCallback(const std_msgs::Float32::ConstPtr &amp;msg) { grippers.setDesired(RIGHT_GRIPPER, msg-&gt;data); } //topic "au_gDesiredJoint" moves both grippers to symmetrical points around the center void grDirJointCallback(const std_msgs::Float32::ConstPtr &amp;msg) { //assumes both grippers move ccw with increasing value grippers.setDesired(LEFT_GRIPPER, (grippers.getMin(LEFT_GRIPPER) + msg-&gt;data + grippers.getOffset(LEFT_GRIPPER))); grippers.setDesired(RIGHT_GRIPPER, (grippers.getMax(RIGHT_GRIPPER) - msg-&gt;data + grippers.getOffset(RIGHT_GRIPPER))); } void dirArmCallback(const std_msgs::Float32::ConstPtr &amp;msg) { grippers.setDesired(ARM, msg-&gt;data); } int main(int argc, char **argv) { ros::init(argc, argv, "manipulator_node"); ros::NodeHandle n; grippers.setup(); grippers.setSpeed(LEFT_GRIPPER,DESIRED_SPEED); grippers.setSpeed(RIGHT_GRIPPER,DESIRED_SPEED); //publishers to send out acutator positions std_msgs::Float32 curLeftPub; ros::Publisher topicCurrentLeft = n.advertise&lt;std_msgs::Float32&gt;("au_gCurrentLeft", 100); std_msgs::Float32 curRightPub; ros::Publisher topicCurrentRight = n.advertise&lt;std_msgs::Float32&gt;("au_gCurrentRight", 100); std_msgs::Float32 curArmPub; ros::Publisher topicCurrentArm = n.advertise&lt;std_msgs::Float32&gt;("au_currentArm", 100); //subscribers for desired positions //only want to keep the most recent desired position ros::Subscriber topicGrDirLeft = n.subscribe("au_gDesiredLeft", 1, grDirLeftCallback); ros::Subscriber topicGrDirRight = n.subscribe("au_gDesiredRight", 1, grDirRightCallback); ros::Subscriber topicGrDirJoin = n.subscribe("au_gDesiredJoint", 1, grDirJointCallback); ros::Subscriber topicDirArm = n.subscribe("au_desiredArm", 1, dirArmCallback); ros::Rate loop_rate(10); while (ros::ok()) { grippers.run(); grippers.read(); curLeftPub.data = grippers.getCurrent(LEFT_GRIPPER); curRightPub.data = grippers.getCurrent(RIGHT_GRIPPER); topicCurrentLeft.publish(curLeftPub); topicCurrentRight.publish(curRightPub); ros::spinOnce(); loop_rate.sleep(); } grippers.shutdown(); return 0; } </code></pre> <p>manipulator.h:</p> <pre><code>#include "ros/ros.h" #include "std_msgs/String.h" #include "std_msgs/Float32.h" #include "../include/dynamixel_sdk/dynamixel_sdk.h" #include "grippers.h" </code></pre> <p>grippers.h</p> <pre><code>#ifndef GRIPPERS_H #define GRIPPERS_H #include "../include/dynamixel_sdk/dynamixel_sdk.h" //this node already contains some code for expansion when the manipulator is replaced with a dynamixel motor //only the grippers are implmented currently #define NUM_DEVICES 4 //actually only 3 but dynamixel ids are 1 indexed and I want the numbers to line up. min/max/dir[0] is unused #define LEFT_GRIPPER 1 #define RIGHT_GRIPPER 2 #define ARM 3 #define NOT_IN_USE -1 // Control table address for MX-64-AT #define ADDR_MX_TORQUE_ENABLE 24 #define ADDR_MX_GOAL_POSITION 30 #define ADDR_MX_MOVING_SPEED 32 #define ADDR_MX_PRESENT_POSITION 36 // Data Byte Length #define LEN_MX_GOAL_POSITION 2 #define LEN_MX_PRESENT_POSITION 2 // Protocol version #define PROTOCOL_VERSION 1.0 // See which protocol version is used in the Dynamixel // Default setting #define BAUDRATE 57600 #define DEVICENAME "/dev/ttyUSB0" // Check which port is being used on your controller #define TORQUE_ENABLE 1 // Value for enabling the torque #define TORQUE_DISABLE 0 // Value for disabling the torque #define DXL_MOVING_STATUS_THRESHOLD 10 // Dynamixel moving status threshold #define DEGREES_PER_STEP 0.088 #define DESIRED_SPEED 100 class Grippers { float min[NUM_DEVICES] = {NOT_IN_USE,165,40,0}; float max[NUM_DEVICES] = {NOT_IN_USE,185,60,360}; float current[NUM_DEVICES] = {0}; //current position in degrees uint16_t dir[NUM_DEVICES] = {0}; //goal position in steps bool newDirPos = false; bool move[NUM_DEVICES] = {false}; dynamixel::PortHandler *portHandler; dynamixel::PacketHandler *packetHandler; dynamixel::GroupSyncWrite groupSyncWrite; float offsetLeft = 0; float offsetRight = 0; uint8_t dxl_error = 0; uint8_t param_goal_position[2] = {0}; uint16_t dxl1_present_position = 0, dxl2_present_position = 0; int dxl_comm_result = COMM_TX_FAIL; // Communication result bool dxl_addparam_result = false; // addParam result public: Grippers(); ~Grippers(); void setDesired(int, float); bool setup(); void shutdown(); void run(); void read(); float getCurrent(int); float getDesired(int); void setSpeed(int,int); float getMin(int); float getMax(int); float getOffset(int); }; #endif // GRIPPERS_H </code></pre> <p>grippers.cpp</p> <pre><code>#include "../include/manipulator/grippers.h" Grippers::Grippers() : portHandler(dynamixel::PortHandler::getPortHandler(DEVICENAME)), packetHandler(dynamixel::PacketHandler::getPacketHandler(PROTOCOL_VERSION)), groupSyncWrite(portHandler, packetHandler, ADDR_MX_GOAL_POSITION, LEN_MX_GOAL_POSITION) { } Grippers::~Grippers() { delete portHandler; delete packetHandler; } void Grippers::setDesired(int device, float value) { float desiredDegrees; if (value &gt; max[device]) { desiredDegrees = max[device]; } else if (value &lt; min[device]) { desiredDegrees = min[device]; } else { desiredDegrees = value; } dir[device] = desiredDegrees / DEGREES_PER_STEP; //converts angles to steps move[device] = true; newDirPos = true; //flag so that communication only occurs once per new command } void Grippers::run() { if (move[LEFT_GRIPPER]) { // Allocate goal position value into byte array param_goal_position[0] = DXL_LOBYTE(dir[LEFT_GRIPPER]); param_goal_position[1] = DXL_HIBYTE(dir[LEFT_GRIPPER]); // Add Dynamixel#1 goal position value to the Syncwrite storage dxl_addparam_result = groupSyncWrite.addParam(LEFT_GRIPPER, param_goal_position); if (dxl_addparam_result != true) { fprintf(stderr, "[ID:%03d] groupSyncWrite addparam failed", LEFT_GRIPPER); } move[LEFT_GRIPPER] = false; } if (move[RIGHT_GRIPPER]) { param_goal_position[0] = DXL_LOBYTE(dir[RIGHT_GRIPPER]); param_goal_position[1] = DXL_HIBYTE(dir[RIGHT_GRIPPER]); // Add Dynamixel#2 goal position value to the Syncwrite parameter storage dxl_addparam_result = groupSyncWrite.addParam(RIGHT_GRIPPER, param_goal_position); if (dxl_addparam_result != true) { fprintf(stderr, "[ID:%03d] groupSyncWrite addparam failed", RIGHT_GRIPPER); } move[RIGHT_GRIPPER] = false; } //only write the move command once per received goal if (newDirPos) { // Syncwrite goal position dxl_comm_result = groupSyncWrite.txPacket(); if (dxl_comm_result != COMM_SUCCESS) printf("%s\n", packetHandler-&gt;getTxRxResult(dxl_comm_result)); // Clear syncwrite parameter storage groupSyncWrite.clearParam(); newDirPos = false; } } void Grippers::setSpeed(int device, int speed) { dxl_comm_result = packetHandler-&gt;write2ByteTxRx(portHandler, device, ADDR_MX_MOVING_SPEED, speed, &amp;dxl_error); if (dxl_comm_result != COMM_SUCCESS) { printf("%s\n", packetHandler-&gt;getTxRxResult(dxl_comm_result)); } else if (dxl_error != 0) { printf("%s\n", packetHandler-&gt;getRxPacketError(dxl_error)); } else { printf("speed set to %d\n", speed); } } void Grippers::read() { // Read left gripper present position dxl_comm_result = packetHandler-&gt;read2ByteTxRx(portHandler, LEFT_GRIPPER, ADDR_MX_PRESENT_POSITION, &amp;dxl1_present_position, &amp;dxl_error); if (dxl_comm_result != COMM_SUCCESS) { printf("%s\n", packetHandler-&gt;getTxRxResult(dxl_comm_result)); } else if (dxl_error != 0) { printf("%s\n", packetHandler-&gt;getRxPacketError(dxl_error)); } // Read right gripper present position dxl_comm_result = packetHandler-&gt;read2ByteTxRx(portHandler, RIGHT_GRIPPER, ADDR_MX_PRESENT_POSITION, &amp;dxl2_present_position, &amp;dxl_error); if (dxl_comm_result != COMM_SUCCESS) { printf("%s\n", packetHandler-&gt;getTxRxResult(dxl_comm_result)); } else if (dxl_error != 0) { printf("%s\n", packetHandler-&gt;getRxPacketError(dxl_error)); } //printf("[ID:%03d] GoalPos:%03d PresPos:%03d\t[ID:%03d] GoalPos:%03d PresPos:%03d\n", LEFT_GRIPPER, dir[LEFT_GRIPPER], dxl1_present_position, RIGHT_GRIPPER, dir[RIGHT_GRIPPER], dxl1_present_position); current[LEFT_GRIPPER] = dxl1_present_position * DEGREES_PER_STEP; current[RIGHT_GRIPPER] = dxl2_present_position * DEGREES_PER_STEP; } void Grippers::shutdown() { printf("shutting down port...\n"); // on node shut down turn off motor torque and close the connection // Disable left gripper Torque dxl_comm_result = packetHandler-&gt;write1ByteTxRx(portHandler, LEFT_GRIPPER, ADDR_MX_TORQUE_ENABLE, TORQUE_DISABLE, &amp;dxl_error); if (dxl_comm_result != COMM_SUCCESS) { printf("%s\n", packetHandler-&gt;getTxRxResult(dxl_comm_result)); } else if (dxl_error != 0) { printf("%s\n", packetHandler-&gt;getRxPacketError(dxl_error)); } else { printf("turned off dxl1 torque\n"); } // Disable right gripper Torque dxl_comm_result = packetHandler-&gt;write1ByteTxRx(portHandler, RIGHT_GRIPPER, ADDR_MX_TORQUE_ENABLE, TORQUE_DISABLE, &amp;dxl_error); if (dxl_comm_result != COMM_SUCCESS) { printf("%s\n", packetHandler-&gt;getTxRxResult(dxl_comm_result)); } else if (dxl_error != 0) { printf("%s\n", packetHandler-&gt;getRxPacketError(dxl_error)); } else { printf("turned off dxl2 torque\n"); } // Close port portHandler-&gt;closePort(); printf("port closed\n"); } bool Grippers::setup() { if (portHandler-&gt;openPort()) { printf("Succeeded to open the port!\n"); } else { printf("Failed to open the port!\n"); return 0; } // Set port baudrate if (portHandler-&gt;setBaudRate(BAUDRATE)) { printf("Succeeded to change the baudrate!\n"); } else { printf("Failed to change the baudrate!\n"); return 0; } // Enable Dynamixel#1 Torque dxl_comm_result = packetHandler-&gt;write1ByteTxRx(portHandler, LEFT_GRIPPER, ADDR_MX_TORQUE_ENABLE, TORQUE_ENABLE, &amp;dxl_error); if (dxl_comm_result != COMM_SUCCESS) { printf("%s\n", packetHandler-&gt;getTxRxResult(dxl_comm_result)); } else if (dxl_error != 0) { printf("%s\n", packetHandler-&gt;getRxPacketError(dxl_error)); } else { printf("Dynamixel#%d has been successfully connected \n", LEFT_GRIPPER); } // Enable Dynamixel#2 Torque dxl_comm_result = packetHandler-&gt;write1ByteTxRx(portHandler, RIGHT_GRIPPER, ADDR_MX_TORQUE_ENABLE, TORQUE_ENABLE, &amp;dxl_error); if (dxl_comm_result != COMM_SUCCESS) { printf("%s\n", packetHandler-&gt;getTxRxResult(dxl_comm_result)); } else if (dxl_error != 0) { printf("%s\n", packetHandler-&gt;getRxPacketError(dxl_error)); } else { printf("Dynamixel#%d has been successfully connected \n", RIGHT_GRIPPER); } return true; } float Grippers::getCurrent(int device) { return current[device]; } float Grippers::getDesired(int device) { return dir[device]; } float Grippers::getMin(int device) { return min[device]; } float Grippers::getMax(int device) { return max[device]; } float Grippers::getOffset(int device) { return (device == 1) ? offsetLeft : offsetRight; } </code></pre> <p>Any advice would be appreciated, if anything doesn't make sense I'll try to explain.</p>
[]
[ { "body": "<p>Welcome to Code Review. First of all, I would like to say: <em>embrace C++ fully, not partially</em>.</p>\n\n<ul>\n<li>use <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"nofollow noreferrer\">std::unique_ptr</a> where appropriate - <code>portHandler</code> and <code>packetHa...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T23:18:18.687", "Id": "207113", "Score": "4", "Tags": [ "c++", "c++11", "serial-port", "device-driver" ], "Title": "ROS node to control Dynamixel servo motors" }
207113
<p>I have an AT89S52 and an AT89C4051 microcontroller (both in the 8052 family) in which the bit lines of the data bus, one control pin and one status pin are connected together. In code, the data bus is labelled "D", the status pin is labelled "ACK" and the control pin is labelled "ACT".</p> <p>The AT89S52 does many tasks, it cannot afford to hold up other tasks over data transfer to the AT89C4051.</p> <p>The AT89C4051 is ok with putting everything else on hold when it communicates with the AT89S52.</p> <p>My code for processing one byte from the AT89C4051 to AT89S52 is as follows:</p> <pre><code>uCdat: mov D,A ;Prepare to send one byte clr ACT ;Send one byte now jb ACK,$ ;Wait until remote received it mov D,#0FFh ;Tristate bus setb ACT ;Tell remote were ready jnb ACK,$ ;Wait until remote has data mov A,D ;Read result ret </code></pre> <p>It simply takes the value of the local accumulator, sends it down to AT89S52 and waits until AT89S52 has a response then its stored back in the local accumulator. This is perfect for the AT89C4051 but not for the AT89S52 since its a busy microcontroller.</p> <p>I made the following code as an attempt to receive a set of data from the AT89C4051 to memory and send code back. I feel I have to do one byte at a time back and forth and the direction in which data is sent is the level of the ACT and ACK lines.</p> <p>The local memory format is as follows.</p> <p>data at start address of REQMEM represents number of data bytes to follow and can be any value from 0 to 15.</p> <p>So if REQMEM = 2, then REQMEM+1 = 1st byte of data and REQMEM+2 = 2nd (and last) byte of data.</p> <p>I'd like to know if this code can be simplified, but still can be run asynchronously. This function will be called very frequently from the busy AT89S52.</p> <pre><code>miniuCdat: ;UCIO=memory bit for data direction: 0=incoming, 1=outgoing jb UCIO,noucinc ;mode here is accept data... jb ACT,noUdat ;...only if remote lowered ACT line mov D,#0FFh ;tristate data line setb UCIO ;change mode to "send result" mov A,D ;get a byte from remote clr ACK ;tell remote we got byte ;REQRES=memory bit to know what were doing. ;REQRES: 0=requesting data. 1=sending result jb REQRES,noUdat ;here we store data into local request memory (REQMEM) mov @R0,A cjne R0,#REQMEM,noUCs ;We are on byte 1 which is length of data anl A,#0Fh ;make length 15 bytes max mov R2,A inc R2 ;make counter = length + 1 noUCs: inc R0 ;go to next byte in REQMEM djnz R2,noUCe ;here the length went back to 0, so reset pointer mov R0,#REQMEM noUCe: noUdat: ret noucinc: ;Here we are sending a 1-byte response back... jnb ACT,noUdat2 ;...only if remote raised the ACT line mov A,@R1 ;Load byte from memory jb REQRES,noUdat2b ;If we are requesting data clr A ;Make zero as the result noUdat2b: mov D,A ;Send result out to data line setb ACK ;Tell remote we sent data out clr UCIO ;switch mode to "accept data" jnb REQRES,noUdat2 cjne R1,#REQMEM,noUCs2 ;Again, 1st byte is length anl A,#0Fh mov R3,A inc R3 noUCs2: inc R1 djnz R3,noUCe2 mov R1,#REQMEM ;Go to beginning of ram if all bytes are processed noUCe2: noUdat2: ret </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T02:35:17.813", "Id": "399647", "Score": "0", "body": "The question can use some more context, like app-level protocol (i.e. how and when the function is called), required data rate, and (in)ability to use interrupts." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-06T23:38:13.120", "Id": "207115", "Score": "1", "Tags": [ "strings", "assembly", "stream", "memory-optimization" ], "Title": "Swapping variable length strings asynchronously with connected microcontroller (Byte-banging)" }
207115
<p><strong>Updated</strong>, below is <a href="https://codereview.stackexchange.com/a/247796/35474">a more current and simple version</a> of this. Also, if you track the progress of TC39's &quot;ECMAScript Cancellation&quot; proposal, <a href="https://github.com/rbuckton/prex/issues/3" rel="nofollow noreferrer">this thread</a> might be worth checking out.</p> <hr> <p>I'm playing with <a href="https://github.com/rbuckton/prex#readme" rel="nofollow noreferrer">Promise Extensions for JavaScript (prex)</a> library and I like it a lot. Amongst other things, this library appears to be a prototype behind the current <a href="https://github.com/tc39/proposal-cancellation" rel="nofollow noreferrer">ECMA TC39 proposal for cancellation</a> and it uses the familiar cancellation token approach, popularized by .NET Task API.</p> <p>I want to extend the standard <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" rel="nofollow noreferrer">Promise class</a> with cancellation support, similar to how it is <a href="http://bluebirdjs.com/docs/api/cancellation.html" rel="nofollow noreferrer">implemented in Bluebird</a> (i.e., with an optional <code>oncancel</code> callback) but using <a href="https://github.com/rbuckton/prex/blob/master/docs/cancellation.md#class-cancellationtoken" rel="nofollow noreferrer">prex.CancellationToken</a>.</p> <p>Here is a draft that can be run with NodeJS:</p> <pre><code>const prex = require('prex'); class CancellablePromise extends Promise { constructor(executor, token) { if (!token) { // if no token supplied, just delegate to the parent class super(executor); return; } const observeCancellation = async () =&gt; { // prex.Deferred is similar to TaskCompletionSource in .NET const deferred = new prex.Deferred(); executor( deferred.resolve, deferred.reject, cancelListener =&gt; deferred.cancelListener = cancelListener); const registration = token.register(() =&gt; { try { // capture the CancelError token.throwIfCancellationRequested(); } catch (cancelError) { try { // the token cancellation callback is synchronous, // and so is the executor-provided cancelListener callback deferred.cancelListener &amp;&amp; deferred.cancelListener(cancelError); // reject here if cancelListener has not resolved/rejected it deferred.reject(cancelError); } catch (error) { // in case cancelListener throws deferred.reject(error); } } }); try { return await deferred.promise; } finally { registration.unregister(); } }; super((resolve, reject) =&gt; observeCancellation().then(resolve, reject)); } } // delayWithCancellation function delayWithCancellation(timeoutMs, token) { console.log(`delayWithCancellation: ${timeoutMs}`); return new CancellablePromise((resolve, reject, setCancelListener) =&gt; { token.throwIfCancellationRequested(); const id = setTimeout(resolve, timeoutMs); setCancelListener(e =&gt; clearTimeout(id)); }, token); } // main async function main() { const tokenSource = new prex.CancellationTokenSource(); setTimeout(() =&gt; tokenSource.cancel(), 2000); // cancel after 1500ms const token = tokenSource.token; await delayWithCancellation(1000, token); console.log(&quot;successfully delayed.&quot;); // we should reach here await delayWithCancellation(1500, token); console.log(&quot;successfully delayed.&quot;); // we should not reach here } main().catch(error =&gt; console.log(error)); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T03:26:33.623", "Id": "485214", "Score": "1", "body": "Assuming you're still using the npm package `prex` for `CancellationTokenSource`, you have a bug. The constructor takes an [iterable of tokens](https://github.com/rbuckton/prex/b...
[ { "body": "<p>You can override the executor and can pass an onCancel function to it like following:</p>\n<pre class=\"lang-js prettyprint-override\"><code>class ResponsePromise extends Promise {\n constructor(executor) {\n const onCancel = (cb) =&gt; {\n //using nextTick because we cant use &quot;this...
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T00:52:49.323", "Id": "207116", "Score": "5", "Tags": [ "javascript", "node.js", "promise" ], "Title": "Extending native JavaScript Promise with cancellation support" }
207116
<p>I'm new to programming and I sort of understand the concept of methods but, I am little overwhelmed by this program and want to shorten it using methods to make it easier to read and understand. </p> <hr> <pre><code>import java.util.Scanner; public class NewCalculator { public static void main(String[] args) { String usrInput = ""; String Num1Input = ""; String Num2Input = ""; int Num1Int = 0; int Num2Int = 0; int SumOfTwo = 0; Scanner scnr = new Scanner(System.in); Scanner Num1 = new Scanner(System.in); Scanner Num2 = new Scanner(System.in); System.out.println("Please Enter (M)ultiplication, (D)ivision, (A)ddition, or (S)ubtraction"); usrInput = scnr.next(); System.out.println(usrInput); if (usrInput.equals("M")|| usrInput.equals("m")|| usrInput.equals("D")|| usrInput.equals("d")|| usrInput.equals("A")|| usrInput.equals("a")|| usrInput.equals("S")|| usrInput.equals("s") ) { //If Bracket switch (usrInput) {//Switch Bracket case "M": System.out.println("Please enter Number 1"); Num1Input = Num1.next(); System.out.println("Please enter Number 2"); Num2Input = Num2.next(); Num1Int = Integer.parseInt(Num1Input); Num2Int = Integer.parseInt(Num2Input); SumOfTwo = Num1Int * Num2Int; System.out.println("The Answser to " + Num1Input + " * " + Num2Input + " Equals " + SumOfTwo); break; case "m": System.out.println("Please enter Number 1"); Num1Input = Num1.next(); System.out.println("Please enter Number 2"); Num2Input = Num2.next(); Num1Int = Integer.parseInt(Num1Input); Num2Int = Integer.parseInt(Num2Input); SumOfTwo = Num1Int * Num2Int; System.out.println("The Answser to " + Num1Input + " * " + Num2Input + " Equals " + SumOfTwo); break; case "D": System.out.println("Please enter Number 1"); Num1Input = Num1.next(); System.out.println("Please enter Number 2"); Num2Input = Num2.next(); Num1Int = Integer.parseInt(Num1Input); Num2Int = Integer.parseInt(Num2Input); SumOfTwo = Num1Int / Num2Int; System.out.println("The Answser to " + Num1Input + " / " + Num2Input + " Equals " + SumOfTwo); break; case "d": System.out.println("Please enter Number 1"); Num1Input = Num1.next(); System.out.println("Please enter Number 2"); Num2Input = Num2.next(); Num1Int = Integer.parseInt(Num1Input); Num2Int = Integer.parseInt(Num2Input); SumOfTwo = Num1Int / Num2Int; System.out.println("The Answser to " + Num1Input + " / " + Num2Input + " Equals " + SumOfTwo); break; case "A": System.out.println("Please enter Number 1"); Num1Input = Num1.next(); System.out.println("Please enter Number 2"); Num2Input = Num2.next(); Num1Int = Integer.parseInt(Num1Input); Num2Int = Integer.parseInt(Num2Input); SumOfTwo = Num1Int + Num2Int; System.out.println("The Answser to " + Num1Input + " + " + Num2Input + " Equals " + SumOfTwo); break; case "a": System.out.println("Please enter Number 1"); Num1Input = Num1.next(); System.out.println("Please enter Number 2"); Num2Input = Num2.next(); Num1Int = Integer.parseInt(Num1Input); Num2Int = Integer.parseInt(Num2Input); SumOfTwo = Num1Int + Num2Int; System.out.println("The Answser to " + Num1Input + " + " + Num2Input + " Equals " + SumOfTwo); break; case "S": System.out.println("Please enter Number 1"); Num1Input = Num1.next(); System.out.println("Please enter Number 2"); Num2Input = Num2.next(); Num1Int = Integer.parseInt(Num1Input); Num2Int = Integer.parseInt(Num2Input); SumOfTwo = Num1Int - Num2Int; System.out.println("The Answser to " + Num1Input + " - " + Num2Input + " Equals " + SumOfTwo); break; case "s": System.out.println("Please enter Number 1"); Num1Input = Num1.next(); System.out.println("Please enter Number 2"); Num2Input = Num2.next(); Num1Int = Integer.parseInt(Num1Input); Num2Int = Integer.parseInt(Num2Input); SumOfTwo = Num1Int - Num2Int; System.out.println("The Answser to " + Num1Input + " - " + Num2Input + " Equals " + SumOfTwo); break; default: System.out.println("We are in the case"); break; }}else{ System.out.println("You may only enter 'M', 'D', 'A', or 'S'"); } }//Main Bracket }//Class Bracket </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T02:07:52.687", "Id": "399644", "Score": "1", "body": "Your title should give the purpose of the code and that should be explained in more detail in your description" } ]
[ { "body": "<p>Actually breaking your code into methods is the least of your problems.</p>\n\n<p>You can re-use the same <code>Scanner</code> for each input.</p>\n\n<p>The <code>Scanner</code> class has a <code>nextInt()</code>. Using this does away with the strings to store the input.</p>\n\n<p>The <code>defau...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T01:10:42.367", "Id": "207117", "Score": "1", "Tags": [ "java", "beginner", "calculator" ], "Title": "Beginner's calculator, supporting M, D, A, S operations on two numbers" }
207117
<p>I'm new to writing PowerShell scripts, and this would be my first relatively large undertaking in the language. Any feedback regarding style and readability would be greatly appreciated. Particularly, I was unsure of the best way of iterating through the various strings, and was wondering if there was a more elegant way of doing so.</p> <p>The code is also available through <a href="https://gist.github.com/ConorOBrien-Foxx/ac1a55a6f1982d533beb38d6e9c593dd" rel="nofollow noreferrer">this gist</a>, where a sample CSV is provided to test the program.</p> <pre><code>function ShowHelp() { echo "Insufficient arguments passed." echo "" echo "Usage: " echo " .\morse.ps1 ""words"" [path\to\table.csv]" echo "" echo "``morse`` takes a series of words as input through the first command line" echo "parameter and causes the Caps Lock key to blink accordingly." echo "" echo " words the words to display" echo " [path\to\table.csv] uses the referenced file as the morse table." echo " default: $DefaultCsvPath" echo "" echo "Examples:" echo " .\morse.ps1 ""SOS send help""" echo " .\morse.ps1 ""wot is this???"" .\punct.csv" } # Definitions: # - A `symbol` is one of $LongBlinkSymbol or $ShortBlinkSymbol # - A `sequence` is a series of concatenated symbols # - A `letter` is any character # - A `letter` is valid if and only if it occurs in MorseTable # - A `word` is a series of concatenated letters # - A `sentence` is a series of `words` joined by whitespace characters $TimeUnit = 200 # in milliseconds $ShortBlinkDuration = 1 * $TimeUnit $LongBlinkDuration = 3 * $TimeUnit $BetweenSymbolsDuration = 1 * $TimeUnit $BetweenLettersDuration = 3 * $TimeUnit $BetweenWordsDuration = 7 * $TimeUnit $LongBlinkSymbol = '1' $ShortBlinkSymbol = '0' $DefaultCsvPath = ".\morse.csv" # strings which match this regex are valid symbol strings $ValidSymbolRegex = "^($( [Regex]::Escape($LongBlinkSymbol) )|$( [Regex]::Escape($ShortBlinkSymbol) ))*$" # error types $EmptyTableError = 1 $MalformedHeaderError = 2 $InvalidSequenceError = 3 $InvalidCharacterError = 4 $NoArgumentsPassedError = 5 # WScript interface for sending keys $wshell = New-Object -ComObject wscript.shell function SendKeys([string] $keys) { $wshell.SendKeys($keys) } function CapsLock() { SendKeys("{CAPSLOCK}") } function IsValidSequence([string] $code) { $code -match $ValidSymbolRegex } # NOTE: MorseTable is indexed by characters, **not** singleton strings $MorseTable = @{} function LoadMorseTable([string] $pathToCsv) { $csv = Import-Csv "$pathToCsv" # ensure non-empty csv if($csv.length -eq 0) { Write-Error "Table read was empty" exit $EmptyTableError } # ensure proper column naming $head = $csv[0] # sample csv; we know the first element must exist if($head.Symbol -eq $null -or $head.Sequence -eq $null) { Write-Error "Malformed table header" exit $MalformedHeaderError } # update $MorseTable $csv | foreach { # ensure proper formatting of Sequence if(-not (IsValidSequence($_.Sequence))) { Write-Error "Entry '$($_.Symbol)' has an invalid sequence '$($_.Sequence)'" exit $InvalidSequenceError } $MorseTable[[char] $_.Symbol] = $_.Sequence } } # given sequence of $LongBlinkSymbol and $ShortBlinkSymbol, blinks the light # for the appropriate duration function BlinkSequence([string] $code) { for($i = 0; $i -lt $code.length; $i++) { $char = $code[$i] CapsLock if($char -eq $LongBlinkSymbol) { Sleep -m $LongBlinkDuration } else { Sleep -m $ShortBlinkDuration } CapsLock # do not wait after the last symbol if($i + 1 -ne $code.length) { Sleep -m $BetweenSymbolsDuration } } } function GetSequence([char] $char) { return $MorseTable[$char] } function BlinkWord([string] $word) { for($i = 0; $i -lt $word.length; $i++) { $char = $word[$i] $code = GetSequence($char) BlinkSequence($code) # do not wait after the last letter if($i + 1 -ne $word.length) { Sleep -m $BetweenLettersDuration } } } function BlinkSentence([string] $sentence) { $words = $sentence.ToUpper().split() # verify that no invalid symbols occur $letterset = $words | % { $_.ToCharArray() } | Sort-Object | Get-Unique $letterset | foreach { if($MorseTable[$_] -eq $null) { Write-Error "Input contains the invalid character '$_'" exit $InvalidCharacterError } } # all symbols must be valid for($i = 0; $i -lt $words.length; $i++) { $word = $words[$i] BlinkWord($word) # do not wait after the last word if($i + 1 -ne $words.length) { Sleep -m $BetweenWordsDuration } } } if($args.length -eq 0) { ShowHelp exit $NoArgumentsPassedError } $input = $args[0] $pathToCsv = $DefaultCsvPath if($args.length -ge 2) { $pathToCsv = $args[1] } LoadMorseTable $pathToCsv BlinkSentence $input </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-02T16:57:24.580", "Id": "403545", "Score": "1", "body": "I'd advise you to to read and follow some _best practices_ article, for instance comprehensive [Building PowerShell Functions: Best Practices](http://ramblingcookiemonster.github...
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T01:46:29.453", "Id": "207119", "Score": "3", "Tags": [ "beginner", "powershell", "morse-code" ], "Title": "Morse Code Blinking through Caps Lock in PowerShell" }
207119
<p>I have a generic pipeline in SnapLogic that logs the start time of the executions of a group of incremental jobs. Suppose, the log table is as follows.</p> <pre><code>CREATE TABLE sl_control.interface_parameters_values ( interface_id varchar NOT NULL, parameter_name varchar NOT NULL, parameter_value varchar NULL ); </code></pre> <p>A few points to remember:</p> <ul> <li>There may or may not be an entry for a particular job (interface)</li> <li>This generic pipeline <strong>only</strong> updates the <code>IncrementalTimestamp</code> parameter of the interface. So, there will be only one entry to insert/update per interface.</li> <li>The individual values (for example, <code>'TEST0001', 'IncrementalTimestamp', 0</code>) are being generated by a script and are being passed in batches of <code>150</code> to the query. So, <code>VALUES</code> part of the query will have at most 150 entries for each execution.</li> <li>Although I'm setting the batch as <code>150</code>, the average number of interfaces I'm expecting is ~30.</li> </ul> <p>Following is my upsert query:</p> <pre><code>WITH /* write the new values */ v ( interface_id, parameter_name, parameter_value ) AS ( VALUES ('TEST0001', 'IncrementalTimestamp', 0), ('TEST0002', 'IncrementalTimestamp', 0), ('TEST0003', 'IncrementalTimestamp', 0), ('TEST0004', 'IncrementalTimestamp', 0), ('TEST0005', 'IncrementalTimestamp', 0) ), /* update existing rows */ upsert AS ( UPDATE sl_control.interface_parameters_values ipv SET interface_id = v.interface_id, parameter_name = v.parameter_name, parameter_value = v.parameter_value FROM v WHERE ( ipv.interface_id = v.interface_id AND ipv.parameter_name = v.parameter_name ) RETURNING ipv.interface_id ) /* insert missing rows */ INSERT INTO sl_control.interface_parameters_values ( interface_id, parameter_name, parameter_value ) SELECT interface_id , parameter_name , parameter_value FROM v WHERE v.interface_id NOT IN ( SELECT interface_id FROM upsert ) </code></pre> <p>I had to take this approach because this particular PostgreSQL instance is version 9.4 and it does not support the <code>ON CONFLICT</code> syntax.</p> <p>This query is working fine but is there any way this can be optimized further? Or is there any unseen pitfall to this approach. If this approach is good then I'll use this in one of our integration pipelines.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-01T13:48:12.347", "Id": "403419", "Score": "1", "body": "Looks good to me." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T03:43:49.090", "Id": "207120", "Score": "2", "Tags": [ "sql", "postgresql" ], "Title": "Upsert query using CTE in PostgreSQL 9.4" }
207120
<p>I have some really wide data in R that I want to transform into the "tidy data" format. Unfortunately, I cannot change the process that generates this data, so it must be done within R.</p> <p>My raw data looks like this (but with more records):</p> <pre><code>+---------+-----------+-------+------+------+----------+-----------+---------+------+------+---------+-----------+------+------+------+ | FTname | FTleader | FT1 | FT2 | FT3 | FT2name | FT2leader | FT21 | FT22 | FT23 | FT3name | FT3leader | FT31 | FT32 | FT33 | +---------+-----------+-------+------+------+----------+-----------+---------+------+------+---------+-----------+------+------+------+ | Billing | Rob | Rob | Ryan | Brad | Shipping | Brad | Brad | Dave | Kim | | | | | | | Sales | Sarah | Sarah | Drew | | | | | | | | | | | | | Phone | Tim | Tim | Zach | Ron | Store | Michael | Michael | Ron | | Email | Sean | Sean | Ron | Ben | | Repair | Evan | Evan | Tim | Jim | | | | | | | | | | | +---------+-----------+-------+------+------+----------+-----------+---------+------+------+---------+-----------+------+------+------+ </code></pre> <ul> <li><code>FTname</code> contains the name of the team</li> <li><code>FTleader</code> contains the leader for that team</li> <li><code>FT1</code>, <code>FT2</code>, <code>FT3</code> are the members of the that team</li> <li>An individual might belong to only 1 team, or they might belong to multiple teams</li> <li>Each team has 1 team leader</li> <li>There are 7 separate teams (Billing, Shipping, Sales, Store, Email, ..., etc.)</li> </ul> <p>Ultimately, I want to reshape this data to look like below. Ideally, a row represents each person, the team they're on, and their role on that team. People will be listed multiple times, as they might be a part of more than 1 team. The first person on the team is always going to be the team leader, so no need to list them twice.</p> <pre><code>+---------+------+----------+ | Name | Role | Team | +---------+------+----------+ | Rob | TL | Billing | | Rob | DR | Billing | | Ryan | DR | Billing | | Brad | DR | Billing | | Brad | TL | Shipping | | Brad | DR | Shipping | | Dave | DR | Shipping | | Kim | DR | Shipping | | Sarah | TL | Sales | | Sarah | DR | Sales | | Drew | DR | Sales | | Tim | TL | Phone | | Tim | DR | Phone | | Zach | DR | Phone | | Ron | DR | Phone | | Michael | TL | Store | | Michael | DR | Store | | Ron | DR | Store | | Sean | TL | Email | | Sean | DR | Email | | Ron | DR | Email | | Ben | DR | Email | | Evan | TL | Repair | | Evan | DR | Repair | | Tim | DR | Repair | | Jim | DR | Repair | +---------+------+----------+ </code></pre> <p>Whatever solution I arrive at needs to be flexible to handle a variety of teams that a single person can be a part of.</p> <p>Here is my approach so far:</p> <pre><code>library(dplyr) library(reshape2) # read data into a datarfame data &lt;- read.csv('tests/testthat/panel.csv', stringsAsFactors = FALSE, na = c('')) # add team number to columns FT1 columns names(data)[names(data)=="FTname"] &lt;- "FT1name" names(data)[names(data)=="FTleader"] &lt;- "FT1leader" names(data)[names(data)=="FT1"] &lt;- "FT11" names(data)[names(data)=="FT2"] &lt;- "FT12" names(data)[names(data)=="FT3"] &lt;- "FT13" names(data)[names(data)=="FT4"] &lt;- "FT14" names(data)[names(data)=="FT5"] &lt;- "FT15" names(data)[names(data)=="FT6"] &lt;- "FT16" names(data)[names(data)=="FT7"] &lt;- "FT17" names(data)[names(data)=="FT8"] &lt;- "FT18" names(data)[names(data)=="FT9"] &lt;- "FT19" # subset data to only columns that start with "FT" plus a number teams &lt;- data[ , grep("FT\\d+" , names(data))] # get the teams represented in the dataset team_names &lt;- substr(names(teams[grep("FT\\d+\\leader", names(teams))]), 0, 3) # create an empty list to hold individual team dataframes team_data = list() # iterate over each team... for (t in team_names){ # grab the columns associated with that team... team_t &lt;- teams %&gt;% select(starts_with(t)) # rename columns by dropping team number asscoiated with the team colnames(team_t) = gsub(t, substr(t, 1, 2), colnames(team_t)) # add team data to the list team_data[[t]] &lt;- team_t } # combine list into one dataframe team_data_combined &lt;- bind_rows(team_data) # get only the unique rows team_data_combined &lt;- unique(team_data_combined) # drop rows where the whole row is blank team_data_combined &lt;- team_data_combined[apply(team_data_combined,1,function(x)any(!is.na(x))),] # drop unnecessary columns team_data_combined$FTrole &lt;- NULL team_data_combined$FTsize &lt;- NULL # reshape the data from wide to narrow df &lt;- melt(team_data_combined, id=c("FTname")) # rename columns in new dataframe names(df)[names(df)=="FTname"] &lt;- "team" names(df)[names(df)=="variable"] &lt;- "role" names(df)[names(df)=="value"] &lt;- "name" # drop rows where name is empty df &lt;- df[!is.na(df$name),] # drop exact duplicates df &lt;- unique(df) # drop rows where role is "FT1" as these are the leaders df &lt;- subset(df, role!='FT1') # impute team leader and direct report status df$role &lt;- as.character(df$role) df$role[df$role == "FTleader"] &lt;- "TL" df$role[df$role != "TL"] &lt;- "DR" df$role &lt;- as.factor(df$role) df$team &lt;- as.factor(df$team) </code></pre> <p>While I believe this approach appears to get me to what I'm looking forward, I'm open to any improvements that might make the improve the process. </p> <p>Here is a sample of the data that I'm working with:</p> <pre><code>df &lt;- structure(list(Email = c("JPerkins@company.com", "JClayton@company.com", "SBowen@company.com", "LThomas@company.com", "PDaniel@company.com", "BRomero@company.com", "OGarrett@company.com", "GGill@company.com", "PRowe@company.com", "SMurray@company.com", "GGibson@company.com", "LWells@company.com", "JDiaz@company.com", "SSpencer@company.com", "AWatkins@company.com", "LRyan@company.com", "JMyers@company.com", "CWilliamson@company.com", "CSimon@company.com", "DWilkerson@company.com", "YMorton@company.com", "KWeber@company.com", "JWoods@company.com", "RWarner@company.com", "ASantiago@company.com", "KReid@company.com", "JChavez@company.com", "IFerguson@company.com", "CAndrews@company.com", "WBrooks@company.com", "NNorris@company.com", "HWatson@company.com", "TSchmidt@company.com", "JGarner@company.com", "OClarke@company.com", "GJacobs@company.com", "MMccormick@company.com", "IJefferson@company.com", "HPatterson@company.com", "SSims@company.com", "SPratt@company.com", "RCastillo@company.com", "ADaniels@company.com", "ERivera@company.com", "DDouglas@company.com", "BErickson@company.com", "CDrake@company.com", "CHiggins@company.com", "LSharp@company.com", "RHarrington@company.com", "RNorman@company.com", "KParsons@company.com", "TTaylor@company.com", "WFord@company.com", "FManning@company.com", "JHampton@company.com", "MMitchell@company.com", "SFloyd@company.com", "AKennedy@company.com", "CSummers@company.com"), First.Name = c("Juan", "Janice", "Stella", "Leigh", "Pearl", "Bethany", "Oliver", "Glen", "Pat", "Shaun", "Gretchen", "Loretta", "Jeffrey", "Sally", "Andrea", "Lynda", "Jerry", "Cristina", "Cecilia", "Danny", "Yvette", "Katrina", "Janis", "Rosemary", "Albert", "Kristi", "Jim", "Ismael", "Clint", "Warren", "Noah", "Hazel", "Ted", "Jean", "Oscar", "Geneva", "Milton", "Iris", "Henry", "Santos", "Sam", "Randy", "Abel", "Enrique", "Daniel", "Bob", "Connie", "Carl", "Lana", "Ramiro", "Rosemarie", "Kristen", "Taylor", "Willard", "Frederick", "Jan", "Mike", "Sonia", "Archie", "Cary"), Last.Name = c("Perkins", "Clayton", "Bowen", "Thomas", "Daniel", "Romero", "Garrett", "Gill", "Rowe", "Murray", "Gibson", "Wells", "Diaz", "Spencer", "Watkins", "Ryan", "Myers", "Williamson", "Simon", "Wilkerson", "Morton", "Weber", "Woods", "Warner", "Santiago", "Reid", "Chavez", "Ferguson", "Andrews", "Brooks", "Norris", "Watson", "Schmidt", "Garner", "Clarke", "Jacobs", "Mccormick", "Jefferson", "Patterson", "Sims", "Pratt", "Castillo", "Daniels", "Rivera", "Douglas", "Erickson", "Drake", "Higgins", "Sharp", "Harrington", "Norman", "Parsons", "Taylor", "Ford", "Manning", "Hampton", "Mitchell", "Floyd", "Kennedy", "Summers"), External.Data.Reference = c(34L, 35L, 44L, 48L, 14L, 29L, 40L, 47L, 52L, 23L, 28L, 38L, 12L, 43L, 8L, 57L, 31L, 19L, 6L, 7L, 9L, 33L, 39L, 55L, 13L, 21L, 27L, 54L, 1L, 17L, 30L, 3L, 37L, 45L, 51L, 2L, 20L, 56L, 25L, 36L, 42L, 59L, 46L, 10L, 41L, 24L, 26L, 5L, 49L, 50L, 53L, 4L, 32L, 58L, 60L, 11L, 15L, 18L, 22L, 16L), Language = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), ELTname = c("Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team"), Role = c("ELT", "ELT", "CEO", "ELT", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM", "MM"), FTname = c("Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Company Top Management Team", "Accounting team", "Accounting team", "Accounting team", "Accounting team", "Accounting team", "Asset Management team", "Asset Management team", "Asset Management team", "Asset Management team", "Asset Management team", "Business Development team", "Business Development team", "Business Development team", "Drilling &amp; Completion team", "Drilling &amp; Completion team", "Drilling &amp; Completion team", "Drilling &amp; Completion team", "Drilling &amp; Completion team", "Drilling &amp; Completion team", "Production Operations &amp; Company Midstream Services team", "Production Operations &amp; Company Midstream Services team", "Production Operations &amp; Company Midstream Services team", "Production Operations &amp; Company Midstream Services team", "EH&amp;S team", "EH&amp;S team", "EH&amp;S team", "EH&amp;S team", "Investor Relations team", "Investor Relations team", "Investor Relations team", "Investor Relations team", "Investor Relations team", "Business Development Company Midstream team", "Business Development Company Midstream team", "Human Resources &amp; Employee Development team", "Human Resources &amp; Employee Development team", "Human Resources &amp; Employee Development team", "Human Resources &amp; Employee Development team", "Human Resources &amp; Employee Development team", "Infrastructure &amp; Technology team", "Infrastructure &amp; Technology team", "Infrastructure &amp; Technology team", "IT Strategy team", "IT Strategy team", "IT Strategy team", "IT Strategy team", "IT Strategy team", NA, "Legal team", "Legal team", "Legal team", "Marketing team", "Marketing team", "Marketing team", "Government Affairs &amp; Regulatory Compliance team", "Government Affairs &amp; Regulatory Compliance team"), FTrole = c("DR", "DR", "TL", "DR", "DR", "TL", "DR", "DR", "DR", "DR", "DR", "DR", "DR", "TL", "TL", "DR", "DR", "TL", "DR", "DR", "DR", "DR", "DR", "TL", "DR", "DR", "DR", "DR", "DR", "DR", "DR", "DR", "DR", "DR", "TL", "DR", "TL", "DR", "DR", "TL", "DR", "DR", "DR", "DR", "DR", "TL", "TL", "DR", "DR", "DR", "DR", NA, "DR", "TL", "DR", "DR", "DR", "TL", "DR", "DR"), FTnum = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 7L, NA, NA, NA, NA, NA, NA, NA, NA, NA, 16L, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), FTsize = c(4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 3L, 3L, 3L, 6L, 6L, 6L, 6L, 6L, 6L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 2L, 2L, 5L, 5L, 5L, 5L, 5L, 3L, 3L, 3L, 5L, 5L, 5L, 5L, 5L, 0L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), FTleader = c("Stella Bowen", "Stella Bowen", "Stella Bowen", "Stella Bowen", "Bethany Romero", "Bethany Romero", "Bethany Romero", "Bethany Romero", "Bethany Romero", "Bret Newton", "Bret Newton", "Bret Newton", "Bret Newton", "Bret Newton", "Robin Clark", "Robin Clark", "Robin Clark", "Cristina Williamson", "Cristina Williamson", "Cristina Williamson", "Cristina Williamson", "Cristina Williamson", "Cristina Williamson", "Rosemary Warner", "Rosemary Warner", "Rosemary Warner", "Rosemary Warner", "Yvette Morton", "Yvette Morton", "Yvette Morton", "Yvette Morton", "Richard Robuck ", "Richard Robuck ", "Richard Robuck ", "Richard Robuck ", "Richard Robuck ", "Milton Mccormick", "Milton Mccormick", "Santos Sims", "Santos Sims", "Santos Sims", "Santos Sims", "Santos Sims", "Bob Erickson", "Bob Erickson", "Bob Erickson", "Connie Drake", "Connie Drake", "Connie Drake", "Connie Drake", "Connie Drake", "Kristen Parsons", "Willard Ford", "Willard Ford", "Willard Ford", "Sonia Floyd", "Sonia Floyd", "Sonia Floyd", "Michael Kucuk", "Michael Kucuk"), FT1 = c("Stella Bowen", "Stella Bowen", "Stella Bowen", "Stella Bowen", "Bethany Romero", "Bethany Romero", "Bethany Romero", "Bethany Romero", "Bethany Romero", "Bret Newton", "Bret Newton", "Bret Newton", "Bret Newton", "Bret Newton", "Robin Clark", "Robin Clark", "Robin Clark", "Cristina Williamson", "Cristina Williamson", "Cristina Williamson", "Cristina Williamson", "Cristina Williamson", "Cristina Williamson", "Rosemary Warner", "Rosemary Warner", "Rosemary Warner", "Rosemary Warner", "Yvette Morton", "Yvette Morton", "Yvette Morton", "Yvette Morton", "Oscar Clarke", "Oscar Clarke", "Oscar Clarke", "Oscar Clarke", "Oscar Clarke", "Milton Mccormick", "Milton Mccormick", "Santos Sims", "Santos Sims", "Santos Sims", "Santos Sims", "Santos Sims", "Bob Erickson", "Bob Erickson", "Bob Erickson", "Connie Drake", "Connie Drake", "Connie Drake", "Connie Drake", "Connie Drake", "Kristen Parsons", "Willard Ford", "Willard Ford", "Willard Ford", "Sonia Floyd", "Sonia Floyd", "Sonia Floyd", "Michael Kucuk", "Michael Kucuk" ), FT2 = c("Leigh Thomas", "Leigh Thomas", "Leigh Thomas", "Leigh Thomas", "Pearl Daniel", "Pearl Daniel", "Pearl Daniel", "Pearl Daniel", "Pearl Daniel", "Loretta Wells", "Loretta Wells", "Loretta Wells", "Loretta Wells", "Loretta Wells", "Jerry Myers", "Jerry Myers", "Jerry Myers", "Janis Woods", "Janis Woods", "Janis Woods", "Janis Woods", "Janis Woods", "Janis Woods", "Jim Chavez", "Jim Chavez", "Jim Chavez", "Jim Chavez", "Clint Andrews", "Clint Andrews", "Clint Andrews", "Clint Andrews", "Doug Madeley ", "Doug Madeley ", "Doug Madeley ", "Doug Madeley ", "Doug Madeley ", "Iris Jefferson", "Iris Jefferson", "Henry Patterson", "Henry Patterson", "Henry Patterson", "Henry Patterson", "Henry Patterson", "Enrique Rivera", "Enrique Rivera", "Enrique Rivera", "Lana Sharp", "Lana Sharp", "Lana Sharp", "Lana Sharp", "Lana Sharp", NA, "Taylor Taylor", "Taylor Taylor", "Taylor Taylor", "Mike Mitchell", "Mike Mitchell", "Mike Mitchell", "Archie Kennedy", "Archie Kennedy" ), FT3 = c("Juan Perkins", "Juan Perkins", "Juan Perkins", "Juan Perkins", "Oliver Garrett", "Oliver Garrett", "Oliver Garrett", "Oliver Garrett", "Oliver Garrett", "Jeffrey Diaz", "Jeffrey Diaz", "Jeffrey Diaz", "Jeffrey Diaz", "Jeffrey Diaz", "Lynda Ryan", "Lynda Ryan", "Lynda Ryan", "Katrina Weber", "Katrina Weber", "Katrina Weber", "Katrina Weber", "Katrina Weber", "Katrina Weber", "Kristi Reid", "Kristi Reid", "Kristi Reid", "Kristi Reid", "Warren Brooks", "Warren Brooks", "Warren Brooks", "Warren Brooks", "Geneva Jacobs", "Geneva Jacobs", "Geneva Jacobs", "Geneva Jacobs", "Geneva Jacobs", NA, NA, "Abel Daniels", "Abel Daniels", "Abel Daniels", "Abel Daniels", "Abel Daniels", "Daniel Douglas", "Daniel Douglas", "Daniel Douglas", "Carl Higgins", "Carl Higgins", "Carl Higgins", "Carl Higgins", "Carl Higgins", NA, "Frederick Manning", "Frederick Manning", "Frederick Manning", "Jan Hampton", "Jan Hampton", "Jan Hampton", "Cary Summers", "Cary Summers"), FT4 = c("Janice Clayton", "Janice Clayton", "Janice Clayton", "Janice Clayton", "Glen Gill", "Glen Gill", "Glen Gill", "Glen Gill", "Glen Gill", "Gretchen Gibson", "Gretchen Gibson", "Gretchen Gibson", "Gretchen Gibson", "Gretchen Gibson", NA, NA, NA, "Cecilia Simon", "Cecilia Simon", "Cecilia Simon", "Cecilia Simon", "Cecilia Simon", "Cecilia Simon", "Albert Santiago", "Albert Santiago", "Albert Santiago", "Albert Santiago", "Daniel Shehan", "Daniel Shehan", "Daniel Shehan", "Daniel Shehan", "Hazel Watson", "Hazel Watson", "Hazel Watson", "Hazel Watson", "Hazel Watson", NA, NA, "Randy Castillo", "Randy Castillo", "Randy Castillo", "Randy Castillo", "Randy Castillo", NA, NA, NA, "Ramiro Harrington", "Ramiro Harrington", "Ramiro Harrington", "Ramiro Harrington", "Ramiro Harrington", NA, NA, NA, NA, NA, NA, NA, NA, NA), FT5 = c(NA, NA, NA, NA, "Pat Rowe", "Pat Rowe", "Pat Rowe", "Pat Rowe", "Pat Rowe", "Shaun Murray", "Shaun Murray", "Shaun Murray", "Shaun Murray", "Shaun Murray", NA, NA, NA, "Danny Wilkerson", "Danny Wilkerson", "Danny Wilkerson", "Danny Wilkerson", "Danny Wilkerson", "Danny Wilkerson", NA, NA, NA, NA, "Noah Norris", "Noah Norris", "Noah Norris", "Noah Norris", "Jean Garner", "Jean Garner", "Jean Garner", "Jean Garner", "Jean Garner", NA, NA, "Sam Pratt", "Sam Pratt", "Sam Pratt", "Sam Pratt", "Sam Pratt", NA, NA, NA, "Rosemarie Norman", "Rosemarie Norman", "Rosemarie Norman", "Rosemarie Norman", "Rosemarie Norman", NA, NA, NA, NA, NA, NA, NA, NA, NA), FT6 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "Yvette Morton", "Yvette Morton", "Yvette Morton", "Yvette Morton", "Yvette Morton", "Yvette Morton", NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), FT7 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), FT8 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), FT2role = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "TL", NA, NA, NA, NA, NA, NA, NA, NA, NA, "TL", NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), FT2name = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "EH&amp;S team", NA, NA, NA, NA, NA, NA, NA, NA, NA, "Government Affairs &amp; Regulatory Compliance team", NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), FT2size = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 5L, NA, NA, NA, NA, NA, NA, NA, NA, NA, 3L, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), FT2leader = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "Yvette Morton", NA, NA, NA, NA, NA, NA, NA, NA, NA, "Noah Norris", NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), FT21 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "Yvette Morton", NA, NA, NA, NA, NA, NA, NA, NA, NA, "Noah Norris", NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), FT22 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "Clint Andrews", NA, NA, NA, NA, NA, NA, NA, NA, NA, "Archie Kennedy", NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), FT23 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "Warren Brooks", NA, NA, NA, NA, NA, NA, NA, NA, NA, "Cary Summers", NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), FT24 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "Daniel Shehan", NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), FT25 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "Noah Norris", NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), FT26 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), FT27 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), FT28 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), X = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA)), class = "data.frame", row.names = c(NA, -60L)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T07:12:57.440", "Id": "399662", "Score": "0", "body": "Can you supply your example data with `dput` so we can copy and run your example?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T02:26:48.020", ...
[ { "body": "<p>Using <code>tidyverse</code> you could do the following :</p>\n\n<pre><code>library(tidyverse)\nres &lt;- df %&gt;%\n select(FTname, FTrole,matches(\"^FT\\\\d+$\")) %&gt;%\n gather(col,Name,matches(\"^FT\\\\d+$\")) %&gt;%\n filter(!is.na(Name)) %&gt;%\n select(-col)\n\n\nhead(res)\n# ...
{ "AcceptedAnswerId": "207393", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T04:06:52.733", "Id": "207121", "Score": "1", "Tags": [ "r" ], "Title": "Transform wide dataset into \"tidy-data\" within R" }
207121
<p>I implemented a function to check a MS Word document is contain a given word or not. The function will return true if filePath is contain word. Otherwise it will return false.</p> <p>This is my solution based on <strong>Aspose framework.</strong> Is there any better solution?</p> <pre><code>public class FindContentOfWordDoc { public bool FindContent(string filePath, string content) { var doc = new Document(filePath); var findReplaceOptions = new FindReplaceOptions { ReplacingCallback = new FindCallBack(), Direction = FindReplaceDirection.Backward }; var regex = new Regex(content, RegexOptions.IgnoreCase); doc.Range.Replace(regex, "", findReplaceOptions); return (findReplaceOptions.ReplacingCallback as FindCallBack)?.IsMatch ?? false; } private class FindCallBack : IReplacingCallback { public bool IsMatch { get; private set; } ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e) { IsMatch = true; return ReplaceAction.Stop; } } } </code></pre> <p>Thanks!</p>
[]
[ { "body": "<p>Some quick remarks:</p>\n<ul>\n<li><p><code>FindContentOfWordDoc</code> is a bad class name, in the first place because it contains a verb. Please follow the <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/names-of-classes-structs-and-interfaces\" rel=\"nofollow norefe...
{ "AcceptedAnswerId": "207141", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T08:47:20.380", "Id": "207127", "Score": "0", "Tags": [ "c#", ".net" ], "Title": "search a given word in word file by Aspose" }
207127
<p>Please review my design and code implementation and suggest if any optimisation is possible in terms of performance (time complexity / space complexity ) or any better way of design or implementation. You are welcome to provide your review comments so that I learn to code and design better. </p> <p>Git hub link : <a href="https://github.com/lalitkumar-kulkarni15/Consumer-Producer-case-study" rel="nofollow noreferrer">https://github.com/lalitkumar-kulkarni15/Consumer-Producer-case-study</a></p> <p>Problem statement :- </p> <h1>Consumer-Producer-case-study</h1> <p># Case Study: ## Provided Together with this document we provide <code>src</code> directory containing source code, which is the basis for the task. ## Expectation Implement the task as described below. You can start whenever you like and send us the result once you are done. Add documentation like you would in a real project. Bring the code to a production standard (not more, not less). Do not spend more than 2 hours on this exercise. ## User Story There is a producer (Producer) of price updates for stocks. This producer will generate constant price updates for a fix number of stocks. The producer should not block, every price update should be consumed as quickly as possible. Furthermore there is a load handler (LoadHandler) which will consume the price updates of the producer. In the current implementation the load handler is just passing on the update to a consumer. This should be changed. The consumer (Consumer) will receive the price updates from the load handler. (The current implementation will just print out all price updates for convenience sake.) The consumer is representing a legacy system that cannot consumer more than a certain number of price updates per second. Otherwise it would fall over. ## Task The task of this exercise is to extend the LoadHandler to limit the updates per second to the consumer to a certain given number (MAX_PRICE_UPDATES). In order to achieve this, it is allowed to drop price updates, since otherwise the application will run out of memory, if the application will keep all of them. It is important that, if a price update will be send to the consumer, it has to be the most recent price. ## Result - Fork the project - Implement your solution</p> <p>Below are the classes :- </p> <p>1) Producer.java</p> <pre><code> package com.exercise.producer; import com.exercise.model.PriceUpdate; import com.exercise.producer.Producer; import com.exercise.regulator.LoadHandler; public class Producer extends Thread { private LoadHandler loadHandler; public Producer(LoadHandler loadHandler) { this.loadHandler = loadHandler; } @Override public void run() { System.out.println("Run inside the producer is called."); try { generateUpdates(); } catch (InterruptedException e) { e.printStackTrace(); } } public void generateUpdates() throws InterruptedException{ for (int i = 1; i &lt; 10000000; i++) { System.out.println("Stock set start"); Thread.sleep(5000); System.out.println("-----------------------"); loadHandler.receive(new PriceUpdate("Apple", 97.85)); loadHandler.receive(new PriceUpdate("Google", 160.71)); loadHandler.receive(new PriceUpdate("Facebook", 91.66)); loadHandler.receive(new PriceUpdate("Google", 160.73)); loadHandler.receive(new PriceUpdate("Facebook", 91.71)); loadHandler.receive(new PriceUpdate("Google", 160.76)); loadHandler.receive(new PriceUpdate("Apple", 97.85)); loadHandler.receive(new PriceUpdate("Google", 160.71)); loadHandler.receive(new PriceUpdate("Facebook", 91.63)); System.out.println("-----------------------"); System.out.println("Stock set over"); } } } </code></pre> <p>2) Consumer.java </p> <pre><code> package com.excercise.consumer; import java.util.List; import com.exercise.model.PriceUpdate; /** * Please do not change the Consumer. * */ public class Consumer { public void send(List&lt;PriceUpdate&gt; priceUpdates) { System.out.println("List of price updates received at consumer class is size : "+priceUpdates.size()); priceUpdates.forEach(System.out::println); } } </code></pre> <p>3) PriceUpdate.java</p> <pre><code> package com.exercise.model; import java.time.LocalDateTime; public class PriceUpdate { private final String companyName; private final double price; private LocalDateTime localDateTime; public PriceUpdate(String companyName, double price) { this.companyName = companyName; this.price = price; this.localDateTime = LocalDateTime.now(); } public String getCompanyName() { return this.companyName; } public double getPrice() { return this.price; } public LocalDateTime getLocalDateTime() { return localDateTime; } public void setLocalDateTime(LocalDateTime localDateTime) { this.localDateTime = localDateTime; } @Override public String toString() { return companyName + " - " + price +" - "+localDateTime; } @Override public boolean equals(Object obj) { if(null==obj) { return false; } else if(null != obj &amp;&amp; obj instanceof PriceUpdate) { final PriceUpdate priceUpdate = (PriceUpdate) obj; if(null!=priceUpdate &amp;&amp; priceUpdate.getCompanyName().equalsIgnoreCase(this.getCompanyName()) &amp;&amp; priceUpdate.getPrice()==(this.getPrice()) &amp;&amp; (priceUpdate.getLocalDateTime().equals(this.getLocalDateTime()))) { System.out.println("Equals returning true"); return true; } } System.out.println("Equals returning false"); return false; } @Override public int hashCode() { int hash = this.companyName.hashCode() * Double.valueOf(this.price).hashCode() * this.localDateTime.hashCode(); return hash; } } </code></pre> <p>4) LoadHandler.java</p> <pre><code> package com.exercise.regulator; import java.util.LinkedList; import java.util.Queue; import com.excercise.consumer.Consumer; import com.exercise.model.PriceUpdate; public class LoadHandler { private static final int MAX_PRICE_UPDATES = 100; private final Consumer consumer; public LoadHandler (Consumer consumer) { this.consumer = consumer; Scheduler scheduler = new Scheduler(consumer); scheduler.startConsumerFeedJobThread(); } private static Queue&lt;PriceUpdate&gt; priceUpdateQueue = new LinkedList&lt;&gt;(); public static Queue&lt;PriceUpdate&gt; getPriceUpdateQueue() { return priceUpdateQueue; } public static void setPriceUpdateQueue(Queue&lt;PriceUpdate&gt; priceUpdateQueue) { LoadHandler.priceUpdateQueue = priceUpdateQueue; } public void receive(PriceUpdate priceUpdate) { if(null!=priceUpdate) { if(priceUpdateQueue.size()&lt;MAX_PRICE_UPDATES) { priceUpdateQueue.add(priceUpdate); System.out.println("Stock price added successfully."); } else { priceUpdateQueue.poll(); System.out.println("Stock price polled successfully."); priceUpdateQueue.add(priceUpdate); System.out.println("Stock price added after poll successfully."); } } } } </code></pre> <p>5) RemoveOlderStcksPredicate.java</p> <pre><code> package com.exercise.regulator; import java.time.LocalDateTime; import java.util.function.Predicate; import com.exercise.model.PriceUpdate; public class RemoveOlderStcksPredicate { public static Predicate&lt;PriceUpdate&gt; isStockEqual(LocalDateTime localDateTime){ System.out.println("Inside is stock equal localdateTime is ::"+localDateTime); return p-&gt;p.getLocalDateTime().isBefore(localDateTime); } } </code></pre> <p>6) StockPredicate.java</p> <pre><code> package com.exercise.regulator; import java.util.HashSet; import java.util.Queue; import java.util.function.Predicate; import com.exercise.model.PriceUpdate; public class StockPredicate { public static Predicate&lt;PriceUpdate&gt; isStockEqual(Queue&lt;PriceUpdate&gt; stocksSentToConsumerList){ return new HashSet&lt;&gt;(stocksSentToConsumerList)::contains; } } </code></pre> <p>7) Scheduler.java</p> <pre><code> package com.exercise.regulator; import java.time.LocalDateTime; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.Queue; import com.excercise.consumer.Consumer; import com.exercise.model.PriceUpdate; public class Scheduler { private Consumer consumer; private static Deque&lt;PriceUpdate&gt; stocksSentToConsumerList = new LinkedList&lt;&gt;(); private static LocalDateTime lastSentDateTime; public static void setLastSentDateTime(LocalDateTime lastSentDateTime) { Scheduler.lastSentDateTime = lastSentDateTime; } public Scheduler(final Consumer consumer) { this.consumer = consumer; } public void startConsumerFeedJobThread() { final Runnable stockReguRunnable = getRunnableForstockRegu(); final Thread stockRegulatorThread = new Thread(stockReguRunnable); stockRegulatorThread.start(); } private Runnable getRunnableForstockRegu() { final Runnable runnable = () -&gt; { try { sendRegulatedStcksToCnsmr(); } catch (InterruptedException exception) { exception.printStackTrace(); } }; return runnable; } private void sendRegulatedStcksToCnsmr() throws InterruptedException { System.out.println("----Starting the scheduler for fetch in scheduler----"); while (true) { askThreadToSleep(); System.out.println("Got the stock price collection from main queue"); Queue&lt;PriceUpdate&gt; priceUpdateQueue = LoadHandler.getPriceUpdateQueue(); System.out.println("Price update queue size after fetching ::"+priceUpdateQueue.size()); List&lt;PriceUpdate&gt; priceUpdateQueueCopy = new LinkedList&lt;&gt;(priceUpdateQueue); System.out.println("Copied the stock collection into new queue"); System.out.println("Going to check for already sent stock prices"); System.out.println("-----Printing stocks inside stocksSentToConsumerList------"); stocksSentToConsumerList.forEach(System.out::println); System.out.println("-----------------------------------------------------------"); System.out.println("-----Printing stocks inside priceUpdateQueueCopy------"); priceUpdateQueueCopy.forEach(System.out::println); System.out.println("-----------------------------------------------------------"); if(stocksSentToConsumerList.size()&gt;0) { priceUpdateQueueCopy.removeIf((StockPredicate.isStockEqual(stocksSentToConsumerList).or(RemoveOlderStcksPredicate.isStockEqual(lastSentDateTime)))); } else{ priceUpdateQueueCopy.removeIf((StockPredicate.isStockEqual(stocksSentToConsumerList))); } System.out.println("-----Printing stocks inside priceUpdateQueueCopy after filtering------"); priceUpdateQueueCopy.forEach(System.out::println); System.out.println("-----------------------------------------------------------"); System.out.println("Got filtered stock list with size ::"+priceUpdateQueueCopy.size()); this.consumer.send(priceUpdateQueueCopy); if(null!=priceUpdateQueueCopy &amp;&amp; priceUpdateQueueCopy.size()&gt;0) { savePrevConsumdStcks(priceUpdateQueueCopy); } } } private void askThreadToSleep() throws InterruptedException { System.out.println("----Scheduler sleeping for 1 sec----"); Thread.sleep(1000); System.out.println("----Scheduler woke up after 1 sec----"); } private void savePrevConsumdStcks(final List&lt;PriceUpdate&gt; priceUpdateListToSend) { System.out.println("Clearing the stock sent to consumer list before adding the price update list"); stocksSentToConsumerList.clear(); stocksSentToConsumerList.addAll(priceUpdateListToSend); setLastSentDateTime(stocksSentToConsumerList.peekLast().getLocalDateTime()); System.out.println("Added the stock price sent list to the collection for next cycle comparison."); System.out.println("Last sent timestamp is :"+lastSentDateTime); } } </code></pre> <p>8) Exercise.java ( Main class ) </p> <pre><code> package com.exercise.init; import com.excercise.consumer.Consumer; import com.exercise.producer.Producer; import com.exercise.regulator.LoadHandler; /** * Scenario: There is a producer (Producer) of price updates for stocks. * This producer will generate constant price updates for a fix number of stocks. * The producer should not block, every price update should be consumed as quickly as possible. * * Furthermore there is a load handler (LoadHandler) which will consume the price updates of the producer. * In the current implementation the load handler will just pass on the update to a consumer. This should be changed. * * The consumer (Consumer) will receive the price updates from the load handler. * (The current implementation will just print out all price updates for convenience sake.) * The consumer should represent a legacy system that cannot consumer more than a certain number of price updates per second. * Otherwise it will fall over. * * The task of this exercise is to extend the LoadHandler to limit the updates per second to the consumer to a certain given number (MAX_PRICE_UPDATES). * In order to achieve this, it is a allowed to drop price updates, since otherwise the application will run out of memory, if the application will keep all of them. * It is important that, if a price update will be send to the consumer, it has to be the most recent price. * * Example: * * Updates arrive in this order from the consumer: * * Apple - 97.85 * Google - 160.71 * Facebook - 91.66 * Google - 160.73 * * The load balancer has received all updates and is going to send them out to the consumer like this now: * * Apple - 97.85 * Google - 160.73 * Facebook - 91.66 * * So the first Google update (160.73) has been dropped. * * In order to limit the number of updates per second to the consumer, * it will be necessary to write some sort of scheduler/timer. * It is acceptable to send the updates as bulk once per second. * Ideally the load should be spread out into smaller chunks during that second. * * Please consider that the number of stocks might be bigger than the number of allowed updates per second to the consumer. * Make sure that the application will not run out of memory, even if the number of stocks or updates per second might be bigger than MAX_PRICE_UPDATES. * * Please implement the &lt;b&gt;hashCode&lt;/b&gt; and &lt;b&gt;equals&lt;/b&gt; in PriceUpdate, * since those methods might be relevant for the task. * * It is fine to create additional classes and tests. * * You can use all features of Java 8 as well as any additional library as long as it is open source and will be provided with the solution. * * */ public class Exercise { public static void main(String[] args) { Consumer consumer = new Consumer (); LoadHandler loadHandler = new LoadHandler(consumer); Producer producer = new Producer(loadHandler); producer.run(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T10:17:02.050", "Id": "399671", "Score": "1", "body": "Please post the relevant code section on the website in your post github links are only allowed as a bonus" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "20...
[ { "body": "<p>I've taken a look into your github files and here are my thoughts:</p>\n\n<h2>IStockProducer</h2>\n\n<p>You might've another taste than me, but I still want to say that: Marker interfaces are useless. They don't help, they don't add any value and they just grow your hierarchy. You should remove it...
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T10:14:11.710", "Id": "207134", "Score": "2", "Tags": [ "java", "performance", "algorithm", "multithreading", "producer-consumer" ], "Title": "Producer consumer design and implementation using Java 8" }
207134
<p>I have implemented a simple example for inter thread communication which have 2 threads to print even and odd numbers in sequence.</p> <p>I am looking for a feedback and points for improving the example. </p> <p>My code looks like:</p> <pre><code>public class InterThreadCommunicationEvenOddExample { public static void main(String[] args) { NumberResource numberResource = new NumberResource(); new EvenThread(numberResource); new OddThread(numberResource); } } class EvenThread implements Runnable { NumberResource numberResource; EvenThread(final NumberResource numberResource) { this.numberResource = numberResource; new Thread(this, "Even").start(); } public void run() { while (true) { System.out.println("Even Thread::" + this.numberResource.getNextEven()); try { Thread.sleep(1000); } catch (InterruptedException e) { } } } } class OddThread implements Runnable { NumberResource numberResource; OddThread(final NumberResource numberResource) { this.numberResource = numberResource; new Thread(this, "Odd").start(); } public void run() { while (true) { System.out.println("Odd Thread::" + this.numberResource.getNextOdd()); try { Thread.sleep(1000); } catch (InterruptedException e) { } } } } class NumberResource { private int number = 0; public synchronized int getNextEven() { while (isEven(number)) { try { wait(); } catch (InterruptedException e) { } } number++; notify(); return number; } public synchronized int getNextOdd() { while (!isEven(number)) { try { wait(); } catch (InterruptedException e) { } } number++; notify(); return number; } private boolean isEven(int number) { return number % 2 == 0; } } </code></pre>
[]
[ { "body": "<p>There is some refactoring that could be made.</p>\n\n<h2>Naming</h2>\n\n<p><code>EvenThread</code> and <code>OddThread</code> aren't really threads since they don't implement the <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html\" rel=\"nofollow noreferrer\"><code>Thread</c...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T11:03:55.687", "Id": "207135", "Score": "0", "Tags": [ "java", "multithreading" ], "Title": "Inter Thread Communication Even Odd Example" }
207135
<p>Following <a href="https://stackoverflow.com/questions/53126305/pretty-printing-numpy-ndarrays-using-unicode-characters">this idea</a> for pretty printing of numpy ndarrays, I have developed a very primitive prototype:</p> <pre><code>def ndtotext(A, w=None, h=None): if A.ndim==1: if w == None : return str(A) else: s ='['+' '*(max(w[-1],len(str(A[0])))-len(str(A[0]))) +str(A[0]) for i,AA in enumerate(A[1:]): s += ' '*(max(w[i],len(str(AA)))-len(str(AA))+1)+str(AA) s +='] ' elif A.ndim==2: w1 = [max([len(str(s)) for s in A[:,i]]) for i in range(A.shape[1])] w0 = sum(w1)+len(w1)+1 s= u'\u250c'+u'\u2500'*w0+u'\u2510' +'\n' for AA in A: s += ' ' + ndtotext(AA, w=w1) +'\n' s += u'\u2514'+u'\u2500'*w0+u'\u2518' elif A.ndim==3: h=A.shape[1] s1=u'\u250c' +'\n' + (u'\u2502'+'\n')*h + u'\u2514'+'\n' s2=u'\u2510' +'\n' + (u'\u2502'+'\n')*h + u'\u2518'+'\n' strings=[ndtotext(a)+'\n' for a in A] strings.append(s2) strings.insert(0,s1) s='\n'.join(''.join(pair) for pair in zip(*map(str.splitlines, strings))) return s </code></pre> <p>for example:</p> <pre><code>shape = 4, 5, 3 C=np.random.randint(10000, size=np.prod(shape)).reshape(shape) print(ndtotext(C)) ┌┌────────────────┐┌────────────────┐┌────────────────┐┌────────────────┐┐ │ [9298 4404 1759] [5426 3488 9267] [8884 7721 579] [6872 4226 1858] │ │ [6723 271 8466] [9885 6760 8949] [ 295 7422 5659] [5322 4239 7446] │ │ [7156 6077 9390] [2712 6379 2832] [6956 626 5534] [ 142 4090 6390] │ │ [9377 9033 1953] [8986 3791 4538] [2466 8572 662] [1528 8922 9656] │ │ [1449 7319 3939] [7350 9619 928] [7542 4704 1477] [ 980 6037 869] │ └└────────────────┘└────────────────┘└────────────────┘└────────────────┘┘ </code></pre> <p>I would appreciate it if you could review this code and let me know how I can improve it.</p> <p>I hope to see:</p> <ul> <li>possible mistakes or cases to break the code</li> <li>how to make it faster, more performant, pythonic</li> <li>how to extend it to higher dimensions</li> </ul> <p><strong>P.S.</strong> For those who follow up this idea I have integrated everythin here in <a href="https://notebooks.azure.com/fsfarimani/projects/numpy-pprint" rel="nofollow noreferrer">this Jupyter Notebook</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T13:26:22.400", "Id": "399696", "Score": "1", "body": "How many dimensions does this work with? 1-3." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T13:29:07.340", "Id": "399697", "Score": "0",...
[ { "body": "<p>If <code>A.ndim</code> is not in <code>1, 2, 3</code>, your code tries to return a non-existing string <code>s</code>. It would be better to be explicit about what your code supports atm:</p>\n\n<pre><code>def ndtotext(A, w=None, h=None):\n ...\n else:\n raise NotImplementedError(\"Cu...
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T13:23:48.673", "Id": "207139", "Score": "16", "Tags": [ "python", "numpy", "formatting", "ascii-art", "unicode" ], "Title": "Pretty printing of the numpy ndarrays" }
207139
<p>This is the first time I've ever tried to write unit tests before, so I wanted to post here to see if I'm doing it "right". I read a couple of articles on the subject, but I work alone so I want to ensure that I fully understand the standard ideas before continuing. Could you please take a look at this and let me know what you think?</p> <p>Here's an example method:</p> <pre><code>def is_in_range(value: float, allowed_range: (float, float), inclusive: bool = True) -&gt; bool: """Checks if the given value falls within the allowed range. Raises: ValueError: If value or range are non numeric. """ if float(allowed_range[0]) != allowed_range[0] or float( allowed_range[1]) != allowed_range[1] or float(value) != value: raise ValueError("Inputs must be numeric.") if inclusive: return min(allowed_range) &lt;= value &lt;= max(allowed_range) else: return min(allowed_range) &lt; value &lt; max(allowed_range) </code></pre> <p>And here are the unit tests I wrote:</p> <pre><code>class Test_IsInRange(object): def test_in_range(self): value = 4 surrounding_range = (value-1, value+1) assert utilities.is_in_range(value, surrounding_range) def test_out_range(self): value = 76 not_surrounding_range = (value+1, value+2) assert not utilities.is_in_range(value, not_surrounding_range) def test_exclusive_range(self): value = 23 inclusive_range = (value, value+10) assert not utilities.is_in_range(value, inclusive_range, inclusive=False) def test_inclusive_range(self): value = 1003 inclusive_range = (value-500, value) assert utilities.is_in_range(value, inclusive_range, inclusive=True) def test_string(self): string_input = "tt" with pytest.raises(ValueError): utilities.is_in_range(string_input, ("a","zzz")) </code></pre> <p>Am I testing properly? Am I testing too many different cases? Too few? Should I combine or separate any tests? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T13:32:03.463", "Id": "399698", "Score": "0", "body": "Welcome to Code Review, do you want a review of just the unit-tests or are you happy for people to critique `is_in_range` too?" }, { "ContentLicense": "CC BY-SA 4.0", ...
[ { "body": "<p>Regarding your tests. You definitely don't have too many. You actually could have too few. Consider:</p>\n\n<p>In one dimension, you have 5 cases you can check:</p>\n\n<ul>\n<li><code>val &lt; min</code></li>\n<li><code>val == min</code></li>\n<li><code>min &lt; val &lt; max</code></li>\n<li><c...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T13:29:45.453", "Id": "207140", "Score": "5", "Tags": [ "python", "unit-testing" ], "Title": "Unit testing for Python function that checks whether a value is in a range" }
207140
<p>My <strong>purpose</strong> is to add two <code>__m512i</code> variables (<code>c = a + b</code>) as efficiently as possible. To do so, I'd like to use the <a href="https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_addcarryx_u64" rel="nofollow noreferrer">_addcarryx_u64</a> function which takes <code>uint64_t</code> as inputs.</p> <pre><code>unsigned char _addcarryx_u64 (unsigned char c_in, unsigned __int64 a, unsigned __int64 b, unsigned __int64 * out) </code></pre> <p>I manage to obtain a working function based on buffers:</p> <pre><code>__m512i _m512_add(const __m512i a, const __m512i b) { const size_t n = sizeof(__m512i) / sizeof(uint64_t); uint64_t buf_a[n], buf_b[n], buf_c[n]; _mm512_storeu_si512((__m512i *)buf_a, a); _mm512_storeu_si512((__m512i *)buf_b, b); unsigned char c_in = 0; for (unsigned i = n-1; i &lt; n; --i) c_in = _addcarryx_u64(c_in, buf_a[i], buf_b[i], &amp;(buf_c[i])); return _mm512_setr_epi64(buf_c[0], buf_c[1], buf_c[2], buf_c[3], buf_c[4], buf_c[5], buf_c[6], buf_c[7]); } </code></pre> <p>But it is not as efficient as I expected. Note that I compare timing and result with the GMP library and another function (based on intrinsics functions but not <code>_addcarryx_u64</code>) that I previously wrote.</p> <p>My <strong>question</strong> is the following, is there a more efficient way to access the different <code>uint64_t</code> than using some buffers? I was thinking like a table (<code>a[i]</code>) or using extraction functions but didn't find anything satisfying my needs / didn't manage to do it.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T15:34:37.083", "Id": "399718", "Score": "0", "body": "Which compiler did you use? Because GCC really mangles the add with carry (it reifies the carry into `al` and then turns it back into a carry flag again), but Clang doesn't" },...
[ { "body": "<p>Probably not what you're expecting, but it's possible to do a 512-bit add directly with AVX512 registers. The <code>_addcarryx_u64()</code> intrinsic is not necessary nor do you need to break up the register into scalars.</p>\n\n<p>Taken from my blog: <a href=\"http://www.numberworld.org/y-crunche...
{ "AcceptedAnswerId": "207195", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T14:11:41.740", "Id": "207143", "Score": "6", "Tags": [ "c", "integer", "simd" ], "Title": "AVX512 - Add two 512-bit integers using _addcarryx_u64 function" }
207143
<p>I know that <code>sort</code> in R uses radix sort, and I played around in implementing it (mainly to be sure I understood the algorithm properly). However, my implementation is an order of magnitude slower than the native implementation in R. </p> <p>I'm curious: <strong>is there a way to implement radix sort in R so that it wouldn't be so slow?</strong></p> <p>My code:</p> <pre><code>get_digit &lt;- function(x, d) { # digits from the right # i.e.: first digit is the ones, second is the tens, etc. (x %% 10^d) %/% (10^(d-1)) } radix_sort &lt;- function(x) { # k is maximum number of digits k &lt;- max(nchar(x)) for(i in 1:k) { x_digit_i &lt;- get_digit(x, i) # split numbers based on their i digit x_by_bucket &lt;- split(x, x_digit_i) # recombine the vectors, now sorted to the i'th digit x &lt;- unlist(x_by_bucket, use.names = FALSE) } # since each iteration is a stable sort, the final result # is a sorted array, yay! x } </code></pre> <p>Checking the running time:</p> <pre><code>&gt; library(microbenchmark) &gt; x &lt;- sample(100) &gt; microbenchmark(radix_sort(x), sort(x)) Unit: microseconds expr min lq mean median uq max neval cld radix_sort(x) 459.378 465.895 485.58322 480.4835 496.779 649.956 100 b sort(x) 27.314 29.487 33.05064 31.9710 33.212 73.563 100 a &gt; x &lt;- sample(10000) &gt; microbenchmark(radix_sort(x), sort(x)) Unit: microseconds expr min lq mean median uq max radix_sort(x) 44317.123 44777.8965 46062.3446 45204.3715 45714.807 63838.148 sort(x) 158.609 165.7485 198.3083 186.6995 206.099 750.832 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T14:38:50.550", "Id": "399711", "Score": "4", "body": "Welcome, currently your title makes your question sound off-topic and so is likely the cause of your downvote. This is as asking us to write algorithms for you is off-topic. I'd ...
[ { "body": "<p>Putting these comments into an answer...</p>\n\n<p>As pointed out, it will be a tall order to beat or even approach the computation times of the native <code>sort</code> function, as it is compiled from C. Often with R, the trick to make your code faster consists in composing with some of these fa...
{ "AcceptedAnswerId": "207890", "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T14:19:46.310", "Id": "207144", "Score": "1", "Tags": [ "performance", "r", "radix-sort" ], "Title": "Radix sort function in R" }
207144
<p>I have been developing a <strong>little</strong>, private Blog Site to make notes/ stories of pen and paper rpg games available for me and my players. </p> <p>This is my first project. As I am new to coding in PHP and MySQL I'd very much appreciate your opinions on the code I have written. I am interested in any feedback you can give me - but especially on the security of the script I have written. The input form is actually secured by a randomly created username and password authentication via .htaccess. (Side note: the website uses proper encryption for the user input including HSTS and ranks as an A+ on ssllabs.com.)</p> <p>I have been reading much lately on script injection and SQL injection (for example on <a href="https://phpdelusions.net/pdo/sql_injection_example" rel="nofollow noreferrer">https://phpdelusions.net/pdo/sql_injection_example</a>) and using variables to create a query was often considered unsafe. Still - in my inexperiencedness - I've made a script thats using the (static) keys of the <strong>$_POST Array</strong> to determine the database columns and placeholders for values which are used in my PDO query. Afterwards I bind each submited value to its PDO placeholder.</p> <p>I do not expect to enter any html Input, which is why I decided to use the <strong>stripslashes</strong> and <strong>htmlspecialchars</strong> funcions on the input values before binding it to the PDO querys and I <strong>haven't</strong> used any str_replace function to <strong>escape backtics</strong> since every value is directly bound to the designated PDO placeholder.</p> <pre><code>if (isset ($_POST['session_submit'])) { $table = 'sessions'; foreach ($_POST as $column=&gt;$value){ $column = input_behandlung_sessions($column); $secure_value = input_behandlung_sessions($value); $formular_daten[$column] = $secure_value; } $kampagne = $formular_daten['kampagne']; $count = $pdo-&gt;prepare('SELECT COUNT(kampagne) FROM sessions WHERE kampagne = :kampagne'); $count-&gt;bindParam(':kampagne', $kampagne, PDO::PARAM_STR); $count-&gt;execute(); $rowcount = $count-&gt;fetchColumn(0); $newrowcount = ++$rowcount; unset($formular_daten['session_submit']); foreach ($formular_daten as $column=&gt;$value){ if ($value == "") unset($formular_daten[$column]); } foreach ($formular_daten as $column=&gt;$value){ $non_empty_columns[] = $column; $columns_param = ':'.$column; $array_columns_param[] = $columns_param; $to_bind[$columns_param] = $value; } $text_non_empty_columns = implode (", ", $non_empty_columns); $parameter_columns = implode (', ', $array_columns_param); $sql_string = 'INSERT INTO '.$table.' (session_uid, '.$text_non_empty_columns.') VALUES ('.$newrowcount.', '.$parameter_columns.')'; $stmt = $pdo-&gt;prepare($sql_string); foreach ($to_bind as $key=&gt;$param){ $stmt-&gt;bindValue($key, $param); } $stmt-&gt;execute(); unset($_POST); } function input_behandlung_sessions($data) { $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } </code></pre> <p>And here is the form used to submit the data (in case you are interested).</p> <pre><code>echo ' &lt;form method="post" action="#v-pills-session"&gt; &lt;div class="row"&gt; &lt;div class="form-group col-md-2 col-sm-6"&gt;&lt;label for="formGroupExampleInput"&gt;Kampagne: &lt;/label&gt;&lt;/div&gt; &lt;div class="col-md-4 col-sm-6"&gt;&lt;input required="true" type="text" class="form-control" id="formGroupExampleInput" name="kampagne" placeholder="Kürzel der Kampagne eintragen"&gt;&lt;/div&gt; &lt;div class="form-group col-md-2 col-sm-6"&gt;&lt;label for="formGroupExampleInput"&gt;Kapitel-Nr.: &lt;/label&gt;&lt;/div&gt; &lt;div class="col-md-4 col-sm-6"&gt;&lt;input required="true" type="text" class="form-control" id="formGroupExampleInput" name="session_story_arc" placeholder="Nummer des Kapitels eintragen"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="form-group row"&gt; &lt;div class="col-md-1 col-sm-12"&gt;&lt;label for="formGroupExampleInput"&gt;Name: &lt;/label&gt;&lt;/div&gt; &lt;div class="col-md-11 col-sm-12"&gt;&lt;input required="true" type="text" class="form-control" id="formGroupExampleInput" name="session_name" placeholder="Hier den Namen der Session eintragen"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="form-group row"&gt; &lt;div class="col-md-1 col-sm-12"&lt;label for="formGroupExampleInput2"&gt;Spieler: &lt;/label&gt;&lt;/div&gt; &lt;div class="col-md-11 col-sm-12"&gt;&lt;input type="text" required="true" class="form-control" id="formGroupExampleInput2" name="session_charaktere_aktiv" placeholder="Hier die Namen der aktiven Charaktere eintragen"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="form-group row"&gt; &lt;div class="col-md-1 col-sm-12"&gt;&lt;label for="formGroupExampleInput2"&gt;Quests: &lt;/label&gt;&lt;/div&gt; &lt;div class="col-md-11 col-sm-12"&gt;&lt;input type="text" class="form-control" id="formGroupExampleInput2" name="session_quests" placeholder="Hier die Quests in dieser Session eintragen"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="form-group row"&gt; &lt;div class="col-md-1 col-sm-12"&gt;&lt;label for="formGroupExampleInput2"&gt;NPCs&lt;/label&gt;&lt;/div&gt; &lt;div class="col-md-11 col-sm-12"&gt;&lt;input type="text" class="form-control" required="true" id="formGroupExampleInput2" name="session_npc" placeholder="Hier die Namen der NPCs aus dieser Session eintragen"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="form-group row"&gt; &lt;div class="col-md-1 col-sm-12"&gt;&lt;label for="formGroupExampleInput2"&gt;Orte: &lt;/label&gt;&lt;/div&gt; &lt;div class="col-md-11 col-sm-12"&gt;&lt;input type="text" class="form-control" required="true" id="formGroupExampleInput2" name="session_orte" placeholder="Hier die Orte eintragen, in welchen die Abenteure unterwegs waren"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;input required="true" type="submit" name="session_submit" class="form-control btn-primary" id="formGroupExampleInput2" placeholder="Submit"&gt; &lt;/div&gt; &lt;/form&gt;'; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T17:01:31.460", "Id": "399723", "Score": "0", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for ...
[ { "body": "<p>When you expect get reviewed from poeple speaking English, try to use only English in your code (and in comments).</p>\n\n<p>Why go through <code>formular_daten</code> twice when you can check if the value is empty and, if not do the processing in a single loop?</p>\n", "comments": [ { ...
{ "AcceptedAnswerId": "207161", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T15:50:39.887", "Id": "207149", "Score": "3", "Tags": [ "php", "html", "mysql", "pdo", "sql-injection" ], "Title": "using $_POST array to prepare PDO statement with variables" }
207149
<p>We need to calculate the number of sub-sequences of an array having its median lying in the sub-sequence itself. My code is - </p> <pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; #define MOD 1000000007 #define fori0n for(int i=0;i&lt;n;i++) #define inputLoop for(int j=0;j&lt;t;j++) // FAST SCANNING .. template&lt;typename T&gt; void scan(T &amp;x) { x = 0; bool neg = 0; register T c = getchar(); if (c == '-') neg = 1, c = getchar(); while ((c &lt; 48) || (c &gt; 57)) c = getchar(); for ( ; c &lt; 48||c &gt; 57 ; c = getchar()); for ( ; c &gt; 47 &amp;&amp; c &lt; 58; c = getchar() ) x= (x &lt;&lt; 3) + ( x &lt;&lt; 1 ) + ( c &amp; 15 ); if (neg) x *= -1; } // FAST PRINTING.. template&lt;typename T&gt; void print(T n) { bool neg = 0; if (n &lt; 0) n *= -1, neg = 1; char snum[65]; int i = 0; do { snum[i++] = n % 10 + '0'; n /= 10; } while (n); --i; if (neg) putchar('-'); while (i &gt;= 0) putchar(snum[i--]); putchar('\n'); } float median(vector&lt;int&gt; new_array, int num){ sort(new_array.begin(), new_array.end()); float median = (num % 2 != 0) ? (new_array[((num+1)/2)-1]) : (float)(new_array[(num/2)-1] + new_array[num/2]) / 2; return median; } void subsetsUtil(vector&lt;int&gt;&amp; A, vector&lt;vector&lt;int&gt; &gt;&amp; res, vector&lt;int&gt;&amp; subset, int index) { for (int i = index; i &lt; A.size(); i++) { // include the A[i] in subset. subset.push_back(A[i]); res.push_back(subset); // move onto the next element. subsetsUtil(A, res, subset, i + 1); subset.pop_back(); } return; } vector&lt;vector&lt;int&gt; &gt; subsets(vector&lt;int&gt;&amp; A) { vector&lt;int&gt; subset; vector&lt;vector&lt;int&gt; &gt; res; // include the null element in the set. //res.push_back(subset); // keeps track of current element in vector A; int index = 0; subsetsUtil(A, res, subset, index); return res; } int main() { //ios_base::sync_with_stdio(false); //cin.tie(NULL); int t; scan(t); //cin&gt;&gt;t; inputLoop { int n; scan(n); //cin&gt;&gt;n; // find the subsets of below vector. vector&lt;int&gt; arr; int input; fori0n { //cin&gt;&gt;input; scan(input); arr.push_back(input); } vector&lt;vector&lt;int&gt; &gt; res = subsets(arr); int goodMedian = 0; // Print result for (int i = 0; i &lt; res.size(); i++) { //cout&lt;&lt;"Sub set : "&lt;&lt;i&lt;&lt;" _ With Size : "&lt;&lt;res[i].size()&lt;&lt;" == "; // if size == 1 or 3 if(res[i].size() % 2 != 0) { // there will always be a good median //cout&lt;&lt;"GOOD MEDIAN "; goodMedian++; } else if(res[i].size() == 2) { if(median(res[i], 2) == res[i][0] || median(res[i], 2) == res[i][1]) { //cout&lt;&lt;"GOOD MEDIAN "; goodMedian++; } } else if(res[i].size() % 2 == 0) { int size = res[i].size(); if(median(res[i], res[i].size()) == res[i][size / 2] || median(res[i], res[i].size()) == res[i][(size - 1)/2]) { //cout&lt;&lt;"GOOD MEDIAN "; goodMedian++; } } //for (int j = 0; j &lt; res[i].size(); j++) // cout &lt;&lt; res[i][j] &lt;&lt; " "; //cout &lt;&lt; endl; } print(goodMedian % MOD); } return 0; } </code></pre> <p>Can anyone suggest any better algorithm for this problem ? </p>
[]
[ { "body": "<p>Beginning with some depressingly-common standard observations:</p>\n\n<ul>\n<li><code>&lt;bits/stdc++.h&gt;</code> is non-standard and a bad choice for user code.</li>\n<li><code>using namespace std;</code> is harmful and should be avoided</li>\n<li>Avoid preprocessor macros for constants or simpl...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T16:54:27.377", "Id": "207153", "Score": "5", "Tags": [ "c++", "algorithm", "array", "statistics" ], "Title": "Count sub-sequences of an array having median lying in that subsequence itself" }
207153
<h2>Intro</h2> <p>I'm going through the K&amp;R book (2nd edition, ANSI C ver.) and want to get the most from it: learn (outdated) C and practice problem-solving at the same time. I believe that the author's intention was to give the reader a good exercise, to make him think hard about what he can do with the tools introduced, so I'm sticking to program features introduced so far and using "future" features and standards only if they don't change the program logic.</p> <p>Compiling with <code>gcc -Wall -Wextra -Wconversion -pedantic -std=c99</code>.</p> <h2>K&amp;R Exercise 1-21</h2> <p>Write a program <code>entab</code> that replaces strings of blanks by the minimum number of tabs and blanks to achieve the same spacing. Use the same tab stops as for <code>detab</code>. When either a tab or a single blank would suffice to reach a tab stop, which should be given preference?</p> <h2>Solution</h2> <p>The solution attempts to reuse functions coded in the previous exercises (<code>getline</code> &amp; <code>copy</code>) and make the solution reusable as well. In that spirit, a new function <code>size_t entab(char s[], size_t tw);</code> is coded to solve the problem. For lines that can fit in the buffer, the solution is straightforward. However, what if they can't? The <code>main</code> routine deals with that, and most of the lines are treating the special case where we must merge the blanks from 2 <code>getline</code> calls. This exercise is just after the chapter where <code>extern</code> variables are introduced, and they really are convenient here enabling the <code>entab</code> function to be aware of the column we're at.</p> <h2>Code</h2> <pre><code>/* Exercise 1-21. Write a program `entab` that replaces strings of * blanks by the minimum number of tabs and blanks to achieve the same * spacing. Use the same tab stops as for `detab`. When either a tab or * a single blank would suffice to reach a tab stop, which should be * given preference? */ #include &lt;stdio.h&gt; #include &lt;stdbool.h&gt; #define MAXTW 4 // max. tab stop width #define LINEBUF MAXTW // line buffer size, must be &gt;=MAXTW size_t col = 0; // current column size_t tcol = 0; // target column size_t getline(char line[], size_t sz); void copy(char * restrict to, char const * restrict from); size_t entab(char s[], size_t tw); int main(void) { extern size_t col; // current column extern size_t tcol; // target column char line[LINEBUF]; // input buffer size_t len; // input buffer string length size_t tw = 4; // tab width if (tw &gt; MAXTW) { return -1; } len = getline(line, LINEBUF); while (len &gt; 0) { len = entab(line, tw); if (line[len-1] == '\n') { // base case, working with a full, properly terminated line // or a tail of one; we can safely print it col = 0; tcol = 0; printf("%s", line); len = getline(line, LINEBUF); } else if (line[len-1] != ' ') { // could be part of a bigger line or end of stream and we // don't have dangling blanks; we can safely print it printf("%s", line); len = getline(line, LINEBUF); } else { // we have some dangling blanks and must peek ahead to // know whether we can merge them into a tab or not bool cantab = false; char pline[LINEBUF]; // peek buffer size_t plen; // peek buffer string length plen = getline(pline, LINEBUF); if (plen &gt; 0) { if (pline[0] == ' ') { // count spaces in the peek; pspc = 1 because if // we're here then we already know pline[0] == ' ' size_t pspc; for (pspc = 1; (pline[pspc] == ' ' || pline[pspc] == '\t') &amp;&amp; pspc &lt; plen &amp;&amp; pspc &lt; tw; ++pspc) { if (pline[pspc] == '\t') { cantab = true; } } // enough to warrant a tab stop? if (col + pspc &gt;= (col + tw)/tw*tw) { cantab = true; } } else if (pline[0] == '\t') { cantab = true; } } // else we got EOF and those spaces have to stay if (cantab) { // pop the spaces and adjust current column accordingly while (len &gt; 0 &amp;&amp; line[--len] == ' ') { --col; line[len] = '\0'; } // no need to fix len, as it gets reset below } printf("%s", line); len = plen; copy(line, pline); } } return 0; } /* entab: process string from `s`, replace in-place spaces with tabs. * Assume '\0' terminated string. Relies on extern variable for column * alignment. * tw - tab width */ size_t entab(char s[], size_t tw) { extern size_t col; // current column extern size_t tcol; // target column size_t j = 0; bool gotnul = false; for (size_t i = 0; !gotnul; ++i) { // on blank or tab just continue reading and move our target // column forward if (s[i] == ' ') { ++tcol; } else if (s[i] == '\t') { tcol = (tcol+tw)/tw*tw; } else { // on non-blank char, if we're lagging behind target fill-up // with tabs &amp; spaces and then write the char, else just // write the char if (tcol &gt; col) { for (size_t at = (tcol/tw*tw-col/tw*tw)/tw; at &gt; 0; --at) { s[j] = '\t'; ++j; col = (col+tw)/tw*tw; } for (size_t as = tcol-col; as &gt; 0; --as) { s[j] = ' '; ++j; ++col; } } s[j] = s[i]; if (s[j] == '\0') { gotnul = true; } else { ++j; ++col; ++tcol; } } } return j; } /* getline: read a line into `s`, return string length; * `sz` must be &gt;1 to accomodate at least one character and string * termination '\0' */ size_t getline(char s[], size_t sz) { int c; size_t i = 0; bool el = false; while (i + 1 &lt; sz &amp;&amp; !el) { c = getchar(); if (c == EOF) { el = true; // note: `break` not introduced yet } else { s[i] = (char) c; ++i; if (c == '\n') { el = true; } } } if (i &lt; sz) { if (c == EOF &amp;&amp; !feof(stdin)) { // EOF due to read error i = 0; } s[i] = '\0'; } return i; } /* copy: copy a '\0' terminated string `from` into `to`; * assume `to` is big enough; */ void copy(char * restrict to, char const * restrict from) { size_t i; for (i = 0; from[i] != '\0'; ++i) { to[i] = from[i]; } to[i] = '\0'; } </code></pre> <h2>Test</h2> <h3>Input</h3> <pre><code> sdas a a aaa aasa aaa d dfsdf aaa ss s g aa asd s f f f X asf </code></pre> <p>Showing the tabs as <code>^I</code>:</p> <pre><code>$ cat -T test.txt sdas a a aaa aasa^I aaa^I d dfsdf aaa ss s g aa^I ^Iasd^I s^If^If f^IX ^I ^I asf ^I^I^I ^I </code></pre> <h3>Output</h3> <pre><code> sdas a a aaa aasa aaa d dfsdf aaa ss s g aa asd s f f f X asf </code></pre> <p>Showing the tabs as <code>^I</code>:</p> <pre><code>$ cat -T out.txt ^I^I^I^I^I^I^I^I^I^Isdas^I^I^I^I ^Ia^Ia^Iaaa^Iaasa^I aaa^I^I^I^Id^Idfsdf^I^I^Iaaa^Iss^Is^I^Ig aa^I^Iasd^I^I s^If^If f^IX^I ^I^I asf^I^I^I^I </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T22:51:50.063", "Id": "399796", "Score": "0", "body": "`gcc` has `-ansi`, `-std=c90`, or `-std=c89` instead of `-std=c99` if you want `c99` extensions to give you a warning/error." }, { "ContentLicense": "CC BY-SA 4.0", "...
[ { "body": "<p>OP only asked a few direct questions.</p>\n<blockquote>\n<p>When either a tab or a single blank would suffice to reach a tab stop, which should be given preference?</p>\n</blockquote>\n<p>Use <em>blanks</em> <code>' '</code>.</p>\n<p><a href=\"https://stackoverflow.blog/2017/06/15/developers-use-s...
{ "AcceptedAnswerId": "207498", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T17:29:20.313", "Id": "207159", "Score": "6", "Tags": [ "beginner", "c", "strings", "formatting", "io" ], "Title": "K&R Exercise 1-21. Write a program `entab` that replaces strings of blanks with tabs" }
207159
<p>A simple binary expression tree in Haskell without operator precedence and without parentheses.</p> <p>Any comments would be much appreciated.</p> <pre><code>data Tree a= Const a | X | Plus (Tree a) (Tree a) | Mult (Tree a) (Tree a) | Minus (Tree a) (Tree a) | Div (Tree a) (Tree a) | Power (Tree a) (Tree a) | Cos (Tree a) | Sin (Tree a) deriving Show eval :: ( Eq t, Floating t) =&gt; Tree t-&gt; t -&gt; Maybe t eval (Const a) x = Just (a) eval X x = Just x eval (Plus a b) x = (+) &lt;$&gt; eval a x &lt;*&gt; eval b x eval (Mult a b) x = (*) &lt;$&gt; eval a x &lt;*&gt; eval b x eval (Minus a b) x = (-) &lt;$&gt; eval a x &lt;*&gt; eval b x eval (Power a b) x = (**) &lt;$&gt; eval a x &lt;*&gt; eval b x eval (Div a b) x = if (eval b x) == (Just 0) then Nothing else (/) &lt;$&gt; eval a x &lt;*&gt; eval b x eval (Cos a) x =(cos) &lt;$&gt; eval a x eval (Sin a) x = (cos) &lt;$&gt; eval a x dif :: ( Eq t, Floating t) =&gt; Tree t-&gt;Tree t dif (Const a) = Const 0 dif X = Const 1 dif (Plus a b) =Plus (dif a) (dif b ) dif (Mult a b) = Plus (Mult (dif a) b) (Mult a (dif b)) dif (Minus a b) = Minus (dif a) (dif b) dif (Div a b) = Div (Minus (Mult (dif a) b) (Mult a (dif b))) (Mult b b) dif (Power (Const a) (Const b)) = Const 0 dif (Power a (Const b)) = Mult (Const b) (Power X (Minus (Const b) (Const 1))) dif (Cos a) = Minus (Const 0) (Mult (dif a) (Sin a)) dif (Sin a) = (Mult (dif a) (Cos a)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T19:47:21.797", "Id": "399753", "Score": "0", "body": "_\"I couldn't fit the Floating constraint into the declaration.\"_ So we should suspect your code doesn't work as intended and that's _off-topic_ here (not ready for review)" }...
[ { "body": "<p>You have a copy-and-paste error here:</p>\n\n<blockquote>\n<pre><code>eval (Cos a) x =(cos) &lt;$&gt; eval a x\neval (Sin a) x = (cos) &lt;$&gt; eval a x\n</code></pre>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", ...
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T19:29:07.993", "Id": "207169", "Score": "1", "Tags": [ "haskell", "expression-trees", "symbolic-math" ], "Title": "Expression tree in Haskell with support for differentiation" }
207169
<p>I have been writing R scripts for about a week. I have been writing code for 20 years. I have a series of yes-no questions that I hope to predict yes-no outcomes so I know the R-squared will be terrible but as long as the variable is significant I am fine.</p> <p>Since I am creating a number with my yes-no questions the order makes a difference and I have 14 questions which I plan to turn into 8-bit numbers (121,080,960 permutations). This is taking about 88 hours on my desktop. I am looking for anyplace to optimize my code. I have read about Multi core/thread SNOW but that is beyond me right now without some help. I also know I can compile functions but my code is short and only see one place to do so.</p> <p>Please review my code, any help would be appreciated.</p> <pre><code>library(data.table) ffName = "Perms8bit.csv" # Read table of 1s and 0s Bin_Matrix &lt;-read.table("LC_FR_F17BIN.csv",header=TRUE,sep=",") Perm_Best &lt;- 0 holdR &lt;- 0 s&lt;- Sys.time() cnt &lt;-0 # Read the file 121,080,960 permutations to test # Originally read the file in blocks but benchmark testing rawData &lt;- fread(ffName, sep=",") for (cnt in 1:121080960){ # create a table result x binary number Bin_num &lt;- data.table(result = c(Bin_Matrix[,15]),numb = c(2^0* (Bin_Matrix [,as.numeric(rawData[cnt,1])]) + 2^1*(Bin_Matrix [,as.numeric(rawData[cnt,2])]) + 2^2*(Bin_Matrix [,as.numeric(rawData[cnt,3])]) + 2^3*(Bin_Matrix [,as.numeric(rawData[cnt,4])]) + 2^4*(Bin_Matrix [,as.numeric(rawData[cnt,5])]) + 2^5*(Bin_Matrix [,as.numeric(rawData[cnt,6])]) + 2^6*(Bin_Matrix [,as.numeric(rawData[cnt,7])]) + 2^7*(Bin_Matrix [,as.numeric(rawData[cnt,8])]))) #linear regession linearMod &lt;- lm(result ~ numb, data = Bin_num) ModSum &lt;- summary(linearMod) theR &lt;- ModSum$r.squared # Find the top R squared, result is 1s and 0s so R squared will not be high if (theR &gt; .0175) { holdR = theR Perm_Best &lt;- data.table(cnt = cnt,R = holdR,rawData[cnt,]) #append a file with best fits write(toString(Perm_Best,nrows= 1),file = "RSQ.txt", append = TRUE) } } print (Sys.time()-s) #benchmark print(holdR) # just to let me know its done print (Perm_Best) </code></pre> <p><code>Bin_Matrix</code> is a file with around 2,000 rows, header, and a bunch of 1s and 0s in csv form. <code>RawData</code> is a table with 121 million rows with the different permutations (examples:</p> <pre><code>1,2,3,4,5,6,7,8 1,2,3,4,5,6,7,9 ... 14,1,2,3,4,5,6,7 14,1,2,3,4,5,6,8 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T08:55:36.513", "Id": "399834", "Score": "0", "body": "Can you supply small example of your data objects `Bin_Matrix` & `rawData`? preferably in `dput` format, so we can copy/paste and test your code. Like in other questions, for exa...
[ { "body": "<p>Unfortunately, without the two csv files, we are not able to test your code... Maybe if you could show us the profiler output (see the example in <code>?summaryRprof</code>) on a few iterations, it would help. What I suspect is that it will show most of the time is wasted either in the <code>lm</c...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T19:45:13.577", "Id": "207170", "Score": "3", "Tags": [ "performance", "r" ], "Title": "A series of yes-no questions to predict yes-no outcomes" }
207170
<p>I was inspired after <a href="https://stackoverflow.com/questions/1344221/how-can-i-generate-random-alphanumeric-strings">this</a> thread on Stack Overflow to create a random 8 character alphanumeric password generator.</p> <p>Sadly, it is closed, so I cannot provide an answer there. Anyway, here is the code. Let me know if there are any bugs/bias going on.</p> <pre><code>using System.Collections.Generic; using System.Security.Cryptography; public class AlphanumericGen { public virtual string Generate(byte length) { ICollection&lt;char&gt; chars = new LinkedList&lt;char&gt;(); var buffer = new byte[1]; short counter = 0; using (var rng = new RNGCryptoServiceProvider()) { while (counter &lt; length) { rng.GetBytes(buffer); var nextChar = (char)buffer[0]; if (nextChar &gt;= '0' &amp;&amp; nextChar &lt;= '9') { goto addChar; } if (nextChar &gt;= 'A' &amp;&amp; nextChar &lt;= 'Z') { goto addChar; } if (nextChar &gt;= 'a' &amp;&amp; nextChar &lt;= 'z') { goto addChar; } continue; addChar: chars.Add(nextChar); ++counter; } } return string.Concat(chars); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T03:57:20.307", "Id": "399813", "Score": "1", "body": "Why aren't you using `Char.IsDigit()` and `Char.IsLetter()` instead of your own range tests?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T12:08...
[ { "body": "<p>As a general rule of thumb, any time you feel the need to use <code>goto</code>, take a couple of aspirin and lay down until the feeling passes. They probably should have been deprecated decades ago.</p>\n\n<p>In this particular case, using a string of allowed characters and randomly picking an i...
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-07T20:08:50.510", "Id": "207171", "Score": "7", "Tags": [ "c#", "random" ], "Title": "Random alphanumeric password generator with GOTOs" }
207171
<p>This is my first Machine Learning algorithm using Python and SkLearn. The code works, which is pretty awesome. I'm getting about 65-70% of accuracy after training it with about 4k rows of data.</p> <p>Although it works, it seems like is less than optimal. I'm guessing it would be better to organize it with functions and etc - I don't know - it just seems that is more complex than it should be...</p> <p><strong>Pre processing</strong></p> <pre><code>data = pd.read_csv('data/class_full.csv', encoding='latin1', error_bad_lines=False, delimiter=';') # Define column names &amp; Change label to Pandas "Category" data.columns = ['desc', 'value', 'label'] data['desc'] = data['desc'].str.replace('[^\w\s]','') data['label'] = data['label'].astype('category') # Assign data as "string" labels = data['label'].values.astype(str) feature1 = data['desc'].values.astype(str) # Vectorizes strings with Tf-IDF Vectorizer vectorizer = TfidfVectorizer() vectors = vectorizer.fit_transform(feature1) # Train Data vectors_ = vectorizer.transform(feature1) # Test Data </code></pre> <p><strong>Fitting the model</strong></p> <pre><code>#Test train_features, test_features, train_labels, test_labels = tts(vectors, labels, test_size=0.05) # ExtraTree Classifier print('\nEstimating score with ExtraTree Classifier...') extra_model = ExtraTreesClassifier(n_estimators=100, max_depth=None, min_samples_split=10, random_state=42) extra_model.fit(train_features, train_labels) predictions_extra = extra_model.predict(vectors_) print('Score: {:.2f}'.format(extra_model.score(test_features, test_labels)*100) + ' ExtraTree Classifier') </code></pre> <p><strong>Print accuracy</strong></p> <pre><code># Print of all results print('Score: {:.2f}'.format(extra_model.score(test_features, test_labels)*100) + ' ExtraTree Classifier\n') # Voting Classifier eclf = VotingClassifier(estimators=[('extra', extra_model)], voting='soft') for clf, label in zip([extra_model, eclf], ['Extra']): scores = cross_val_score(clf, test_features, test_labels, cv=5, scoring='accuracy') print("Accuracy: %0.2f (+/- %0.2f) [%s]" % (scores.mean(), scores.std(), label)) </code></pre> <p><strong>Make Predictions</strong></p> <pre><code># Statement to be classified statement = pd.read_csv('data/extrato.csv', encoding='latin1', error_bad_lines=False, delimiter=',') # Defining the column and vectorizing it newFeatures = statement['memo'].values.astype(str) newVectorizer = TfidfVectorizer() newVector = newVectorizer.fit_transform(newFeatures) newVector_ = newVectorizer.transform(newFeatures) # Predictions with Random Forest, Decision Tree &amp; SVC models predictions_extra = extra_model.predict(vectorizer.transform(newFeatures)) predictions_extra = numpy.asarray(predictions_extra) predictions_extra = pd.DataFrame(predictions_extra) # Finding probabilities for each of the assigned categories extra_prob = extra_model.predict_proba(vectorizer.transform(newFeatures)) extra_prob = numpy.asarray(extra_prob) extra_prob = pd.DataFrame(extra_prob) extra_prob = extra_prob.max(axis=1) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T10:49:04.287", "Id": "399854", "Score": "2", "body": "Imports are missing. And we can't run the code without input data." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-24T04:17:36.743", "Id": "40235...
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T05:23:09.317", "Id": "207188", "Score": "3", "Tags": [ "python", "machine-learning" ], "Title": "Auto classification of my bank transactions" }
207188
<p><strong>Background</strong></p> <p>I wrote a function <code>update_list_v2()</code>. And this function "maintains" a sorted list, <code>g_list</code>. <code>g_list</code> is declared globally like below.</p> <pre><code>static vector&lt;element&gt; g_list; </code></pre> <p><code>update_list_v2()</code> do below works.</p> <p>1) remove every element of <code>g_list</code>, if the element exists in <code>v</code></p> <p>2) add a element to <code>g_list</code>, if a element exists in <code>v</code> and does not exist in <code>g_list</code>.</p> <p>3) if a element exists in <code>v</code> and in <code>g_list</code> and <code>max_bmi</code> of the element increases, print information of the element. (you can think the element is a person)</p> <p><code>v</code> is a list for recent data and <code>update_list_v2()</code> have to update <code>g_list</code>.</p> <p>And I wrote some other functions to work <code>update_list_v2()</code>.</p> <p><strong>Questions</strong></p> <p>I am not that familiar to c++ and vector. I wonder how to improve <code>update_list_v2()</code> and rest of my code.</p> <p><strong>Code</strong></p> <p>Here is code of <code>update_list_v2()</code></p> <pre><code>int update_list_v2(vector&lt;element&gt; &amp;v) { vector&lt;element&gt; new_items; if (g_list.size() == 0) { sort(v.begin(), v.end(), element::is_lower_id); g_list = v; for (int i=0; i&lt;g_list.size(); i++) { g_list[i].update_bmi(v[i]); } return 0; } // initialize 'remove' for (int i=0; i&lt;g_list.size(); i++) { g_list[i].remove = true; } for (int i=0; i&lt;v.size(); i++) { int f = find_element(v[i]); if (f&gt;=0) { g_list[f].remove = false; if (v[i].bmi &gt; g_list[f].max_bmi) { printf("max_bmi will be increased!\n"); printf("old data:"); g_list[f].print(); g_list[f].update_bmi(v[i]); printf("new data:"); g_list[f].print(); } else { g_list[f].update_bmi(v[i]); } } else { new_items.push_back(v[i]); } } // remove every element which 'remove' is true. for (vector&lt;element&gt;::iterator it = g_list.begin(); it != g_list.end(); ++it) { while (it != g_list.end()){ if (it-&gt;remove) { g_list.erase(it); } else { break; } } } // now, merge new_items to g_list for (int i=0; i&lt;new_items.size(); i++) { g_list.push_back(new_items[i]); new_items[i].update_bmi(new_items[i]); } // finally, sort g_list sort(g_list.begin(), g_list.end(), element::is_lower_id); } </code></pre> <p>And this is rest of my source code.</p> <pre><code>#include &lt;vector&gt; #include &lt;string&gt; #include &lt;algorithm&gt; #include &lt;stdio.h&gt; using namespace std; class element { public: long long id; string name; int bmi; // body mass index int max_bmi; bool remove; static bool is_lower_id(element a, element b) { return a.id &lt; b.id; } static bool is_same(element a, element b) { return (a.id == b.id) &amp;&amp; (0 == a.name.compare(b.name)); } void update_bmi(element &amp;a) { this-&gt;bmi = a.bmi; this-&gt;max_bmi = max(this-&gt;max_bmi, a.bmi); } void print() { printf("id/name bmi(max) : %lld/%s %d(%d)\n", this-&gt;id, this-&gt;name.c_str(), this-&gt;bmi, this-&gt;max_bmi); } }; int find_element(element &amp;e) { // find an element using binary search algorithm. int l = 0; int r = g_list.size() - 1; int m; while (l&lt;=r) { m = l + (r-l) / 2; if (element::is_same(g_list[m], e)){ return m; } if (element::is_lower_id(g_list[m], e)) l = m + 1; else r = m - 1; } return -1; } int print_list(vector&lt;element&gt; &amp;v) { printf("%s:%d\n",__func__,__LINE__); for(int i=0; i&lt;v.size(); i++){ v[i].print(); } } int main(int argc, const char *argv[]) { int a_id[] = {12, 11, 13, 5, 6, 7}; const char * a_name[] = {"a", "b", "c", "d", "e", "f"}; int a_bmi[] = {12, 11, 13, 5, 6, 7}; int b_id[] = {12, 1, 13, 5, 6, 99}; const char * b_name[] = {"a", "x", "c", "d", "e", "y"}; int b_bmi[] = {20, 5, 5, 10, 6, 5}; vector&lt;element&gt; a, b; for(int i=0; i&lt;6; i++){ element x; x.id = a_id[i]; x.name = string(a_name[i]); x.bmi = a_bmi[i]; a.push_back(x); } update_list_v2(a); print_list(g_list); for(int i=0; i&lt;6; i++){ element x; x.id = b_id[i]; x.name = string(b_name[i]); x.bmi = b_bmi[i]; b.push_back(x); } update_list_v2(b); print_list(g_list); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T08:20:11.820", "Id": "399832", "Score": "0", "body": "What's \"do something\"? An unfinished code or some removed stuff for the purpose of this example? [Code Review is about improving existing, working code](https://codereview.meta...
[ { "body": "<h2>Don't use <code>using namespace std;</code></h2>\n\n<p><a href=\"https://stackoverflow.com/a/1453605/5416291\">It's bad practice</a> that can cause a lot of problems that are easy to avoid, most people are used to the prefix, and three letters aren't that hard to type.</p>\n\n<hr>\n\n<h2>Don't wr...
{ "AcceptedAnswerId": "207506", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T06:14:30.467", "Id": "207190", "Score": "3", "Tags": [ "c++", "beginner", "vectors" ], "Title": "Manipulating and maintaining vector" }
207190
<p>I'm a data scientist attempting to build stronger CS fundamentals, particularly in Data Structures &amp; Algorithms.</p> <p>Below is my attempt at implementing a Singly Linked List. Looking for advice regarding:</p> <ol> <li>Code style</li> <li>Can space/time complexity of methods be improved? </li> <li>Debugging in case I missed any edge cases</li> <li>Checking for premature optimizations</li> </ol> <h1>Note this is an edit from the original post: <a href="https://codereview.stackexchange.com/questions/206943/linked-list-implementation-in-python/207181?noredirect=1#comment399795_207181">Linked List implementation in Python</a></h1> <p>Have made the following edits to the code according to the answer by @AJNeufeld:</p> <ol> <li>Made <code>Node</code> class &amp; its attributes private</li> <li>Added <code>__slots__</code> to save memory</li> <li>Added docstrings for all methods - including one for class that explains the assumed structure and indexing</li> <li>Removed unnecessary attribute <code>self._args</code></li> <li>Added private helper methods: <ol> <li><code>_is_head(self, index)</code></li> <li><code>_is_tail(self, index)</code></li> <li><code>_get_values(self)</code></li> </ol></li> <li>Made <code>__repr__(self)</code> in accordance with Python Standard</li> <li>Added <code>__str__(self)</code> to represent "Linking values"</li> <li>Added iteration protocol <ul> <li>I think the way I built it is <code>O(n^2)</code> and wondering if there is a faster implementation?</li> <li>I did not account for the container size changing through iteration? Any hints on this?</li> <li>Also is anything ever put in the <code>__iter__(self)</code> method, or should it just trivially return the object?</li> </ul></li> </ol> <h1>Please find below the new implementation</h1> <pre><code>class Linkedlist: """A linear container data structure that provides O(1) time insertion/deletion of items to/from the head and tail of the sequence of values. Utilizes _Node object as underlying data structure ---------------------------------------------------- Structure of class is as follows: Index 0: 1st Node &lt;- Head Node Index 1: 2nd Node Index 2: 3rd Node ... Index n - 1: Nth Node &lt;- Tail Node ---------------------------------------------------- Methods: 1). __getitem__(self, index) Time Complexity: O(n) Space Complexity: O(1) 2). __delitem__(self, index) Time Complexity: O(n) Space Complexity: O(1) 3). __iter__(self) Time Complexity: O(n^2) Space Complexity: O(1) 4). __repr__(self) Time Complexity: O(n) Space Complexity: O(n) 5). __str__(self) Time Complexity: O(n) Space Complexity: O(n) 6). append(self, value) Time Complexity: O(1) Space Complexity: O(1) 7). prepend(self, value) Time Complexity: O(1) Space Complexity: O(1) 8). insert(self, value, index) Time Complexity: O(n) Space Complexity: O(n) """ class _Node: """Data structure used to implement Linked List - has fields: 1. Data value 2. Pointer to next node """ def __init__(self, value=None): __slots__ = ('_value', '_next') self._value = value self._next = None def __init__(self, *args): self.head = self._Node() self.tail = self.head self._size = 0 self._iter_counter = 1 for val in args: self.append(val) def __len__(self): """Returns number of non-empty nodes in Linked List""" return self._size def _get_prev_node(self, index): """helper method to obtain Node previous to given index in O(n) time i.e. if index is 1, will return 1st Node i.e. if size of linked list is 6 &amp; index is -3, will return 4th Node """ if index &lt; 0: index += self._size cur_node = self.head prev_node_number = 1 while prev_node_number &lt; index: cur_node = cur_node._next prev_node_number += 1 return cur_node def _is_head(self, index): """Helper method to determine if given index is head node""" if index &gt;= self._size or index &lt; -self._size: raise IndexError return index == 0 or index == -self._size def _is_tail(self, index): """Helper method to determine if given index is tail node""" if index &gt;= self._size or index &lt; -self._size: raise IndexError return index == -1 or index == self._size - 1 def _get_values(self): """Helper method to generate string values of all node values""" cur_node = self.head for _ in range(self._size): yield str(cur_node._value) cur_node = cur_node._next def __getitem__(self, index): """Getter method to obtain value of a node at given index in O(1) time - this is considering that finding the node is encapsulated by helper method self._get_prev_node(index) """ if self._is_head(index): return self.head._value else: prev_node = self._get_prev_node(index) cur_node = prev_node._next return cur_node._value def __delitem__(self, index): """Method to delete value of a node at given index in O(1) time - this is considering that finding the node is encapsulated by helper method self._get_prev_node(index) """ if self._is_head(index): self.head = self.head._next else: prev_node = self._get_prev_node(index) prev_node._next = prev_node._next._next if self._is_tail(index): self.tail = prev_node self._size -= 1 def __iter__(self): """Returns iterator object which user can iterate through""" return self def __next__(self): """Loops through iterator returning each Node value""" # TODO See if there's a way to improve iteration speed from quadratic to linear cur_node = self.head if self._iter_counter &gt; self._size: self._iter_counter = 1 raise StopIteration prev_node = self._get_prev_node(self._iter_counter) self._iter_counter += 1 return prev_node._value def __repr__(self): """Provides valid Python expression that can be used to recreate an object with the same value""" values = ', '.join(self._get_values()) cls_name = type(self).__name__ return f'{cls_name}({values})' def __str__(self): """Displays printable representation of Linked List""" return ' -&gt; '.join(self._get_values()) def append(self, value): """Inserts node with given value to end of Linked List in O(1) time""" if self.head._value is None: self.head._value = value else: new_node = self._Node(value) self.tail._next = new_node self.tail = new_node self._size += 1 def prepend(self, value): """Inserts node with given value to front of Linked List in O(1) time""" if self.head._value is None: self.head._value = value else: new_node = self._Node(value) new_node._next = self.head self.head = new_node self._size += 1 def insert(self, value, index): """Inserts node with given value at a given index of Linked List in O(n) time. If insertion occurs at head or tail of Linked List, operation becomes O(1). n := len(self) * Index must be in interval [-n, n] """ if abs(index) &gt; self._size: raise IndexError elif self._is_head(index): self.prepend(value) elif index == self._size: self.append(value) else: prev_node = self._get_prev_node(index) new_node = self._Node(value) new_node._next = prev_node._next prev_node._next = new_node self._size += 1 def main(): def disp_attributes(lnk_list_obj): print(f'Linked List: {lnk_list_obj}') print(f'\tSize: {len(lnk_list_obj)}') print(f'\tHead node value: {lnk_list_obj.head._value}') print(f'\tTail node value: {lnk_list_obj.tail._value}') print('&lt;&lt; Instantiate empty Linked List &gt;&gt;') lnk = Linkedlist() disp_attributes(lnk) print('&lt;&lt; Append -3, 1, 0 to Linked List &gt;&gt;') values = -3, 1, 0 for val in values: lnk.append(val) disp_attributes(lnk) print('&lt;&lt; Prepend -12 to Linked List &gt;&gt;') lnk.prepend(-12) disp_attributes(lnk) print(f'Linked List value at first Node: {lnk[0]}') print('&lt;&lt; Instantiate Linked List with values 1, -2, -6, 0, 2 &gt;&gt;') lnk2 = Linkedlist(1, -2, -6, 0, 2) disp_attributes(lnk2) print('&lt;&lt; Prepend 6 to Linked List &gt;&gt;') lnk2.prepend(6) disp_attributes(lnk2) print(f'Linked List value at second Node: {lnk2[1]}') print('&lt;&lt; Delete 1st Node &gt;&gt;') del lnk2[0] disp_attributes(lnk2) print('&lt;&lt; Delete Last Node &gt;&gt;') del lnk2[-1] disp_attributes(lnk2) print('&lt;&lt; Append 7 to LinkedList &gt;&gt;') lnk2.append(7) disp_attributes(lnk2) print('&lt;&lt; Delete 3rd Node &gt;&gt;') del lnk2[2] disp_attributes(lnk2) print('&lt;&lt; Insert -10 before 2nd Node &gt;&gt;') lnk2.insert(-10, 1) disp_attributes(lnk2) if __name__ == '__main__': main() </code></pre>
[]
[ { "body": "<p>I think you’ve misunderstood the purpose of <code>\"\"\"docstrings\"\"\"</code>. If someone using your code types <code>help(LinkedList)</code>, they will get the contents of the class’s docstring and the public member docstrings, formatted together into one long output string describing (ideally...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T07:25:12.843", "Id": "207192", "Score": "5", "Tags": [ "python", "object-oriented", "python-3.x", "linked-list" ], "Title": "Implementation of Singly Linked List" }
207192
<p>So as the title states, I am trying to add a specific Items to an ArrayList if they not already exist. So here is how the Array starts.</p> <pre><code>[a, b, c, d, e, f] </code></pre> <p>I have this items inside the ArrayList</p> <p>and I'm gonna add some items after the item <code>d</code> if it doesn't exist already in a pattern.</p> <pre><code>[a, b, c, d, x, y, z, e, f] </code></pre> <p>I had a successful run of the items I have provided resulting with the output</p> <pre><code>[a, b, c, d, e, f] Adding string x to index 3 Adding string y to index 4 Adding string z to index 5 [a, b, c, d, x, y, z, e, f] String already exists x skipping... String already exists y skipping... String already exists z skipping... [a, b, c, d, x, y, z, e, f] </code></pre> <p>here is the code that I have created to get this result</p> <pre><code>public static void addStringIfNotAlreadyExists(List&lt;String&gt; list, int index, String... strings) { for (String s : strings) { if (!list.get(index + 1).equals(s)) { System.out.println("Adding string " + s + " to index " + index); list.add(index + 1, s); } else { System.out.println("String already exists " + s + " skipping..."); } index++; } } </code></pre> <p>It's not the best code I have written but it works.</p> <p>and here is how I call it for the test.</p> <pre><code>public static void main(String[] args) { List&lt;String&gt; list = new ArrayList&lt;&gt;(); list.add("a"); list.add("b"); list.add("c"); list.add("d"); list.add("e"); list.add("f"); System.out.println(list); addStringIfNotAlreadyExists(list, 3, "x", "y", "z"); System.out.println(list); addStringIfNotAlreadyExists(list, 3, "x", "y", "z"); System.out.println(list); } </code></pre> <p>What I am curious in if this code can fail in certain tests, Or how I can improve the code.</p>
[]
[ { "body": "<p>A few things come to mind:</p>\n\n<ul>\n<li>First of all, as you access the list at <code>index + 1</code> without any bounds check, the code will fail if a user attempts to use the method to add elements to the end of the string. You should probably handle that gracefully.</li>\n<li>Changing the ...
{ "AcceptedAnswerId": "207210", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T07:49:22.987", "Id": "207194", "Score": "1", "Tags": [ "java", "array" ], "Title": "Add Strings in-between index of ArrayList if not already exists" }
207194
<p>I've read various posts about how letting users to upload files can create vulnerabilities to your website such as a user injecting PHP code in an image. </p> <p>So I've created a small test project where you can upload (outside of web root) and see uploaded images keeping it as simple as I could having in mind security but I'm not an expert and it would be really helpful if you could answer some of my questions and tell me if something could be done better.</p> <ol> <li><p>Do you spot anything wrong regarding permissions?</p></li> <li><p>Are the checks that I do in <code>upload_images.php</code> to check that the files that are being uploaded are images of the allowed formats sufficient? Could I do something better?</p></li> <li><p>Fetching multiple images using <code>base64_encode(file_get_contents($images[$i]))</code> seems a bit slow and also the string that is being put inside img src is huge...can this be a problem (for example images don't appear in xiaomis MIUI browser)? Is there a better alternative?</p></li> <li><p>Let's say that a malicious image bypasses my checks during uploading. When I fetch an images using the following PHP code get the response in js using ajax and then append it to the dom to be shown to the user using <code>&lt;img src='data:"+ data.extention[i] +";base64," + data.images[i] + "'&gt;</code> is it possible to be harmful in any way?</p></li> <li><p>Is storing images outside of root trying to prevent access of malicious users too much of a hassle? Is it better maybe (security-speed-browser compatibility wise) to just store them inside root and make use of .htaccess to prevent someone from doing harm? Would an .htaccess like the following ( secure_images/.htaccess ) be sufficient for that purpose?</p></li> </ol> <h2>Structure</h2> <pre class="lang-none prettyprint-override"><code>/ public_html (root) 755 .htaccess 444 index.php 644 images.php 644 javascript 755 show_images.js 644 upload.js 644 php_scripts 755 fetch_images.php 600 upload_images.php 600 logo.png 644 secure_images .htaccess 444 201811051007191220027687.jpg 644 20181105100719574368017.jpeg 644 secure_php_scripts 500 fetch_images.php 600 upload_images.php 600 </code></pre> <h2><code>public_html/.htaccess</code></h2> <pre><code>#Deny access to .htaccess files &lt;Files .htaccess&gt; order allow,deny deny from all &lt;/Files&gt; #Enable the DirectoryIndex Protection, preventing directory index listings and defaulting Options -Indexes DirectoryIndex index.html index.php /index.php #Trackback Spam protection RewriteCond %{REQUEST_METHOD} =POST RewriteCond %{HTTP_USER_AGENT} ^.*(opera|mozilla|firefox|msie|safari).*$ [NC] RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /.+/trackback/?\ HTTP/ [NC] RewriteRule .? - [F,NS,L] </code></pre> <h2>Upload images related files</h2> <h3><code>public_html/index.php</code></h3> <pre class="lang-html prettyprint-override"><code>&lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Image upload security test&lt;/title&gt; &lt;meta name="description" content="Image upload security test"&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="upload_form" method="post" enctype="multipart/form-data"&gt; Select image to upload: &lt;input type="file" name="filesToUpload[]" id="filesToUpload" multiple&gt; &lt;input type="submit" value="Upload Image" name="submit"&gt; &lt;/form&gt; &lt;a href="images.php"&gt;See images&lt;/a&gt; &lt;script src="js/upload.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <h3><code>public_html/javascript/upload.js</code></h3> <pre class="lang-javascript prettyprint-override"><code>$("#upload_form").submit(function(e) { e.preventDefault(); $.ajax({ url:"../php_scripts/upload_images.php", method:"POST", data:new FormData(this), processData: false, contentType: false, dataType:"JSON", success:function(data) { if(data.outcome) { console.log("Images succesfully uploaded"); } else { console.log(data.msg); } } }); }); </code></pre> <h3><code>public_html/php_scripts/upload_images.php</code></h3> <pre class="lang-php prettyprint-override"><code>&lt;?php include_once($_SERVER['DOCUMENT_ROOT'] . "/../secure_php_scripts/upload_images.php"); </code></pre> <h3><code>secure_php_scripts/upload_images.php</code></h3> <pre class="lang-php prettyprint-override"><code>&lt;?php $uploaded_images[0]["path"] = null; try { $isValid = validateArray($_FILES['filesToUpload']); if($isValid[0]) { $data['outcome'] = true; $data['msg'] = "Images uploaded successfully"; for($i=0; $i&lt;count($_FILES['filesToUpload']['tmp_name']); $i++) { $new_name = date('YmdHis',time()).mt_rand() . "." . pathinfo($_FILES['filesToUpload']['name'][$i], PATHINFO_EXTENSION); $path_to_be_uploaded_to = $_SERVER['DOCUMENT_ROOT'] . "/../secure_images/" . $new_name; if(!chmod($_FILES['filesToUpload']['tmp_name'][$i], 0644) || !move_uploaded_file($_FILES['filesToUpload']['tmp_name'][$i], $path_to_be_uploaded_to) ) { $data['outcome'] = false; $data['msg'] = "There was an error uploading your file"; break; } else { $uploaded_images[$i]["path"] = $path_to_be_uploaded_to; } } } else { $data['outcome'] = false; $data['msg'] = $isValid[1]; } echo json_encode($data); } catch (Exception $e) { //If there is an exception delete all uploaded images if($uploaded_images[0]["path"] != null) { foreach($uploaded_images as $item) { if( file_exists($item["path"]) ) { unlink($item["path"]); } } } // Also delete all uploaded files from tmp folder (Files user uploads first go there) foreach($_FILES['filesToUpload']['tmp_name'] as $item) { if( file_exists($item) ) { unlink($item); } } $data['outcome'] = false; $data['msg'] = "There was an error please try again later"; echo json_encode($data); } // Create a new blank image using imagecreatetruecolor() // Copy our image to the new image using imagecopyresampled() // And also add a logo in the process function add_watermark($path_to_img, $ext) { try { if($ext == 'png') { $img = imagecreatefromjpeg($path_to_img); } else { $img = imagecreatefromjpeg($path_to_img); } $stamp = imagecreatefrompng('logo.png'); // Set the margins for the stamp and get the height/width of the stamp image $marge_right = 10; $marge_bottom = 10; $sx = imagesx($stamp); $sy = imagesy($stamp); list($width, $height) = getimagesize($path_to_img); $dest_imagex = 900;//width of new image $dest_imagey = 900;//height of new image $dest_image = imagecreatetruecolor($dest_imagex, $dest_imagey);//create new image imagecopyresampled($dest_image, $img, 0, 0, 0, 0, $dest_imagex, $dest_imagey, $width,$height);//#im to $dest_image //Now $dest_image is an image of 800x800 // Copy the stamp image onto our photo using the margin offsets and the photo width to calculate positioning of the stamp. imagecopy($dest_image, $stamp, $dest_imagex - $sx - $marge_right, $dest_imagey - $sy - $marge_bottom, 0, 0, $sx, $sy); $filename = $path_to_img; if($ext == 'png') { if(!imagepng($dest_image, $filename)) { return false;} } else { if(!imagejpeg($dest_image, $filename)) { return false;} } return true; } catch (Exception $e) { return false; } } // Checks // if the element provided is a 2D array with the expected elements (multiple pictures per upload) // if there is an error // if file extentions are the allowed ones // is each file size is bellow 1GB // if the file number is less than 16 // if file exists and if it was uploaded via HTTP POST function validateArray($array) { try{ if( $array &amp;&amp; is_array($array) ) { if( !is_array($array['name'])) { return [false, "Wrong array format"]; } else { $pic_number = count($array['name']); } if($pic_number &gt; 15) { return [false, "Maximum image number allowed is 15"]; } if( !is_array($array['type']) || count($array['type']) != $pic_number || !is_array($array['tmp_name']) || count($array['tmp_name']) != $pic_number || !is_array($array['error']) || count($array['error']) != $pic_number || !is_array($array['size']) || count($array['size']) != $pic_number ) { return [false, "Wrong array format"]; } $allowedExts = array('png', 'jpeg', 'jpg'); $allowedExts2 = array('image/png', 'image/jpg', 'image/jpeg'); $fileinfo = finfo_open(FILEINFO_MIME_TYPE); for($i=0; $i&lt;count($array['name']); $i++) { if( is_array($array['name'][$i]) || is_array($array['tmp_name'][$i]) || is_array($array['error'][$i]) || is_array($array['size'][$i]) ) { return [false, "Wrong array format"]; } $ext = pathinfo($array['name'][$i], PATHINFO_EXTENSION); if( !in_array($ext, $allowedExts) ) { return [false, "Only PNG JPEG JPG images are allowed"]; } if(!file_exists($array['tmp_name'][$i]) || !is_uploaded_file($array['tmp_name'][$i])) { return [false, "File doesn't exists, try again"]; } if(!is_uploaded_file($array['tmp_name'][$i])) { return [false, "File has to be uploaded using our form"]; } if(!exif_imagetype($array['tmp_name'][$i])) { return [false, "Only images allowed"]; } if(filesize($array['tmp_name'][$i]) &lt; 12) { return [false, "All images has to be more than 11 bytes"]; } if (!in_array(finfo_file($fileinfo, $array['tmp_name'][$i]), $allowedExts2)) { return [false, "Only PNG JPEG JPG images are allowed"]; } if($array['error'][$i] !== 0) { return [false, "File error"]; } if($array['size'][$i] &gt; 1000000) { return [false, "Maximum image size allowed is 1GB"]; } if(!add_watermark($array['tmp_name'][$i], $ext)) { return [false, "There was an error uploading your file"]; } } } else { return [false, "Element provided is not a valid array"];} return [true, "Chill dude images are ok"]; } catch (Exception $e) { return [false, "There was an error please try again later"]; } } </code></pre> <h2>Show images related files</h2> <h3><code>public_html/images.php</code></h3> <pre class="lang-html prettyprint-override"><code>&lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Image upload security test&lt;/title&gt; &lt;meta name="description" content="Image upload security test"&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"&gt;&lt;/script&gt; &lt;style&gt; section{display:block;text-align:center;} content{display:inline-block;margin:10px;height:400px;width:400px;} content img{max-height:100%;max-width:100%;min-height:100%;min-width:100%;} &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;section&gt; &lt;/section&gt; &lt;script src="js/show_images.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <h3><code>public_html/javascript/show_images.js</code></h3> <pre class="lang-javascript prettyprint-override"><code>window.onload = function() { $.ajax({ url:"../php_scripts/fetch_images.php", method:"POST", dataType:"JSON", success:function(data) { if(data.outcome) { if(data.images) { if(data.images.length &gt; 0) { let text = []; for( let i=0; i&lt; data.images.length; i++) { text[i] = "&lt;content&gt;&lt;img src='data:"+ data.extention[i] +";base64," + data.images[i] + "'&gt;&lt;/content&gt;"; } $("section").append(text); } } else {console.log("no images found"); } } else { console.log("An error occured please try again later"); } } }); }; </code></pre> <h3><code>public_html/php_scripts/fetch_images.php</code></h3> <pre class="lang-php prettyprint-override"><code>&lt;?php include_once($_SERVER['DOCUMENT_ROOT'] . "/../secure_php_scripts/fetch_images.php"); </code></pre> <h3><code>secure_php_scripts/fetch_images.php</code></h3> <pre class="lang-php prettyprint-override"><code>&lt;?php try { $data["outcome"] = true; $directory = $_SERVER['DOCUMENT_ROOT'] . "/../secure_images/"; $images = glob($directory . "*.{[jJ][pP][gG],[pP][nN][gG],[jJ][pP][eE][gG]}", GLOB_BRACE); $fileinfo = finfo_open(FILEINFO_MIME_TYPE); for ($i = 0; $i &lt; count($images); $i++) { $extention = finfo_file($fileinfo, $images[$i]); header('Content-Type: ' . $extention); $data["extention"][$i] = $extention; $data["images"][$i] = base64_encode(file_get_contents($images[$i])); } echo json_encode($data); } catch(Exception $e) { $data["outcome"] = false; $data["images"][0] = []; echo json_encode($data); } </code></pre> <h3><code>secure_images/.htaccess</code></h3> <pre><code>#Deny access to .htaccess files &lt;Files .htaccess&gt; order allow,deny deny from all &lt;/Files&gt; #Enable the DirectoryIndex Protection, preventing directory index listings and defaulting Options -Indexes DirectoryIndex index.html index.php /index.php #Securing directories: Remove the ability to execute scripts AddHandler cgi-script .php .pl .py .jsp .asp .htm .shtml .sh .cgi Options -ExecCGI </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T10:03:42.453", "Id": "399848", "Score": "2", "body": "I would recommend to split your post into several smaller questions. Uploading images is one thing while displaying is another." }, { "ContentLicense": "CC BY-SA 4.0", ...
[ { "body": "<p>First, to your questions</p>\n\n<blockquote>\n <p>Do you spot anything wrong regarding permissions?</p>\n</blockquote>\n\n<p>Overkill. Permissions has very little to do with web-servers, as there is only one user - one under which a web-server (or a php process) runs. So it doesn't really matter ...
{ "AcceptedAnswerId": "207422", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T08:54:40.490", "Id": "207197", "Score": "3", "Tags": [ "javascript", "php", "security", "image", ".htaccess" ], "Title": "Uploading and showing images securely" }
207197
<p>We implemented a small dependency injection mechanism which we use in our project. Now after 2 years of developing our project we need our classes to know who instantiated them via dependency injection. Therefore we pass to the constructor of every class which is "injectable" a property called creator. To achieve this we had two options:</p> <ul> <li>create a super-class which every "injectable" has to extend</li> <li>create an interface which every "injectable" has to implement</li> </ul> <p>Both options had downsides but we decided to go with the second option because we didn't want to force classes to extend "injectable" which do not have to do anything with "injection" and only need to extend "injectable" because we can not do multiple inheritance. This lead to the problem that we had to touch every class and clutter them with properties which are only used for DI. Since we use TypeScript we tried to do something with a class decorator, we got the idea from their last example on <a href="https://www.typescriptlang.org/docs/handbook/decorators.html#class-decorators" rel="nofollow noreferrer">https://www.typescriptlang.org/docs/handbook/decorators.html#class-decorators</a>.</p> <p>This works quite well but there was the problem, that the creator property was not available in the constructor. Since you can not alter the constructor of an ES6 class we came up with the following solution:</p> <pre><code>export function injectable(Base) { return class extends Base { public _creator_; constructor(...args) { const creator = args.shift(); Base.prototype._creator_ = creator; super(...args); Base.prototype._creator_ = null; delete Base.prototype._creator_; this._creator_ = creator; } }; } </code></pre> <p>Now in the DI basically the following happens (this is more "pseudo-code" because we use TypeScript and the original code is a little bit more involved):</p> <pre><code>// "pseudo-code" because we use TypeScript and the original code is a little bit more involved class Container { static lookup(specifier, requester) { const instance = Container._find(specifier, requester._creator_); if (instance) { return instance; } // call to injectable is normally done by TypeScript class decorator const ExtendedBase = injectable(Container._findClassDefinition(specifier)); const newInstance = new ExtendedBase(requester._creator_); this._set(specifier, newInstance, creator); } static _find(specifier, creator) { // return the instance which belongs to the specifier if it's already created for the given creator } static _set(specifier, instance, creator) { // set the instance of a given specifier for the creator } static _findClassDefinition(specifier) { // find the class definition to a specifier } } class X { constructor() { // this is done by a property decorator by TypeScript this._injectedService = Container.lookup('injectedService', this); } run() { this._injectedService.doStuff(); } } class Main { constructor() { this._creator_ = getNextCreator(); this._x = Container.lookup('x', this._creator_); } run() { this._x.run(); } } const main = new Main(); main.run(); </code></pre> <p>At first glance, this works quite well for us but we are not quite sure if this is really a sophisticated solution or if we can run into troubles if there are concurrent calls to <code>DI.inject(X)</code>. We know that JavaScript is not multi-threaded but maybe there are problems with different contexts like WebWorkers or ServiceWorkers etc. We are especially worried because we touch the prototype of the base class. So our question is mostly around the <code>function injectable</code>.</p> <p>Would be great to get some feedback of you so we can evaluate pros and cons of our approach :-)</p> <p><strong>EDIT</strong>: updated the second code snippet due to @Blindman67's feedback (see the comments of the question)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T12:44:27.277", "Id": "399885", "Score": "0", "body": "Could you clarify the second snippet because as it is it makes no sense... Is the last line meant to be `const xInstance = DI.inject(X)` and `DI.inject` thus should be `static`,...
[]
{ "AcceptedAnswerId": null, "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T09:14:00.280", "Id": "207200", "Score": "3", "Tags": [ "javascript", "multithreading", "concurrency", "dependency-injection", "typescript" ], "Title": "Override prototype inside of constructor of ES6 class for dependency injection" }
207200
<p>I am pretty new to powershell and I'm not great at coding, but I have managed to cobble together code from around the net to help save time when removing old students accounts in AD.</p> <p>Code currently does the following;</p> <ul> <li>Takes leavers from .csv file</li> <li>Moves the leavers to leavers OU, Disables Account, and removes from all groups</li> <li>Moves their home folder to the Leavers Archive share</li> <li>Deletes their profiles .v5 and .v6 folders</li> </ul> <p>What I'm hoping is that someone can take a look at the code and possibly explain how it could be tidied and cleaned up and condensed if possible, We have 4 different shares split A-D, E-J, K-R, S-Z</p> <p>In order to do what I needed for each share I just duplicated the code for each share.</p> <p>Here's the code.</p> <pre><code>################################################################################ #Disables Student accounts for leavers and moves them to the leavers OU #Disables Parent Accounts, Strips groups, Moves to Parent Leavers OU ################################################################################ #Import users to be disabled ################################################################################ Import-Module ActiveDirectory #Create working directory #New-Item -ItemType directory "C:\LeaversExports" Import-Csv "C:\Leavers.csv" | ForEach-Object { $samAccountName = $_."samAccountName" Get-ADUser -Identity $samAccountName | Disable-ADAccount Write-host -ForegroundColor Green "$samAccountName Disabled" } ################################################################################ #Move users from SD1 to Leavers SD1 $SD1 = "OU=SD1,OU=Students,DC=Contoso,DC=ac,DC=uk" $SD1Leavers = "OU=Leavers SD1,OU=Students,OU=Leavers,DC=Contoso,DC=ac,DC=uk" Get-ADUser -filter {Enabled -eq $false } -SearchBase $SD1 -properties name,samaccountname,DistinguishedName,homedirectory,ProfilePath |select SamAccountName,homedirectory,ProfilePath | export-csv C:\LeaversExports\SD1_Leavers.csv -nti Search-ADAccount –AccountDisabled –UsersOnly –SearchBase $SD1 | Move-ADObject –TargetPath $SD1Leavers Write-Host -ForegroundColor Green "SD1 - Disabled users Moved" # Remove User from All Group Memberships $Users = Get-ADUser -SearchBase $SD1Leavers -Filter * Get-ADGroup -Filter * | Remove-ADGroupMember -Members $users -Confirm:$False $users = Get-ADUser -SearchBase $SD1Leavers -Filter * foreach($user in $users){ $groups = Get-ADPrincipalGroupMembership $user.SamAccountName | Where-Object {$_.name -NotLike '*Domain*'} foreach($group in $groups){ Remove-ADGroupMember -Identity $group -Members $user -erroraction silentlycontinue } } Write-Host -ForegroundColor Green "SD1 Leavers removed from all Groups" #Move SD1 Leavers Home Area to Archive $CSVPath = 'C:\LeaversExports\SD1_Leavers.csv' $NewHomeRoot = '\\FS1\A-D Leavers$\Leavers 18-19$' #$NewHomeLocal = 'D:\Data\Users' $Users = Import-Csv $CSVPath foreach( $User in $Users ){ $NewHome = Join-Path -Path $NewHomeRoot -ChildPath $User.SamAccountName Robocopy.exe $User.homedirectory $NewHome /MIR /MOVE } Write-Host -ForegroundColor Green "All SD1 Leavers Home Folders Moved to Archive" #Delete Profile Folders $CSVPath = 'C:\LeaversExports\SD1_Leavers.csv' $Users = Import-Csv $CSVPath $samAccountName = $Users.SamAccountName $profilepathv6 = $Users.ProfilePath + ".V6" $profilepathv5 = $Users.ProfilePath + ".V5" foreach( $User in $Users ){ if (Test-Path $profilepathv6){ Write-Host -ForegroundColor Yellow "$profilepathv6 Path Found" Remove-Item ($profilepathv6)-Force -Confirm:$false Write-Host -ForegroundColor Green "$profilepathv6 - has been deleted" } Else{ Write-Host -ForegroundColor Red ".V6 Path Not found - Skipped" } if (Test-Path $profilepathv5){ Write-Host -ForegroundColor Yellow "$profilepathv5 Path Found" Remove-Item ($profilepathv5)-Force -Confirm:$false Write-Host -ForegroundColor Green "$profilepathv5 - has been deleted" } Else{ Write-Host -ForegroundColor Red ".V5 Path Not found - Skipped" } } Write-Host -BackgroundColor Green -ForegroundColor Black "Profiles deleted" #Clean up working files #Remove-Item "C:\LeaversExports" -Force -recurse ################################################################################ ################################################################################ #Move users from SD2 to Leavers SD2 $SD2 = "OU=SD2,OU=Students,DC=Contoso,DC=ac,DC=uk" $SD2Leavers = "OU=Leavers SD2,OU=Students,OU=Leavers,DC=Contoso,DC=ac,DC=uk" Get-ADUser -filter {Enabled -eq $false } -SearchBase $SD2 -properties name,samaccountname,DistinguishedName,homedirectory,ProfilePath |select SamAccountName,homedirectory,ProfilePath | export-csv C:\LeaversExports\SD2_Leavers.csv -nti Search-ADAccount –AccountDisabled –UsersOnly –SearchBase $SD2 | Move-ADObject –TargetPath $SD2Leavers Write-Host -ForegroundColor Green "SD2 - Disabled users Moved" # Remove User from All Group Memberships $Users = Get-ADUser -SearchBase $SD2Leavers -Filter * Get-ADGroup -Filter * | Remove-ADGroupMember -Members $users -Confirm:$False $users = Get-ADUser -SearchBase $SD2Leavers -Filter * foreach($user in $users){ $groups = Get-ADPrincipalGroupMembership $user.SamAccountName | Where-Object {$_.name -NotLike '*Domain*'} foreach($group in $groups){ Remove-ADGroupMember -Identity $group -Members $user -erroraction silentlycontinue } } Write-Host -ForegroundColor Green "SD2 Leavers removed from all Groups" #Move SD2 Leavers Home Area to Archive $CSVPath = 'C:\LeaversExports\SD2_Leavers.csv' $NewHomeRoot = '\\FS1\E-J Leavers$\Leavers 18-19' #$NewHomeLocal = 'D:\Data\Users' $Users = Import-Csv $CSVPath foreach( $User in $Users ){ $NewHome = Join-Path -Path $NewHomeRoot -ChildPath $User.SamAccountName Robocopy.exe $User.homedirectory $NewHome /MIR /MOVE } Write-Host -ForegroundColor Green "All SD2 Leavers Home Folders Moved to Archive" #Delete Profile Folders $CSVPath = 'C:\LeaversExports\SD2_Leavers.csv' $Users = Import-Csv $CSVPath $samAccountName = $Users.SamAccountName $profilepathv6 = $Users.ProfilePath + ".V6" $profilepathv5 = $Users.ProfilePath + ".V5" foreach( $User in $Users ){ if (Test-Path $profilepathv6){ Write-Host -ForegroundColor Yellow "$profilepathv6 Path Found" Remove-Item ($profilepathv6)-Force -Confirm:$false Write-Host -ForegroundColor Green "$profilepathv6 - has been deleted" } Else{ Write-Host -ForegroundColor Red ".V6 Path Not found - Skipped" } if (Test-Path $profilepathv5){ Write-Host -ForegroundColor Yellow "$profilepathv5 Path Found" Remove-Item ($profilepathv5)-Force -Confirm:$false Write-Host -ForegroundColor Green "$profilepathv5 - has been deleted" } Else{ Write-Host -ForegroundColor Red ".V5 Path Not found - Skipped" } } Write-Host -BackgroundColor Green -ForegroundColor Black "Profiles deleted" #Clean up working files #Remove-Item "C:\LeaversExports" -Force -recurse ################################################################################ ################################################################################ #Move users from SD3 to Leavers SD3 $SD3 = "OU=SD3,OU=Students,DC=Contoso,DC=ac,DC=uk" $SD3Leavers = "OU=Leavers SD3,OU=Students,OU=Leavers,DC=Contoso,DC=ac,DC=uk" Get-ADUser -filter {Enabled -eq $false } -SearchBase $SD3 -properties name,samaccountname,DistinguishedName,homedirectory,ProfilePath |select SamAccountName,homedirectory,ProfilePath | export-csv C:\LeaversExports\SD3_Leavers.csv -nti Search-ADAccount –AccountDisabled –UsersOnly –SearchBase $SD3 | Move-ADObject –TargetPath $SD3Leavers Write-Host -ForegroundColor Green "SD3 - Disabled users Moved" # Remove User from All Group Memberships $Users = Get-ADUser -SearchBase $SD3Leavers -Filter * Get-ADGroup -Filter * | Remove-ADGroupMember -Members $users -Confirm:$False $users = Get-ADUser -SearchBase $SD3Leavers -Filter * foreach($user in $users){ $groups = Get-ADPrincipalGroupMembership $user.SamAccountName | Where-Object {$_.name -NotLike '*Domain*'} foreach($group in $groups){ Remove-ADGroupMember -Identity $group -Members $user -erroraction silentlycontinue } } Write-Host -ForegroundColor Green "SD3 Leavers removed from all Groups" #Move SD3 Leavers Home Area to Archive $CSVPath = 'C:\LeaversExports\SD3_Leavers.csv' $NewHomeRoot = '\\FS2\K-R Leavers$\Leavers 18-19' #$NewHomeLocal = 'D:\Data\Users' $Users = Import-Csv $CSVPath foreach( $User in $Users ){ $NewHome = Join-Path -Path $NewHomeRoot -ChildPath $User.SamAccountName Robocopy.exe $User.homedirectory $NewHome /MIR /MOVE } Write-Host -ForegroundColor Green "All SD3 Leavers Home Folders Moved to Archive" #Delete Profile Folders $CSVPath = 'C:\LeaversExports\SD3_Leavers.csv' $Users = Import-Csv $CSVPath $samAccountName = $Users.SamAccountName $profilepathv6 = $Users.ProfilePath + ".V6" $profilepathv5 = $Users.ProfilePath + ".V5" foreach( $User in $Users ){ if (Test-Path $profilepathv6){ Write-Host -ForegroundColor Yellow "$profilepathv6 Path Found" Remove-Item ($profilepathv6)-Force -Confirm:$false Write-Host -ForegroundColor Green "$profilepathv6 - has been deleted" } Else{ Write-Host -ForegroundColor Red ".V6 Path Not found - Skipped" } if (Test-Path $profilepathv5){ Write-Host -ForegroundColor Yellow "$profilepathv5 Path Found" Remove-Item ($profilepathv5)-Force -Confirm:$false Write-Host -ForegroundColor Green "$profilepathv5 - has been deleted" } Else{ Write-Host -ForegroundColor Red ".V5 Path Not found - Skipped" } } Write-Host -BackgroundColor Green -ForegroundColor Black "Profiles deleted" #Clean up working files #Remove-Item "C:\LeaversExports" -Force -recurse ################################################################################ ################################################################################ #Move users from SD4 to Leavers SD4 $SD4 = "OU=SD4,OU=Students,DC=Contoso,DC=ac,DC=uk" $SD4Leavers = "OU=Leavers SD4,OU=Students,OU=Leavers,DC=Contoso,DC=ac,DC=uk" Get-ADUser -filter {Enabled -eq $false } -SearchBase $SD4 -properties name,samaccountname,DistinguishedName,homedirectory,ProfilePath |select SamAccountName,homedirectory,ProfilePath | export-csv C:\LeaversExports\SD4_Leavers.csv -nti Search-ADAccount –AccountDisabled –UsersOnly –SearchBase $SD4 | Move-ADObject –TargetPath $SD4Leavers Write-Host -ForegroundColor Green "SD4 - Disabled users Moved" # Remove User from All Group Memberships $Users = Get-ADUser -SearchBase $SD4Leavers -Filter * Get-ADGroup -Filter * | Remove-ADGroupMember -Members $users -Confirm:$False $users = Get-ADUser -SearchBase $SD4Leavers -Filter * foreach($user in $users){ $groups = Get-ADPrincipalGroupMembership $user.SamAccountName | Where-Object {$_.name -NotLike '*Domain*'} foreach($group in $groups){ Remove-ADGroupMember -Identity $group -Members $user -erroraction silentlycontinue } } Write-Host -ForegroundColor Green "SD4 Leavers removed from all Groups" #Move SD4 Leavers Home Area to Archive $CSVPath = 'C:\LeaversExports\SD4_Leavers.csv' $NewHomeRoot = '\\FS2\S-Z Leavers$\Leavers 18-19' #$NewHomeLocal = 'D:\Data\Users' $Users = Import-Csv $CSVPath foreach( $User in $Users ){ $NewHome = Join-Path -Path $NewHomeRoot -ChildPath $User.SamAccountName Robocopy.exe $User.homedirectory $NewHome /MIR /MOVE } Write-Host -ForegroundColor Green "All SD4 Leavers Home Folders Moved to Archive" #Delete Profile Folders $CSVPath = 'C:\LeaversExports\SD4_Leavers.csv' $Users = Import-Csv $CSVPath $samAccountName = $Users.SamAccountName $profilepathv6 = $Users.ProfilePath + ".V6" $profilepathv5 = $Users.ProfilePath + ".V5" foreach( $User in $Users ){ if (Test-Path $profilepathv6){ Write-Host -ForegroundColor Yellow "$profilepathv6 Path Found" Remove-Item ($profilepathv6)-Force -Confirm:$false Write-Host -ForegroundColor Green "$profilepathv6 - has been deleted" } Else{ Write-Host -ForegroundColor Red ".V6 Path Not found - Skipped" } if (Test-Path $profilepathv5){ Write-Host -ForegroundColor Yellow "$profilepathv5 Path Found" Remove-Item ($profilepathv5)-Force -Confirm:$false Write-Host -ForegroundColor Green "$profilepathv5 - has been deleted" } Else{ Write-Host -ForegroundColor Red ".V5 Path Not found - Skipped" } } Write-Host -BackgroundColor Green -ForegroundColor Black "Profiles deleted" #Clean up working files #Remove-Item "C:\LeaversExports" -Force -recurse ################################################################################ </code></pre> <p>So I haven't been able to test this code just yet but could you take a look and let me know if what I have done looks correct based on your explanation of a Function.</p> <pre><code>function Cleanup-Shares { Param( [Parameter(mandatory=$true)] [string]$ShareName, [String]$OU, [String]$LeaversOU, [String]$CSVPath, [String]$NewHomeRoot, [String]$LExport ) } ########################################################################################################## #Disables Student accounts for leavers and moves them to the leavers OU #Disables Parent Accounts, Strips groups, Moves to Parent Leavers OU ########################################################################################################## #Import users to be disabled ######################################################################################################### Import-Module ActiveDirectory #Create working directory #New-Item -ItemType directory "C:\LeaversExports" Import-Csv "C:\Leavers.csv" | ForEach-Object { $samAccountName = $_."samAccountName" Get-ADUser -Identity $samAccountName | Disable-ADAccount Write-host -ForegroundColor Green "$samAccountName Disabled" } ########################################################################################################### #Move users from SD1 to Leavers SD1 Get-ADUser -filter {Enabled -eq $false } -SearchBase $OU -properties name,samaccountname,DistinguishedName,homedirectory,ProfilePath |select SamAccountName,homedirectory,ProfilePath | export-csv C:\LeaversExports\$LExport.csv -nti Search-ADAccount –AccountDisabled –UsersOnly –SearchBase $OU | Move-ADObject –TargetPath $LeaversOU Write-Host -ForegroundColor Green "Disabled users Moved" # Remove User from All Group Memberships $Users = Get-ADUser -SearchBase $LeaversOU -Filter * Get-ADGroup -Filter * | Remove-ADGroupMember -Members $users -Confirm:$False $users = Get-ADUser -SearchBase $LeaversOU -Filter * foreach($user in $users){ $groups = Get-ADPrincipalGroupMembership $user.SamAccountName | Where-Object {$_.name -NotLike '*Domain*'} foreach($group in $groups){ Remove-ADGroupMember -Identity $group -Members $user -erroraction silentlycontinue } } Write-Host -ForegroundColor Green "$users removed from all Groups" #Move Leavers Home Area to Archive $Users = Import-Csv $CSVPath foreach( $User in $Users ){ $NewHome = Join-Path -Path $NewHomeRoot -ChildPath $User.SamAccountName Robocopy.exe $User.homedirectory $NewHome /MIR /MOVE } Write-Host -ForegroundColor Green "All Leavers Home Folders Moved to Archive" #Delete Profile Folders $Users = Import-Csv $CSVPath $samAccountName = $Users.SamAccountName $profilepathv6 = $Users.ProfilePath + ".V6" $profilepathv5 = $Users.ProfilePath + ".V5" foreach( $User in $Users ){ if (Test-Path $profilepathv6){ Write-Host -ForegroundColor Yellow "$profilepathv6 Path Found" Remove-Item ($profilepathv6)-Force -Confirm:$false Write-Host -ForegroundColor Green "$profilepathv6 - has been deleted" } Else{ Write-Host -ForegroundColor Red ".V6 Path Not found - Skipped" } if (Test-Path $profilepathv5){ Write-Host -ForegroundColor Yellow "$profilepathv5 Path Found" Remove-Item ($profilepathv5)-Force -Confirm:$false Write-Host -ForegroundColor Green "$profilepathv5 - has been deleted" } Else{ Write-Host -ForegroundColor Red ".V5 Path Not found - Skipped" } Write-Host -BackgroundColor Green -ForegroundColor Black "Profiles deleted" } Cleanup-Shares -OU "OU=SD1,OU=Students,DC=Contoso,DC=ac,DC=uk" -LeaversOU "OU=Leavers SD1,OU=Students,OU=Leavers,DC=contoso,DC=ac,DC=uk" -CSVPath "C:\LeaversExports\SD1_Leavers.csv" -NewHomeRoot "\\FS1\A-D Leavers$\Leavers 18-19$" -LExport "SD1" Cleanup-Shares -OU "OU=SD2,OU=Students,DC=Contoso,DC=ac,DC=uk" -LeaversOU "OU=Leavers SD2,OU=Students,OU=Leavers,DC=contoso,DC=ac,DC=uk" -CSVPath "C:\LeaversExports\SD2_Leavers.csv" -NewHomeRoot "\\FS1\E-J Leavers$\Leavers 18-19" -LExport "SD2" Cleanup-Shares -OU "OU=SD3,OU=Students,DC=Contoso,DC=ac,DC=uk" -LeaversOU "OU=Leavers SD3,OU=Students,OU=Leavers,DC=contoso,DC=ac,DC=uk" -CSVPath "C:\LeaversExports\SD3_Leavers.csv" -NewHomeRoot "\\FS2\K-R Leavers$\Leavers 18-19" -LExport "SD3" Cleanup-Shares -OU "OU=SD4,OU=Students,DC=Contoso,DC=ac,DC=uk" -LeaversOU "OU=Leavers SD4,OU=Students,OU=Leavers,DC=contoso,DC=ac,DC=uk" -CSVPath "C:\LeaversExports\SD4_Leavers.csv" -NewHomeRoot "\\FS2\S-Z Leavers$\Leavers 18-19" -LExport "SD4" </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-31T12:20:13.630", "Id": "399838", "Score": "0", "body": "at this point `$profilepathv6 = $Users.ProfilePath + \".V6\"` the `$Users` variable otta contain a COLLECTION. that means your `.ProfilePath` will also be a collection. ///// i d...
[ { "body": "<p>Two solutions comes in my mind for shorting the script.</p>\n\n<p>Either use a function which contains the main code, and then on the end you can call the function with the necessary variables. In this with the different drive letters.</p>\n\n<p>The other way is to use a Foreach cycle in a list, a...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-31T12:09:40.003", "Id": "207202", "Score": "2", "Tags": [ "beginner", "csv", "powershell", "active-directory" ], "Title": "Powershell script to remove old student accounts from ActiveDirectory" }
207202
<p>I had to calculate the total number of days from overlapping date ranges (coming from MySQL in my case) excluding weekends and here is a working version of what I did.</p> <p>I am looking for a cleaner solution in terms of code quality and readability, ideally native <code>Carbon</code> solution.</p> <p>Any ideas how to improve this or maybe an entirely different approach to what I am trying to achieve? If not I'll leave it like this as it seems to work just fine so far.</p> <p>Sample input:</p> <pre><code>//date ranges (end date can be omitted) [ ['2018-10-25', '2018-11-10'], ['2018-10-25', '2018-10-30'], ['2018-10-29', '2018-10-30'], ['2018-10-29', '2018-11-07'], ['2018-10-31', '2018-11-03'], ['2018-10-31', '2018-11-10'] ] </code></pre> <p>Function part:</p> <pre><code>/** * @param array $intervals * * @param bool $excludeWeekendDays * * @return int */ public static function calculateDaysByIntervals(array $intervals, $excludeWeekendDays = false) { //placeholder to store dates $days = []; //now $now = Carbon::now()-&gt;toDateTimeString(); //loop over provided date ranges foreach ($intervals as $dateRange) { //skip interval if start date is missing if(!isset($dateRange[0])) { continue; } try { $startDate = Carbon::parse($dateRange[0])-&gt;toDateString(); $endDate = Carbon::parse($dateRange[1] ?? $now)-&gt;toDateString(); //get date periods $period = CarbonPeriod::between($startDate, $endDate); //only weekdays if($excludeWeekendDays) { $period-&gt;addFilter(function (Carbon $date) { return $date-&gt;isWeekday(); }); } foreach ($period as $date) { //get date $day = $date-&gt;format('Y-m-d'); //store day as array key $days[$day] = 1; } //skip interval on exception } catch(Throwable $x) { continue; } } return count($days); } </code></pre> <p>Unit test part</p> <pre><code>/** * @dataProvider additionProvider * * @param $dateRanges * @param $excludeWeekends * @param $expectedResult */ function testCalculateDaysByIntervals($dateRanges, $excludeWeekends, $expectedResult) { $actualResult = $this-&gt;DateTimeHelper-&gt;calculateDaysByIntervals($dateRanges, $excludeWeekends); $this-&gt;assertEquals($expectedResult, $actualResult); } /** * @return array */ public function additionProvider() { //put different sets of data return [ [ //date ranges [], false, //exclude weekends 0 //result in days without weekends ], [ //date ranges [ ['2018-10-6', '2018-10-7'] //Weekend ], true, //exclude weekends 0 //result in days without weekends ], [ //date ranges [ ['2018-10-6', '2018-10-7'] //Weekend ], false, //exclude weekends 2 //result in days with weekends ], [ //date ranges [ ['2018-10-1', '2018-10-1'] ], true, //exclude weekends 1 //result in days without weekends ], [ //date ranges [ ['2018-10-1', '2018-10-10'] ], true, //exclude weekends 8 //result in days without weekends ], [ //date ranges [ ['2018-10-25', '2018-10-30'], ['2018-10-29', '2018-10-30'], ['2018-10-29', '2018-11-07'], ['2018-10-31', '2018-11-03'], ['2018-10-31', '2018-11-10'], ], true, //exclude weekends 12 //result in days without weekends ], [ //date ranges [ ['2018-10-25', '2018-10-30'], ['2018-10-29', '2018-10-30'], ['2018-10-29', '2018-11-07'], ['2018-10-31', '2018-11-03'], ['2018-10-31', '2018-11-10'], ], false, //exclude weekends 17 //result in days with weekends ], [ //date ranges - invalid [ ['2018-10-25', '2017-10-05'], //start &gt; end ['2018-10-25', 'Fake'], //can't parse [null, 'Fake'], //will be skipped ], false, //exclude weekends 0 //result in days with weekends ], [ //date ranges [ //'' will parse to NOW and null will be replaced with NOW ['', null] ], false, //exclude weekends 1 //result in days with weekends ] ]; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T11:01:09.417", "Id": "399856", "Score": "0", "body": "You have a flag `compareDateOnly`. Do you really need it? If so, there should be a unit test covering it, otherwise delete it." }, { "ContentLicense": "CC BY-SA 4.0", ...
[ { "body": "<p>Upgrade to php7 in order to use strict typings. (I consider type safety a maintenance boost.)</p>\n\n<hr>\n\n<p>I recommend decreasing the amount of lines per method. Rule of thumb: A method should not be longer than 15 lines, as anything longer becomes hard to reason about. Try to figure out chun...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T10:08:35.297", "Id": "207206", "Score": "3", "Tags": [ "php", "datetime" ], "Title": "Count days from overlapping date periods with Carbon" }
207206
<p>I want to learn how/when/why to use the <em>GoF Design Patterns</em>. These last days are dedicated to the <em>Bridge Pattern</em>, which means: </p> <blockquote> <p>Decouple an abstraction from its implementation so that the two can vary independently.</p> </blockquote> <p>Everyone has a different understanding of this vague description, but if I well-understood the global point, it cuts an abstraction into multiple independant implementations which relies on each other, in a chain.</p> <hr> <p>On this premise, let's try to implement a <em>four-arrow remote control</em>. First, let's define what's awaited with interfaces:</p> <pre><code>public interface ITopBottomButtonsControl { void TopButtonPressed(); void BottomButtonPressed(); } public interface ILeftRightButtonsControl { void LeftButtonPressed(); void RightButtonPressed(); } public interface IRemoteControl : ILeftRightButtonsControl, ITopBottomButtonsControl { } </code></pre> <hr> <p>Here is an example of the BP implementation:</p> <pre><code>public class ChannelControl : ILeftRightButtonsControl { public void LeftButtonPressed() =&gt; Console.WriteLine("Previous channel"); public void RightButtonPressed() =&gt; Console.WriteLine("Next channel"); } public class ChapterControl : ILeftRightButtonsControl { public void LeftButtonPressed() =&gt; Console.WriteLine("Previous chapter"); public void RightButtonPressed() =&gt; Console.WriteLine("Next chapter"); } </code></pre> <hr> <pre><code>public abstract class BPRemoteControl : IRemoteControl { ILeftRightButtonsControl LeftRightControl { get; } public BPRemoteControl(ILeftRightButtonsControl leftRight) { LeftRightControl = leftRight; } public void LeftButtonPressed() =&gt; LeftRightControl.LeftButtonPressed(); public void RightButtonPressed() =&gt; LeftRightControl.RightButtonPressed(); public abstract void TopButtonPressed(); public abstract void BottomButtonPressed(); } </code></pre> <hr> <pre><code>public class SpeedControl : BPRemoteControl { public SpeedControl(ILeftRightButtonsControl leftRight) : base(leftRight) { } public override void BottomButtonPressed() =&gt; Console.WriteLine("Slow down"); public override void TopButtonPressed() =&gt; Console.WriteLine("Speed up"); } public class VolumeControl : BPRemoteControl { public VolumeControl(ILeftRightButtonsControl leftRight) : base(leftRight) { } public override void BottomButtonPressed() =&gt; Console.WriteLine("Volume down"); public override void TopButtonPressed() =&gt; Console.WriteLine("Volume up"); } </code></pre> <hr> <p>The fact is that, when I implemented this to test the pattern, it made me think back the <em>Entity Component System</em>. So, I tried to implement the same application, but this time with an ECS approach.<br> The classes <code>ChannelControl</code> and <code>ChapterControl</code> remains the same, but the rest is different:</p> <pre><code>public class SpeedControl : ITopBottomButtonsControl { public void BottomButtonPressed() =&gt; Console.Write("Slow down"); public void TopButtonPressed() =&gt; Console.WriteLine("Speed up"); } public class VolumeControl : ITopBottomButtonsControl { public void BottomButtonPressed() =&gt; Console.WriteLine("Volume down"); public void TopButtonPressed() =&gt; Console.WriteLine("Volume up"); } </code></pre> <hr> <pre><code>public class ECSRemoteController : IRemoteControl { private ITopBottomButtonsControl TopBottomButtonsComponent { get; } private ILeftRightButtonsControl LeftRightButtonsComponent { get; } public ECSRemoteController(ITopBottomButtonsControl topBottom, ILeftRightButtonsControl leftRight) { TopBottomButtonsComponent = topBottom; LeftRightButtonsComponent = leftRight; } public void TopButtonPressed() =&gt; TopBottomButtonsComponent.TopButtonPressed(); public void BottomButtonPressed() =&gt; TopBottomButtonsComponent.BottomButtonPressed(); public void LeftButtonPressed() =&gt; LeftRightButtonsComponent.LeftButtonPressed(); public void RightButtonPressed() =&gt; LeftRightButtonsComponent.RightButtonPressed(); } </code></pre> <hr> <p>Finally, these two solutions seems to be the same, with the following difference: </p> <blockquote> <p>The Bridge Pattern is vertically-organized: <code>S(a -&gt; b -&gt; c)</code><br> The Entity-Component-System is horizontally-organized: <code>S(a, b, c)</code></p> </blockquote> <p>Is there really a difference between these two solutions? When should one be prefered to the other?</p> <hr> <p><strong>HOW TO TEST:</strong> separate the two solutions into two folders <code>BridgePattern</code> and <code>EntityComponentPattern</code>, and fill the console application with the following code:</p> <pre><code> static void Main(string[] args) { BridgePattern(); Console.WriteLine(); EntityComponentSystem(); Console.ReadLine(); } static void BridgePattern() { Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("BridgePattern version"); Console.WriteLine("----------"); IRemoteControl TVRemoteControl = new BridgePattern.VolumeControl(new BridgePattern.ChannelControl()); IRemoteControl DVDRemoteControl = new BridgePattern.SpeedControl(new BridgePattern.ChapterControl()); Console.WriteLine($"1. {nameof(TVRemoteControl)}:"); UseRemoteControl(TVRemoteControl); Console.WriteLine($"2. {nameof(DVDRemoteControl)}:"); UseRemoteControl(DVDRemoteControl); } static void EntityComponentSystem() { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("EntityComponentSystem version"); Console.WriteLine("----------"); IRemoteControl TVRemoteControl = new EntityComponentSystem.ECSRemoteController(new EntityComponentSystem.VolumeControl(), new EntityComponentSystem.ChannelControl()); IRemoteControl DVDRemoteControl = new EntityComponentSystem.ECSRemoteController(new EntityComponentSystem.SpeedControl(), new EntityComponentSystem.ChapterControl()); Console.WriteLine($"1. {nameof(TVRemoteControl)}:"); UseRemoteControl(TVRemoteControl); Console.WriteLine($"2. {nameof(DVDRemoteControl)}:"); UseRemoteControl(DVDRemoteControl); } static void UseRemoteControl(IRemoteControl remoteControl) { remoteControl.LeftButtonPressed(); remoteControl.RightButtonPressed(); remoteControl.TopButtonPressed(); remoteControl.BottomButtonPressed(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T11:49:30.380", "Id": "399862", "Score": "5", "body": "I find it's very cool that you've created this code with volume and remote controls rather than with meaningless foos and bars ;-)" }, { "ContentLicense": "CC BY-SA 4.0",...
[ { "body": "<h2>Hybrid Pattern</h2>\n\n<p>The <em>bridge pattern</em> you have implemented is a combination of the <em>composite pattern</em> and <em>inheritance</em>. Why did you decide to let your <code>ILeftRightButtonsControl</code> implementation use composition and <code>ITopBottomButtonsControl</code> use...
{ "AcceptedAnswerId": "221096", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T10:21:06.653", "Id": "207207", "Score": "5", "Tags": [ "c#", "design-patterns", "comparative-review", "entity-component-system" ], "Title": "Bridge-Pattern or Entity-Component-System" }
207207
<p>I wanted to create a function which accepts a string &amp; a delimiter. Finds the small blocks of string separated by the delimiters and replace the block based on some logic.</p> <p>I have created a simple example below to represent the logic I am trying to write. I also tried to make sure that I handle all cases where the user can by-mistakely pass a lone delimiter.</p> <p>Eg. Usage: </p> <pre><code>findDelimitedBlocks(inString,"@@#") inString: @@#animal@@# is a great hunter, he likes @@#food@@#. outString: LION is a great hunter, he likes deer..... </code></pre> <p>API:</p> <pre><code>void main() { char queryInStringg[10000] = "@@#animal@@# is a great hunter, he likes @@#food@@#...."; printf("\nString Before [%s]",queryInStringg);fflush(stdout); findDelimitedBlocks(queryInStringg,"@@#"); printf("\nString After [%s]",queryInStringg);fflush(stdout); return 0; } int findDelimitedBlocks(char *inString, char *delimiter) { char string_Variable[5000] ; char outString[strlen(inString)+5000] ; long string_Variable_Index = 0 ; long inStringIndex = 0 ; long outStringIndex = 0 ; int logical_Variable = 0 ; long i_loop_counter = 0 ; long j_loop_counter = 0 ; long delimiter_Size = 0 ; memset(string_Variable, 0x00, sizeof(string_Variable)); memset(outString, 0x00, sizeof(outString)); delimiter_Size = strlen(delimiter); while(1) { if(inString[inStringIndex] == 0x00) { outString[outStringIndex] = 0x00; break; } if(inString[inStringIndex] == delimiter[0]) { for(i_loop_counter = 1 ; ; i_loop_counter++) { if(inString[inStringIndex+i_loop_counter] == 0x00) { logical_Variable = 0; break; } if(delimiter[i_loop_counter] == 0x00) { logical_Variable = 1; break; } if(inString[inStringIndex+i_loop_counter] != delimiter[i_loop_counter]) { logical_Variable = 0; break; } } if(logical_Variable == 1) { memset(string_Variable, 0x00, sizeof(string_Variable)); string_Variable_Index = 0; logical_Variable = 0; for(j_loop_counter = 0 ; ; j_loop_counter++) { if(inString[inStringIndex+delimiter_Size+j_loop_counter] == 0x00) { outString[outStringIndex++] = inString[inStringIndex]; break; } if(inString[inStringIndex+delimiter_Size+j_loop_counter] == delimiter[0]) { for(i_loop_counter = 1 ; ; i_loop_counter++) { if(delimiter[i_loop_counter] == 0x00) { logical_Variable = 1; break; } if(inString[inStringIndex+delimiter_Size+j_loop_counter+i_loop_counter] != delimiter[i_loop_counter] || inString[inStringIndex+delimiter_Size+j_loop_counter+i_loop_counter] == 0x00) { logical_Variable = 0; break; } } if(logical_Variable == 1) { string_Variable[string_Variable_Index] = 0x00; /*After Finding I will incorporate the rest of the replace logic*/ if(strcmp(string_Variable,"animal") == 0) { memset(string_Variable, 0x00, strlen(string_Variable)); sprintf(string_Variable,"LION"); } else if(strcmp(string_Variable,"food") == 0) { memset(string_Variable, 0x00, strlen(string_Variable)); sprintf(string_Variable,"deer"); } else { memset(string_Variable, 0x00, strlen(string_Variable)); sprintf(string_Variable,"IREPLACE"); } strcat(outString,string_Variable); outStringIndex += strlen(string_Variable); inStringIndex += string_Variable_Index+delimiter_Size+delimiter_Size - 1; break; } else { string_Variable[string_Variable_Index++] = inString[inStringIndex+delimiter_Size+j_loop_counter]; } } else { string_Variable[string_Variable_Index++] = inString[inStringIndex+delimiter_Size+j_loop_counter]; } } } else { outString[outStringIndex++] = inString[inStringIndex]; } } else { outString[outStringIndex++] = inString[inStringIndex] ; } inStringIndex ++ ; } memset(inString, 0x00, strlen(inString)); strcpy(inString,outString); return(0); } </code></pre> <p>I want to know </p> <ul> <li>If there are any more exceptions that I might have missed or there is any bug in the code?</li> <li>Is there a better/more efficient way to write the function?</li> </ul>
[]
[ { "body": "<h1>The interface is dangerous</h1>\n<p>Functions that write to user-provided memory absolutely need to know how much memory is valid, and not write beyond the bounds. I could write something like this:</p>\n<pre><code> char s[] = &quot;some string with tags&quot;;\n findDelimitedBlocks(s, &quot;@&q...
{ "AcceptedAnswerId": "207216", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T11:10:28.497", "Id": "207211", "Score": "0", "Tags": [ "c" ], "Title": "Function to find and replace delimited blocks of string" }
207211
<p>First of all, project Euler has been a great help for me to learn Clojure. I tried for months trying to get web projects going but ended up frustrated with and struggling with tooling and libraries more than anything else. The code below gives the solution to <a href="https://projecteuler.net/problem=49" rel="nofollow noreferrer">Problem 49</a> in Project Euler:</p> <blockquote> <p>The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are permutations of one another.</p> <p>There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence.</p> <p>What 12-digit number do you form by concatenating the three terms in this sequence?</p> </blockquote> <pre><code>;; gen-primes Taken from https://stackoverflow.com/a/7625207/466694 (defn gen-primes "Generates an infinite, lazy sequence of prime numbers" [] (let [reinsert (fn [table x prime] (update-in table [(+ prime x)] conj prime))] (defn primes-step [table d] (if-let [factors (get table d)] (recur (reduce #(reinsert %1 d %2) (dissoc table d) factors) (inc d)) (lazy-seq (cons d (primes-step (assoc table (* d d) (list d)) (inc d)))))) (primes-step {} 2))) (defn get-digits [num] (-&gt;&gt; [num []] (iterate (fn [[num digits]] (when (&gt; num 0) [(quot num 10) (conj digits (rem num 10))]))) (take-while some?) (last) (second))) (defn are-permutations-of-each-other? [num1 num2] (= (sort (get-digits num1)) (sort (get-digits num2)))) (let [four-digit-primes (-&gt;&gt; (gen-primes) (drop-while #(&lt; % 1000)) (take-while #(&lt; % 10000)) (apply sorted-set))] (-&gt;&gt; (for [i four-digit-primes j four-digit-primes] [i j]) (remove #(apply = %)) (filter #(apply are-permutations-of-each-other? %)) (filter (fn [[n1 n2]] (let [mx (max n1 n2) mn (min n1 n2) diff (- mx mn) next (+ mx diff)] (and (&lt; next 10000) (four-digit-primes next) (are-permutations-of-each-other? n1 next))))) (map sort) (distinct) (map #(cons (+ (second %) (- (second %) (first %))) %)) (map sort) (map #(map str %)) (map (partial apply str)) (second))) </code></pre> <p>For example, the last <code>let</code> expression is the result of tinkering for half an hour or so until I get the information I want out of it. Two questions:</p> <ol> <li>I've found threading macros (especially <code>-&gt;&gt;</code>) a pure joy to work with. But, is there such a thing as a threading expression that is too long?</li> <li>I know that this is throw-away coding, but what things can I do to improve this code to fit best practices? Are there things I'm doing wrong?</li> </ol>
[]
[ { "body": "<p>There's a few things that can be improved here:</p>\n\n<p>First, I'm not sure if you neglected it here or if you actually aren't using it, but every file should start with a call to <code>ns</code>. This sets the namespace that the code following it will be in so other files can <code>require</cod...
{ "AcceptedAnswerId": "207230", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T11:33:44.360", "Id": "207213", "Score": "2", "Tags": [ "programming-challenge", "clojure" ], "Title": "Project Euler #49: Find 12-digit number concatenating a three terms sequence" }
207213
<p>Currently I am working on reducing function calls in my tool.</p> <p>My function is called <strong>add_field_and_calc</strong></p> <pre><code> def add_field_and_calc( f_class, name_of_new_field, condition, field): """Creates new field, make selection and fills with specific value from selection""" arcpy.AddField_management(f_class, name_of_new_field, "TEXT", field_length = 100) arcpy.MakeFeatureLayer_management(f_class, temp) arcpy.SelectLayerByAttribute_management(temp, "NEW_SELECTION", condition) try: with arcpy.da.UpdateCursor(temp, [field, name_of_new_field]) as cursor: for row in cursor: row[1] = row[0] cursor.updateRow(row) except RuntimeError: print(row[1]) del row,cursor </code></pre> <p>I need to call it 20-30 times. Everytime with diffrent arguments.</p> <p>I dont want to my code like this:</p> <pre><code>add_field_and_calc( fc_1,'Z6_Z8_city',condition_city,'osm_name') add_field_and_calc( fc_1,'Z9_Z14_cityTown',condition_city_town,'osm_name') add_field_and_calc( fc_1,'Z12_Z16_VillageSuburbQuarter',condition_village_suburb_quarter,'osm_name') add_field_and_calc( fc_1,'Z15_20_5_smaller',condition_5_smaller,'osm_name') add_field_and_calc( fc_1,'Z17_Z20_Square',condition_square,'osm_name') </code></pre> <p>Here is my try of maping function calls:</p> <pre><code>tupel_fc = [( fc_1, 'Z6_Z8_city', condition_city,'osm_name'), (fc_1, 'Z9_Z14_cityTown', condition_city_town,'osm_name'), (fc_1, 'Z12_Z16_VillageSuburbQuarter', condition_village_suburb_quarter,'osm_name'), (fc_1,'Z15_20_5_smaller', condition_5_smaller,'osm_name'), (fc_1,'Z17_Z20_Square', condition_square,'osm_name'), (...)] # &lt;&lt;&lt; more records to come if this a good approach #lambda to use all things from tupel creating_lambda = lambda tupel: add_field_and_calc( tupel[0], tupel[1], tupel[2], tupel[3]) #map to eliminate need of copy - pasting same function many times map(creating_lambda, tupel_fc) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T11:57:50.113", "Id": "399865", "Score": "1", "body": "Since syntax errors are raised by the parser before your code runs, if you have any your code can't possibly work. Could you ensure the code you've posted has none. Thanks." },...
[ { "body": "<p>Your current code could be made nicer by using <a href=\"https://www.geeksforgeeks.org/packing-and-unpacking-arguments-in-python/\" rel=\"nofollow noreferrer\">tuple unpacking</a>. So instead of explicitly writing:</p>\n\n<pre><code>lambda tupel: add_field_and_calc(tupel[0], tupel[1], tupel[2], tu...
{ "AcceptedAnswerId": "207217", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T11:53:37.103", "Id": "207214", "Score": "-3", "Tags": [ "python", "hash-map" ], "Title": "Reducing function calls with Map" }
207214
<p>I am developing a bot for Starcraft II. In my code for unit movement, I often find myself doing this:</p> <ul> <li>Calculate points around the current position of the unit</li> <li>Check if these points are valid and can be reached</li> <li>Get the best n points that fit condition A (for example, the n points that are furthest away from the closest enemy unit)</li> <li>Of these n points, get the best point that fits condition B (for example, the point that is closest to the closest friendly unit)</li> </ul> <p>I already made a numpy version to speed it up a bit, but would like this to run even faster. Maybe there is a way to combine the two conditions somehow.</p> <pre><code>import heapq import math import timeit import numpy as np # Point2 objects are needed here for the starcraft bot, they have .x and .y properties # positions have 15 decimal places from sc2.position import Point2 DIRECTIONS_AMOUNT = 16 # add [0] to have current position in points DIRECTION_OFFSETS = ( [0] + [round(math.cos(2 * math.pi / DIRECTIONS_AMOUNT * p), 15) for p in range(DIRECTIONS_AMOUNT)], [0] + [round(math.sin(2 * math.pi / DIRECTIONS_AMOUNT * p), 15) for p in range(DIRECTIONS_AMOUNT)], ) # the current position of the unit position = Point2((65.11906509381345, 127.15779037493655)) # urrent position of closest enemy closestEnemy = Point2((74.11906509381345, 112.15779037493655)) # current position of closest friend closestFriend = Point2((68.11906509381345, 131.15312313133655)) # directions + original position for the case that standing still is the best option retreatPoints = [ Point2((position.x + DIRECTION_OFFSETS[0][p], position.y + DIRECTION_OFFSETS[1][p])) for p in range(DIRECTIONS_AMOUNT + 1) ] # select some points which are far away from the enemy retreatPointsChoice = heapq.nlargest(3, retreatPoints, key=lambda p: p.distance_to(closestEnemy)) # final point where the unit moves to based on distance to closest friend retreatPoint = min(retreatPointsChoice, key=lambda p: p.distance_to(closestFriend)) # with numpy, i improved it to this: np_retreatPoints = np.array(retreatPoints) def numpy_distance_sort(direction_points, target_point, amount=6, sort="min"): if sort == "max": results = np.add( np.square(np.subtract(target_point.x, direction_points[:, 0])), np.square(np.subtract(target_point.y, direction_points[:, 1])), ) if sort == "min": results = -1 * np.add( np.square(np.subtract(target_point.x, direction_points[:, 0])), np.square(np.subtract(target_point.y, direction_points[:, 1])), ) return [np_retreatPoints[i] for i in np.argpartition(-results, amount)[:amount]] np_retreatPointsChoice = numpy_distance_sort(np_retreatPoints, closestEnemy, 3, "max") np_retreatPoint = min(retreatPointsChoice, key=lambda p: p.distance_to(closestFriend)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-09T07:13:48.357", "Id": "400049", "Score": "0", "body": "Assuming you have enemy unit A at 3 distance away, and B at 4 distance away. According to your logic, I can move 2 distance away from A and towards B, so that I am now 2 distance...
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T12:51:02.903", "Id": "207220", "Score": "1", "Tags": [ "python", "python-3.x", "numpy", "computational-geometry" ], "Title": "Get directions for unit movement with conditions" }
207220
<p>I have a set of parameters, and I need to get the expression:</p> <p>So I got this parameters:</p> <pre><code>filters = { "type": 'human', "age": [{'min': 4, 'max': 8}, {'min': 15, 'max': 30}], "size": [{'min': 60}], } </code></pre> <p>And my goal is to obtain this string from it:</p> <pre><code>type == 'human' and ((age &gt;= 4 and age &lt;= 8) or (age &gt;= 15 and age &lt;= 30)) and size &gt;= 60 </code></pre> <p>But when I am writing my script to do so, I keep having small details that bother me like the position of the 'or' or 'and' or the parenthesis. And i think it really hit the readability here. So I thought maybe there was a better way, but searching Google only shows me the inverse of what I want, that is transforming expression to expression tree.</p> <p>I am trying to generate a string expression from a set of data (for a filter).</p> <p>So if someone have a better idea, (or algo, or ...)</p> <p>Here is my script:</p> <pre><code>#!/usr/bin/python3 # goal : type == 'human' and ((age &gt;= 4 and age &lt;= 8) or (age &gt;= 15 and age &lt;= 30)) and size &gt;= 60 filters = { "type": 'human', "age": [{'min': 4, 'max': 8}, {'min': 15, 'max': 30}], "size": [{'min': 60}], } s = '' type_first = True for key, value in filters.items(): if type_first: type_first = False s += "(" else: s += " and (" value_first = True if(isinstance(value, str)): s += "%s == %s" % (key, value) elif(isinstance(value, list)): if value_first: value_first = False else: s += " and" dict_first = True for dict_ in value: if dict_first: dict_first = False s += "(" else: s += " or (" if dict_.get('min', 0): s += "%s &gt;= %s" % (key, dict_['min']) if dict_.get('max', 0): s += " and " if dict_.get('max', 0): s += "%s &lt;= %s" % (key, dict_['max']) s += ")" s += ")" print(s) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T16:48:28.313", "Id": "399949", "Score": "1", "body": "what if you want to make `((age >= 4 and age <= 8) and (age >= 15 and age <= 30))`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-09T05:57:37.330",...
[ { "body": "<ul>\n<li>Please note that I am not actually reviewing your code, but guiding you towards hopefully better design, so that you can fix the issues yourself</li>\n<li>In that same vein, the code snippets I am including do not contain a full solution, but only the hints towards it.</li>\n</ul>\n\n<hr>\n...
{ "AcceptedAnswerId": "207281", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T13:01:47.237", "Id": "207221", "Score": "1", "Tags": [ "python", "algorithm" ], "Title": "Generating string expression from data for filter" }
207221
<p>I have implemented a simple HTTP server which can process <code>GET</code> and <code>POST</code> requests from the client. I have written it in Java. For the client part, I just simply type in <code>localhost:8080(file_name_here.file_type_here)</code> in the browser. For the <code>GET</code> request, the server tries to find the requested file in the directory. If it finds it successfully, it shows the file on the browser and shows an error message if it fails to do so. For the <code>POST</code> request the server simply collects a username from a HTTP post form and shows the username in a HTML page. Any sort of constructive criticism on the code design or structure will be appreciated. </p> <pre><code>import java.io.*; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Date; public class HTTPServer { static Writer writer; private static ServerSocket serverConnect; private static final int PORT = 8080; static int id = 0; private static void serverSocketCreate(){ try { serverConnect = new ServerSocket(PORT); } catch (IOException e) { e.printStackTrace(); } System.out.println("Server started.\nListening for connections on port : " + PORT + " ...\n"); } private static void logFileCreate(){ File logFile = new File("log.txt"); boolean result = false; try { result = Files.deleteIfExists(logFile.toPath()); if(result) logFile.createNewFile(); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(logFile), StandardCharsets.UTF_8)); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) throws IOException { serverSocketCreate(); logFileCreate(); while(true) { Socket s = serverConnect.accept(); WorkerThread wt = new WorkerThread(s); Thread t = new Thread(wt); t.start(); System.out.println("Thread number is: " + id); } } } class Information{ private String method; private String fileName; private String fileType; public Information(){ method = fileName = fileType = ""; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getFileType() { return fileType; } public void setFileType(String fileType) { this.fileType = fileType; } } class WorkerThread implements Runnable{ private Socket s; private BufferedReader in; private DataOutputStream out; private static String MIME_TYPE; private static final String SUCCESS_HEADER = "HTTP/1.1 200 OK\r\n"; private static final String ERROR_HEADER = "HTTP/1.1 404 Not Found\r\n"; private static final String OUTPUT_HEADERS = "Content-Type: " + MIME_TYPE + "\r\nContent-Length: "; private static final String OUTPUT_END_OF_HEADERS = "\r\n\r\n"; private static final String FILE_NOT_FOUND = "&lt;html&gt;\n&lt;head&gt;\n&lt;title&gt;\nError\n&lt;/title&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;p&gt;\n&lt;h1&gt;404-File Not Found&lt;/h1&gt;\n&lt;/p&gt;\n&lt;/body&gt;\n&lt;/html&gt;"; public WorkerThread(Socket s){ this.s = s; try{ in = new BufferedReader(new InputStreamReader(s.getInputStream())); out = new DataOutputStream(s.getOutputStream()); } catch (IOException e){ e.printStackTrace(); } HTTPServer.id++; } private void closeConnection() throws IOException{ out.flush(); out.close(); in.close(); s.close(); //HTTPServer.writer.close(); } private void sendData(byte [] data) throws IOException{ out.writeBytes(SUCCESS_HEADER); out.writeBytes(OUTPUT_HEADERS); out.write(data.length); out.writeBytes(OUTPUT_END_OF_HEADERS); out.write(data); } private void sendPostData(String POST_DATA) throws IOException{ out.writeBytes(SUCCESS_HEADER); out.writeBytes(OUTPUT_HEADERS); out.write(POST_DATA.length()); out.writeBytes(OUTPUT_END_OF_HEADERS); out.writeBytes(POST_DATA); } private void sendErrorMessage() throws IOException{ out.writeBytes(ERROR_HEADER); out.writeBytes(OUTPUT_HEADERS); out.write(FILE_NOT_FOUND.length()); out.writeBytes(OUTPUT_END_OF_HEADERS); out.writeBytes(FILE_NOT_FOUND); } private void setMimeType(String fileType){ if(fileType.equals("html")){ MIME_TYPE = "text/html"; } else if(fileType.equals("png")){ MIME_TYPE = "image/png"; } else if(fileType.equals("pdf")){ MIME_TYPE = "application/pdf"; } else if(fileType.equals("jpg")){ MIME_TYPE = "image/jpg"; } else if(fileType.equals("jpeg")){ MIME_TYPE = "image/jpeg"; } else if(fileType.equals("bmp")){ MIME_TYPE = "image/bmp"; } else if(fileType.equals("tiff")){ MIME_TYPE = "image/tiff"; } else if(fileType.equals("tif")){ MIME_TYPE = "image/tiff"; } else if(fileType.equals("default")){ MIME_TYPE = "text/html"; } } private byte [] readFileIntoByteArray(File file) throws IOException{ FileInputStream fileInputStream = new FileInputStream(file); byte [] data = new byte[(int) file.length()]; fileInputStream.read(data); fileInputStream.close(); return data; } private void writeToLogFile(String message,String statusCode,int fileSize) throws IOException { HTTPServer.writer.write(InetAddress.getByName("localHost").getHostAddress() + "--" + "[" + new Date().toString() + "] \"" + message + "\" " + statusCode + " " + fileSize); HTTPServer.writer.flush(); } private void addNewLineToLogFile() throws IOException{ HTTPServer.writer.write("\r\n"); HTTPServer.writer.flush(); } private String readRequest() throws IOException{ return in.readLine(); } private Information extractInformation(String message){ Information information = new Information(); information.setMethod(message.substring(0,message.indexOf(' '))); information.setFileName(message.substring(message.indexOf("/") + 1,message.lastIndexOf(' '))); if(information.getFileName().isEmpty()) information.setFileName("index.html"); information.setFileType(information.getFileName().substring(information.getFileName().indexOf(".") + 1)); return information; } private int contentLength() throws IOException{ String str; int postDataI = -1; while((str = readRequest()) != null) { if(str.isEmpty()) break; final String contentHeader = "Content-Length: "; if(str.contains(contentHeader)){ postDataI = Integer.parseInt(str.substring(contentHeader.length())); } } return postDataI; } private String userName(int postDataI) throws IOException{ String USER_DATA = null; char [] charArray = new char[postDataI]; in.read(charArray); USER_DATA = new String(charArray); return USER_DATA; } private String modifyUserName(String USER_DATA){ USER_DATA = USER_DATA.replaceAll("\\+"," "); USER_DATA = USER_DATA.substring(USER_DATA.indexOf("=") + 1); return USER_DATA; } @Override public void run() { try{ String message = readRequest(); Information info = new Information(); if(message != null){ info = extractInformation(message); } if(info.getMethod().equals("GET")){ File file = new File(info.getFileName()); // image format - bmp,jpg,png,tiff // file type - pdf , html if(file.isFile()){ // check if the file exists in the directory // send the file setMimeType(info.getFileType()); byte [] data = readFileIntoByteArray(file); sendData(data); writeToLogFile(message,"200",data.length); } else{ // file not found - 404 setMimeType("default"); sendErrorMessage(); writeToLogFile(message,"404",FILE_NOT_FOUND.length()); } } else if(info.getMethod().equals("POST")){ // read the post data int postDataI = contentLength(); String USER_DATA = userName(postDataI); USER_DATA = modifyUserName(USER_DATA); if(!USER_DATA.isEmpty()){ String POST_DATA = "&lt;html&gt;\n&lt;head&gt;\n&lt;title&gt;\nPost Request\n&lt;/title&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;p&gt;\n&lt;h1&gt;" + USER_DATA +"&lt;/h1&gt;\n&lt;/p&gt;\n&lt;/body&gt;\n&lt;/html&gt;"; sendPostData(POST_DATA); writeToLogFile(message,"200",USER_DATA.length()); } else{ // blank username String POST_DATA = "&lt;html&gt;\n&lt;head&gt;\n&lt;title&gt;\nPost Request\n&lt;/title&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;p&gt;\n&lt;h1&gt;Blank User Name&lt;/h1&gt;\n&lt;/p&gt;\n&lt;/body&gt;\n&lt;/html&gt;"; sendPostData(POST_DATA); writeToLogFile(message,"200",0); } } addNewLineToLogFile(); closeConnection(); } catch (IOException e){ e.printStackTrace(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-09T09:27:18.180", "Id": "400079", "Score": "0", "body": "Without testing this myself, it looks rather buggy. Could you edit the question to describe the tests you've performed?" }, { "ContentLicense": "CC BY-SA 4.0", "Creat...
[ { "body": "<ol>\n<li>You are not limiting the number of worker threads which are getting created. Hence, if there is a flood of requests, you website may go down.</li>\n<li>Consider using ExecutorService which creates a pool of reusable threads, rather creating a new Thread for every request.</li>\n<li>Lastly c...
{ "AcceptedAnswerId": "207305", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T14:51:42.663", "Id": "207226", "Score": "1", "Tags": [ "java", "http" ], "Title": "A simple HTTP server implementation in Java" }
207226
<p>I've got here from stackoverflow</p> <p>I have a table with this data:</p> <p><a href="https://i.stack.imgur.com/n01Xw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n01Xw.png" alt="Data"></a></p> <p>I have this code:</p> <pre><code>Sub HorariosReal() Dim LastRow As Long, Horario As String, i As Long, arr1 As Variant, Comprueba As Variant, a As Long, arrHechos() As String, _ YaHecho As Variant, arrFichajes() As String, arrFinal() As String 'Insert people with schedule into one array LastRow = ws2.Range("A1").End(xlDown).Row arr1 = ws2.Range("A2:A" &amp; LastRow).Value2 'some tweaking for the data LastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row With ws.Range("F2:J" &amp; LastRow) .FormulaR1C1 = "=IFERROR(VALUE(RC[-5]),RC[-5])" .Value = .Value .Cut Destination:=ws.Range("A2") End With 'Insert data into one array ReDim arrFichajes(0 To LastRow, 0 To 4) For i = 0 To UBound(arrFichajes, 1) For a = 0 To UBound(arrFichajes, 2) arrFichajes(i, a) = ws.Cells(i + 2, a + 1) If a = 2 Or a = 3 Then arrFichajes(i, a) = Format(ws.Cells(i + 2, a + 1), "hh:mm") 'just need a string If a = 4 Then arrFichajes(i, a) = Application.Round(ws.Cells(i + 2, a + 1), 2) 'round the number because vba gives wrong numbers later Next a Next i ReDim arrHechos(0 To 0) 'to keep the ones already done ReDim arrFinal(0 To 4, 0 To 0) 'final array with clean data On Error Resume Next 'i'm expecting people without schedule so it will throw errors For i = 0 To UBound(arrFichajes, 1) Horario = Format(arrFichajes(i, 2), "hh:mm") &amp; "-" &amp; Format(arrFichajes(i, 3), "hh:mm") 'Columns C and D YaHecho = Application.Match(arrFichajes(i, 0) &amp; arrFichajes(i, 1), arrHechos, 0) 'check if already exists so I can update his schedule If IsError(YaHecho) Then 'if doesn't exists, fill a new line on the final array arrFinal(0, UBound(arrFinal, 2)) = arrFichajes(i, 0) 'Column A arrFinal(1, UBound(arrFinal, 2)) = arrFichajes(i, 1) 'Column B arrFinal(2, UBound(arrFinal, 2)) = Horario 'Column C + D arrFinal(3, UBound(arrFinal, 2)) = ws2.Cells(ws2.Cells.Find(arrFichajes(i, 1)).Row, Day(arrFichajes(i, 0) + 6)) 'here we look for his schedule. If arrFinal(3, UBound(arrFinal, 2)) = vbNullString Then arrFinal(3, UBound(arrFinal, 2)) = "No aparece en programación" 'if doesn't have schedule we mark it. arrFinal(4, UBound(arrFinal, 2)) = arrFichajes(i, 4) 'Column E If arrHechos(UBound(arrHechos)) &lt;&gt; vbNullString Then ReDim Preserve arrHechos(0 To UBound(arrHechos) + 1) 'add one row to the array arrHechos(UBound(arrHechos)) = arrFinal(0, UBound(arrFinal, 2)) &amp; arrFinal(1, UBound(arrFinal, 2)) 'fill the last row to keep up the ones i've done ReDim Preserve arrFinal(0 To 4, 0 To UBound(arrFinal, 2) + 1) 'add a row to the final array with clean data Else 'if already exists YaHecho = YaHecho - 1 ' application.match starts on 1 and my array on 0, so need to balance arrFinal(2, YaHecho) = arrFinal(2, YaHecho) &amp; "/" &amp; Horario 'update the schedule arrFinal(4, YaHecho) = arrFinal(4, YaHecho) + arrFichajes(i, 4) 'add the hours worked End If Next i On Error GoTo 0 End Sub </code></pre> <p>The IDs are just a sample, but the thing is that one ID (Column B) can have multiple entries (Columns C and D) on the same day (Column A).</p> <p>This is data from workers, their in (Column C) and outs (Column D) from their work, I need to merge all the entries from one worker on the same day in one row (on column C), then on column D find his schedule.</p> <p>The code works ok, but extremely slow. I noticed that if I keep stopping the code, it goes faster (¿?¿? is this possible).</p> <p>I decided to work with arrays because this is one week and it has 35k + rows, still it takes ages to end.</p> <p>What I am asking is if there is something wrong on my code that slows down the process. Any help would be appreciated.</p> <p>Thanks!</p> <p>Edit:</p> <p>I'm using this sub before this one is called:</p> <pre><code>Sub AhorroMemoria(isOn As Boolean) Application.Calculation = IIf(isOn, xlCalculationManual, xlCalculationAutomatic) Application.EnableEvents = Not (isOn) Application.ScreenUpdating = Not (isOn) ActiveSheet.DisplayPageBreaks = False End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T16:27:00.640", "Id": "399944", "Score": "0", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for ...
[ { "body": "<p>An easy win would be to <a href=\"https://docs.microsoft.com/en-us/office/vba/api/excel.application.screenupdating\" rel=\"nofollow noreferrer\">disable screen updating</a>. This will cause your script to run faster, as excel will not try and rerender as your macro runs. I've found this can speed ...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T15:35:09.783", "Id": "207234", "Score": "0", "Tags": [ "performance", "vba", "excel" ], "Title": "Speed up array loop vba Excel" }
207234
<p>I'm new to hash codes/hash tables, so I'm very unsure of my implementation. I want to create a hash table, but I can only use arrays. Specifically, I want to be able to insert things like a dictionary (a word and its meaning). Here is what I have:</p> <pre><code>public class HashTable { String[][] table; int tableSize; HashTable(int size) { table = new String[size][]; tableSize = size; } public void add(String key, String value) { if (key == null || value == null) { System.out.println("Cannot input null values"); } int iter = 0; int code = Math.abs(key.hashCode()) % tableSize; if (table[code] == null) { table[code] = new String[]{key, value}; } else { while (table[code] != null) { if (table[code][0].equals(key)) { System.out.println("Already submitted submitted the word " + key); return; } if (iter == tableSize) { System.out.println("Table is full. Cannot add word \"" + key + "\""); return; } code++; code %= tableSize; iter++; } table[code] = new String[]{key, value}; } } public void remove(String key) { if (key == null) { System.out.println("Cannot input null value"); } int iter = 0; int code = Math.abs(key.hashCode()) % tableSize; if (table[code][0].equals(key)) { table[code] = null; } else { while (!table[code][0].equals(key)) { if (iter == tableSize) { System.out.println("Could not find word \"" + key + "\""); return; } code++; code %= tableSize; iter++; } table[code] = null; } } public String get(String key) { if (key == null) { return "Cannot input null value."; } int iter = 0; int code = Math.abs(key.hashCode()) % tableSize; if (table[code][0].equals(key)) { return table[code][1]; } else { while (!table[code][0].equals(key)) { if (iter == tableSize) { return "Could not find word \"" + key + "\""; } code++; code %= tableSize; iter++; } return table[code][1]; } } } </code></pre> <p>Is this an okay implementation? How can I make it better?</p> <p>Thanks!</p>
[]
[ { "body": "<ul>\n<li><p>Do not special case an immediate success. The test for <code>table[code] == null</code> in</p>\n\n<pre><code> if (table[code] == null) {\n table[code] = new String[]{key, value};\n } else {\n while (table[code] != null) {\n ....\n</code></pre>\n\n<p>does not do...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T15:45:01.840", "Id": "207236", "Score": "2", "Tags": [ "java", "hash-map", "hashcode" ], "Title": "Using Java to implement a hash table (dictionary) with only arrays" }
207236
<p>So I've been working on a tracklist generator that scrapes from Amazon Music using a url using Python for albums with one artist. I've made uhhh this, I'm really new to this requests and beautifulsoup4 thing. I wonder if I can improve it to make it more efficient.</p> <pre><code>import requests from bs4 import BeautifulSoup Amazon=str(input("Please enter an Amazon music url:")) r=requests.get(Amazon) soup = BeautifulSoup(r.text,'html.parser') name=soup.find_all('a', attrs={'class':'a-link-normal a-color-base TitleLink a-text-bold'}) #find out the names of the track title time=soup.find_all('td',attrs={'class':'a-text-right a-align-center'}) #find the duration of the track artist= soup.find('a', attrs={'id':'ProductInfoArtistLink'}) #find the creator of the track, which for now can only take one for i in range(1,len(name),2): print(str(int(i/2+1))+'. '+name[int(i)].text+' - '+ artist.text + ' (' + time[int((i-1)/2)].text[12:16] + ')') #first int produces a placeholder number for the track e.g 1., 2. #second int produces track name, which len shows twice of number of tracks #artist text gives artist name #time gives time and puts it in brackets </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T22:08:10.963", "Id": "400018", "Score": "0", "body": "80 character line limit and comments need to be on their own line about the line they're supposed to be commenting about. I'm not listing this as an answer because these two thin...
[ { "body": "<p>Whenever you find yourself writing long (or sometimes even short) comments explaining a single line/a block of lines, you should ask yourself if this was not better placed in a function. Functions can be given a meaningful name and you can add a <a href=\"https://www.python.org/dev/peps/pep-0257/\...
{ "AcceptedAnswerId": "207299", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T15:51:03.423", "Id": "207238", "Score": "2", "Tags": [ "python", "python-3.x", "web-scraping" ], "Title": "Python webscrape Amazon Music, generate tracklist" }
207238
<p>Is there any better way how to mix items in list? In my example: I want to sort list items as male, female, male, ... My solution is probably very time and resource demanding. Can I do it somehow with LINQ?</p> <pre><code>private List&lt;Child&gt; MixGender(List&lt;Child&gt; children) { List&lt;Child&gt; male = new List&lt;Child&gt;() { }; List&lt;Child&gt; female = new List&lt;Child&gt;() { }; male = children.Where(c =&gt; c.Sex == "male").ToList(); female = children.Where(c =&gt; c.Sex == "female").ToList(); int childrenCount = children.Count; int indexMale = 0; int indexFemale = 0; children.Clear(); for (int i = 0; i &lt; childrenCount; i++) { if (i % 2 == 1) { if (indexMale &lt; male.Count) { children.Add(male[indexMale]); indexMale++; } else { children.Add(female[indexFemale]); indexFemale++; } } else { if (indexFemale &lt; female.Count) { children.Add(female[indexFemale]); indexFemale++; } else { children.Add(male[indexMale]); indexMale++; } } } return children; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T16:25:00.030", "Id": "399943", "Score": "4", "body": "Could you reframe your question and the requirements? You write about mixing items in lists but then about sorting... I'm very confused." }, { "ContentLicense": "CC BY-SA...
[ { "body": "<p>My only comment is don't mutate the input and then return it.</p>\n\n<pre><code>private List&lt;Child&gt; MixGender(List&lt;Child&gt; children)\n</code></pre>\n\n<p>Return a fresh <code>List&lt;Child&gt;</code>.</p>\n\n<p>Male and female should be enum.</p>\n", "comments": [ { "C...
{ "AcceptedAnswerId": "207252", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T16:18:05.900", "Id": "207240", "Score": "8", "Tags": [ "c#", "collections" ], "Title": "Alternating items in a collection" }
207240
<p>Given our <a href="https://codegolf.stackexchange.com/questions/175485/the-first-the-last-and-everything-between">spec from Code Golf</a>:</p> <blockquote> <p>Given two integers, output the two integers, and then the range between them. The order of the range must be the same as the input.</p> <h3>Examples:</h3> <pre><code> Input Output 0, 5 -&gt; [0, 5, 1, 2, 3, 4] -3, 8 -&gt; [-3, 8, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7] 4, 4 -&gt; [4, 4] 4, 5 -&gt; [4, 5] 8, 2 -&gt; [8, 2, 7, 6, 5, 4, 3] -2, -7 -&gt; [-2, -7, -3, -4, -5, -6] </code></pre> </blockquote> <p>Using our test driven approach :) </p> <pre><code>import org.junit.Test; import java.util.List; import static org.assertj.core.api.Assertions.*; public class CodeGolfTest { @Test public void firstLastAndEverythingBetweenExampleOTo5() { final List&lt;Integer&gt; integers = CodeGolf.firstLastAndEverythingBetween(0, 5); assertThat(integers).isNotNull().hasSize(6).containsExactly(0,5,1,2,3,4); } @Test public void firstLastAndEverythingBetweenExampleMinus3To8() { final List&lt;Integer&gt; integers = CodeGolf.firstLastAndEverythingBetween(-3, 8); assertThat(integers).isNotNull().hasSize(12).containsExactly(-3,8,-2,-1,0,1,2,3,4,5,6,7); } @Test public void firstLastAndEverythingBetweenExample4To4() { final List&lt;Integer&gt; integers = CodeGolf.firstLastAndEverythingBetween(4, 4); assertThat(integers).isNotNull().hasSize(2).containsExactly(4,4); } @Test public void firstLastAndEverythingBetweenExample4To5() { final List&lt;Integer&gt; integers = CodeGolf.firstLastAndEverythingBetween(4, 5); assertThat(integers).isNotNull().hasSize(2).containsExactly(4,5); } @Test public void firstLastAndEverythingBetweenExample8To2() { final List&lt;Integer&gt; integers = CodeGolf.firstLastAndEverythingBetween(8, 2); assertThat(integers).isNotNull().hasSize(7).containsExactly(8,2,7,6,5,4,3); } @Test public void firstLastAndEverythingBetweenExampleMinus2ToMinus7() { final List&lt;Integer&gt; integers = CodeGolf.firstLastAndEverythingBetween(-2, -7); assertThat(integers).isNotNull().hasSize(6).containsExactly(-2,-7,-3,-4,-5,-6); } } </code></pre> <p>Can we optimize further this code?</p> <p>The implementation:</p> <pre><code>import java.util.ArrayList; import java.util.List; public final class CodeGolf { private CodeGolf() { } public static List&lt;Integer&gt; firstLastAndEverythingBetween(final int a, final int b) { if (a == b) { return addAB(a, b); } final List&lt;Integer&gt; result = addAB(a, b); int initial = getInitial(a, b); for (int n = 1; n &lt; Math.abs(b - a); n++) { result.add(initial); if (b &gt; a) { initial++; } else { initial--; } } return result; } private static int getInitial(int a, int b) { return (b &gt; a) ? (a + 1) : (a - 1); } private static List&lt;Integer&gt; addAB(int a, int b) { final List&lt;Integer&gt; result = new ArrayList&lt;&gt;(); result.add(a); result.add(b); return result; } } </code></pre>
[]
[ { "body": "<p>As you ask for optimization:</p>\n\n<ul>\n<li>You re-evaluate <code>Math.abs()</code> in each iteration of the loop, which is a constant value. Consider <code>for(int n = 1, upperBound = Math.abs(b - a); n &lt; upperBound; n++)</code> instead.</li>\n<li>The same goes for <code>if (b &gt; a)</code>...
{ "AcceptedAnswerId": "207288", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T16:49:45.310", "Id": "207243", "Score": "4", "Tags": [ "java", "object-oriented", "programming-challenge", "unit-testing" ], "Title": "Print the first, last, and in-between integers of a range" }
207243
<p>I am pretty knew to the VBA world but I am really eager to improve my skills. I have a case where I would like to match cancellation with new business to see what we get back from our dropped business as new orders.</p> <p>The matching is as follows: a variable called <code>Fastighet</code> (meaning "real estate" in Swedish) will be specified and takes a value from the dropped business and searches in the new orders business. If they match with same real estate then will check the date of new business if it is +/- 90 days then it will bring me back something called "Service-ID". The macros below work and get me the result but it takes 3 hours every time to finish matching as it matches 2200 rows in dropped business with 25000 rows of new orders!</p> <p><strong>My question is</strong>: Is there a way to make it faster? </p> <pre><code>Sub MatchingNedVSUpp() Dim LRow, LRow2, i, n, serviceID As Long Dim Fastighet As String LRow = Sheet5.Range("A" &amp; Rows.Count).End(xlUp).Row LRow2 = Sheet6.Range("A" &amp; Rows.Count).End(xlUp).Row For i = 3 To LRow Fastighet = Sheet5.Range("CA" &amp; i).Value For n = 3 To LRow2 serviceID = Sheet6.Range("B" &amp; n).Value If Sheet6.Range("BH" &amp; n).Value = Fastighet And Sheet6.Range("AH" &amp; n) &lt;= Sheet5.Range("BM" &amp; i) And Sheet6.Range("AH" &amp; n) &gt;= Sheet5.Range("BL" &amp; i) And Sheet5.Application.WorksheetFunction.CountIf(Range("BU:BU"), serviceID) = 0 Then Sheet6.Range("B" &amp; n).Copy Sheet5.Range("BU" &amp; i).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False Application.CutCopyMode = False End If Next n Next i End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T19:35:12.320", "Id": "399984", "Score": "0", "body": "Wathcing this videos: [Excel VBA Introduction Part 5 - Selecting Cells (Range, Cells, Activecell, End, Offset)](https://www.youtube.com//watch?v=c8reU-H1PKQ&index=5&list=PLNIs-AW...
[ { "body": "<p>The line <code>Dim LRow, LRow2, i, n, serviceID As Long</code> isn't doing what you think it is. When you declare multiple variables on the same line, you need to individually assign types to all of them - otherwise the default to <code>Variant</code>. I'm assuming that line was meant to be <code...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T18:06:34.900", "Id": "207248", "Score": "1", "Tags": [ "performance", "vba", "excel" ], "Title": "Matching huge data set of business data" }
207248
<p>I am having issue making this code more efficient. The problem to be solved is as follows:</p> <blockquote> <p>By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.</p> <p>What is the 10,001st prime number?</p> </blockquote> <p>I'm looking to complete this in powershell. My code runs well up until about 4.8k primes.</p> <pre><code>$incNum1 = 1 $incNum2 = 2 $divisNum = 2 * $incNum2 - 1 $highestNum = 0 $k = 1 $nextNum = 2 * $incNum1 + 1 while($k -lt 6000){ $upTo = [int][Math]::Ceiling(($nextNum / 2)) $break = $false while($divisNum -lt $upTo){ $modRes = $nextNum % $divisNum if($modRes -eq 0){ $break = $true break } $incNum2++ $divisNum = 2 * $incNum2 - 1 } if(!$break){ $highestNum = $nextNum echo $nextNum $k++ } $incNum2 = 2 $divisNum = 2 * $incNum2 - 1 $incNum1++ $nextNum = 2 * $incNum1 + 1 } echo $highestNum </code></pre>
[]
[ { "body": "<p>I'd start with </p>\n\n<ul>\n<li>removing redundancy</li>\n<li>measuring the time automatically</li>\n<li>output to screen slows down, comment it out</li>\n</ul>\n\n<p>depending on the speed of the computer used I get results of ~74..120 seconds.<br>\nCompared with 0.450 secs <a href=\"http://me-l...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T18:12:12.080", "Id": "207250", "Score": "4", "Tags": [ "performance", "programming-challenge", "primes", "powershell" ], "Title": "Euler Problem 7 (finding the 10001st prime) in Powershell" }
207250
<p>I have a matrix with roughly 500,000 features that I'd like to correlate and find features that have correlations >= 0.90, then cluster these into one group. Is there an efficient algorithm to do this? R's <code>cor()</code> function will not work as this data is too large to compute a 500k x 500k matrix, let alone storing this in memory. I'm only interested in finding these features that satisfy a correlation threshold. </p> <pre><code>cluster_number &lt;- 1 for (b in seq(1, 500000)) { # INIT b1 &lt;- to_cluster[b] if(b == 1){ selected$R_CLUST[selected$BIN %in% b1] &lt;- cluster_number } # COMPUTE COR sel &lt;- subset(selected, R_CLUST != 0) sel &lt;- sel[!duplicated(sel$R_CLUST), ] sel &lt;- as.vector(sel$BIN) sel &lt;- sel[! sel %in% b1] if(length(sel) == 0){ next } r2 &lt;- round(cor(signal[, c(b1, sel)], method = "pearson", use = "everything"), 5) diag(r2) &lt;- 0 r2 &lt;- subset(melt(r2), value &gt;= r_cutoff &amp; Var1 == b1) if(nrow(r2) &gt; 0){ correlate &lt;- r2$Var2 selected$R_CLUST[selected$BIN %in% b1] &lt;- selected$R_CLUST[selected$BIN %in% correlate] } else { cluster_number &lt;- cluster_number + 1 selected$R_CLUST[selected$BIN %in% b1] &lt;- cluster_number } } </code></pre> <p>Here I am iterating through my features and placing correlated features aside in the <code>selected</code> data.frame if they satisfy a correlation threshold. This does not work though because the <code>selected</code> data.frame gets very large and computing <code>cor()</code> becomes computationally intensive. I should mention that the ultimate goal here is to cluster these features into groups such that the guarantee is that each group satisfies a correlation threshold. I'm also thinking about perhaps taking a nearest-neighbor approach by taking, say, the top 10 closest features to a given feature and create a graph based on this and find largely connected components, but I know the guarantee is not necessarily satisfied in this way. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T21:03:47.107", "Id": "400009", "Score": "0", "body": "Welcome to Code Review! Could you clarify what you mean by \"something like this\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T21:12:50.773",...
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T20:46:27.917", "Id": "207262", "Score": "1", "Tags": [ "r", "clustering" ], "Title": "Cluster correlations for many (> 500k) features by threshold" }
207262
<p>Here is a variation of quick-sort where-in the pivot selection is based on calculating the average of the values of the highest and lowest numbers. </p> <pre><code>pivot = (high + low)/2 </code></pre> <p>The pivot as such is usually a virtual one.</p> <p>This approach performs a pass on every iteration to determine the <strong>high</strong> and <strong>low</strong> values.</p> <p>My understanding is that this approach requires a maximum of <span class="math-container">\$2 \cdot n \cdot \log_2(n)\$</span>.</p> <p>The rationale is as follows:</p> <p>Best case scenario would be one where the numbers are sorted and are sequential.</p> <p>Example: 1,2,3,4,5,6,7,8.</p> <p>First run would yield <span class="math-container">\$\frac{1+8}{2}=4.5\$</span> which in turn can be rounded off to 4. Second run would then yield <span class="math-container">\$\frac{1+4}{2}=2.5\$</span> for the left sub-array and <span class="math-container">\$\frac{5+8}{2}=6.5\$</span> for the right sub-array and so on.</p> <p>The worst case for the above would then be a sequence that doubles. Effectively a sequence in the powers of 2. </p> <p>Example: 1,2,4,8,16,32,64,128,256,512....</p> <p>However, given that numbers are typically represented as byte (8), short (16), int (32), long (64), for a given datatype - e.g.: integer, the maximum number in the worst case sequence would be: 2,147,483,648. So basically for an integer datatype, the sequence - 1,2,4,8,16,..., would reach a maximum of 2,147,483,648 after 30 steps after which the sequence must repeat.</p> <p>To illustrate the same with a byte (unsigned), the sequence would look something like this: </p> <p>1,2,4,8,16,32,64,128,256,1,2,4,8,16,32,64,128,256,1,2,4,8,16,32,64,128,256,...</p> <p>simply because the byte can't hold more than 256 (unsigned).</p> <p>As such in case of worst case input as well, the approach: (high+low)/2 would still only have to deal with a depth of <span class="math-container">\$log_2 n\$</span> because the numbers would repeat.</p> <p>Although above would not hold where the number of elements in the array is small compared to the datatype itself... e.g.: 10% of the total capacity, where in it's still possible to induce worst-case scenarios for the given data-set, for data-sets with sizes comparable to the maximum value supported by the data-type, the approach would work.</p> <p>What is less clear is:</p> <p>Given that the best-case scenario is in <span class="math-container">\$\mathcal{O}(n \cdot \log_2(n))\$</span>, and given that for worst-case scenarios, for data-sets with sizes comparable to the maximum value the datatype also the scenarios appears to be <span class="math-container">\$n \cdot \log_2(n)\$</span>, is it true for average-case scenario as well?</p> <p>From what I can tell, it's true and as such the entire approach is in <span class="math-container">\$\mathcal{O}(n \cdot \log_2(n))\$</span>. </p> <p>However, I need confirmation on the approach, understanding and the conclusion.</p> <pre><code>package org.example.so.sorts.qs; //import java.util.Arrays; import java.util.Random; /** * * * &lt;pre&gt; Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. * &lt;/pre&gt; * * &lt;p&gt; * Simple Averaged Virtual Pivot - Quick Sort * &lt;/p&gt; * * &lt;p&gt; * Unstable, In-place, Big-O-Notation Classification : n*log(n) * &lt;/p&gt; * * &lt;p&gt; * A variation of quick sort where the pivot is calculated using simple average * of highest and lowest values. * &lt;/p&gt; * * * * @author Ravindra HV * @version 0.2.1 * @since 2013 */ public class QSortSAVP { /* * The pivot calculation works only for numbers with the same sign. As such, * first step is to partition positive and negative numbers, thus preventing * arithmetic overflow */ private static final int INITIAL_PIVOT = 0; private static volatile int RECURSION_COUNT = 0; private static volatile int MAX_RECURSION_DEPTH = 0; private static volatile int RECURSION_DEPTH = 0; private static final int[] POWERS_OF_TWO = { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536 }; public static void main(String[] args) { // int[] arr = {0,4,2,6,-1,-5,-3,-7}; // int[] arr = {0,4,2,6,-1,-5,-3,-7,35,41,2,6,-34,76}; // int[] arr = {1,2,4,8,16,32,64,128,256,512}; // int[] arr = {1024,32,64,1,2,4,8,16,128,256,512}; // int[] arr = {-256,-512,-1,-2,-4,-8,-16,-32,-64,-128,}; // int[] arr = // {1,2,4,8,16,32,64,128,256,512,1,2,4,8,16,32,64,128,256,512,1,2,4,8,16,32,64,128,256,512,1,2,4,8,16,32,64,128,256,512,1,2,4,8,16,32,64,128,256,512,1,2,4,8,16,32,64,128,256,512,1,2,4,8,16,32,64,128,256,512,1,2,4,8,16,32,64,128,256,512,1,2,4,8,16,32,64,128,256,512,1,2,4,8,16,32,64,128,256,512}; // int[] arr = // {-2,1,1,1,1,1,-1,-1,-1,-1,-1,0,0,0,0,0,-1,-1,-1,-1,-1,0,0,0,0,0,1,1,1,1,1,2}; int[] arr = new int[1024 * 1024]; Random random = new Random(); for (int i = 0; i &lt; arr.length; i++) { arr[i] = random.nextInt(arr.length); // arr[i] = i; // arr[i] = arr.length-i; // arr[i] = arr[i] % 1024; // int j = i % POWERS_OF_TWO.length; // arr[i] = POWERS_OF_TWO[j]; // if( i % 2 == 0) { // arr[i] = arr.length-i; // } // else { // arr[i] = random.nextInt(arr.length); // } } /* */ // handlePrintLine(Arrays.toString(arr)); long start = System.currentTimeMillis(); sort(arr); // Arrays.sort(arr); long end = System.currentTimeMillis(); System.out.println("Time taken : " + (end - start) + "... Recursion count :" + RECURSION_COUNT+", Recursion-Depth :"+RECURSION_DEPTH+", MaxRecursionDepth :"+MAX_RECURSION_DEPTH); // handlePrintLine(Arrays.toString(arr)); validate(arr); // handlePrintLine("Recursion count : "+RECURSION_COUNT ); } /** * Sorts the given array in ascending order * * @param arr */ public static void sort(int[] arr) { if (arr.length &lt; 2) { return; } sort(arr, INITIAL_PIVOT, 0, arr.length, true); } /** * @param arr * @param createCopy * (to ensure correctness in the event of concurrent modification of * given array) * @return */ public static int[] sort(int[] arr, boolean createCopy) { int[] resArr = null; if (createCopy) { int[] tempArr = new int[arr.length]; System.arraycopy(arr, 0, tempArr, 0, tempArr.length); sort(tempArr); resArr = tempArr; } else { sort(arr); resArr = arr; } return resArr; } private static void sort(int[] arr, int pivotVal, int lowIndex, int highIndex, boolean firstIteration) { RECURSION_COUNT++; // handlePrintLine("First Print Statement"); // handlePrintLine("Low-Index : "+lowIndex); // handlePrintLine("High-Index : "+highIndex); // print(arr, lowIndex, highIndex); // handlePrintLine("Pivot : "+pivotVal); int tempLowIndex = lowIndex; int tempHighIndex = highIndex; while (tempLowIndex &lt; tempHighIndex) { while ((tempLowIndex &lt; highIndex) &amp;&amp; (arr[tempLowIndex] &lt;= pivotVal)) { tempLowIndex++; } if (!firstIteration &amp;&amp; tempLowIndex == highIndex) { // handlePrintLine("Returning..."); return; // all entries in given range are less than or equal to pivot.. } while ((tempHighIndex &gt; tempLowIndex) &amp;&amp; (arr[tempHighIndex - 1] &gt; pivotVal)) { tempHighIndex--; } if (tempLowIndex &lt; tempHighIndex) { swap(arr, tempLowIndex, tempHighIndex - 1); tempLowIndex++; tempHighIndex--; } } // handlePrintLine("Final-Low-Index : "+tempLowIndex); // handlePrintLine("Final-High-Index : "+tempHighIndex); // handlePrintLine("Second Print Statement"); // print(arr, lowIndex, highIndex); if ((tempLowIndex - lowIndex) &gt; 1) { int leftPartPivotVal = determinePivot(arr, lowIndex, tempLowIndex); RECURSION_DEPTH++; MAX_RECURSION_DEPTH = (RECURSION_DEPTH&gt;MAX_RECURSION_DEPTH) ? RECURSION_DEPTH:MAX_RECURSION_DEPTH; sort(arr, leftPartPivotVal, lowIndex, tempLowIndex, false); RECURSION_DEPTH--; } if ((highIndex - tempLowIndex) &gt; 1) { int rightPartPivotVal = determinePivot(arr, tempLowIndex, highIndex); RECURSION_DEPTH++; MAX_RECURSION_DEPTH = (RECURSION_DEPTH&gt;MAX_RECURSION_DEPTH) ? RECURSION_DEPTH:MAX_RECURSION_DEPTH; sort(arr, rightPartPivotVal, tempLowIndex, highIndex, false); RECURSION_DEPTH--; } } /** * &lt;p&gt; * Pivot is calculated as the simple average of the highest and lowest elements, * while ensuring that there is no overflow. * &lt;/p&gt; * * @param arr * @param lowIndex * @param highIndex * @return */ private static int determinePivot(int[] arr, int lowIndex, int highIndex) { int pivotVal = 0; int lowVal = arr[lowIndex]; int highVal = lowVal; for (int i = lowIndex; i &lt; highIndex; i++) { if (arr[i] &lt; lowVal) { lowVal = arr[i]; } if (arr[i] &gt; highVal) { highVal = arr[i]; } } pivotVal = lowVal + ((highVal - lowVal) / 2); // pivotVal = lowVal+((highVal-lowVal)&gt;&gt;1); return pivotVal; } private static void swap(int[] arr, int lowIndex, int highIndex) { int tempVal = arr[lowIndex]; arr[lowIndex] = arr[highIndex]; arr[highIndex] = tempVal; } private static void print(int[] arr, int lowIndex, int highIndex) { for (int i = lowIndex; i &lt; highIndex; i++) { if (i == 0) { handlePrint(arr[i]); } else { handlePrint(" " + arr[i]); } } handlePrintLine(""); } private static void validate(int[] arr) { boolean sorted = true; for (int i = 0; i &lt; arr.length - 1; i++) { if (arr[i] &gt; arr[i + 1]) { sorted = false; break; } } if (sorted) { handlePrintLine("SUCCESS : ARRAY SORTED. Length : " + arr.length); } else { handlePrintLine("ERROR : ARRAY NOT SORTED. Length : " + arr.length); } } private static void handlePrint(Object object) { System.out.print(object.toString()); } private static void handlePrintLine(Object object) { System.out.println(object.toString()); } } </code></pre> <p>Basically, the goal is to determine whether it's comparable to the median-of-three approach that java uses in its <code>Arrays.sort()</code> implementation.</p> <p>In test cases that I've run, it appears to be comparable to the time taken by the median-of-three algorithm - even for random data sets. So, I want to know if the concept holds good as well or if it's just by chance and there is a data set where the median-of-three is better than this approach.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-09T08:23:43.820", "Id": "400057", "Score": "0", "body": "(Did you check the Java runtime you plan to use to compare does use MoT in `Arrays.sort()`?) Decide and document whether you care about \"huge\" sorts (cache small compared to da...
[ { "body": "<p><code>the goal is to determine whether [pivot selection as average of extrema] is comparable to median-of-three</code><br>\nwhich probably is to say <em>How <strong>does</strong> pivot selection as presented here compare to MoT?</em><br>\nIf that is <em>goal of this post</em> rather than <em>goal ...
{ "AcceptedAnswerId": null, "CommentCount": "21", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T21:08:02.050", "Id": "207266", "Score": "3", "Tags": [ "java", "algorithm", "sorting", "comparative-review", "quick-sort" ], "Title": "Evaluation of a variation of quick-sort (pivot-selection)" }
207266
<p>I'm looking for a simpler code that isn't resource hungry that can compare two strings stored in different locations in the extended memory of a classic 8052 (namely the AT89S52 microcontroller) to make sure the characters match exactly.</p> <p>The error flag can be a bit value, but the only thing that concerns me is that I need scanning to begin at any two 16-bit memory locations of my choice and that the same number of consecutive bytes in each location need to be scanned.</p> <p>I was considering applying boolean logic to DPH or the DPL variables (example ANL and ORL) but at the same time will I be able to make that programmer friendly? I don't want to make the memory addressing confusing later on. Also, I'm looking for code that can replace this that can provide better performance (meaning fewer instructions required to execute a string comparison code).</p> <p>Any ideas are welcome.</p> <pre><code>;Load # bytes to check in R7 mov R7,#BYTESTOCHECK ;R6 = our error status. Assume no error here mov R6,#0h ;Load first memory pointer address to R2:R3 mov R2,#HIGHBYTE1 mov R3,#LOWBYTE1 ;Load second memory pointer address to R4:R5 mov R4,#HIGHBYTE2 mov R5,#LOWBYTE2 checknextbyte: mov DPL,R2 mov DPH,R3 ;DPTR here = R2:R3 movx A,@DPTR ;Store value at DPTR in B mov B,A inc DPTR mov R3,DPH mov R2,DPL mov DPL,R4 mov DPH,R5 ;DPTR here = R4:R5 movx A,@DPTR ;Store value at DPTR in A inc DPTR mov R5,DPH mov R4,DPL CJNE A,B,notsame ;Both addresses aren't same so string isn't same ;make R7=1 to exit loop faster mov R7,#1h ;Make R6=1 to show we have error mov R6,#1h notsame: djnz R7,checknextbyte </code></pre>
[]
[ { "body": "<ul>\n<li><p><code>AT89S52</code> is not a classic <code>8052</code>. Like all modern 8052 variants I know of, it has one feature which really shines here. Namely, it is dual data pointers. Instead of reloading <code>DPL</code> and <code>DPH</code> every time, initialize them once, and just toggle th...
{ "AcceptedAnswerId": "207272", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T23:36:57.127", "Id": "207269", "Score": "4", "Tags": [ "performance", "strings", "validation", "assembly", "embedded" ], "Title": "Compare two strings in extended memory - classic 8052" }
207269
<p>During an interview I was asked to do an OO design for a digital renting system for books/movies. This is the design that I came up with.</p> <p>My assumptions: When the customer has downloaded a list of products, the rent data is also sent ie they won't have to do an extra network call for getting rent info. Basically I had to come up with a system for caching these. </p> <p>My main objects are:</p> <ul> <li>The <code>Product</code> object</li> <li>The <code>Rent</code> object. </li> <li>The <code>MenuHandler</code> object.</li> <li>Each product has a <code>rent</code> property where it dictates the: <ul> <li>price</li> <li>expiration<strong>TimeInSeconds</strong>. Using that I create an expirationDate. I persist the expiration<strong>Date</strong> per productId. Any access to a rentedItem has to be validated with this expirationDate. If it's expired then no longer access is given. </li> <li>type of users that can rent it. The rent price varies based on <code>userType</code>. I wasn't able to model that in a decent way. So that's definitely something I'm looking for feedbacks. </li> </ul></li> <li>The <code>RentStatus</code> enum. It will either <code>expires</code> at a future date, or has already <code>expired</code> at a past date.</li> <li>Also I'd like to know if my usage of structs vs. class is a good decision here or not. </li> <li>Any other feedback regarding naming and especially the system design is welcomed</li> </ul> <p> <pre><code>import UIKit typealias ProductId = String typealias RegionId = String class RentManager : RentManagerProtocol { func charge(_ product: Product) { // Cart.shared.add(product) } var rentedProducts: [ProductId : Date] = [:] func rent(_ product: Product, for user: UserType) { guard let rent = product.rent else { fatalError("shouldn't be attempting to rent an un-rentable product") } if rent.avaialableUsers.contains(user) { store(product) }else{ // suggest user to upgrade to: rent.avaialableUsers } } func store(_ product: Product) { rentedProducts[product.id] = expiredTime(of: product) charge(product) } // to be used in the Rented/Downloaded Screen/ViewController func validate(_ productId: ProductId) -&gt; RentStatus { if let expiryDateOfRentedProduct = rentedProducts[productId]{ if expiryDateOfRentedProduct.timeIntervalSinceNow &gt; 0 { return .expires(date: Date(timeIntervalSinceNow: expiryDateOfRentedProduct.timeIntervalSinceNow)) }else if expiryDateOfRentedProduct.timeIntervalSinceNow &lt; 0 { return .expired(date: Date(timeIntervalSinceNow: expiryDateOfRentedProduct.timeIntervalSinceNow)) } else { return .expired(date: Date()) } }else { assertionFailure("ERROR: rentedProduct is not among rented Items!") return .expired(date: Date()) } } func expiredTime(of product: Product) -&gt; Date{ guard let rent = product.rent else { fatalError("shouldn't be attempting to rent an un-rentable product") } let expiredTime = Date().addingTimeInterval(rent.expirationTimeInSeconds) return expiredTime } } struct Product { let id: String let name: String let productURLString: String let rent : Rent? // some products may not be rentable at all! } struct Rent { let cost: Cost let expirationTimeInSeconds: TimeInterval // server will send this in epoc time, we will use currentTimeSince1970 + this epoc time to calculate expired Date! let avaialableUsers: Set&lt;UserType&gt; // &lt;s&gt; some products are not available for rent for anyone&lt;/s&gt; } struct Cost { var platinum: Double // some products are free to rent for platinum users var gold: Double var silver: Double func getPrice(for user: UserType) -&gt; Double { switch user { case .platinum: return platinum case .gold: return gold case .silver: return silver } } } struct User { let id: String let regionID: RegionId let type: UserType } enum UserType { case platinum case gold case silver } protocol RentManagerProtocol { var rentedProducts : [ProductId : Date] {get set} func store(_ product: Product) func charge(_ product: Product) func rent(_ product : Product, for user: UserType) func validate(_ productId: ProductId) -&gt; RentStatus } enum RentStatus { case expired(date: Date) case expires(date: Date) } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-09T03:01:03.883", "Id": "207275", "Score": "1", "Tags": [ "object-oriented", "interview-questions", "swift", "cache" ], "Title": "Design a system for renting digital movies/books" }
207275
<p>The Main program. This program pulls from a .txt document with two separate strings, and outputs a .cs program that will display those two string via console when run. It uses a structure.txt file for the code it inputs the strings into.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace ConsoleApplication3 { class Program { static void Main(string[] args) { //structure.txt contains the program we will enter our values into. String filePath = "Structure.txt"; WriteToFile(filePath); } public static void WriteToFile(string filePath) { //create a string array to gather our text file information. StreamReader reader = new StreamReader(filePath); StreamReader info = new StreamReader("Structure.txt"); StreamWriter writer = new StreamWriter("Hello.cs", true); String temp = String.Empty; while (!info.EndOfStream) { String tempstring = String.Empty; tempstring = reader.ReadLine(); while (!reader.EndOfStream) { temp = reader.ReadLine(); writer.WriteLine(temp); if (temp == "//break") { writer.WriteLine($"String1 = {tempstring}"); } else if (temp == "//break 2") { writer.WriteLine($"String2 = {tempstring}"); } } } reader.Close(); info.Close(); writer.Close(); } } } </code></pre> <p>structure.txt is just a basic program that prints the two strings gathered from the main program unto the console.</p> <pre><code>using System; namespace HelloWorld { class Hello { static void Main() { //break //break 2 Console.WriteLine(string1); // Keep the console window open in debug mode. Console.WriteLine("Press any key to continue."); Console.ReadKey(); Console.WriteLine(string2); Console.ReadKey(); } } //end } </code></pre> <p>This program runs, but I am wanting to improve the code and increase its efficiency.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-09T10:23:09.470", "Id": "400100", "Score": "0", "body": "Hello, welcome on Code Review. Can you explaine the difference between `while (!info.EndOfStream)` and `while (!reader.EndOfStream)` please?" }, { "ContentLicense": "CC B...
[ { "body": "<p>I wonder if you even have tested this program:</p>\n\n<p>This:</p>\n\n<blockquote>\n<pre><code> while (!info.EndOfStream)\n {\n String tempstring = String.Empty;\n tempstring = reader.ReadLine();\n\n while (!reader.EndOfStream)\n {\n</code></pre>\n</blockquote>\n\n<p>will run forever...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-09T03:26:18.037", "Id": "207276", "Score": "0", "Tags": [ "c#", "console", "stream" ], "Title": "Text reading and string inputting program" }
207276
<p>I'm writing a simple function: given a number, it will return a sequence or a collection of the digits in the number (in the correct order). i.e <code>(get-digits-fn 1234567) =&gt; (1 2 3 4 5 6 7) / [1 2 3 4 5 6 7]</code></p> <p>Below are five attempts at the same function:</p> <pre><code>(defn get-digits-1 [num] (-&gt;&gt; [num '()] (iterate (fn [[num digits]] (when (&gt; num 0) [(quot num 10) (conj digits (rem num 10))]))) (take-while some?) (last) (second))) (defn get-digits-2 [num] (when (&gt; num 0) (lazy-seq (concat (get-digits-2 (quot num 10)) '((rem num 10)))))) ;; Suggested by Carcigenate (defn get-digits-3 [num] (-&gt;&gt; (str) (map str) (map int) (into '()))) (defn get-digits-4 [num] (loop [n num res '()] (if (= n 0) res (recur (quot n 10) (conj res (rem n 10)))))) (defn get-digits-5 [num] (-&gt;&gt; (iterate (fn [[n digits]] [(quot n 10) (conj digits (rem n 10))]) [num '()]) (drop-while #(not= 0 (first %))) (first) (second))) </code></pre> <p>A helper function for testing performance:</p> <pre><code>(defn quick-bench-get-digits [fn range] (quick-bench (-&gt;&gt; range (map fn) (map (partial apply vector)) (into [])))) </code></pre> <p>The perf results (output truncated to only show execution time mean):</p> <pre><code>eul&gt; (quick-bench-get-digits get-digits-1 (range 1 100000)) Execution time mean : 129.516521 ms eul&gt; (quick-bench-get-digits get-digits-2 (range 1 100000)) Execution time mean : 128.637055 ms eul&gt; (quick-bench-get-digits get-digits-3 (range 1 100000)) Execution time mean : 24.267716 ms eul&gt; (quick-bench-get-digits get-digits-4 (range 1 100000)) Execution time mean : 25.083393 ms eul&gt; (quick-bench-get-digits get-digits-5 (range 1 100000)) Execution time mean : 145.430443 ms </code></pre> <p>It looks like <code>get-digits-3</code> is the fastest while <code>get-digits-4</code> is closely behind. (As the numbers increase, <code>get-digits-3</code> outperforms <code>get-digits-4</code>. i.e try <code>(range 1000000 2000000)</code>)</p> <ol> <li>Any way to increase performance more without leaving Clojure land?</li> <li>If mutability and Java inter-op is allowed, is there a way to increase performance?</li> </ol> <p>p.s. functions 1 and 5 are almost identical. This was incremental exploration.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-09T17:59:02.687", "Id": "400194", "Score": "0", "body": "Is performance of this code specifically really a concern? I'm doubtful that this is what would be the choking point of the program. 24ms is very fast, especially for an inflated...
[ { "body": "<p>I'm afraid your code has errors, so your benchmarking is invalid. </p>\n\n<ul>\n<li>The <code>get-digits-3</code> function is wrong.</li>\n<li>A corrected version runs about twelve times slower than\n<code>get-digits-4</code>.</li>\n</ul>\n\n<p><strong>Repairing <code>get-digits-3</code></strong>...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-09T03:47:00.123", "Id": "207277", "Score": "0", "Tags": [ "performance", "comparative-review", "clojure" ], "Title": "Five functions to get the digits of a number" }
207277
<p>I am making a paint program in Python using Pygame. Right now the program is very laggy, and I wanted to get my code reviewed incase the reason is in the way I have written the code.</p> <p><strong>EDIT:</strong> I was mostly able to fix the performance issue by changing the way layers work. The issue was too much blitting and I fixed it by showing everything on the active layer and only blitting that. It would still be useful if someone reviewed the code.</p> <p>(Code below is the updated version)</p> <pre><code>import pygame as pg import pygame.gfxdraw import sys,os,math pg.init() pg.event.set_allowed([pg.QUIT,pg.MOUSEMOTION,pg.MOUSEBUTTONDOWN,pg.KEYDOWN]) # Settings: clock = pygame.time.Clock() fps = 120 font = pg.font.SysFont('consolas',20) screenres = (500,500) realres = (screenres[0]*1.2,screenres[1]*1.2) updated = False dirtyrects = [] # Colors | R | G | B | A | clear = ( 0, 0, 0, 0) white = (255,255,255) gray = (150,150,150) black = ( 0, 0, 0) red = (255, 0, 0) orange = (255,125, 0) yellow = (255,255, 0) green = ( 0,225, 0) blue = ( 0, 0,255) purple = (150, 0,150) colors = [black,white,red,orange,yellow,green,blue,purple] numkey = [ pg.K_1, pg.K_2, pg.K_3, pg.K_4, pg.K_5, pg.K_6, pg.K_7, pg.K_8 ] # Surfaces: window = pg.display.set_mode(screenres,pg.DOUBLEBUF) window.fill(white) canvas = pg.Surface((realres[0],realres[1]*0.84)).convert_alpha() canvas.fill(white) latest1 = canvas.copy() latest2 = canvas.copy() latest3 = canvas.copy() latest4 = canvas.copy() latest5 = canvas.copy() layers = [latest1,latest2,latest3,latest4,latest5] for layer in layers: layer.fill(clear) overlay = pg.Surface(screenres).convert_alpha() # Rects: realrect = pg.Rect(0,0,realres[0],int(realres[1]*0.84)) screenrect = pg.Rect(0,0,screenres[0],int(screenres[1]*0.84)) toolbar = pg.Rect(0,420,500,80) r = 25 clr = black startpoint = None endpoint = None ongoing = False undone = 0 maxundone = 0 holdingclick = False def button(color,rect): global clr,holdingclick if 0 &lt;= rect &lt;= 9: rect = pg.Rect(48*rect+12,446,44,44) if pg.mouse.get_pressed()[0] and rect.collidepoint(mousepos) and not holdingclick: clr = color dirtyrects.append(toolbar) if clr == color: pg.draw.rect(overlay,color,rect) pg.draw.rect(overlay,black,rect,3) else: pg.draw.rect(overlay,color,(rect[0]+4,rect[1]+4,rect[2]-8,rect[3]-8)) pg.draw.rect(overlay,black,(rect[0]+4,rect[1]+4,rect[2]-8,rect[3]-8),3) def drawline(): global startpoint,endpoint,start if startpoint == None: startpoint = x,y endpoint = x,y if r &gt; 1: if startpoint != endpoint: dx,dy = endpoint[0]-startpoint[0],endpoint[1]-startpoint[1] angle = math.atan2(-dy,dx)%(2*math.pi) dx,dy = math.sin(angle)*(r*0.999),math.cos(angle)*(r*0.999) a = startpoint[0]+dx,startpoint[1]+dy b = startpoint[0]-dx,startpoint[1]-dy c = endpoint[0]-dx,endpoint[1]-dy d = endpoint[0]+dx,endpoint[1]+dy pointlist = [a,b,c,d] pg.draw.polygon(latest1,clr,pointlist) pg.draw.circle(latest1,clr,(x,y),r) else: pg.draw.line(latest1,clr,startpoint,endpoint,r) startpoint = x,y def shiftdown(): for layer in reversed(layers): if layer == latest5: canvas.blit(latest5,(0,0)) else: layers[layers.index(layer)+1].blit(layer,(0,0)) def shiftup(): for layer in layers: if layer == latest5: layer.fill(clear) else: layer.fill(clear) layer.blit(layers[layers.index(layer)+1],(0,0)) # Drawing static parts of overlay: overlay.fill(clear) pg.draw.rect(overlay,gray,toolbar) pg.draw.rect(overlay,black,toolbar,3) # Drawing number indicators for colors: for color in colors: text = font.render(str(colors.index(color)+1),True,black) overlay.blit(text,(48*colors.index(color)+28,424)) overlaybg = overlay.copy() while True: for event in pg.event.get(): if event.type == pg.QUIT or pg.key.get_pressed()[pg.K_ESCAPE]: pg.quit() sys.exit() if event.type == pg.MOUSEMOTION: mousepos = pg.mouse.get_pos() x = int(mousepos[0]*(realres[0]/screenres[0])) y = int(mousepos[1]*(realres[1]/screenres[1])) holdingclick = True if screenrect.collidepoint(mousepos): dirtyrects.append(screenrect) if event.type == pg.MOUSEBUTTONDOWN: holdingclick = False if screenrect.collidepoint(mousepos): dirtyrects.append(screenrect) # Changing brush size: if event.button == 4 and r &lt; 100: r += 1 dirtyrects.append(screenrect) elif event.button == 5 and r &gt; 2: r -= 1 dirtyrects.append(screenrect) if event.type == pg.KEYDOWN: if event.key in numkey: clr = colors[numkey.index(event.key)] dirtyrects.append(toolbar) # Emptying canvas: if event.key == pg.K_e: canvas.fill(white) latest5.fill(clear) latest4.fill(clear) latest3.fill(clear) latest2.fill(clear) latest1.fill(clear) undone = 0 maxundone = 0 dirtyrects.append(screenrect) # Undoing and redoing: if event.key == pg.K_u and undone &lt; maxundone: undone += 1 dirtyrects.append(screenrect) if event.key == pg.K_i and undone &gt; 0: undone -= 1 dirtyrects.append(screenrect) # Painting: if pg.mouse.get_pressed()[0] and screenrect.collidepoint(mousepos): if not ongoing: while undone &gt; 0: shiftup() undone -= 1 maxundone -= 1 shiftdown() drawline() ongoing = True else: startpoint = None if ongoing: if maxundone &lt; 5: maxundone += 1 ongoing = False if screenrect in dirtyrects: # Drawing canvas: window.fill(white) for layer in layers: if layers.index(layer) == undone: window.blit(pg.transform.smoothscale(layer,(screenrect[2],screenrect[3])),screenrect) # Drawing overlay: overlay.fill(clear) if r &gt; 1: pg.gfxdraw.aacircle(overlay,mousepos[0],mousepos[1],int(r*screenres[0]/realres[0]),gray) overlay.blit(overlaybg,screenrect) for color in colors: button(color,colors.index(color)) window.blit(overlay,screenrect) pg.display.set_caption('Draw | FPS: ' + str(int(clock.get_fps()))) clock.tick(fps) # Updating display: if not updated: pg.display.update() updated = True pg.display.update(dirtyrects) dirtyrects.clear() </code></pre>
[]
[ { "body": "<p>Sorry I don't have time rn to properly look all through your code for you but one quick thing I noticed is that it would be much nicer to put your colours in a dictionary. It could be implemented like:</p>\n\n<pre><code>colours = {\"black\": ( 0, 0, 0),\n \"white\": (255,255,255),\n ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-09T06:40:04.680", "Id": "207284", "Score": "10", "Tags": [ "python", "performance", "python-3.x", "pygame" ], "Title": "Paint program made in PyGame" }
207284
<p>This is a very simple web API for a school assignment, as a part of a bigger system. The web API returns a list of courses or a single course as json. I doubt that I will get any feedback on the code since Java is taught in the course so I am posting it here. </p> <p>I am a beginner in Racket but have experience with C-style languages (C, C#, Python, etc). </p> <ul> <li>I want to know how I can improve my solution and to be more idiomatic?</li> <li>My function for converting the row-result from the database query to json (<code>rows-result-&gt;json</code>) is very messy, how can improve this? I have added example results (<code>mock-row-result</code>) from the database query that can be used as an argument.</li> </ul> <p>The web api has two end points:</p> <ul> <li>GET /course/{courseid}</li> <li>GET /course with optional parameters: CourseCode, StudyPeriod</li> </ul> <p>The database is a single table in an sqlite-database with the rows:</p> <ul> <li>id - int</li> <li>AppCode - text</li> <li>CourseCode - text</li> <li>StudyPeriod - text</li> <li>Name - text</li> </ul> <p>Code:</p> <pre><code>#lang racket (require web-server/servlet web-server/servlet-env web-server/dispatch db json net/url-structs) (define PORT 8081) (define DATABASE "paraplyet.db") ; Database connection (define paraplyet-db (sqlite3-connect #:database DATABASE)) ; Convert results from database to json, messy (define (rows-result-&gt;json result) (define column-names (map (lambda (r) (string-&gt;symbol (cdr (first r)))) (rows-result-headers result))) (define rows-lists (map vector-&gt;list (rows-result-rows result))) ; Create a list of hashmaps to be able to use jsexpr-&gt;string (define result-hashmaps (map (lambda (row) (make-hash (map cons column-names row))) rows-lists)) (jsexpr-&gt;string result-hashmaps)) ; Mock results from database query, can be used for the function rows-result-&gt;json (define mock-row-result (rows-result '(((name . "AppCode") (decltype . "TEXT")) ((name . "CourseCode") (decltype . "TEXT")) ((name . "StudyPeriod") (decltype . "TEXT")) ((name . "Name") (decltype . "TEXT"))) '(#("LTU-37067" "D0004N" "HT2018" "Databaser I") #("LTU-17045" "D0020N" "HT2018" "Utveckling av informationssystem")))) ; Return list of courses with optional filtering the the parameters CourseCode and StudyPeriod (define (get-courses req) (define params (make-hash (url-query (request-uri req)))) (define courses (query paraplyet-db "SELECT AppCode, CourseCode, StudyPeriod, Name FROM Course WHERE CourseCode = UPPER(COALESCE($1, CourseCode)) AND StudyPeriod = UPPER(COALESCE($2, StudyPeriod))" (hash-ref params 'CourseCode sql-null) (hash-ref params 'StudyPeriod sql-null))) ; Respond with json (response/xexpr (rows-result-&gt;json courses) #:mime-type (string-&gt;bytes/utf-8 "application/json"))) ; Return a specific course (define (get-course req app-code) (define courses (query paraplyet-db "SELECT AppCode, CourseCode, StudyPeriod, Name FROM Course WHERE AppCode = $1" app-code)) ; Return 404 if course is missing, otherwise return JSON (if (empty? (rows-result-rows courses)) (response/xexpr "404: Resource not found" #:code 404) (response/xexpr (rows-result-&gt;json courses) #:mime-type (string-&gt;bytes/utf-8 "application/json")))) ; Function to respond with 404 (define (not-found req) (response/xexpr "404: Not Found" #:code 404)) ; Definition of routing ; /course Get many courses (filter with parameters) ; /course/{AppCode} Get course with specific AppCode (define-values (go _) (dispatch-rules [("course" (string-arg)) #:method "get" get-course] [("course") #:method "get" get-courses] [else not-found])) (define (start-server) (serve/servlet go #:port PORT #:servlet-regexp #rx"" #:launch-browser? #f )) (start-server) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-09T09:04:18.770", "Id": "400069", "Score": "0", "body": "Welcome to Code Review. Could you add some more information, e.g. your API end points and the scheme of the underlying tables? That will make it easier for reviewers to concentra...
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-09T08:57:21.220", "Id": "207290", "Score": "2", "Tags": [ "beginner", "sql", "sqlite", "racket" ], "Title": "Simple web API that access sqlite database" }
207290
<p>Follow up of <a href="https://codereview.stackexchange.com/questions/206921/object-oriented-student-library">Object-oriented student library</a></p> <p>Question: How do you refactor this code so that it is pythonic, follows OOP, reads better and is manageable? How can I write name functions and classes better? How do you know which data structure you need to use so as to manage data effectively?</p> <pre><code>from collections import defaultdict from datetime import datetime, timedelta class StudentDataBaseException(Exception): pass class NoStudent(StudentDataBaseException): pass class NoBook(StudentDataBaseException): pass """To keep of a record of students who have yet to return books and their due dates""" class CheckedOut: loan_period = 10 fine_per_day = 2 def __init__(self): self.due_dates = {} def check_in(self, name): due_date = datetime.now() + timedelta(days=self.loan_period) self.due_dates[name] = due_date def check_out(self, name): current_date = datetime.now() if current_date &gt; self.due_dates[name]: delta = current_date - self.due_dates[name] overdue_fine = self.fine_per_day * delta.days print("Fine Amount: ", overdue_fine) # This only contains the title name for now class BookStatus: def __init__(self, title): self.title = title def __repr__(self): return self.title def __hash__(self): return 0 def __eq__(self, other): return self.title == other # contains a set of books class Library: record = CheckedOut() def __init__(self): self.books = set() def add_book(self, new_book): self.books.add(new_book) def display_books(self): if self.books: print("The books we have made available in our library are:\n") for book in self.books: print(book) else: print("Sorry, we have no books available in the library at the moment") def lend_book(self, requested_book): if requested_book in self.books: print(f'''You have now borrowed \"{requested_book}\"''') self.books.remove(requested_book) return True else: print(f'''Sorry, \"{requested_book}\" is not there in our library at the moment''') return False # container for students class StudentDatabase: def __init__(self): self.books = defaultdict(set) def borrow_book(self, name, book, library): if library.lend_book(book): self.books[name].add(book) return True return False def return_book(self, name, book, library): if book not in self.books[name]: raise NoBook(f'''\"{name}\" doesn't seem to have borrowed "{book}"''') return False else: library.add_book(book) self.books[name].remove(book) return True def students_with_books(self): for name, books in self.books.items(): if books: yield name, books def borrow_book(library, book_tracking): name = input("Student Name: ") book = BookStatus(input("Book Title: ")) if book_tracking.borrow_book(name, book, library): library.record.check_in(name) def return_book(library, book_tracking): name = input("Student Name: ") returned_book = BookStatus(input("Book Title: ")) if book_tracking.return_book(name, returned_book, library): library.record.check_out(name) line = "_" * 100 menu = "Library Management System \n\n \ 1) Add Book \n \ 2) Display all Books \n \ 3) Borrow a Book \n \ 4) Return a Book \n \ 5) Lending Record \n \ 6) Exit" library = Library() book_tracking = StudentDatabase() while True: print(line) print(menu) choice = get_valid_choice(min=1, max=6) print(line) if choice == 1: library.add_book(BookStatus(input("Book Title: "))) elif choice == 2: library.display_books() elif choice == 3: borrow_book(library, book_tracking) elif choice == 4: return_book(library, book_tracking) elif choice == 5: students = tuple(book_tracking.students_with_books()) if students: for name, book in students: print(f"{name}: {book}") else: print("No students have borrowed books at the moment") elif choice == 6: break </code></pre>
[]
[ { "body": "<p>I think the general construction of your code is poor.</p>\n\n<ol>\n<li>A book is owned by a library even if the book is on loan.</li>\n<li>Your code doesn't seem to be able to handle books with the same name.</li>\n<li>Without running your code it looks like you can steal books by taking one out ...
{ "AcceptedAnswerId": "207307", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-09T11:56:25.427", "Id": "207303", "Score": "3", "Tags": [ "python", "beginner", "object-oriented", "python-3.x" ], "Title": "Object-oriented student library 2" }
207303
<p>This is an interview question I saw online and thought to give it a try.<br> The question is about implementing a hash map with a <code>setAll(V value)</code> function. This function assignes a value to all the keys in the map at <code>O(1)</code>.<br> Examples: </p> <pre><code>HashMapSetAll&lt;Integer,String&gt; map = new HashMapSetAll&lt;Integer,String&gt;(); map.put(1, "1"); map.put(2, "2"); map.setAll("all"); map.put(3,"3"); System.out.println(map.get(1)); // prints "all" System.out.println(map.get(2)); // prints "all" System.out.println(map.get(3)); // prints "3" </code></pre> <p>I added the implementation below - please tell me what you think about it - I mostly care about correctness and efficiency. </p> <p>Also, pay attention to the call to <code>Thread.sleep(0,1)</code> - the reason I'm calling it is beacuase <code>isAfter</code> method of <code>ZonedDateTime</code> smallest unit compare is nano-seconds (and I want to make sure that at least one nano-seconds passes between to calls to <code>ZonedDateTime.now()</code>). Please tell me if there is a cleaner way of doing this time compare. </p> <p>HashMapSetAll.java: </p> <pre><code>import java.time.ZonedDateTime; import java.util.HashMap; import java.util.Map; public class HashMapSetAll&lt;K,V&gt; extends HashMap&lt;K,V&gt; { private Map&lt;K,ZonedDateTime&gt; keyDates; private ZonedDateTime setAllTime; private V setAllVal; public HashMapSetAll() { super(); keyDates = new HashMap&lt;K,ZonedDateTime&gt;(); setAllTime = null; setAllVal = null; } @Override public V get(Object key) { ZonedDateTime time = this.keyDates.get(key); if (time == null) return null; if ( (this.setAllTime == null) || (time.isAfter(this.setAllTime)) ) return super.get(key); return this.setAllVal; } @Override public V put(K key, V value) { V oldVal = super.put(key, value); this.keyDates.put(key, ZonedDateTime.now()); try { Thread.sleep(0, 1); } catch (InterruptedException e) { e.printStackTrace(); } return oldVal; } public void setAll(V value) { this.setAllTime = ZonedDateTime.now(); try { Thread.sleep(0, 1); } catch (InterruptedException e) { e.printStackTrace(); } this.setAllVal = value; } } </code></pre> <p>Also added some tests in HashMapSetAllTest.java: </p> <pre><code>import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class HashMapSetAllTest { HashMapSetAll&lt;Integer, String&gt; setAllMap = new HashMapSetAll&lt;Integer, String&gt;(); @BeforeEach void setUp() throws Exception { setAllMap.clear(); } @Test void testPutFirst() { String val = setAllMap.put(1, "hi"); assertNull(val); } @Test void testPutSecond() { String val; setAllMap.put(1, "hi"); val = setAllMap.put(1, "hi2"); assertTrue(val.equals("hi")); } @Test void testGetNormalNull() { assertNull(setAllMap.get(1)); } @Test void testGetNormalValue() { setAllMap.put(1, "hi"); assertTrue(setAllMap.get(1).equals("hi")); } @Test void testGetValAfterSetAll() { // value assigned after setAll setAllMap.setAll("all"); setAllMap.put(1, "mine"); assertTrue(setAllMap.get(1).equals("mine")); } @Test void testGetValBeforeSetAll() { // values assigned before setAll setAllMap.put(1, "mine"); setAllMap.setAll("all"); assertTrue(setAllMap.get(1).equals("all")); } @Test void testGetValBeforeAndAfterSetAll() { // values assigned before setAll setAllMap.put(1, "1"); setAllMap.setAll("all"); setAllMap.put(2, "2"); assertTrue(setAllMap.get(1).equals("all")); assertTrue(setAllMap.get(2).equals("2")); } } </code></pre>
[]
[ { "body": "<p>The obvious solution, replacing all values, is <span class=\"math-container\">\\$O(n)\\$</span> - the trick is to do it in <span class=\"math-container\">\\$O(1)\\$</span>. With that in mind, your approach makes sense - store the new 'all' value, and customize <code>get</code> so it knows whether ...
{ "AcceptedAnswerId": "207315", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-09T13:41:42.570", "Id": "207309", "Score": "4", "Tags": [ "java", "performance", "hash-map" ], "Title": "Hash Map implementation with a function to set all values" }
207309
<p>This is just straight bruteforce with the ability to select multiple charset for one word, being able to mash up the linearity with a modulo. This code is also posted <a href="https://github.com/e2002e/zhou/tree/f8bf2490b898277be263f8d7e2d18847e6492225" rel="nofollow noreferrer">on GitHub</a>.</p> <h3>Generateur.h</h3> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; class Generateur { private: bool two, three; int length1, length2, length3, min, max, loop, size3; char *first, *middle, *last, *tmp, *ptr; long counter2, counter3, *array; void exiterr(char *msg); void gen(long index0); public: Generateur(int argc, char *argv[]); ~Generateur(); }; </code></pre> <h3>zhou.cpp</h3> <pre><code>#include "Generateur.h" int main(int argc, char *argv[]) { Generateur gen(argc, argv); } </code></pre> <h3>Generateur.cpp</h3> <pre><code>#include "Generateur.h" Generateur::Generateur(int argc, char *argv[]) { if (argc &lt; 4) { printf("./zhou min max [first] middle [last [length]].\n");exit(-1); } if(!(min = atoi(argv[1]))) { printf("./zhou min max [first] middle [last [length]].\n");exit(-1); } if(!(max = atoi(argv[2]))) { printf("./zhou min max [first] middle [last [length]].\n");exit(-1); } long index0;//this one runs two = three = false; index0 = loop = 0; //index is the core variable with the array, loop is needed in case max &gt; min counter2 = counter3 = 0; size3 = 1; //when not used we need it anyway because we are substracting it to the password's length for looping array = new long[max]; tmp = new char[max]; first = new char[strlen(argv[3])]; strcpy(first, argv[3]); length1 = strlen(first); if(argc &gt; 4)//is there a second charset ? { two = true; middle = new char[strlen(argv[4])]; strcpy(middle, argv[4]); length2 = strlen(middle); } if(argc &gt; 5)//a third ? { if(argc &lt; 7) { printf("Needs expand of last character set\n"); exit(-1); } three = true; last = new char[strlen(argv[5])]; strcpy(last, argv[5]); length3 = strlen(last); size3 = atoi(argv[6]); } for(int i=0; i&lt;max; i++) { array[i] = 0; } gen(index0);//Entry } Generateur::~Generateur() { delete(tmp); delete(first); if(two) delete(middle); if(three) delete(last); } void Generateur::gen(long index0) { if(index0 == 0) { for(loop=0; loop&lt;max-min+1; loop++) for(array[index0]=0; array[index0]&lt;length1; array[index0]++) if(index0 &lt; min+loop-1) gen(index0+1); } else { for(array[index0]=0; array[index0]&lt;length1; array[index0]++) { if(index0 &lt; min+loop-1 &amp;&amp; !two) gen(index0+1); else { ptr = &amp;tmp[0]; for(int a=0; a &lt; min+loop; a++) { snprintf(ptr, 2, "%c", first[(array[a]+counter3)%length1]); ptr++; } if(two) { for(array[index0]; array[index0]&lt;length2; array[index0]++) { if(index0 &lt; min+loop-size3) gen(index0+1); else { ptr = &amp;tmp[1]; for(int a=0; a &lt; min+loop-size3; a++) { snprintf(ptr, 2, "%c", middle[(array[a+1]+counter2)%length2]); ptr++; } if(three) { for(array[index0]; array[index0]&lt;length3; array[index0]++) { if(index0 &lt; min+loop-1) gen(index0+1); else { ptr = &amp;tmp[min+loop-size3]; for(int a=0; a&lt;size3; a++) { snprintf(ptr, 2, "%c", last[(array[min+loop-size3+a])%length3]); ptr++; } printf("%s\n", tmp); counter3++; } } } else printf("%s\n", tmp); counter2++; } } } else printf("%s\n", tmp); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-25T01:15:46.527", "Id": "402436", "Score": "2", "body": "Please see [What should I do when someone answers my question?](/help/someone-answers). The code in the question must not be modified after it has been reviewed. I have rolled ba...
[ { "body": "<p>Do arg parsing in main and pass the result of that to the constructor of Generateur.</p>\n\n<p>Use <code>std::vector&lt;long&gt;</code> instead of the <code>new long[]</code> array. Use <code>std::string</code> or <code>std::vector&lt;char&gt;</code> instead of the <code>new[]</code>ed char arrays...
{ "AcceptedAnswerId": "207323", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-09T14:41:06.563", "Id": "207314", "Score": "4", "Tags": [ "c++", "recursion" ], "Title": "Password generator with multiple charset" }
207314
<p>This is my first attempt to do unit test for one of my controllers.</p> <pre><code>@RunWith(MockitoJUnitRunner.class) public class AddressControllerUnitTests { private MockMvc mockMvc; @Mock SubmissionService submissionService; @Mock MessageSource messageSource; @InjectMocks AddressController addressController; @Before public void setup() { mockMvc = MockMvcBuilders.standaloneSetup(addressController).build(); } @Test public void submitSuccess() throws Exception { when(submissionService.isEmailAvailable("email@email.com",0)).thenReturn(true); when(messageSource.getMessage("form.submitted.success", null, Locale.ENGLISH)).thenReturn("Form has been submitted successfully"); this.mockMvc .perform(post("/address") .param("address", "my address") .param("phone", "08123456789") .param("email", "email@email.com") .param("userId", "14")) .andExpect(status().isFound()) .andExpect(flash().attribute("message", "Form has been submitted successfully")) .andExpect(redirectedUrl("/address")); } } </code></pre> <p>Do I really need to perform <code>expect</code> on the flashAttribute ? Or Should I just remove it completely ? It looks funny that I have to set</p> <pre><code>when(messageSource.getMessage("form.submitted.success", null, Locale.ENGLISH)).thenReturn("Form has been submitted successfully"); </code></pre> <p>and then </p> <pre><code>.andExpect(flash().attribute("message", "Form has been submitted successfully")) </code></pre>
[]
[ { "body": "<p>You've written 40 lines of code to test 2-3 assignment statements and possibly one if statement. You've also tighly coupled your test to the implementation. This does not seem like a good tradeoff to me.</p>\n\n<p>Read <a href=\"https://martinfowler.com/bliki/UnitTest.html\" rel=\"nofollow norefer...
{ "AcceptedAnswerId": "207412", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-09T16:37:06.677", "Id": "207322", "Score": "3", "Tags": [ "java", "unit-testing", "junit" ], "Title": "Unit Testing for Spring Controller" }
207322
<p>In one of my frameworks that I use with many tools I have an <code>ExpressionVisitor</code> whose job is to resolve the exact property, it's declaring type and instance. I later need this information to create keys/names for my settings (to query a database or read the app.config)</p> <blockquote> <p>Namespace+Type.Member</p> </blockquote> <p>also other (shorter) combinations of that three parts.</p> <p>The code might look as if there were a couple of <em>workarounds</em> but it has to cope with some special cases to get to the right member and type; this means it needs to be able to resolve it from</p> <ul> <li>inside an instance or static class <code>() =&gt; Property</code></li> <li>outside of a class <code>() =&gt; instance.Property</code></li> <li>the right instance if there are multiple expression within the same scope.</li> <li>members of derived classes - this one is tricky because expressions resolve to the base class member (which apparently <a href="https://github.com/dotnet/roslyn/issues/30636" rel="nofollow noreferrer">is not a bug</a>) so just before returning the result I have to check if the resolved type and the declaring-type are different and if this is true I need to get another member - this time the right one. This is important because otherwise the name would be invalid as the name of the base class would be wrong.</li> </ul> <p>Here's an example of it pure usage:</p> <pre><code>void Main() { var user1 = new User(); var user2 = new SuperUser(); // multiple expressions var expr1 = (Expression&lt;Func&lt;object&gt;&gt;)(() =&gt; user1.Name); var expr2 = (Expression&lt;Func&lt;object&gt;&gt;)(() =&gt; user2.Name); var expr3 = (Expression&lt;Func&lt;object&gt;&gt;)(() =&gt; User.Default); // needs to be able to identify the right one SettingVisitor.GetSettingInfo(expr2).Dump(); // SuperUser, instance, Name SettingVisitor.GetSettingInfo(expr1).Dump(); // User, instance, Name SettingVisitor.GetSettingInfo(expr3).Dump(); // User, null, Default } class User { public string Name { get; set; } public static User Default { get; } = new User(); } class SuperUser : User { public string SuperName { get; set; } } </code></pre> <p>I have more helpers build on top of it so the actual usage is much more convenient and moste of the time looks like this:</p> <blockquote> <pre><code>class User { ... public string Name { get =&gt; _configuration.GetValue(() =&gt; Name); set =&gt; _configuration.SetValue(() =&gt; Name, value); } } </code></pre> </blockquote> <p>An this is the API (1:1 copy from my project):</p> <pre><code>internal class SettingVisitor : ExpressionVisitor { private readonly bool _nonPublic; private Type _type; private object _instance; private MemberInfo _member; private string _closureMemberName; private SettingVisitor(bool nonPublic) =&gt; _nonPublic = nonPublic; public static (Type Type, object Instance, MemberInfo Member) GetSettingInfo(LambdaExpression expression, bool nonPublic = false) { var visitor = new SettingVisitor(nonPublic); visitor.Visit(expression); if (visitor._type is null) { throw ("UnsupportedSettingExpression", "Member's declaring type could not be determined.").ToDynamicException(); } // This fixes the visitor not resolving the overriden member correctly. if (visitor._member.DeclaringType != visitor._type) { visitor._member = visitor._type.GetMember(visitor._member.Name).Single(); } return (visitor._type, visitor._instance, visitor._member); } protected override Expression VisitMember(MemberExpression node) { // Supports: // - static fields and properties // - instance fields and properties // The first member is the setting. _member = _member ?? node.Member; switch (node.Member) { // (() =&gt; Type.Member) - static usage case FieldInfo field when field.IsStatic: case PropertyInfo property when property.GetGetMethod(_nonPublic).IsStatic: _type = node.Member.DeclaringType; break; // (() =&gt; instance.Member) - via instance (also this) case FieldInfo field: case PropertyInfo property: // This is necessary to correctly resolve the member when there are multiple instances. _closureMemberName = node.Member.Name; break; } return base.VisitMember(node); } protected override Expression VisitConstant(ConstantExpression node) { // Supports: // - Member (closures) // - instance.Member if (node.Type.Name.StartsWith("&lt;&gt;c__DisplayClass")) { var closureType = node.Type.GetField(_closureMemberName); _type = closureType.FieldType; _instance = closureType.GetValue(node.Value); } else { _type = node.Value.GetType(); _instance = node.Value; } return base.VisitConstant(node); } protected override Expression VisitParameter(ParameterExpression node) { // Supports: // - types passed via generics like .From&lt;T&gt;().Select(x =&gt; x.Y); _type = node.Type; return base.VisitParameter(node); } } </code></pre> <p>Now you can tear it apart and tell me how good or bad it is and if there is anything that can be improved.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-09T19:28:44.150", "Id": "400203", "Score": "0", "body": "Why do you even need to get `MemberInfo` of the override? (I mean you have the `_type` already). The only think that *smells a bit* is `node.Type.Name.StartsWith(\"<>c__DisplayCl...
[ { "body": "<p>I have read the link and the conclusion about the bug was: \"no bug, but as designed\". This is something I cannot comprehend.</p>\n\n<p>This clearly is bad design. When visiting <code>SuperUser</code> for <code>MemberInfo</code> <code>Name</code>, I expect correct behavior; that is:</p>\n\n<ul>\n...
{ "AcceptedAnswerId": "222408", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-09T17:13:52.130", "Id": "207324", "Score": "4", "Tags": [ "c#", "object-oriented", "reflection", "configuration", "expression-trees" ], "Title": "Dynamic setting names based on properties" }
207324
<p>I use bash scripts to process last names through a Perl program, and I parallelize the execution like this, by name initials:</p> <pre><code>for alpha in a b c d e f g h i j do perl process_names.pl -init $alpha &amp; done wait </code></pre> <p>I've determined that ~10 parallel executions is about optimal, to complete the work quickly but also to leave the computer to do other work.</p> <p>But this is inefficient, because some letters have more records to process than others, so sometimes 8 or 9 have finished and there's a lingering program execution during which I'd like to begin processing another batch of name initials.</p> <hr> <p>So I wanted to use Perl's <code>fork</code> to keep 10 processes running at a time. Imagine that the following code block is run by a program invocation like this: <code>perl process_names.pl -all</code> Then the <code>system()</code> call would invoke the program as child processes, like this: <code>perl process_names.pl -init a</code>, <code>b</code>, <code>c</code>, etc., processing 10 at a time until all are finished.</p> <p>This <em>seems</em> to work fine. No zombie processes that I can tell, work gets done, and it's faster. But I've never used the bare <code>fork</code> interface like this. Am I doing it correctly? Are there any gotchas that I've overlooked?</p> <pre><code>my $data = { 'remaining' =&gt; ['a' ... 'z'], 'running' =&gt; [], # &lt;- currently running list of child pids 'children' =&gt; [], # &lt;- all child pids; added to list as spawned, then waited on 'cur_init' =&gt; '' }; while (scalar @{$data-&gt;{remaining}}) { if (scalar @{$data-&gt;{running}} &lt; 10) { $data-&gt;{cur_init} = shift(@{$data-&gt;{remaining}}); my $pid = fork(); if (!$pid) { ## CHILD ## system('perl ' . abs_path($0) . ' -init ' . $data-&gt;{cur_init}); exit; } else { ## PARENT ## push(@{$data-&gt;{running}}, $pid); push(@{$data-&gt;{children}}, $pid); } } my @new; foreach my $cpid (@{$data-&gt;{running}}) { my $is_running = kill(0, $cpid); if ($is_running) { push(@new, $cpid); } } $data-&gt;{running} = \@new; } foreach my $pid (@{$data-&gt;{children}}) { waitpid $pid, 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-09T17:35:24.257", "Id": "400191", "Score": "0", "body": "This is my first contribution to Code Review and it was immediately met with a downvote. I read a bit to make sure that my question accords to the rules, and might be generally h...
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-09T17:21:34.993", "Id": "207326", "Score": "3", "Tags": [ "perl", "multiprocessing" ], "Title": "Using Perl's fork() to parallelize processing" }
207326
<p>I have a feature in my application that should allow users to select items in a drop down menu and move them up and down. Once they select and click on the button I have to loop over the array of objects and pull only records that were selected in the drop down menu.</p> <p>Here is an example of my code:</p> <pre><code>var selectedColumns = ['first','last','city']; var data = [ { first: "Mike", last: "Ross", dob: "05/26/1978", city: "Washington DC", state: "DC", zip: 22904 }, { first: "John", last: "Henderson", dob: "11/06/1988", city: "Iowa City", state: "IA", zip: 52401 }, { first: "Nina", last: "Barkley", dob: "01/16/1968", city: "New York", state: "NY", zip: 11308 }, { first: "Jessie", last: "Kuch", dob: "02/02/1956", city: "Des Moines", state: "IA", zip: 55432 }, { first: "Jenny", last: "Terry", dob: "012/28/1988", city: "Miami", state: "FL", zip: 83943 } ]; </code></pre> <p>In the selected column we only have first, last and city. Then I have to loop over data and pull only selected columns. One way to do that is like this:</p> <pre><code>for(var key in data){ for(var i=0; i&lt;selectedColumns.length; i++){ var columnID = String(columns[i]); console.log($.trim(data[key][columnID])); } } </code></pre> <p>While this solution works just fine, I'm wondering if there is better way to avoid the inner loop and improve efficiency? I use jQuery/JavaScript in my project. If anyone knows a better way to approach this problem please let me know.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-09T20:00:46.403", "Id": "400213", "Score": "0", "body": "Welcome to Code Review? how is `data[key][columnID]` used (other than being logged to the console in the example)?" } ]
[ { "body": "<p>First of all, don't use <code>for-in</code> on arrays. <code>for-in</code> will loop over all enumerable properties, including non-index properties. Also, <code>for-in</code> order is not guaranteed. If you need a loop to go over array items only and in order, use <code>for</code>/<code>while</cod...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-09T19:36:24.917", "Id": "207330", "Score": "0", "Tags": [ "javascript", "jquery", "array" ], "Title": "Checking if an array element exists in a JS object" }
207330
<p>I've been away from C++ for some time and I'd like to get back up to speed with modern practices, so I implemented a small random number generator described <a href="https://burtleburtle.net/bob/rand/smallprng.html" rel="nofollow noreferrer">here</a>. </p> <p>Any advice on this piece of code?</p> <pre><code> #include &lt;cstdint&gt; #include &lt;cstddef&gt; #include &lt;limits&gt; #include &lt;random&gt; // implementation of Bob Jenkins' small prng https://burtleburtle.net/bob/rand/smallprng.html namespace Random { namespace detail { using _rand32_underlying = uint32_t; using _rand64_underlying = uint64_t; template&lt;size_t N&gt; struct rand_type { using type = void; }; template&lt;&gt; struct rand_type&lt;32&gt; { using type = _rand32_underlying; }; template&lt;&gt; struct rand_type&lt;64&gt; { using type = _rand64_underlying; }; } // public template &lt;size_t N&gt; using rand_t = typename detail::rand_type&lt;N&gt;::type; using rand32_t = rand_t&lt;32&gt;; using rand64_t = rand_t&lt;64&gt;; template &lt;size_t N&gt; inline rand_t&lt;N&gt; rot(rand_t&lt;N&gt; x, rand_t&lt;N&gt; k) noexcept { return ((x &lt;&lt; k) | (x &gt;&gt; (N - k))); } template&lt;size_t N&gt; class SmallPrng { public: using result_type = rand_t&lt;N&gt;; inline rand_t&lt;N&gt; min() { return std::numeric_limits&lt;result_type&gt;::min(); } inline rand_t&lt;N&gt; max() { return std::numeric_limits&lt;result_type&gt;::max(); } rand_t&lt;N&gt; a, b, c, d; inline rand32_t prng32() { rand32_t e = a - rot&lt;N&gt;(b, 27); a = b ^ rot&lt;N&gt;(c, 17); b = c + d; c = d + e; d = e + a; return d; } inline rand64_t prng64() { rand64_t e = a - rot&lt;N&gt;(b, 7); a = b ^ rot&lt;N&gt;(c, 13); b = c + rot&lt;N&gt;(d, 37); c = d + e; d = e + a; return d; } public: explicit SmallPrng(result_type seed = 0xdeadbeef) noexcept { static_assert(!(N != 32 &amp;&amp; N != 64), "You can only construct a small prng in 32 or 64 bit mode."); a = 0xf1ea5eed; b = c = d = seed; for(size_t i = 0; i &lt; 20; ++i) (*this)(); } explicit SmallPrng(std::random_device &amp;rd) : SmallPrng(rd()) {} inline rand_t&lt;N&gt; operator()() noexcept { if constexpr(N == 32) return prng32(); return prng64(); } }; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-09T23:18:35.790", "Id": "400237", "Score": "2", "body": "Shouldn't `a, b, c, d` be private?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T00:29:41.973", "Id": "400241", "Score": "3", "body"...
[ { "body": "<ul>\n<li><p>The <code>SmallPrng(std::random_device &amp;rd)</code> constructor seems like an utility method. It spares the client a single call to <code>seed = rd()</code>, but forces an inclusion of (otherwise unnecessary) <code>&lt;random&gt;</code>. IMHO, this constructor is absolutely unnecessar...
{ "AcceptedAnswerId": "207343", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-09T20:08:14.233", "Id": "207333", "Score": "3", "Tags": [ "c++", "random", "c++17" ], "Title": "Small fast pseudorandom number generator in C++" }
207333
<p>I have implemented two pieces of code as part of an Evolutionary Algorithm study: Particle Swarm Optimisation (PSO) and Genetic Algorithm (GA). Both are designed to find an optimal solution to a problem, in this case finding the global minimum of a mathematical function.</p> <p>PSO performs very efficiently and quickly requiring very few iterations. GA, however, uses <strong>a lot</strong> of memory and I cannot see why.</p> <p>The memory used depends on the input dimensions and population size, but it has been well over 8GB in some cases without reaching the max number of iterations (terminated myself). </p> <p>I have tried using the garbage collector, <code>gc</code>, without success. Can anyone see why this may be? Also feel free to comment on the coding style.</p> <p>To run the code, you will need use cec2005real (<code>pip install cec2005real</code>). The idea is a list of numbers is passed into a function from cec2005real, and a single value >0 called the fitness is returned (0 is the optimal solution).</p> <pre><code>import numpy as np from cec2005real.cec2005 import Function np.random.seed(12) class GeneticAlgorithm(): def __init__(self, pop_size, mutation_rate, dimen): self.pop_size = pop_size self.mutation_rate = mutation_rate self.dimen = dimen def _initialize(self): self.population = np.empty(shape=(self.pop_size,self.dimen)) for i in range(self.pop_size): individual = np.random.uniform(-100.0,100.0,self.dimen) self.population[i] = individual def _calculate_fitness(self): pop_fitness = np.empty(self.pop_size) for i,individual in enumerate(self.population): fbench = Function(1, self.dimen) fitness_func = fbench.get_eval_function() fitness = fitness_func(individual) pop_fitness[i]=fitness return pop_fitness def _tournamentSelection(self, pop_fitness): N = len(pop_fitness) best_fitness = 0.0 idx = 0 for i_ in range(3): j = np.random.randint(0,N) fit = pop_fitness[j] if fit &gt; best_fitness: best_fitness = fit idx = j return idx def _mutate(self, individual): for j in range(len(individual)): if np.random.random() &lt; self.mutation_rate: individual[j] = np.random.uniform(-100.0,100.0) return individual def _twoPointCrossover(self, parent1, parent2): N = len(parent1) cx1 = np.random.randint(0,N) cx2 = np.random.randint(0,N) if cx1 == cx2: if cx1 == 0: cx2 += 1 else: cx1 -= 1 if cx2 &lt; cx1: cx1,cx2 = cx2,cx1 child1 = np.concatenate((parent1[:cx1], parent2[cx1:cx2], parent1[cx2:])) child2 = np.concatenate((parent2[:cx1], parent1[cx1:cx2], parent2[cx2:])) return child1, child2 def main(self, iterations): self._initialize() for epoch in range(iterations): pop_fitness = self._calculate_fitness() fittest_individual = self.population[np.argmin(pop_fitness)] min_fitness = min(pop_fitness) pop_fitness = 1/np.array(pop_fitness) mfit = 1/min_fitness probabilities = [f / sum(pop_fitness) for f in pop_fitness] # Determine the next generation new_pop = np.empty(shape=(self.pop_size,self.dimen)) for i in np.arange(0, self.pop_size, 2): idx1 = self._tournamentSelection(pop_fitness) idx2 = self._tournamentSelection(pop_fitness) # Perform crossover to produce children child1, child2 = self._twoPointCrossover(self.population[idx1], self.population[idx2]) # Save mutated children for next generation new_pop[i] = self._mutate(child1) new_pop[i+1] = self._mutate(child2) self.population = new_pop if epoch%1000==0: print ("[Epoch %d, Fitness: %f]" % (epoch+1, min_fitness)) if __name__ == "__main__": ga = GeneticAlgorithm(10, 0.01, 10) ga.main(100000) </code></pre>
[]
[ { "body": "<p>The heavy memory usage was because of the <code>calculate_fitness()</code> function.</p>\n\n<p>I declared a new fitness function from CEC2005 every time I wanted to calculate the fitness, rather than pass in the already declared function.</p>\n\n<p>There are no memory issues anymore. Apologies to ...
{ "AcceptedAnswerId": "207425", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-09T20:09:05.213", "Id": "207334", "Score": "2", "Tags": [ "python", "python-3.x", "numpy", "memory-optimization", "genetic-algorithm" ], "Title": "Genetic Algorithm - heavy memory usage" }
207334
<p>I have this old code and I want it to be easier to understand. Originally, it loaded using an onload on the opening body tag, so I managed to change that to a window.onload, but now redundant code is getting elements by ID, since it first finds the form and after that the actual select box.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var localidades = new Array( new Array("Baja California","Tijuana","Rosarito","Ensenada","Tecate","Mexicali","San Felipe"), new Array("Sonora","San Luis Río Colorado","Sonoita","Sásabe","Nogales","Naco","Agua Prieta"), new Array("Chihuahua","El Berrendo","Puerto Palomas","San Jerónimo","Ciudad Juárez","El Porvenir","Ojinaga"), new Array("Coahuila","Ciudad Acuña","Piedras Negras"), new Array("Nuevo León","Colombia"), new Array("Tamaulipas","Nuevo Laredo","Reynosa","Río Bravo","Nuevo Progreso","Matamoros") ); function seleccionLocal(selection){ var cajon = document.getElementById("forma1").city; for(var x=0;x&lt;localidades.length;x++){ if(selection==localidades[x][0]){ var cities = localidades[x]; cajon.length = cities.length; for(var n=1;n&lt;cities.length;n++){ cajon[n] = new Option(cities[n],cities[n]); } break; } } } window.onload = function StartIt(){ var cajon = document.getElementById("forma1").country; cajon.length = localidades.length+1; for(var x=0;x&lt;localidades.length;x++){ cajon[x+1] = new Option(localidades[x][0],localidades[x][0]); } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;form id="forma1" action="" onsubmit="" style="margin:auto;"&gt; &lt;select name="country" onchange="seleccionLocal(this.options[this.selectedIndex].value)"&gt; &lt;option value="-1" &gt;Estado&lt;/option&gt; &lt;/select&gt; &lt;select name="city"&gt; &lt;option value="-1" &gt;Ciudad&lt;/option&gt; &lt;/select&gt; &lt;/form&gt;</code></pre> </div> </div> </p> <p>It's working, but I guess it can be lighter. What say You?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T08:27:08.513", "Id": "400255", "Score": "0", "body": "Welcome to Code Review. This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about what yo...
[ { "body": "<p>Mixing English and Spanish in code is always awkward. I don't recommend it. If you must do it, though, try to be consistent, and avoid mixing in English identifiers like <code>var cities</code>.</p>\n\n<p>The <code>localidades</code> array, in which the first string of each member array is speci...
{ "AcceptedAnswerId": "207345", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-09T20:31:32.357", "Id": "207335", "Score": "1", "Tags": [ "javascript", "html", "form", "dom" ], "Title": "Drop-down selectors for state and city" }
207335
<p>I'm creating my own implementation of the STL, compliant with the C++17 standard. The only purposeful differences are that the namespace is <code>hsl</code> (homebrew standard library) to prevent name conflicts, and the headers end in .hpp, so that syntax highlighting will work in my editor. I started with <code>hsl::array</code> because it seemed simplest. I'm mostly happy with it, though I have a few questions:</p> <p>Is there a way to make the underlying C-style array private? It's my understanding that that would break aggregate initialization, but it seems awfully inelegant just to leave a comment saying "don't use this!"</p> <p>Should I replace all the <code>T</code>s and <code>N</code>s with the appropriate member types? That seems overly verbose to me, especially down below where I implement the member functions, and I would need to type <code>typename array&lt;T, N&gt;::value_type</code> instead of just <code>T</code>.</p> <p>Is it good practice to place the template implementations in a separate .cpp file, and then include it at the bottom of the header?</p> <p>And the obvious question: is there any place where I'm violating the standard?</p> <pre><code>#pragma once #include "cstddef.hpp" #include "algorithm.hpp" #include "iterator.hpp" // hsl::begin, hsl::end defined here #include "stdexcept.hpp" #include "tuple.hpp" #include "type_traits.hpp" #include "utility.hpp" namespace hsl { template&lt;typename T, size_t N&gt; class array { public: using value_type = T; using reference = T&amp;; using const_reference = const T&amp;; using pointer = T*; using const_pointer = const T*; using iterator = T*; using const_iterator = const T*; using reverse_iterator = hsl::reverse_iterator&lt;T*&gt;; using const_reverse_iterator = hsl::reverse_iterator&lt;const T*&gt;; using size_type = size_t; using difference_type = ptrdiff_t; // Must be public for aggregate initialization to work. // Don't access it directly; use data() method, instead. T arr[N]; // Iterators constexpr T* begin() noexcept; constexpr const T* begin() const noexcept; constexpr T* end() noexcept; constexpr const T* end() const noexcept; constexpr const T* cbegin() const noexcept; constexpr const T* cend() const noexcept; constexpr hsl::reverse_iterator&lt;T*&gt; rbegin() noexcept; constexpr hsl::reverse_iterator&lt;const T*&gt; rbegin() const noexcept; constexpr hsl::reverse_iterator&lt;T*&gt; rend() noexcept; constexpr hsl::reverse_iterator&lt;const T*&gt; rend() const noexcept; constexpr hsl::reverse_iterator&lt;const T*&gt; crbegin() const noexcept; constexpr hsl::reverse_iterator&lt;const T*&gt; crend() const noexcept; // Capacity constexpr size_t size() const noexcept; constexpr size_t max_size() const noexcept; constexpr bool empty() const noexcept; // Element access constexpr T&amp; operator[] (size_t n); constexpr const T&amp; operator[] (size_t n) const; constexpr T&amp; at(size_t n); constexpr const T&amp; at(size_t n) const; constexpr T&amp; front(); constexpr const T&amp; front() const; constexpr T&amp; back(); constexpr const T&amp; back() const; constexpr T* data() noexcept; constexpr const T* data() const noexcept; // Modifiers void fill(const T&amp; val); void swap(array&lt;T, N&gt;&amp; other) noexcept(is_nothrow_swappable&lt;T&gt;::value); }; // Tuple helper class specializations template&lt;size_t I, typename T, size_t N&gt; struct tuple_element&lt;I, array&lt;T, N&gt; &gt; { using type = T; }; template&lt;typename T, size_t N&gt; struct tuple_size&lt;array&lt;T, N&gt; &gt; : public integral_constant&lt;size_t, N&gt; {}; // Relational operators template&lt;typename T, size_t N&gt; bool operator== (const array&lt;T, N&gt;&amp; lhs, const array&lt;T, N&gt;&amp; rhs); template&lt;typename T, size_t N&gt; bool operator&lt; (const array&lt;T, N&gt;&amp; lhs, const array&lt;T, N&gt;&amp; rhs); template&lt;typename T, size_t N&gt; bool operator!= (const array&lt;T, N&gt;&amp; lhs, const array&lt;T, N&gt;&amp; rhs); template&lt;typename T, size_t N&gt; bool operator&lt;= (const array&lt;T, N&gt;&amp; lhs, const array&lt;T, N&gt;&amp; rhs); template&lt;typename T, size_t N&gt; bool operator&gt; (const array&lt;T, N&gt;&amp; lhs, const array&lt;T, N&gt;&amp; rhs); template&lt;typename T, size_t N&gt; bool operator&gt;= (const array&lt;T, N&gt;&amp; lhs, const array&lt;T, N&gt;&amp; rhs); // Tuple-style get template&lt;size_t I, typename T, size_t N&gt; constexpr T&amp; get(array&lt;T, N&gt;&amp; arr) noexcept; template&lt;size_t I, typename T, size_t N&gt; constexpr T&amp; get(array&lt;T, N&gt;&amp;&amp; arr) noexcept; template&lt;size_t I, typename T, size_t N&gt; constexpr const T&amp; get(const array&lt;T, N&gt;&amp; arr) noexcept; // Template member function implementations // Iterators template&lt;typename T, size_t N&gt; constexpr T* array&lt;T, N&gt;::begin() noexcept { return arr; } template&lt;typename T, size_t N&gt; constexpr const T* array&lt;T, N&gt;::begin() const noexcept { return arr; } template&lt;typename T, size_t N&gt; constexpr T* array&lt;T, N&gt;::end() noexcept { return arr+N; } template&lt;typename T, size_t N&gt; constexpr const T* array&lt;T, N&gt;::end() const noexcept { return arr+N; } template&lt;typename T, size_t N&gt; constexpr const T* array&lt;T, N&gt;::cbegin() const noexcept { return arr; } template&lt;typename T, size_t N&gt; constexpr const T* array&lt;T, N&gt;::cend() const noexcept { return arr+N; } template&lt;typename T, size_t N&gt; constexpr reverse_iterator&lt;T*&gt; array&lt;T, N&gt;::rbegin() noexcept { return hsl::reverse_iterator&lt;T*&gt;(end()); } template&lt;typename T, size_t N&gt; constexpr reverse_iterator&lt;const T*&gt; array&lt;T, N&gt;::rbegin() const noexcept { return hsl::reverse_iterator&lt;const T*&gt;(end()); } template&lt;typename T, size_t N&gt; constexpr reverse_iterator&lt;T*&gt; array&lt;T, N&gt;::rend() noexcept { return hsl::reverse_iterator&lt;T*&gt;(begin()); } template&lt;typename T, size_t N&gt; constexpr reverse_iterator&lt;const T*&gt; array&lt;T, N&gt;::rend() const noexcept { return hsl::reverse_iterator&lt;const T*&gt;(begin()); } template&lt;typename T, size_t N&gt; constexpr reverse_iterator&lt;const T*&gt; array&lt;T, N&gt;::crbegin() const noexcept { return hsl::reverse_iterator&lt;const T*&gt;(cend()); } template&lt;typename T, size_t N&gt; constexpr reverse_iterator&lt;const T*&gt; array&lt;T, N&gt;::crend() const noexcept { return hsl::reverse_iterator&lt;const T*&gt;(cbegin()); } // Capacity template&lt;typename T, size_t N&gt; constexpr size_t array&lt;T, N&gt;::size() const noexcept { return N; } template&lt;typename T, size_t N&gt; constexpr size_t array&lt;T, N&gt;::max_size() const noexcept { return N; } template&lt;typename T, size_t N&gt; constexpr bool array&lt;T, N&gt;::empty() const noexcept { return !N; } // Element access template&lt;typename T, size_t N&gt; constexpr T&amp; array&lt;T, N&gt;::operator[] (size_t n) { return arr[n]; } template&lt;typename T, size_t N&gt; constexpr const T&amp; array&lt;T, N&gt;::operator[] (size_t n) const { return arr[n]; } template&lt;typename T, size_t N&gt; constexpr T&amp; array&lt;T, N&gt;::at(size_t n) { if (n &gt;= N) throw out_of_range("hsl::array::at"); return arr[n]; } template&lt;typename T, size_t N&gt; constexpr const T&amp; array&lt;T, N&gt;::at(size_t n) const { if (n &gt;= N) throw out_of_range("hsl::array::at"); return arr[n]; } template&lt;typename T, size_t N&gt; constexpr T&amp; array&lt;T, N&gt;::front() { return arr[0]; } template&lt;typename T, size_t N&gt; constexpr const T&amp; array&lt;T, N&gt;::front() const { return arr[0]; } template&lt;typename T, size_t N&gt; constexpr T&amp; array&lt;T, N&gt;::back() { return arr[N-1]; } template&lt;typename T, size_t N&gt; constexpr const T&amp; array&lt;T, N&gt;::back() const { return arr[N-1]; } template&lt;typename T, size_t N&gt; constexpr T* array&lt;T, N&gt;::data() noexcept { return arr; } template&lt;typename T, size_t N&gt; constexpr const T* array&lt;T, N&gt;::data() const noexcept { return arr; } // Modifiers template&lt;typename T, size_t N&gt; void array&lt;T, N&gt;::fill (const T&amp; val) { for (auto&amp; x : arr) x = val; } template&lt;typename T, size_t N&gt; void array&lt;T, N&gt;::swap(array&lt;T, N&gt;&amp; other) noexcept(is_nothrow_swappable&lt;T&gt;::value) { for (auto it1 = begin(), it2 = other.begin(); it1 != end(); ++it1, ++it2) { hsl::swap(*it1, *it2); } } // Template non-member function implementations // Relational operators template&lt;typename T, size_t N&gt; bool operator== (const array&lt;T, N&gt;&amp; lhs, const array&lt;T, N&gt;&amp; rhs) { return equal(lhs.begin(), lhs.end(), rhs.begin()); } template&lt;typename T, size_t N&gt; bool operator&lt; (const array&lt;T, N&gt;&amp; lhs, const array&lt;T, N&gt;&amp; rhs) { return lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end()); } template&lt;typename T, size_t N&gt; bool operator!= (const array&lt;T, N&gt;&amp; lhs, const array&lt;T, N&gt;&amp; rhs) { return !(lhs == rhs); } template&lt;typename T, size_t N&gt; bool operator&lt;= (const array&lt;T, N&gt;&amp; lhs, const array&lt;T, N&gt;&amp; rhs) { return !(rhs &lt; lhs); } template&lt;typename T, size_t N&gt; bool operator&gt; (const array&lt;T, N&gt;&amp; lhs, const array&lt;T, N&gt;&amp; rhs) { return rhs &lt; lhs; } template&lt;typename T, size_t N&gt; bool operator&gt;= (const array&lt;T, N&gt;&amp; lhs, const array&lt;T, N&gt;&amp; rhs) { return !(lhs &lt; rhs); } // Tuple-style get template&lt;size_t I, typename T, size_t N&gt; constexpr T&amp; get(array&lt;T, N&gt;&amp; arr) noexcept { static_assert(I &lt; N, "I must be less than N"); return arr[I]; } template&lt;size_t I, typename T, size_t N&gt; constexpr T&amp; get(array&lt;T, N&gt;&amp;&amp; arr) noexcept { static_assert(I &lt; N, "I must be less than N"); return arr[I]; } template&lt;size_t I, typename T, size_t N&gt; constexpr const T&amp; get(const array&lt;T, N&gt;&amp; arr) noexcept { static_assert(I &lt; N, "I must be less than N"); return arr[I]; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T08:12:22.873", "Id": "400250", "Score": "0", "body": "Welcome to Code Review. I suggest you to [edit] your post, as it currently sounds like your `array` reimplementation might not work. Avoid words like \"try\" in your description ...
[ { "body": "<p>You said that you want your version compliant with the one from C++17. But with a backward compatibility (C++11, C++14) or do you only aim C++17 and above? (just to be sure) </p>\n\n<ul>\n<li><p>It would be better if you written full include guards instead the non-standard <code>#pragma</code> dir...
{ "AcceptedAnswerId": "207398", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-09T20:55:33.447", "Id": "207337", "Score": "8", "Tags": [ "c++", "array", "reinventing-the-wheel", "c++17" ], "Title": "std::array implementation" }
207337
<p>I'm trying to make a simple game for a school project. Do you have any tips on how to simplify and beautify the code?</p> <p><a href="https://github.com/20nicolas/Game.git" rel="nofollow noreferrer">GitHub</a></p> <pre><code>import pygame as py import os py.init () screen = py.display.set_mode ((800,600)) bg = py.image.load('game-assets-game-background-sidescroller.png') clock = py.time.Clock () idle = [py.image.load(os.path.join('player','Idle (1).png')),py.image.load(os.path.join('player','Idle (2).png')),py.image.load(os.path.join('player','Idle (3).png')),py.image.load(os.path.join('player','Idle (4).png')),py.image.load(os.path.join('player','Idle (5).png')),py.image.load(os.path.join('player','Idle (6).png')),py.image.load(os.path.join('player','Idle (7).png')),py.image.load(os.path.join('player','Idle (8).png')),py.image.load(os.path.join('player','Idle (9).png')),py.image.load(os.path.join('player','Idle (10).png'))] run_right = [py.image.load(os.path.join('player','Run (1).png')),py.image.load(os.path.join('player','Run (2).png')),py.image.load(os.path.join('player','Run (3).png')),py.image.load(os.path.join('player','Run (4).png')),py.image.load(os.path.join('player','Run (5).png')),py.image.load(os.path.join('player','Run (6).png')),py.image.load(os.path.join('player','Run (7).png')),py.image.load(os.path.join('player','Run (8).png'))] jump = [py.image.load(os.path.join('player','Jump (1).png')),py.image.load(os.path.join('player','Jump (2).png')),py.image.load(os.path.join('player','Jump (3).png')),py.image.load(os.path.join('player','Jump (4).png')),py.image.load(os.path.join('player','Jump (5).png')),py.image.load(os.path.join('player','Jump (6).png')),py.image.load(os.path.join('player','Jump (7).png')),py.image.load(os.path.join('player','Jump (8).png')),py.image.load(os.path.join('player','Jump (9).png')),py.image.load(os.path.join('player','Jump (10).png'))] shoot_idle = [py.image.load(os.path.join('player','Shoot (1).png')),py.image.load(os.path.join('player','Shoot (2).png')),py.image.load(os.path.join('player','Shoot (3).png')),py.image.load(os.path.join('player','Shoot (4).png'))] shoot_run = [py.image.load(os.path.join('player','RunShoot (1).png')),py.image.load(os.path.join('player','RunShoot (2).png')),py.image.load(os.path.join('player','RunShoot (3).png')),py.image.load(os.path.join('player','RunShoot (4).png')),py.image.load(os.path.join('player','RunShoot (5).png')),py.image.load(os.path.join('player','RunShoot (6).png')),py.image.load(os.path.join('player','RunShoot (7).png')),py.image.load(os.path.join('player','Run (8).png'))] class player(object): def __init__(self,x,y,width,lenght): self.x = x self.y = y self.width = width self.lenght = lenght self.vel = 5 self.right = False self.left = False self.standing = True self.idlecount = 0 self.runcount = 0 self.jumping = False self.jumpcount = 14 self.direction = 1 self.jumpingcount = 0 self.shooting = False self.shootingcount = 0 def draw (self,screen): if self.idlecount + 1 &gt;= 30: self.idlecount = 0 if self.runcount + 1 &gt;= 24: self.runcount = 0 if self.jumpingcount + 1 &gt;= 31: self.jumpingcount = 0 if self.shootingcount + 1 &gt;= 9: self.shootingcount = 0 if not (self.jumping): if not (self.standing): if self.right: screen.blit (run_right[self.runcount//3],(self.x,self.y)) self.runcount += 1 elif self.left: screen.blit (run_left[self.runcount//3],(self.x,self.y)) self.runcount += 1 else: if self.shooting: if self.direction == 1: screen.blit (shoot_idle[self.shootingcount//2],(self.x,self.y)) self.shootingcount += 1 elif self.direction == -1: screen.blit (shoot_idle2[self.shootingcount//2],(self.x,self.y)) self.shootingcount += 1 elif self.direction == 1: screen.blit (idle[self.idlecount//3],(self.x,self.y)) self.idlecount += 1 elif self.direction == -1: screen.blit (idle2[self.idlecount//3],(self.x,self.y)) self.idlecount += 1 else: if self.direction == 1: screen.blit (jump[self.jumpingcount//3],(self.x,self.y)) self.jumpingcount += 1 self.runcount = 0 elif self.direction == -1: screen.blit (jump2[self.jumpingcount//3],(self.x,self.y)) self.jumpingcount += 1 self.runcount = 0 pows = [py.image.load(os.path.join('player','Bullet_000.png')),py.image.load(os.path.join('player','Bullet_001.png')),py.image.load(os.path.join('player','Bullet_002.png')),py.image.load(os.path.join('player','Bullet_003.png')),py.image.load(os.path.join('player','Bullet_004.png'))] class bulletss (object): def __init__(self,x,y,facing): self.x = x self.y = y self.facing = facing self.vel = 10 * facing self.shootcount = 0 self.lenght = 50 self.width = 50 def draw(self,win): if self.shootcount + 1 == 12: self.shootcount = 0 if self.facing == 1: screen.blit (pows[self.shootcount//3],(self.x+25,self.y-25)) self.shootcount += 1 elif self.facing == -1: screen.blit (pows2[self.shootcount//3],(self.x-75,self.y-25)) self.shootcount += 1 def drawGameScreen (): screen.blit(bg,(0,0)) man.draw (screen) for bullet in bullets: bullet.draw (screen) py.display.update () ##main loop man = player (100,430,100,100) game = True bullets = [] shootloop = 0 idle = [(py.transform.scale(idle[0],(man.width,man.lenght))),(py.transform.scale(idle[1],(man.width,man.lenght))),(py.transform.scale(idle[2],(man.width,man.lenght))),(py.transform.scale(idle[3],(man.width,man.lenght))),(py.transform.scale(idle[4],(man.width,man.lenght))),(py.transform.scale(idle[5],(man.width,man.lenght))),(py.transform.scale(idle[6],(man.width,man.lenght))),(py.transform.scale(idle[7],(man.width,man.lenght))),(py.transform.scale(idle[8],(man.width,man.lenght))),(py.transform.scale(idle[9],(man.width,man.lenght)))] run_right = [(py.transform.scale(run_right[0],(man.width,man.lenght))),(py.transform.scale(run_right[1],(man.width,man.lenght))),(py.transform.scale(run_right[2],(man.width,man.lenght))),(py.transform.scale(run_right[3],(man.width,man.lenght))),(py.transform.scale(run_right[4],(man.width,man.lenght))),(py.transform.scale(run_right[5],(man.width,man.lenght))),(py.transform.scale(run_right[6],(man.width,man.lenght))),(py.transform.scale(run_right[7],(man.width,man.lenght)))] jump = [(py.transform.scale(jump[0],(man.width,man.lenght))),(py.transform.scale(jump[1],(man.width,man.lenght))),(py.transform.scale(jump[2],(man.width,man.lenght))),(py.transform.scale(jump[3],(man.width,man.lenght))),(py.transform.scale(jump[4],(man.width,man.lenght))),(py.transform.scale(jump[5],(man.width,man.lenght))),(py.transform.scale(jump[6],(man.width,man.lenght))),(py.transform.scale(jump[7],(man.width,man.lenght))),(py.transform.scale(jump[8],(man.width,man.lenght))),(py.transform.scale(jump[9],(man.width,man.lenght)))] run_left = [(py.transform.flip(run_right[0],True,False)),(py.transform.flip(run_right[1],True,False)),(py.transform.flip(run_right[2],True,False)),(py.transform.flip(run_right[3],True,False)),(py.transform.flip(run_right[4],True,False)),(py.transform.flip(run_right[5],True,False)),(py.transform.flip(run_right[6],True,False)),(py.transform.flip(run_right[7],True,False))] idle2 = [(py.transform.flip(idle[0],True,False)),(py.transform.flip(idle[1],True,False)),(py.transform.flip(idle[2],True,False)),(py.transform.flip(idle[3],True,False)),(py.transform.flip(idle[4],True,False)),(py.transform.flip(idle[5],True,False)),(py.transform.flip(idle[6],True,False)),(py.transform.flip(idle[7],True,False)),(py.transform.flip(idle[8],True,False)),(py.transform.flip(idle[9],True,False))] jump2 = [(py.transform.flip(jump[0],True,False)),(py.transform.flip(jump[1],True,False)),(py.transform.flip(jump[2],True,False)),(py.transform.flip(jump[3],True,False)),(py.transform.flip(jump[4],True,False)),(py.transform.flip(jump[5],True,False)),(py.transform.flip(jump[6],True,False)),(py.transform.flip(jump[7],True,False)),(py.transform.flip(jump[8],True,False)),(py.transform.flip(jump[9],True,False))] shoot_idle = [(py.transform.scale(shoot_idle[0],(man.width,man.lenght))),(py.transform.scale(shoot_idle[1],(man.width,man.lenght))),(py.transform.scale(shoot_idle[2],(man.width,man.lenght))),(py.transform.scale(shoot_idle[3],(man.width,man.lenght)))] shoot_idle2 = [(py.transform.flip(shoot_idle[0],True,False)),(py.transform.flip(shoot_idle[1],True,False)),(py.transform.flip(shoot_idle[2],True,False)),(py.transform.flip(shoot_idle[3],True,False))] pows = [(py.transform.scale(pows[0],(50,50))),(py.transform.scale(pows[1],(50,50))),(py.transform.scale(pows[2],(50,50))),(py.transform.scale(pows[3],(50,50))),(py.transform.scale(pows[4],(50,50)))] pows2 = [(py.transform.flip(pows[0],True,False)),(py.transform.flip(pows[1],True,False)),(py.transform.flip(pows[2],True,False)),(py.transform.flip(pows[3],True,False)),(py.transform.flip(pows[4],True,False))] while game: clock.tick (30) if shootloop &gt; 0: shootloop += 1 if shootloop &gt; 5: shootloop = 0 for event in py.event.get(): if event == py.QUIT: game = False keys = py.key.get_pressed () for bullet in bullets: if bullet.x &lt; 800 and bullet.x &gt; 0: bullet.x += bullet.vel else: bullets.remove (bullet) if keys[py.K_RIGHT] and man.x &lt;= 700: man.x += man.vel man.right = True man.left = False man.standing = False man.idlecount = 0 man.direction = 1 elif keys[py.K_LEFT] and man.x &gt;= 0: man.x -= man.vel man.right = False man.left = True man.standing = False man.idlecount = 0 man.direction = -1 else: man.standing = True man.shooting = False if keys [py.K_SPACE] and shootloop == 0: if man.left: facing = -1 elif man.right: facing = 1 if len(bullets) &lt; 5: man.standing = True man.shooting = True bullets.append(bulletss(round(man.x + man.lenght//2), round(man.y + man.lenght//2), facing)) shootloop = 1 if not(man.jumping): if keys[py.K_UP]: man.jumping = True man.right = False man.left = False man.standing = False man.walkcount = 0 else: if man.jumpcount &gt;= -14: neg = 1 if man.jumpcount &lt; 0: neg = -1 man.y -= (man.jumpcount ** 2) * 0.2 * neg man.jumpcount -= 1 else: man.jumping = False man.jumpcount = 14 drawGameScreen () </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T22:42:58.437", "Id": "400325", "Score": "0", "body": "Just to note, I'm working on a very detailed answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-12T13:15:39.410", "Id": "400500", "Score...
[ { "body": "<p>This is a big review, and it will be hard to cover everything, so I'll go with some main points and then a few tips (having started my own game in pygame as well, if you want to take a look - it's not perfect though - <a href=\"https://github.com/arthur-hav/hexrl\" rel=\"noreferrer\">https://githu...
{ "AcceptedAnswerId": "207389", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-09T22:47:27.933", "Id": "207339", "Score": "5", "Tags": [ "python", "pygame" ], "Title": "Simple Python Pygame Game" }
207339
<p>I am working on a background project that is a little interactive. Now I am using some collision detection to draw some lines and stuff.</p> <p>The code I have works great but it is very bulky and hard to read.</p> <pre><code>if (background.allPixels[i].location.x - drawLineBetweenPixelRange &lt; background.allPixels[j].location.x + background.allPixels[j].width &amp;&amp; background.allPixels[i].location.x + background.allPixels[i].width + drawLineBetweenPixelRange &gt; background.allPixels[j].location.x &amp;&amp; background.allPixels[i].location.y - drawLineBetweenPixelRange &lt; background.allPixels[j].location.y + background.allPixels[j].height &amp;&amp; background.allPixels[i].location.y + background.allPixels[i].height + drawLineBetweenPixelRange &gt; background.allPixels[j].location.y) </code></pre> <p>It comes down to running this for the x and y coordinates:</p> <pre><code>var result = (x - a &lt; y + b) &amp;&amp; (x + b + a &gt; y) </code></pre> <p>Can this be simplified?</p> <p>I was hoping if the check itself could be shortened by taking stuff out that might counter eachother. </p>
[]
[ { "body": "<p>first, accessing those properties all over again is really confusing</p>\n\n<pre><code>let bgI = background.allPixels[i]\nlet locI = bgI.location\nlet line = drawLineBetweenPixelRange\nlet bgJ = background.allPixels[j]\nlet locJ = bgJ.location\n\n\nif (locI.x - line &lt; locJ.x + bgJ.width &amp;&a...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T01:36:42.737", "Id": "207342", "Score": "1", "Tags": [ "javascript", "collision" ], "Title": "Simplify JavaScript collision detection with offset" }
207342
<p>I wrote a function to calculate an 8-bit CRC/checksum for unknown data types. The only restriction is the data type must be at most 4bytes/32bits.</p> <pre><code>uint8_t crc(void* _crc, ssize_t len, uint8_t _crc_seed) { void* _crc_cpy = malloc(len); memcpy(_crc_cpy, _crc, len); uint32_t* _crc_cpy_pointer = static_cast&lt;uint32_t*&gt;(_crc_cpy); uint8_t _crc_u[len]; for(int i = len; i &gt; 0; i--) { _crc_u[len-i] = ((*_crc_cpy_pointer)&amp;(0xff &lt;&lt; 8*(i-1))) &gt;&gt; (8*(i-1)); } uint8_t crc_seed = _crc_seed; uint8_t crc_u; for(int i = 0; i &lt; len; i++) { crc_u = _crc_u[i] ^= crc_seed; for(int i = 0; i &lt; 8; i++) { crc_u = (crc_u &amp; 0x80) ? 0x7 ^ (crc_u &lt;&lt; 1) : (crc_u &lt;&lt; 1); } crc_seed = crc_u; } return crc_u; } </code></pre> <p>How can I do this better? What are things that I did incorrectly?</p>
[]
[ { "body": "<p>Its always informative to comment the specific crc polynomial. An 8 bit crcs is only marginally better than 8 bit checksum.</p>\n\n<p>First, remove the malloc() and memcpy(). A crc is a calculation that does not affect the input data. There is no need to allocate and copy the input data. Also, you...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T01:38:50.983", "Id": "207344", "Score": "3", "Tags": [ "c++", "checksum" ], "Title": "CRC without knowing the data type or size" }
207344
<p>These are the three steps that need to be taken in order to successfully activate Long Mode. Error reporting is sparse as most real hardware for developing an OS is 64 bit but probably still a good idea to implement this verification procedure.</p> <p>I did a little tweaking of some of the examples that can be found on the web either in whole or in part and believe 74 bytes might be as tight as it can get.</p> <pre><code> PageZero equ 0xb800 ID equ 0b100000 ; AMD 24592 Rev 3.14 2007 Feature detection. Section 3.6 pg 74 ; ------------------------------------------------------------ ; A: Test if CPU supports CPUID pushfd ; Save a current copy of flags ; Create a simplified pointer that becomes essentially SS:BX push ss mov bx, sp ; BX will point to bits 23-16 of EFLAGS pop ds ; Read flags, toggle (ID) and write back to flags. pushfd ; Get another copy of EFLAGS or byte [bx], ID ; Toggle bit 21 (ID) [bit 5 of BX] mov al, [bx] ; Save a copy popfd ; Write value back to EFLAGS ; Read flags again and if ID remains inverted, then processor supports CPUID. pushfd pop dx ; DX = Bits 15 - 0 of EFLAGS pop dx ; DX = Bits 16 - 31 popfd ; Restore flags to original values xor al, dl ; Bit 4 of AL &amp; DL is (ID) jz TstExt ; As this error is very improbable, near center bottom there will be an uppercase "E" ; yellow on red, with two red flashing bars on each side. FncErr: mov di, (22*80+39)*2 ; Point to center position of 21th row in video mov ax, PageZero ; Page 0 of 80x26x16 (Mode 3) mov es, ax mov eax, 0x2e4684b1 ; This makes the desired character combination work stosd stosw cli hlt jmp $ - 1 ; Just hang. ; B: Are extended functions supported TstExt: mov eax, 0x80000000 push eax cpuid ; Extended function limit pop edx cmp eax, edx jb FncErr ; C: Does processor support Long Mode. mov al, 1 ; Set EAX = 0x80000001 cpuid bt edx, 29 ; 64 bit available if bit is on. jnc FncErr </code></pre>
[]
[ { "body": "\n\n<p>Documentation for this flag reads:</p>\n\n<blockquote>\n <p>If a software procedure can <strong>set and clear</strong> this flag, the processor executing the procedure supports the CPUID instruction</p>\n</blockquote>\n\n<p>This clearly means that the flag does not have a defined value. It co...
{ "AcceptedAnswerId": "207445", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T04:38:47.750", "Id": "207348", "Score": "7", "Tags": [ "assembly", "x86" ], "Title": "X86 Feature detection in preparation for Long Mode" }
207348
<p>Kindly review this scala code for given problem and suggest improvements.</p> <p><strong>Problem</strong> - Given an array of integers and a target sum, check if array contains a pair which adds up to sum.</p> <p><strong>Example</strong> - </p> <pre><code>i/p - (1,2,4,5,6) 7 o/p - true i/p - (1,1,1,5,6) 2 o/p - true i/p - (1,4,4,5,6) 13 o/p - false </code></pre> <p><strong>Scala implementation</strong> </p> <pre><code>import scala.collection.immutable._ object FindMatchingSum { def containsMatchingSum(data: Array[Int], complementTable: Set[Int], sum: Int): Boolean = { if (data.isEmpty) false else if (complementTable contains data.head) true else containsMatchingSum(data.drop(1), complementTable ++ Set(sum-data.head), sum) } def main(args: Array[String]):Unit = { println(containsMatchingSum(Array(1,2,4,5,6), Set[Int](), 7)) println(containsMatchingSum(Array(1,1,1,5,6), Set[Int](), 2)) println(containsMatchingSum(Array(1,4,4,5,6), Set[Int](), 9)) println(containsMatchingSum(Array(1,4,4,5,6), Set[Int](), 13)) } } </code></pre> <p><strong>Sample run</strong></p> <pre><code>scalac FindMatchingSum.scala scala FindMatchingSum true true true false </code></pre>
[]
[ { "body": "<p>If you're worried about efficiency you could copy the Array into a Vector or use an index instead of paring down the input.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T20:15:10.767", "Id":...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T05:08:55.790", "Id": "207350", "Score": "1", "Tags": [ "array", "recursion", "interview-questions", "scala", "k-sum" ], "Title": "Check if list contains a pair which adds up to a given sum" }
207350
<p>Is there a better way to write this while maintaining its current functionality? (checking balances, updating, subtracting, etc...) If so, where would I begin? I saw a code briefly in class that was for a similar questions and it looked more streamlined.</p> <pre><code>class Account: # constructor def __init__(self, name, account_number, balance): self.name = name self.account_number = account_number self.balance = balance # returns string representation of object def __str__(self): return"Account Name: {0}\nAccount Number: {1} \nAccount Balance:\ ${2:.2f}".format(self.name, self.account_number, self.balance) # add given amount to balance def deposit(self, amount): self.balance += amount # subtract amount and fee from balance def withdraw(self, amount, fee): self.balance = self.balance - amount - fee if __name__ == '__main__': # make 3 objects acct1 = Account('Guy Mann', 90453889, 100) acct2 = Account('Donald Duck', 83504837, 100) acct3 = Account('Joe Smith', 74773321, 100) # print print(acct1) print(acct2) print(acct3) # deposit and print acct1.deposit(25.85) acct2.deposit(75.50) acct3.deposit(50) print(acct1) print(acct2) print(acct3) # withdraw and print acct1.withdraw(25.85, 2.50) acct2.withdraw(75.50, 1.50) acct3.withdraw(50, 2) print(acct1) print(acct2) print(acct3) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T10:59:23.833", "Id": "400264", "Score": "0", "body": "Now it's looking good :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T11:14:20.457", "Id": "400265", "Score": "0", "body": "Awesom...
[ { "body": "<p>This code is already quite compact. Some <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a> code styling will not hurt. Some spaces here and there, consistency in using quotes in string literals. Also some comments can be turned into <a href=\"https://www.python.org/...
{ "AcceptedAnswerId": "207380", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T10:14:58.850", "Id": "207354", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "Bank account balance, withdraw, deposit: compartmentalize without losing functionality" }
207354
<p>I created a template trait which finds the common <a href="https://en.cppreference.com/w/cpp/iterator#Iterator_categories" rel="nofollow noreferrer">iterator category</a> between a set of given iterator categories. More specifically, it's a class with a member type alias to one of the <a href="https://en.cppreference.com/w/cpp/iterator/iterator_tags" rel="nofollow noreferrer">iterator tags</a> which is the most efficient for the specific requirement set that is implied by both categories given as template arguments (the least "powerful" in the iterator hierarchy).</p> <p>For example, given <code>std::forward_iterator_tag</code>, <code>std::random_access_iterator_tag</code> and <code>std::bidirectional_iterator_tag</code>, it provide <code>std::forward_iterator_tag</code>. </p> <p>If all the given types are <code>std::output_iterator_tag</code> then it will provide <code>std::output_iterator_tag</code>. Otherwise, there is no member type alias. (<code>std::output_iterator_tag</code> must be treated differently because it is not in the input iterator hierarchy.) </p> <pre><code>#include &lt;algorithm&gt; #include &lt;iterator&gt; #include &lt;tuple&gt; #include &lt;type_traits&gt; namespace detail { // Gets the index of the first occurrence of a type in a tuple (inverse of std::tuple_element_t). template &lt;typename T, class Tuple&gt; struct tuple_type_index; // Specialisation for match on parameter pack's first type. template&lt;typename T, typename... Ts&gt; struct tuple_type_index&lt;T, std::tuple&lt;T, Ts...&gt;&gt; : std::integral_constant&lt;std::size_t, 0&gt; {}; // Specialisation for no match on parameter pack's first type. template&lt;typename T, typename U, typename... Ts&gt; struct tuple_type_index&lt;T, std::tuple&lt;U, Ts...&gt;&gt; : std::integral_constant&lt;std::size_t, 1 + tuple_type_index&lt;T, std::tuple&lt;Ts...&gt;&gt;::value&gt; {}; // Helper variable template. template&lt;typename T, class Tuple&gt; constexpr std::size_t tuple_type_index_v = tuple_type_index&lt;T, Tuple&gt;::value; // Hierarchy of input iterator categories (output iterator category is handled separately) from least to most powerful. using iterator_categories = std::tuple&lt;std::input_iterator_tag, std::forward_iterator_tag, std::bidirectional_iterator_tag, std::random_access_iterator_tag&gt;; } // Primary template (for 0 categories). template&lt;class... IteratorCategories&gt; struct common_iterator_category {}; // Helper type alias. template&lt;class... IteratorCategories&gt; using common_iterator_category_t = typename common_iterator_category&lt;IteratorCategories...&gt;::type; // Specialisation for 1 category. template&lt;class IteratorCategory&gt; struct common_iterator_category&lt;IteratorCategory&gt; { using type = IteratorCategory; }; // Specialisation for 2 non-output-iterator categories. template&lt;class IteratorCategory1, class IteratorCategory2&gt; struct common_iterator_category&lt;IteratorCategory1, IteratorCategory2&gt; { using type = std::tuple_element_t&lt; std::min( detail::tuple_type_index_v&lt;IteratorCategory1, detail::iterator_categories&gt;, detail::tuple_type_index_v&lt;IteratorCategory2, detail::iterator_categories&gt;), detail::iterator_categories&gt;; }; // Specialisation for 2 output iterator categories. template&lt;&gt; struct common_iterator_category&lt;std::output_iterator_tag, std::output_iterator_tag&gt; { using type = std::output_iterator_tag; }; // Specialisation for 3+ categories. template&lt;class IteratorCategory1, class IteratorCategory2, class... IteratorCategories&gt; struct common_iterator_category&lt;IteratorCategory1, IteratorCategory2, IteratorCategories...&gt; : common_iterator_category&lt;common_iterator_category_t&lt;IteratorCategory1, IteratorCategory2&gt;, common_iterator_category_t&lt;IteratorCategories...&gt;&gt; {}; </code></pre> <p>The code with tests/examples is live <a href="http://coliru.stacked-crooked.com/a/cedd57af4c70843f" rel="nofollow noreferrer">here</a>.</p> <p>I am specifically interested in feedback with regards to the conciseness/efficiency of the design, and also whether it is well formed (I am worried about UB but "happens to work" or no diagnostic required issues). I'm not so much concerned with the <code>tuple_type_index</code> utility (it's just there because it happens to be required). But feedback of any sort is of course welcome.</p>
[]
[ { "body": "<p>You should try to implement <code>min</code> and a minimal <code>typelist</code> to get rid of <code>std::tuple</code> and <code>std::min</code> (and their headers) and so, make it compatible with c++11 and reduce header dependencies.</p>\n\n<p>but otherwise it's a pretty useful trait, well write...
{ "AcceptedAnswerId": "207411", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T10:29:02.097", "Id": "207356", "Score": "4", "Tags": [ "c++", "c++14", "iterator", "template-meta-programming" ], "Title": "Finding the common iterator category in C++" }
207356
<p>I have an inheritance class that mimics the behavior of C style array's brace initialization by using a class template that has a variadic constructor but the template itself is not a variadic template. The base class stores the contents from two flavors of constructors either a Variadic Constructor, or a Variadic Constructor that takes an <code>std::initializer_list</code> as it's parameter. The base class also contains a size that is inferred by its populated member vector, a function to return its size and an overloaded operator <code>operator()()</code> that will return its internal vector.</p> <p>The child class inherits this functionality. It only has one member and that is a pointer to <code>&lt;T&gt;</code>. It has the corresponding matching constructors as its parent class, a set of overloaded subscript-indexing operators and a public method to retrieve it's internal pointer. This class's internal pointer is set to point to its parent's internal vector's data. </p> <p>As far as I can tell this appears to be bug free to the best of my knowledge and it is producing expected values. Here is what I have so far.</p> <hr> <pre><code>#include &lt;vector&gt; #include &lt;string&gt; #include &lt;sstream&gt; #include &lt;iostream&gt; #include &lt;exception&gt; #include &lt;type_traits&gt; #include &lt;initializer_list&gt; #include &lt;utility&gt; template&lt;typename T&gt; class ParamPack { protected: std::vector&lt;T&gt; values_; size_t size_; public: template&lt;typename... U&gt; ParamPack( U... u ) : values_{ static_cast&lt;T&gt;(u)... } { size_ = values_.size(); } template&lt;typename ... U&gt; ParamPack( std::initializer_list&lt;std::is_same&lt;T, U...&gt;( U...)&gt; il ) : values_( il ) { size_ = values_.size(); } std::vector&lt;T&gt; operator()() { return values_; } const size_t size() const { return size_; } }; template&lt;typename T&gt; class Array : public ParamPack&lt;T&gt; { private: T* items_; public: template&lt;typename... U&gt; Array( U... u ) : ParamPack&lt;T&gt;::ParamPack( u... ) { items_ = this-&gt;values_.data(); } template&lt;typename... U&gt; Array( std::initializer_list&lt;U...&gt; il ) : ParamPack&lt;T&gt;::ParamPack( il ) { items_ = this-&gt;values_.data(); } T&amp; operator[]( int idx ) { return items_[idx]; } T operator[]( int idx ) const { return items_[idx]; } T* data() const { return items_; } }; int main() { try { // Parameter Pack Examples: // Variadic Constructor { ... } std::cout &lt;&lt; "ParamPack&lt;T&gt; Examples:\n"; std::cout &lt;&lt; "Using ParamPack&lt;T&gt;'s Variadic Constructor\n"; ParamPack&lt;int&gt; pp1( 1, 2, 3, 4 ); std::cout &lt;&lt; "Size: " &lt;&lt; pp1.size() &lt;&lt; " | Elements: "; for( auto&amp; v : pp1() ) { std::cout &lt;&lt; v &lt;&lt; " "; } std::cout &lt;&lt; '\n'; //std::initializer_list&lt;int&gt; il{ 1,2,3,4 }; std::cout &lt;&lt; "Using ParamPack&lt;T&gt;'s Initializer List\n"; ParamPack&lt;int&gt; pp2( { 5, 6, 7, 8 } ); std::cout &lt;&lt; "Size: " &lt;&lt; pp2.size() &lt;&lt; " | Elements: "; for( auto&amp; v : pp2() ) { std::cout &lt;&lt; v &lt;&lt; " "; } std::cout &lt;&lt; "\n\n"; // Array Examples: // Using Variadic Constructor std::cout &lt;&lt; "Array&lt;T&gt; Examples:\n"; std::cout &lt;&lt; "Using Array&lt;T&gt;'s Variadic Constructor\n"; Array&lt;int&gt; testA( 9, 8, 7, 6 ); for( size_t i = 0; i &lt; testA.size(); i++ ) { std::cout &lt;&lt; testA[i] &lt;&lt; " "; } std::cout &lt;&lt; '\n'; Array&lt;std::string&gt; testB( "Hello", " World" ); for( size_t i = 0; i &lt; testB.size(); i++ ) { std::cout &lt;&lt; testB[i] &lt;&lt; " "; } std::cout &lt;&lt; "\n\n"; // Using Constructor w/ Initializer List std::cout &lt;&lt; "Using Array&lt;T&gt;'s Constructor with Initializer List\n"; Array&lt;int&gt; testC( { 105, 210, 420 } ); for( size_t i = 0; i &lt; testC.size(); i++ ) { std::cout &lt;&lt; testC[i] &lt;&lt; " "; } std::cout &lt;&lt; "\n\n"; // Using Initializer List with = std::cout &lt;&lt; "Using Array&lt;T&gt;'s Initializer List with =\n"; Array&lt;int&gt; a = { 1, 2, 3, 4 }; for( size_t i = 0; i &lt; a.size(); i++ ) { std::cout &lt;&lt; a[i] &lt;&lt; " "; } std::cout &lt;&lt; '\n'; Array&lt;char&gt; b = { 'a', 'b', 'c', 'd' }; for ( size_t i = 0; i &lt; b.size(); i++ ) { std::cout &lt;&lt; b[i] &lt;&lt; " "; } std::cout &lt;&lt; '\n'; Array&lt;double&gt; c = { 1.2, 3.4, 4.5, 6.7 }; for( size_t i = 0; i &lt; c.size(); i++ ) { std::cout &lt;&lt; c[i] &lt;&lt; " "; } std::cout &lt;&lt; "\n\n"; // Using Initializer List directly std::cout &lt;&lt; "Using Array&lt;T&gt;'s Initalizer List directly\n"; Array&lt;uint32_t&gt; a1{ 3, 6, 9, 12 }; for( size_t i = 0; i &lt; a1.size(); i++ ) { std::cout &lt;&lt; a1[i] &lt;&lt; " "; } std::cout &lt;&lt; "\n\n"; // Using user defined data type struct Point { int x_, y_; Point( int x, int y ) : x_( x ), y_( y ) {} }; Point p1( 1, 2 ), p2( 3, 4 ), p3( 5, 6 ); // Variadic Constructor std::cout &lt;&lt; "Using Array&lt;T&gt;'s Variadic Consturctor with user data type\n"; Array&lt;Point&gt; d1( p1, p2, p3 ); for( size_t i = 0; i &lt; d1.size(); i++ ) { std::cout &lt;&lt; "(" &lt;&lt; d1[i].x_ &lt;&lt; "," &lt;&lt; d1[i].y_ &lt;&lt; ") "; } std::cout &lt;&lt; '\n'; // Initializer List Construtor (reversed order) std::cout &lt;&lt; "Using Array&lt;T&gt;'s Initializer List Constructor with user data type\n"; Array&lt;Point&gt; d2( { p3, p2, p1 } ); for( size_t i = 0; i &lt; d2.size(); i++ ) { std::cout &lt;&lt; "(" &lt;&lt; d2[i].x_ &lt;&lt; "," &lt;&lt; d2[i].y_ &lt;&lt; ") "; } std::cout &lt;&lt; '\n'; // Initializer List Version = {...} p2 first std::cout &lt;&lt; "Using Array&lt;T&gt;'s = Initializer List with user data type\n"; Array&lt;Point&gt; d3 = { p2, p1, p3 }; for( size_t i = 0; i &lt; d3.size(); i++ ) { std::cout &lt;&lt; "(" &lt;&lt; d3[i].x_ &lt;&lt; "," &lt;&lt; d3[i].y_ &lt;&lt; ") "; } std::cout &lt;&lt; '\n'; // Initializer List Directly p2 first p1 &amp; p3 swapped std::cout &lt;&lt; "Using Array&lt;T&gt;'s Initializer List directly with user data type\n"; Array&lt;Point&gt; d4{ p2, p3, p1 }; for( size_t i = 0; i &lt; d4.size(); i++ ) { std::cout &lt;&lt; "(" &lt;&lt; d4[i].x_ &lt;&lt; "," &lt;&lt; d4[i].y_ &lt;&lt; ") "; } std::cout &lt;&lt; "\n\n"; // Need a local copy of the vector instead? std::cout &lt;&lt; "Using Array&lt;T&gt;'s base class's operator()() to retrieve vector\n"; std::vector&lt;Point&gt; points = d4(); // using operator()() for( auto&amp; p : points ) { std::cout &lt;&lt; "(" &lt;&lt; p.x_ &lt;&lt; "," &lt;&lt; p.y_ &lt;&lt; ") "; } std::cout &lt;&lt; '\n'; // Need a local copy of the pointer instead? std::cout &lt;&lt; "Using Array&lt;T&gt;'s data() to get the contents of its internal pointer\n"; Point* pPoint = nullptr; pPoint = d4.data(); for( size_t i = 0; i &lt; d4.size(); i++ ) { std::cout &lt;&lt; "(" &lt;&lt; pPoint[i].x_ &lt;&lt; "," &lt;&lt; pPoint[i].y_ &lt;&lt; ") "; } std::cout &lt;&lt; '\n'; // Will Not Compile: Must Be Instantiated By Type Explicitly // Array e( 1, 2, 3, 4 ); // Array e( { 1,2,3,4 } ); // Array f{ 1, 2, 3, 4 }; // Array g = { 1,2,3,4 }; } catch( const std::runtime_error&amp; e ) { std::cerr &lt;&lt; e.what() &lt;&lt; '\n'; return EXIT_FAILURE; } return EXIT_SUCCESS; } </code></pre> <hr> <p><em>-Output-</em></p> <blockquote> <pre><code>ParamPack&lt;T&gt; Examples: Using ParamPack&lt;T&gt;'s Variadic Constructor Size: 4 | Elements: 1 2 3 4 Using ParamPack&lt;T&gt;'s Initializer List Size: 5 | Elements: 5 6 7 8 Array&lt;T&gt; Examples: Using Array&lt;T&gt;'s Variadic Constructor 9 8 7 6 Hello World Using Array&lt;T&gt;'s Constructor with Initializer List 105 210 420 Using Array&lt;T&gt;'s Initializer List with = 1 2 3 4 a b c d 1.2 3.4 5.6 7.8 Using Array&lt;T&gt;'s Initializer List directly 3 6 9 12 Using Array&lt;T&gt;'s Variadic Constructor with user data type (1,2) (3,4) (5,6) Using Array&lt;T&gt;'s Initializer List Constructor with user data type (5,6) (3,4) (1,2) Using Array&lt;T&gt;'s = Initializer List with user data type (3,4) (1,2) (5,6) Using Array&lt;T&gt;'s Initializer List directly with user data type (3,4) (5,6) (1,2) Using Array&lt;T&gt;'s base class's operator()() to retrieve vector (3,4) (5,6) (1,2) Using Array&lt;T&gt;'s data() to get the contents of its internal pointer (3,4) (5,6) (1,2) </code></pre> </blockquote> <hr> <p>There are few things I'd like to know about this code: The main concerns are more towards the classes themselves than the actual code use within the main function. However, suggestions towards the use of the class are accepted as well.</p> <ul> <li>Does this follow modern best practices? <em>Note:</em> I know I can encapsulate it in an <code>namespace</code> but for simplicity I just posted the classes themselves <ul> <li>If not what changes or fixes need to be made?</li> </ul></li> <li>Is it considered readable enough?</li> <li>Is the code efficient? <ul> <li>What can be done to improve its efficiency?</li> </ul></li> <li>Are there any unforeseen bugs or gotchas that I overlooked?</li> <li>Is this considered portable, reusable, and generic?</li> <li>Will the derived class invoke the appropriate constructor or will it just fall back to one of them? </li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T22:50:14.400", "Id": "400326", "Score": "0", "body": "Did you notice that in your `ParamPack<T>` initializer list test that the size is incorrect?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-11T07:45...
[ { "body": "<ul>\n<li>I think you should make your interface <code>constexpr</code></li>\n<li>Did you expect negative index? If not, try to use <code>std::size_t</code> instead of int. </li>\n<li>Does returning <code>values_</code> by value is a design choice?</li>\n<li>You specify the return type of <code>size...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T10:56:45.853", "Id": "207357", "Score": "5", "Tags": [ "c++", "template", "c++17", "constructor", "variadic" ], "Title": "C++ wrapper class to mimic a C array's brace initialization" }
207357
<p>As an <a href="https://andre.tips/wmh/functions-first-class/" rel="nofollow noreferrer">exercise</a> (scroll to the first set of exercises) for learning Haskell, I have to implement <code>foldl1</code>.</p> <p>I believe I have implemented it successfully and while there is an answer available, it would be great to have the eye of an expert and more importantly, the <em>thought process</em> of why certain decisions were made.</p> <p>Below is my code.</p> <pre><code>foldl1' :: (a -&gt; a -&gt; a) -&gt; [a] -&gt; a foldl1' f [a] = a foldl1' f xs = foldl1' f ((f (xs !! 0) (xs !! 1)):(drop 2 xs)) </code></pre>
[]
[ { "body": "<p>First, I like the explicit statement of the type signature. That's a good habit to get into, and makes it easier to capitalise on perhaps the greatest strength of using Haskell which is all the compile time checking. The provided signature is as general as it can be for lists.</p>\n<p>Second, the ...
{ "AcceptedAnswerId": "207366", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T11:34:00.927", "Id": "207358", "Score": "2", "Tags": [ "beginner", "haskell", "reinventing-the-wheel" ], "Title": "Implementing foldl1 in Haskell" }
207358
<p>I'm new to PDO, and I want to make sure I made this in the correct way. This way is working, but I have a feeling it's unclean.</p> <p>I have this input:</p> <pre><code>$query = $handler-&gt;query('SELECT * FROM content WHERE id=1'); while($r = $query-&gt;fetch()) { ?&gt; &lt;div id="content"&gt; &lt;div class="container"&gt; &lt;form action="&lt;?php echo BASE_URL ?&gt;admin/edit_process.php?edit_about" method="post" autocomplete="off" id="contact_form" name="contact_form" role="form"&gt; &lt;div class="form-group"&gt; &lt;label for="message"&gt;Izmeni sadržaj sa početne strane:&lt;/label&gt; &lt;textarea class="form-control" id="message" name="message" required="" rows="6"&gt;&lt;?php echo $r['edit_about']; ?&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;button class="btn btn-success float-right" type="submit" name="submit"&gt;Sačuvaj&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php } </code></pre> <p>Then it goes to this:</p> <pre><code>if(isset($_REQUEST['edit_about'])){ if(!$user-&gt;isLoggedIn()){ Redirect::to(''.BASE_URL.''); } if(!$user-&gt;hasPermission('admin')) { Redirect::to(''.BASE_URL.''); } if(Input::exists()){ try{ $message = $_POST['message']; $sql = "UPDATE `content` SET `edit_about` = :message WHERE `id` = 1"; $query = $handler-&gt;prepare($sql); $query-&gt;execute(array( ':message' =&gt; $message )); Redirect::to(''.BASE_URL.'index'); }catch(Exception $e){ die($e-&gt;getMessage()); } } } </code></pre> <p>And this is the output:</p> <pre><code>&lt;?php $query = $handler-&gt;query('SELECT * FROM content WHERE id=1'); while($r = $query-&gt;fetch()) { echo $r['edit_about']; } ?&gt; </code></pre>
[]
[ { "body": "<p>The biggest problem with your PDO code is error reporting. <code>die($e-&gt;getMessage());</code> is the <strong>worst method possible</strong>. Citing from my article on <a href=\"https://phpdelusions.net/articles/error_reporting\" rel=\"nofollow noreferrer\">error reporting</a> (which I highly r...
{ "AcceptedAnswerId": "207442", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T13:26:24.120", "Id": "207359", "Score": "1", "Tags": [ "php", "mysql", "pdo" ], "Title": "Edit database content with a web page" }
207359
<p>I come to see you to help me improve an express middleware that allows you to control access resources by checking the rights of the user. The following code is supposed to be as generic as possible so that it can easily be added to another project.</p> <p>But I have doubts both on its genericity and the clarity of its prototype, I let you judge :)</p> <p>acl.ts</p> <pre><code>export let config: ACLConfig = { userField: 'me', roleField: 'roles' }; export function isAllowed(roles: String[], ...cbs: Function[]) { return async function (req, res, next) { let allowed = false; let user = req[config.userField]; if (!user) throw new APIError('ACL module cannot find req.{{userField}}', APICodes.ACL_INTERNAL_ERROR); let userRoles = user[config.roleField] || ''; userRoles = userRoles.split(','); if (roles &amp;&amp; roles.length) { for (let role of roles) { if (userRoles.indexOf(role) !== -1) return next(); } } if (cbs &amp;&amp; cbs.length) { for (let cb of cbs) { if (cb(req) === true) return next(); } } throw new APIError('You do not have the required privileges', APICodes.AUTH_ACCESS_FORBIDDEN, HttpStatus.UNAUTHORIZED, true); } } </code></pre> <p>must be used like this</p> <p><code>route('/...').all(verifyToken, isAllowed(['staff, admin'], policies.isMyArticle))</code></p> <p>maybe this following prototype is better ?</p> <pre><code>isAllow(...args: String | Function) isAllow('staff', policies.isMyArticle, 'staff'); </code></pre>
[]
[ { "body": "<p>The code you've provided is fairly thin and so there's not to much to pick at here, however, I think your checks on <code>roles</code> and <code>cbs</code> can be simplified using <code>Array.isArray()</code>, because the for of iterator cannot iterate an empty array.</p>\n\n<blockquote>\n<pre><co...
{ "AcceptedAnswerId": "207410", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T13:44:36.043", "Id": "207362", "Score": "2", "Tags": [ "node.js", "typescript", "express.js" ], "Title": "ACL express middleware implementation" }
207362
<p>I have an extension that adds values to a class and I was wondering if there was a faster way to do this.</p> <p>Does a for loop execute faster or would a LINQ query do better?</p> <pre><code>public static List&lt;T&gt; DataTableToList&lt;T&gt;(this DataTable dt) where T : class, new() { List&lt;T&gt; dataTableList = new List&lt;T&gt;(); var rowsCount = dt.Rows.Count; var columnCount = dt.Columns.Count; for (int i = 0; i &lt; rowsCount; i++) { T obj = new T(); int j = -1; Type type = obj.GetType(); PropertyInfo[] properties = type.GetProperties(); foreach (PropertyInfo property in properties) { if (j == -1) { property.SetValue(obj, Guid.NewGuid()); } else if (j &lt; columnCount) { if (dt.Rows[i][j] == null) continue; property.SetValue(obj, dt.Rows[i][j].ToString()); } j++; } dataTableList.Add(obj); } return dataTableList; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T15:56:46.747", "Id": "400290", "Score": "0", "body": "Why do you need this to be faster? Is this slow? How did you measure it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-11T13:06:11.067", "Id": ...
[ { "body": "<p>I wouldn't say, your major concern should be performance. I find the method rather error prone and it has a very limited use:</p>\n\n<p>1) All columns have to be of type <code>string</code> - except the first which must be of type <code>Guid</code></p>\n\n<p>2) The order of the columns in the tabl...
{ "AcceptedAnswerId": "207441", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T14:23:38.790", "Id": "207363", "Score": "4", "Tags": [ "c#", "generics", ".net-datatable" ], "Title": "Mapping DataTable to a concrete type" }
207363
<p>This is a follow-up answer "implementation" to a <a href="https://stackoverflow.com/questions/53235919/enforce-printing-sequence-but-threads-waiting-on-each-other-after-one-iteration?noredirect=1#comment93360052_53235919">question</a> I posted on SO. For the sake of convenience, I will repeat my intent: I want one thread (called sub-thread) to print 10 times under outer-loop with 2 iterations; then another (boss-thread) to print 100 times under outer-loop with 2 iterations provided that sub-thread goes first. It will look something like this: </p> <pre><code>Sub Thread- iter = 1 Sub Thread- iter = 2 ... Sub Thread- iter = 10 Boss Thread- iter = 1 Boss Thread- iter = 2 ... Boss Thread- iter = 100 </code></pre> <p>This sub-thread and boss-thread printing sequence will continue for 2 times (outer-loop).</p> <p>Here's my code: </p> <pre><code>public class InterThCom { // flag default to false for checking if sub-thread // gets the lock first private boolean isTh2RunFirst = false; public static void main(String[] args) { InterThCom itc = new InterThCom(); Thread t1 = new Thread(itc.new Th1(), "Boss-thread-"); Thread t2 = new Thread(itc.new Th2(), "Sub-thread-"); t1.start(); t2.start(); } private class Th1 implements Runnable { @Override public void run() { for (int i = 0; i &lt; 2; i++) { synchronized (InterThCom.class) { // lock up inner-loop // boss-thread gets the lock first // wait for sub-thread and let it run; // otherwise, skip this check if (isTh2RunFirst == false) { // wait for sub-thread, if boss-thread gets the lock first try { InterThCom.class.wait(); } catch (InterruptedException e1) { e1.printStackTrace(); } } // print iteration 100 times for (int j = 0; j &lt; 100; j++) { System.out.println(Thread.currentThread().getName() + " iter-" + (j + 1)); } // done printing 100 times // sub-thread should run already at this point isTh2RunFirst = true; // This print helps split boss-th and sub-th prints System.out.println(Thread.currentThread().getName() + " outer-loop iter:" + (i + 1)); // wake up sub-thread InterThCom.class.notify(); // wait for sub-thread try { InterThCom.class.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } private class Th2 implements Runnable { @Override public void run() { for (int i = 0; i &lt; 2; i++) { synchronized (InterThCom.class) { // print iteration 10 times for (int j = 0; j &lt; 10; j++) { System.out.println(Thread.currentThread().getName() + " iter-" + (j + 1)); } // done printing 10 times // sub-thread already prints j iteration isTh2RunFirst = true; // This print helps split boss-th and sub-th prints System.out.println(Thread.currentThread().getName() + " outer-loop iter:" + (i + 1)); // wake up boss-thread InterThCom.class.notify(); // wait for boss-thread try { InterThCom.class.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } synchronized (InterThCom.class) { // boss-thread is waiting at the last iteration, so wake it up InterThCom.class.notify(); } } } } </code></pre> <p>Things I would like help with: </p> <ul> <li><p>Did I use "synchronized" block in an efficient way that aligns with conventional approach? </p></li> <li><p>Are there other locking approach that will make my code less cluttered and cleaner? </p> <ul> <li>My initial thought was using a separate class called <code>PrintStmt</code> to wrap all the statements inside the <code>run</code> and then called it in the run method then lock the invocation. That way, <code>run</code> only has the invocation and the lock.</li> </ul></li> <li><p>Also, my <code>wait</code> and <code>notify</code> pairs are all over, is there a better way to "organize" them in a way that looks better? E.g. one of my <code>notify</code> call is outside of the double for-loop in the sub-thread <code>Th2</code> class. This is an edge case but I am having trouble to integrate that inside the double-loops.</p></li> <li><p>I am new to multi-threading. So, I am grateful for any other addresses and corrections to my implementation of the inter-communication for two threads with some extra requirement. Or other suggestions on implementing thread-communication will be appreciated. </p></li> </ul>
[]
[ { "body": "<p>One completely different approach would be to use RxJava to abstract away any manual thread handling.\nRxJava offers the class Observable. For our purpose here you can think of it as a stream of data that begins to emit values once you call <code>subscribe()</code> on it.\n<code>Observable#onNext<...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T17:26:12.190", "Id": "207370", "Score": "2", "Tags": [ "java", "multithreading" ], "Title": "Enforce printing sequence using wait() and notify()" }
207370
<p>I have to use value type to lock code sections in correspondence to objects identifiers (i.e. <code>Guid</code>, <code>int</code>, <code>long</code>, etc.).</p> <p>So I've written the following generic class/method, which uses a <code>Dictionary</code> to handle object that is a reference in correspondence to the value type (so this objects can be used with the lock instruction).</p> <p>I think the code and comments are self-explanatory enough.</p> <pre><code>public static class Funcall&lt;TDataType, T&gt; { // Object used for lock instruction and handling a lock counter class LockObject { public int Counter = 0; } // Correspondance table between the (maybe) value type and lock objects // The TDatatype above allows to create an independant static lockTable for each given TDatatype static Dictionary&lt;T, LockObject&gt; lockTable = new Dictionary&lt;T, LockObject&gt;(); static LockObject Lock( T valueToLockOn ) { lock ( lockTable ) // Globally locks the table { // Create the lock object if not allready there and increment the counter if ( lockTable.TryGetValue( valueToLockOn, out var lockObject ) == false ) { lockObject = new LockObject(); lockTable.Add( valueToLockOn, lockObject ); } lockObject.Counter++; return lockObject; } } static void Unlock( T valueToLockOn, LockObject lockObject ) { lock ( lockTable ) // Globally locks the table { // Decrement the counter and free the object if down to zero lockObject.Counter--; if ( lockObject.Counter == 0 ) lockTable.Remove( valueToLockOn ); } } public static void Locked( T valueToLockOn, Action action ) { var lockObject = default( LockObject ); try { // Obtain a lock object lockObject = Lock( valueToLockOn ); lock ( lockObject ) // Lock on the object (and so on the corresponding value) { // Call the action action?.Invoke(); } } finally { // Release the lock Unlock( valueToLockOn, lockObject ); } } // Same as above except this is returning a value (Func instead of Action) public static TResult Locked&lt;TResult&gt;( T valueToLockOn, Func&lt;TResult&gt; action ) { var lockObject = default( LockObject ); try { lockObject = Lock( valueToLockOn ); lock ( lockObject ) { return action == null ? default( TResult ) : action(); } } finally { Unlock( valueToLockOn, lockObject ); } } } </code></pre> <p>Which can be used like this:</p> <pre><code>Guid anObjectId = ObtainTheId(); return Funcall&lt;AnObjectClass, Guid&gt;.Locked( anObjectId, () =&gt; { // do something return something; } ); </code></pre> <p>Are there better ways to do that? Any advice is welcome.</p> <p>Edit/note: as asked in the comments, the use case is the following</p> <p>This "lock" system is to be used by a module for which the entry points are dedicated to modify stored objects of a particular type (this object type will be modified by this module only). Externally the module is used by several concurrent workers.</p> <p>More specifically, I use MongoDB 3.4 for objects storage and it does not provides transactions which are new in version 4.0 (I mean here session.Start, session.Commit). Among that, I don't really need a full/complete transactional system, but simply ensure each step of the workers demands are each consistent at the time each demand occurs. I'm aware that this simple "lock" system can be considered as weak, but it is simple and meet my need in the context I am working on.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T19:20:55.787", "Id": "400309", "Score": "0", "body": "Why not locking the objects directly? Why locking its GUID? What is that *do something*? Isn't it working with the object that you could have locked in the first place?" }, {...
[ { "body": "<h2>Thread safety</h2>\n\n<p>I've not tested this, but it looks solid enough, since the only non-trivial logic is held in <code>lock</code> statements. Encapsulation is accordingly good.</p>\n\n<p>Depending on the load, and if performance is critical, some reader/writer locking might help to ease con...
{ "AcceptedAnswerId": "207375", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T17:37:43.093", "Id": "207372", "Score": "5", "Tags": [ "c#", "multithreading", "lambda", "locking" ], "Title": "Using lock with value type (multithread context)" }
207372
<p>I've written a very simple program using Qt that I intend to continue working on as I continue learning C++ and Qt.</p> <p>I'm mostly wondering about my general code and comment style, specifically in terms of C++, less so about the actual program (which is boring and featureless at the moment). </p> <p>I've uploaded the full code to my GitHub here: <a href="https://github.com/cmkluza/task_organizer" rel="nofollow noreferrer">https://github.com/cmkluza/task_organizer</a></p> <p>The main file of interest is <a href="https://github.com/cmkluza/task_organizer/blob/master/mainwindow.cpp" rel="nofollow noreferrer">mainwindow.cpp</a>: </p> <pre><code>#include "mainwindow.h" #include "ui_mainwindow.h" #include &lt;QInputDialog&gt; #include &lt;iostream&gt; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui-&gt;setupUi(this); // disable "add tasks" unless a category is selected ui-&gt;addTaskButton-&gt;setEnabled(false); // at startup, display that there's no categories noCatItem = std::make_unique&lt;QTreeWidgetItem&gt;(); noCatItem-&gt;setIcon(0, QIcon(arrow)); noCatItem-&gt;setText(0, "No Catagories"); ui-&gt;catTreeWidget-&gt;addTopLevelItem(noCatItem.get()); } MainWindow::~MainWindow() { delete ui; } /** * @brief MainWindow::on_addCatButton_clicked Inserts a new category at the end of the current list of categories. */ void MainWindow::on_addCatButton_clicked() { unselectCategories(); bool ok; auto catName = QInputDialog::getText(this, "Add Category", "Category Name:", QLineEdit::Normal, QString(), &amp;ok); if (ok &amp;&amp; !catName.isEmpty()) { auto *newItem = new QTreeWidgetItem(); // if "no categories" is still there, remove it and make this the "active" category if (curIsNoCat()) { ui-&gt;catTreeWidget-&gt;takeTopLevelItem(0); newItem-&gt;setIcon(0, QIcon(arrow)); } newItem-&gt;setText(0, catName); ui-&gt;catTreeWidget-&gt;addTopLevelItem(newItem); } } /** * @brief MainWindow::on_addTaskButton_clicked Inserts a new task at the end of the curren't category's list of tasks. */ void MainWindow::on_addTaskButton_clicked() { unselectCategories(); // if there's no current item, do nothing if (!ui-&gt;catTreeWidget-&gt;currentItem()) return; bool ok; auto taskName = QInputDialog::getText(this, "Add Task", "Task Name:", QLineEdit::Normal, QString(), &amp;ok); if (ok &amp;&amp; !taskName.isEmpty()) { auto *cur = ui-&gt;catTreeWidget-&gt;currentItem(); auto *newItem = new QTreeWidgetItem(cur); newItem-&gt;setText(0, taskName); cur-&gt;addChild(newItem); } } /** * @brief MainWindow::on_nextButton_clicked Makes the next category active. * The "next" category is the subsequently displayed one. */ void MainWindow::on_nextButton_clicked() { unselectCategories(); // make the now previous category "inactive" ui-&gt;catTreeWidget-&gt;topLevelItem(curCatIndex)-&gt;setIcon(0, QIcon()); // get the next category index if (++curCatIndex &gt;= ui-&gt;catTreeWidget-&gt;topLevelItemCount()) curCatIndex = 0; // wrap // make the new category "active" ui-&gt;catTreeWidget-&gt;topLevelItem(curCatIndex)-&gt;setIcon(0, QIcon(arrow)); } /** * @brief MainWindow::unselectCategories Deselcts all selected categories, which also makes "add task' un-clickable. */ void MainWindow::unselectCategories() { // can only unselect if there's items selected if (!ui-&gt;catTreeWidget-&gt;selectedItems().isEmpty()) { ui-&gt;catTreeWidget-&gt;clearSelection(); // disable add tasks ui-&gt;addTaskButton-&gt;setEnabled(false); } } /** * @brief MainWindow::on_catTreeWidget_itemSelectionChanged Adjusts whether or not "add task" is enabled based on what's selected/ * "Add task" should only be enabled when the user has a single, valid category or task under which the new task can be added. */ void MainWindow::on_catTreeWidget_itemSelectionChanged() { if (curIsNoCat()) return; // if a top-level category is selected, enable the add tasks button for (auto &amp;item : ui-&gt;catTreeWidget-&gt;selectedItems()) { if (!item-&gt;parent()) { ui-&gt;addTaskButton-&gt;setEnabled(true); break; } } } /** * @brief MainWindow::curIsNoCat Determines whether the current item is the "no category" item. * @return true if "no categories" is still in the list. */ bool MainWindow::curIsNoCat() { return ui-&gt;catTreeWidget-&gt;indexOfTopLevelItem(noCatItem.get()) != -1; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-12T14:06:28.573", "Id": "400509", "Score": "0", "body": "It's very hard to review without the definitions of `MainWindow` and `Ui::MainWindow`. You should include these directly in the question, rather than behind a link." }, { ...
[ { "body": "<h2>Include order :</h2>\n\n<p><strike>You completely reversered order of includes.</strike> You could include standard header first, then 3rd party header and finally yours. <a href=\"https://github.com/isocpp/CppCoreGuidelines/issues/981\" rel=\"nofollow noreferrer\">Here's the two way</a> and the...
{ "AcceptedAnswerId": "207395", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T19:18:27.687", "Id": "207374", "Score": "1", "Tags": [ "c++", "qt" ], "Title": "Simple Qt GUI to list user-created categories and tasks" }
207374
<p>This is the code I wrote in order to find the smallest value in a list using recursion.However I feel like there would be a better way to do this?</p> <pre><code>def minimum(lst): """ parameters : lst of type list return : the value of the smallest element in the lst """ if len(lst) == 1: return lst[0] if lst[0] &lt; lst[1]: lst.append(lst[0]) return(minimum(lst[1:])) else: return(minimum(lst[1:])) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-11T15:41:17.900", "Id": "400406", "Score": "0", "body": "The best way would of course be to use the built-in `min` ;) I added the [tag:recursion] and [tag:reinventing-the-wheel] tags." } ]
[ { "body": "<p>Remove the else branch and push the last return statement to the same scope as the if-statement. Efficiency-wise, keep an eye on the stack size and memory use. Recursion is elegant but sometimes memory can grow exponentially if you are not careful.</p>\n", "comments": [], "meta_data": { ...
{ "AcceptedAnswerId": "207384", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T19:39:28.427", "Id": "207378", "Score": "5", "Tags": [ "python", "recursion", "reinventing-the-wheel" ], "Title": "Picking the smallest value in a list using recursion" }
207378
<p>I just wanted to ask how can I make my code a bit shorter. As of now, I have way too much code in the class. The program should display about twenty one spinners. I know it's a lot, but in this layout, users have to create their own training plan for 3 training days. In every training day, user has to select up to three body parts (one body part - 3 spinners with exercises, it should look like that)</p> <pre><code>Monday: Chest: -first exercise (spinner) -second exercise (spinner) -third exercise (spinner) Triceps -first exercise (spinner) -second exercise (spinner) -third exercise (spinner) etc.. </code></pre> <p>I've already filled spinners with exercises from database, but I want to make this class shorter because for filling my spinners (just <kbd>Ctrl</kbd>+<kbd>C</kbd>, <kbd>Ctrl</kbd>+<kbd>V</kbd>) I've written about 2400 lines of code where about 2000 it's just copied method, with changed adapter etc. Did can i make it shorter? Here's first method</p> <pre><code>public void setMondayFirstBodyPart_1() { switch (mondayFirstBodyPartFirstExerciseString) { case "shoulders": { List&lt;String&gt; data = db.getShouldersData(); ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter&lt;String&gt;(this, android.R.layout.simple_spinner_item, data); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mondayFirstBodyPartFirstExercise.setAdapter(adapter); mondayFirstBodyPartExerciseTV.setText("Shoulders"); break; } case "chest": { List&lt;String&gt; data = db.getChestData(); ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter&lt;String&gt;(this, android.R.layout.simple_spinner_item, data); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mondayFirstBodyPartFirstExercise.setAdapter(adapter); mondayFirstBodyPartExerciseTV.setText("Chest"); break; } case "back": { List&lt;String&gt; data = db.getBackData(); ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter&lt;String&gt;(this, android.R.layout.simple_spinner_item, data); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mondayFirstBodyPartFirstExercise.setAdapter(adapter); mondayFirstBodyPartExerciseTV.setText("Back"); break; } case "biceps": { List&lt;String&gt; data = db.getBicepsData(); ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter&lt;String&gt;(this, android.R.layout.simple_spinner_item, data); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mondayFirstBodyPartFirstExercise.setAdapter(adapter); mondayFirstBodyPartExerciseTV.setText("Biceps"); break; } case "triceps": { List&lt;String&gt; data = db.getTricepsData(); ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter&lt;String&gt;(this, android.R.layout.simple_spinner_item, data); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mondayFirstBodyPartFirstExercise.setAdapter(adapter); mondayFirstBodyPartExerciseTV.setText("Triceps"); break; } case "forearm": { List&lt;String&gt; data = db.getForearmData(); ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter&lt;String&gt;(this, android.R.layout.simple_spinner_item, data); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mondayFirstBodyPartFirstExercise.setAdapter(adapter); mondayFirstBodyPartExerciseTV.setText("Forearm"); break; } case "stomach": { List&lt;String&gt; data = db.getAbsData(); ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter&lt;String&gt;(this, android.R.layout.simple_spinner_item, data); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mondayFirstBodyPartFirstExercise.setAdapter(adapter); mondayFirstBodyPartExerciseTV.setText("Stomach"); break; } case "legs": { List&lt;String&gt; data = db.getLegsData(); ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter&lt;String&gt;(this, android.R.layout.simple_spinner_item, data); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mondayFirstBodyPartFirstExercise.setAdapter(adapter); mondayFirstBodyPartExerciseTV.setText("Legs"); break; } case "calf": { List&lt;String&gt; data = db.getCalfData(); ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter&lt;String&gt;(this, android.R.layout.simple_spinner_item, data); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mondayFirstBodyPartFirstExercise.setAdapter(adapter); mondayFirstBodyPartExerciseTV.setText("Calf"); break; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T21:27:07.087", "Id": "400319", "Score": "0", "body": "Welcome to Code Review. I suggest that you show more context, so that we can advise you properly. For example, what does the `db` code look like? See [ask]." }, { "Conten...
[ { "body": "<p>Let's take a look at one of the <code>case</code> blocks:</p>\n\n<pre><code>case \"shoulders\": {\n List&lt;String&gt; data = db.getShouldersData();\n ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter&lt;String&gt;(this, android.R.layout.simple_spinner_item, data);\n adapter.setDropDo...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T21:21:06.280", "Id": "207388", "Score": "3", "Tags": [ "java", "android", "sqlite" ], "Title": "Displaying 21 spinners to select body parts" }
207388
<p>I had to create a selection menu for a Contact Directory project for school. This is the second time I've had to create a menu for a particular project so I recycled the menu from my previous project to accommodate this Contact Directory and all went well.</p> <p>But I realized I'm basically just listing the Objects methods for the user to select from in both scenarios so I got bored and decided to try to generalize the menu class I had to work with any directory-type class and this is what I came up with.</p> <pre><code>package menu2; import java.lang.reflect.Method; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import javax.swing.JOptionPane; public class Menu2 { /** * @param args the command line arguments * @throws java.io.IOException */ private String name; private int selection; private int count; private Class c; private String menuDisplay = " "; private Method[] methods; /** *creates menu to navigate directory list * @throws IOException */ public Menu2(Object o) throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { this.c = o.getClass(); menuView(); selection = 0; do { selection = menu(); if(selection != count) { methods[selection-1].invoke(o); } } while (selection != count); } /** *displays menu options * @return */ public void menuView() { methods = c.getDeclaredMethods(); Method[] temp = new Method[methods.length]; count = 0; for (int i = 0; i &lt; methods.length; i++) { System.out.println("public method: " + c.getSimpleName()); if(methods[i].getParameterCount()== 0 &amp;&amp; !methods[i].getName().equalsIgnoreCase("iterator")&amp;&amp;!methods[i].getName().equalsIgnoreCase("tostring")){ menuDisplay += (count+1)+". "+methods[i].getName()+"\n"; temp[count] = methods[i]; count++; } } menuDisplay += count+". Quit"; methods = temp; /*Method[] x = new Method[count]; for(int i = 0; i &lt; count;i++){ x[i] = temp[i]; } methods = x;*/ } public int menu() { String choiceStr; int choice; choiceStr = JOptionPane.showInputDialog(menuDisplay); choice = Integer.parseInt(choiceStr); return choice; } } </code></pre> <p>I'm fairly new to programming so I'm just looking for insight as to how to improve my code or if there's a better way to do this.</p> <p>Driver:</p> <pre><code>package driver; import contactdir.ContactDir; import java.io.IOException; import java.lang.reflect.InvocationTargetException; public class Driver { public static void main(String[] args) throws IOException, IllegalAccessException, InvocationTargetException{ ContactDir dir = new ContactDir(); //Menu dirMenu = new Menu(); } } </code></pre> <p>Directory:</p> <pre><code>package contactdir; import contactinfo.ContactInfo; import javax.swing.JOptionPane; import jsjf.*; import fileman.FileMan; import java.awt.Dimension; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.util.*; import javax.swing.JScrollPane; import javax.swing.JTextArea; import menu2.Menu2; public class ContactDir implements Iterable&lt;ContactInfo&gt;, Serializable { private ArrayOrderedList&lt;ContactInfo&gt; list; private FileMan&lt;ContactInfo&gt; fman; private JScrollPane scroll; private JTextArea text; private boolean value = false; public ContactDir() throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{ this.list = new ArrayOrderedList&lt;&gt;(); this.fman = new FileMan&lt;&gt;(); Menu2 menu = new Menu2(this); } public void addContact(){ list.add(new ContactInfo()); } public void addContact(ContactInfo contact){ if(contact != null &amp;&amp; list != null){ list.add(contact); } } public void deleteContact(ContactInfo contact){ if(contact != null &amp;&amp; list != null) list.remove(contact); } /** *deletes contact from list * @param name * @return */ public boolean deleteContact(String name){ boolean value = false; if(list != null){ deleteContact(findContact(name)); value = true; } return value; } public boolean deleteContact(){ String name = JOptionPane.showInputDialog("Enter the name of the contact to remove:"); boolean value = false; if(list != null){ deleteContact(findContact(name)); value = true; } return value; } /** *finds contact in list * @param name * @return */ public ContactInfo findContact(String name){ for(ContactInfo info : list ){ if(info.getName().equalsIgnoreCase(name)) return info; } return null; } /** *updates existing contact in list * @param name * @return */ public boolean updateContact(String name){ value = false; ContactInfo temp = findContact(name); String choice = "Update Name? Update Address? Update Email? Update Work Number? Update Cell Number?"; Scanner scan = new Scanner(choice); scan.useDelimiter("\\?"); String par = ""; int confirm = 1; while(temp != null &amp;&amp; confirm != JOptionPane.YES_OPTION){ par = scan.next(); System.out.println("par : "+par); confirm = JOptionPane.showConfirmDialog(null,par+"?"); } par = par.trim(); if(par.equalsIgnoreCase("update name")){ JOptionPane.showMessageDialog(null, "Enter the name of the contact..."); String n = JOptionPane.showInputDialog("name: "); temp.setName(n); value = true; } else if(par.equalsIgnoreCase("Update Address")){ JOptionPane.showMessageDialog(null, "Enter the address of the contact..."); String n = JOptionPane.showInputDialog("address: "); temp.setAddress(n); value = true; } else if (par.equalsIgnoreCase("update email")){ JOptionPane.showMessageDialog(null, "Enter the email of the contact..."); String n = JOptionPane.showInputDialog("email: "); temp.setEmail(n); value = true; } else if(par.equalsIgnoreCase("update work number")){ JOptionPane.showMessageDialog(null, "Enter the work number of the contact..."); String n = JOptionPane.showInputDialog("number: "); temp.setWorknum(n); value = true; } else if(par.equalsIgnoreCase("update cell number")){ JOptionPane.showMessageDialog(null, "Enter the cell number of the contact..."); String n = JOptionPane.showInputDialog("number: "); temp.setCellnum(n); value = true; } else System.out.println("Error"); return value; } public boolean updateContact(){ value = false; String name = JOptionPane.showInputDialog("Enter the name of the contact to update:"); ContactInfo temp = findContact(name); String choice = "Update Name? Update Address? Update Email? Update Work Number? Update Cell Number?"; Scanner scan = new Scanner(choice); scan.useDelimiter("\\?"); String par = ""; int confirm = 1; while(temp != null &amp;&amp; confirm != JOptionPane.YES_OPTION){ par = scan.next(); System.out.println("par : "+par); confirm = JOptionPane.showConfirmDialog(null,par+"?"); } par = par.trim(); if(par.equalsIgnoreCase("update name")){ JOptionPane.showMessageDialog(null, "Enter the name of the contact..."); String n = JOptionPane.showInputDialog("name: "); temp.setName(n); value = true; } else if(par.equalsIgnoreCase("Update Address")){ JOptionPane.showMessageDialog(null, "Enter the address of the contact..."); String n = JOptionPane.showInputDialog("address: "); temp.setAddress(n); value = true; } else if (par.equalsIgnoreCase("update email")){ JOptionPane.showMessageDialog(null, "Enter the email of the contact..."); String n = JOptionPane.showInputDialog("email: "); temp.setEmail(n); value = true; } else if(par.equalsIgnoreCase("update work number")){ JOptionPane.showMessageDialog(null, "Enter the work number of the contact..."); String n = JOptionPane.showInputDialog("number: "); temp.setWorknum(n); value = true; } else if(par.equalsIgnoreCase("update cell number")){ JOptionPane.showMessageDialog(null, "Enter the cell number of the contact..."); String n = JOptionPane.showInputDialog("number: "); temp.setCellnum(n); value = true; } else System.out.println("Error"); return value; } /** *displays contact in list * @param name * @return */ public boolean displayContact(){ String name = JOptionPane.showInputDialog("Enter the name of the contact to find:"); if(list != null){ JOptionPane.showMessageDialog(null,findContact(name).toString()); value = true; } else JOptionPane.showMessageDialog(null,"Object not found"); return value; } /** *displays all contacts in list */ public void displayDir(){ text = new JTextArea((this.toString())); text.setLineWrap(true); text.setWrapStyleWord(true); scroll = new JScrollPane(text); scroll.setPreferredSize( new Dimension( 500, 500 ) ); if(list != null) JOptionPane.showMessageDialog(null, scroll); } @Override public String toString() { return "Contact Directory:\n" + list; } /** *saves list to file * @return * @throws IOException */ public boolean save() throws IOException{ fman.save("Directory.txt", list); return value; } /** *loads list from file * @return * @throws IOException */ public boolean load() throws IOException{ list = fman.load("Directory.txt"); return value; } @Override public Iterator&lt;ContactInfo&gt; iterator() { return list.iterator();//To change body of generated methods, choose Tools | Templates. } /** * @param args the command line arguments */ } </code></pre>
[]
[ { "body": "<p>You might want to turn on automatic code formatting in your editor.\nIn Eclipse this can be found under Window>Preferences>Java>Editor>Save actions.\nConsistent formatting will make your code more readable for you and other specially people.</p>\n\n<p>There's also an unused variable in the code. A...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-10T22:25:28.917", "Id": "207394", "Score": "1", "Tags": [ "java" ], "Title": "Menu class in Java" }
207394