body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>The task:</p>
<blockquote>
<p>Given a string, determine whether any permutation of it is a
palindrome.</p>
<p>For example, "carrace" should return <code>true</code>, since it can be rearranged to
form "racecar", which is a palindrome. "daily" should return <code>false</code>, since
there's no rearrangement that can form a palindrome.</p>
</blockquote>
<p>My solution:</p>
<pre><code>const isPalindrome = str => {
const letterOccurrences = str
.split("")
.reduce((acc, x) => {
acc[x] = acc[x] ? acc[x] + 1 : 1;
return acc;
}, {});
let numberOfOddOccurrences = 0;
const isMaxOneOddNumberLetter = x => x % 2 === 0 || ++numberOfOddOccurrences <= 1;
return Object.values(letterOccurrences).every(isMaxOneOddNumberLetter);
};
console.log(isPalindrome("carrace"));
</code></pre>
<p>Is it possible to write the function <code>isMaxOneOddNumberLetter</code> without mutation resp. side effects?</p>
| [] | [
{
"body": "<p>This is similar to a previous question of yours, <a href=\"https://codereview.stackexchange.com/questions/216468/find-the-elements-that-appear-only-once/216502\">Find the elements that appear only once</a>, and the same advice applies: use a Set and maintain a flag instead of a count. If your Set ends up with size of zero or one, it's a palindrome. Otherwise no.</p>\n\n<pre><code>const isPalindrome = s => s.split(\"\").reduce( \n (once, x) => (once.delete(x) || once.add(x), once),\n new Set() \n ).size <= 1\n</code></pre>\n\n<p>If inputs are constrained to 26 letters, you can map each letter to a unique power of 2 and replace the set with a bit vector (aka an \"integer\"), using XOR to track which bits appear an odd number of times. This may or may not be faster than a Set but it will certainly use less memory. I'll leave the implementation as an exercise for the reader.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T01:01:21.500",
"Id": "216828",
"ParentId": "216795",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216828",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T15:46:56.653",
"Id": "216795",
"Score": "4",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"functional-programming"
],
"Title": "Determine whether any permutation of a string is a palindrome"
} | 216795 |
<p>I am using Google Execution API to create an invoice and it's a small part of a bigger system. However, my boss is pretty displeased at the total execution time before an invoice is generated. It takes 16 seconds for an invoice to be generated, and even longer for multiple payments in one invoice. I have been requested to cut it down to minimal. Parameters come from user input.</p>
<pre><code>function doPost(e){
return handleResponse(e);
}
function handleResponse(e) {
var lock = LockService.getPublicLock();
lock.waitLock(30000);
try {
var studentData = e.data; //Sent from function within system.
var conceptData = e.data2; //Sent from function within system.
var headers = Object.keys(studentData);
var row = [];
var date = Utilities.formatDate(new Date(), "GMT-06:00", "d/M/yyyy hh:mm");
studentData.horadate = date;
for (i in headers){
row.push(studentData[headers[i]]);
}
var docTemplates = {'DM':'1UIloenopaZH3J3MXqWQGlzUNNNC6WwsnShj2xROm1WQ',
'PM':'1UIloenopaZH3J3MXqWQGlzUNNNC6WwsnShj2xROm1WQ',
'SM':'1UIloenopaZH3J3MXqWQGlzUNNNC6WwsnShj2xROm1WQ',
'PT':'1UIloenopaZH3J3MXqWQGlzUNNNC6WwsnShj2xROm1WQ',
'SM':'1UIloenopaZH3J3MXqWQGlzUNNNC6WwsnShj2xROm1WQ',
'CM':'1KTmV1JFueqw6-7OvIyROWXxQM9dOyNLEjAEiWxemy8g',
'CT':'1KTmV1JFueqw6-7OvIyROWXxQM9dOyNLEjAEiWxemy8g',
'??':'1UIloenopaZH3J3MXqWQGlzUNNNC6WwsnShj2xROm1WQ'
}
if (!docTemplates[studentData.campus]) {
studentData.campus = '??';
}
var template = DriveApp.getFileById(docTemplates[studentData.campus]).makeCopy(),
id = template.getId(),
doc = DocumentApp.openById(id),
body = doc.getBody(),
header = doc.getHeader(),
footer = doc.getFooter(),
columnIndex = 0
for (;columnIndex < headers.length; columnIndex++) {
if (row[columnIndex]) {
header.getParent().replaceText('<<' + headers[columnIndex] + '>>',
row[columnIndex])
}
}
for (i=0; i<conceptData.length; i++) {
var conc = conceptData[i];
var body = doc.getBody();
var table = body.getTables()[i*1+1];
var copy = table.copy();
var td = table.getCell(0,0);
td.setText('No.Folio:\n'+conc.folio+'\nNo. Doc. \n'+studentData.documento);
var td = table.getCell(0,1);
td.setText('Concepto:\n'+conc.conceptoname);
var td = table.getCell(0,2);
td.setText('Método de pago:\n'+conc.formaDePago+'\nReferencia: \n'+conc.referencia);
var td = table.getCell(0,3);
td.setText('Pagos anterior\n$'+(parseInt(conc.pagos)).toFixed(2)+'\nPagos actual. \n$'+(parseInt(conc.pagosDespues)).toFixed(2));
var td = table.getCell(0,4);
td.setText('Saldo anterior:\n$'+(parseInt(conc.saldoAntes)).toFixed(2)+'\nSaldo actual. \n$'+(parseInt(conc.saldoDespues)).toFixed(2));
var td = table.getCell(0,5);
td.setText('Importe total:\n$'+(parseInt(conc.totalImport)).toFixed(2)+'\nPago realizado. \n$'+(parseInt(conc.monto)).toFixed(2));
var td = table.getCell(0,6);
td.setText('Importe aplicable a \n'+conc.realMonth+' '+conc.realYear);
var td = table.getCell(1,0);
td.setText(conc.montoLetra);
if (i+1 < conceptData.length) {
var newTable = body.insertTable(body.getNumChildren()-1,copy);
}
}
doc.saveAndClose()
var newFile = DriveApp.createFile(template.getAs('application/pdf'))
newFile.setName('Invoice concept '+studentData.conceptoname+' for '+studentData.fullName);
template.setTrashed(true)
var fileid = newFile.getId()
// return json success results
return {'fileid':fileid,'name':newFile.getName(),'data':conc,'data2':studentData}
} catch(e){
return {'A wild error appears':e,'result':e};
} finally { //release lock
lock.releaseLock();
}
}
</code></pre>
<p>If you need even more data such as my execution API function which sends two parameters, or what the actual parameters look like. Don't hestitate to request them. </p>
| [] | [
{
"body": "<p>It is difficult to know exactly what the root cause of the slowness but I see some possible inefficiencies in the code. </p>\n\n<p>The first thing I see is that the <code>body</code> and list of tables are fetched once for each iteration of the length of <code>conceptData</code>: </p>\n\n<blockquote>\n<pre><code>var body = doc.getBody();\nvar table = body.getTables()[i*1+1];\n</code></pre>\n</blockquote>\n\n<p>I am not aware of how expensive those calls are but if they take a lot of time the \n that likely gets multiplied by the number of loop iterations. You could try moving the calls to fetch the body and list of tables out of the <code>for</code> loop:</p>\n\n<pre><code>var body = doc.getBody();\nvar tables = body.getTables();\n</code></pre>\n\n<p>Then inside the <code>for</code> loop set the <code>table</code> accordingly: </p>\n\n<pre><code>for (i=0; i<conceptData.length; i++) {\n var table = tables[i*1+1];\n</code></pre>\n\n<hr>\n\n<p>After reading <a href=\"https://codereview.stackexchange.com/a/200689/120114\">this answer to a similar post about a google apps script tot hide cells</a> and <a href=\"https://developers.google.com/apps-script/guides/support/best-practices\" rel=\"nofollow noreferrer\">this Google Apps Scripts <em>Best Practices</em> page</a> I would suggest you look into fetching a range of cells into an array, modifying the array and then writing out the modified array to the cells. I see there is documentation for <a href=\"https://developers.google.com/sheets/api/guides/values\" rel=\"nofollow noreferrer\">reading and writing ranges of cells</a> though you may need to use different API objects than you currently are using, as well as promises, though maybe you are using an older version of the API. </p>\n\n<hr>\n\n<p>Another thing I noticed is that <code>var td</code> gets repeated for each cell modified in the loop. While it isn’t wrong, you technically don’t need to repeat the <code>var</code> keyword after it has been declared once within the function, and some might argue that there is little need to assign the value because it is only used once (before being re-assigned).</p>\n\n<p>You could avoid the assignment by chaining the calls- for example:</p>\n\n<pre><code>table.getCell(0,0)\n .setText('No.Folio:\\n'+conc.folio+'\\nNo. Doc. \\n'+studentData.documento);\n\ntable.getCell(0,1)\n .setText('Concepto:\\n'+conc.conceptoname);\n</code></pre>\n\n<p>Also, <code>newTable</code> doesn’t appear to be used so there is no point in assigning it:</p>\n\n<blockquote>\n<pre><code>var newTable = body.insertTable(body.getNumChildren()-1,copy);\n</code></pre>\n</blockquote>\n\n<p>Just insert the table:</p>\n\n<pre><code>body.insertTable(body.getNumChildren()-1,copy);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T07:51:49.563",
"Id": "216837",
"ParentId": "216800",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T16:49:35.727",
"Id": "216800",
"Score": "2",
"Tags": [
"javascript",
"performance",
"google-apps-script"
],
"Title": "Google Apps Script to create an invoice"
} | 216800 |
<p>The purpose of this class is to efficiently notify another thread when data is available with minimal blocking to access/pass the data. The data reader/producer thread processes data in bulk which contains many objects. Instead of dispatching each object individually the objects are immediately or periodically pushed into a vector, it invokes an asynchronous notification and then continues to add objects to the vector. This allows the thread interested in the objects the ability to not have to poll for the objects and abstract itself away from the object creation. An example would be reading a continuous stream of data off the network where objects randomly arrive in different amounts and the objects get passed to another thread for processing. The goal is to minimize blocking and not miss a notification and leave an object in the vector. I know the .Net framework is vast so I may be reinventing the wheel. Have at it...</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Remoting.Messaging;
namespace CoreObjects
{
public class NotifyVector<T>
{
public delegate void NotifyCBR();
private NotifyCBR notifyCbr_ = null;
private System.Collections.Generic.List<T> vector_;
private Object dataSyncObject_ = null;
private volatile bool processing_ = false;
private IAsyncResult ar_ = null;
// Class Instantiation requires a Callback routine
private NotifyVector() { }
public NotifyVector(NotifyCBR cbr)
{
notifyCbr_ = cbr;
vector_ = new System.Collections.Generic.List<T>();
dataSyncObject_ = new System.Object();
}
// This member fuction invokes the callback routine
public void Notify()
{
if (processing_ == false)
{
if (notifyCbr_ != null)
{
processing_ = true;
ar_ = notifyCbr_.BeginInvoke(new AsyncCallback(this.EndNotify), null);
}
}
}
// Function used to implement the Async Notification/Callback
void EndNotify(IAsyncResult ar)
{
// Retrieve the delegate.
AsyncResult result = (AsyncResult)ar;
NotifyCBR caller = (NotifyCBR)result.AsyncDelegate;
// Call EndInvoke to complete/cleanup Async call
caller.EndInvoke(ar_);
processing_ = false;
}
// Threadsafe add Object to vector
public void AddObject(T obj)
{
lock (dataSyncObject_)
{
vector_.Add(obj);
}
}
// Threadsafe pop Objects from vector
public bool PopObjects(ref System.Collections.Generic.List<T> inlist)
{
bool retval = false;
lock (dataSyncObject_)
{
if (vector_.Count() > 0)
{
inlist = vector_;
vector_ = new System.Collections.Generic.List<T>();
retval = true;
}
}
return retval;
}
}
}
</code></pre>
<p>I use VS17 Community and my unit test is as follows:</p>
<pre><code>using CoreObjects;
namespace UnitTests.CoreObjectTests
{
public class Foo
{
private Foo() { }
public Foo(string s) { data_ = s; }
public string data_ { get; private set; }
}
[TestClass]
public class NotifyVectorTests
{
public NotifyVector<Foo> collectedFoo_;
private int fooCount_;
public void CallbackRoutine()
{
System.Collections.Generic.List<Foo> fooList = null;
while (collectedFoo_.PopObjects(ref fooList)) // vector handed over
{
for (int i = 0; i < fooList.Count; i++) // Do some work
fooCount_ += 1;
fooList.Clear();
}
fooList = null;
}
[TestMethod]
public void ConstructAndNotify()
{
fooCount_ = 0;
collectedFoo_ = new NotifyVector<Foo>(new
NotifyVector<Foo>.NotifyCBR(this.CallbackRoutine));
collectedFoo_.AddObject(new Foo("One"));
collectedFoo_.AddObject(new Foo("Two"));
collectedFoo_.AddObject(new Foo("Three"));
collectedFoo_.Notify(); // Performs the AsyncCallback
Assert.AreEqual(fooCount_, 0);
System.Threading.Thread.Sleep(1);
Assert.AreEqual(fooCount_, 3);
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T20:40:23.220",
"Id": "419383",
"Score": "0",
"body": "Quick tip: The `readonly` keyword could be useful to help show intention of your member variables. For example, `notifyCbr_` only gets assigned in the constructor and appears to be a good candidate for `readonly`. This way someone can come into your class and see that it isn't assigned anywhere but the constructor and more importantly it will be obvious that members without `readonly` are assigned in places other than the constructor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T12:25:51.267",
"Id": "419446",
"Score": "0",
"body": "Is there a reason you need this \"Notify\" mechanism, instead of just using a `ConcurrentQueue`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T12:57:39.747",
"Id": "419449",
"Score": "0",
"body": "Inbound objects are parsed and added individually. Consumption of the objects I want to grab in bulk and distribute on another thread. ConcurrentQueue will lock on dequeue of each object. I'm used to c++ STL where I can swap the contents of a vector for fast unloading of processed data. Notify mechanism provides ability to not have to poll or peek at the queue. Consuming thread is only bothered when data has arrived."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T18:08:18.623",
"Id": "425446",
"Score": "0",
"body": "A refactored version and new questions here: https://codereview.stackexchange.com/questions/220197/c-asynchronous-notification-vector-v2"
}
] | [
{
"body": "<p>I don't think that screen space is so limited that methods can't be separated by a blank line, and separation makes it slightly easier to see scope.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public delegate void NotifyCBR();\n private NotifyCBR notifyCbr_ = null;\n</code></pre>\n</blockquote>\n\n<p>Is there any reason not to use <code>System.Action</code>?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> private System.Collections.Generic.List<T> vector_;\n</code></pre>\n</blockquote>\n\n\n\n<blockquote>\n<pre><code> dataSyncObject_ = new System.Object();\n</code></pre>\n</blockquote>\n\n<p>Why the fully qualified names?</p>\n\n<p>On the basis of coding to the interface, I think <code>vector_</code> should be typed as <code>IList<T></code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> private Object dataSyncObject_ = null;\n</code></pre>\n</blockquote>\n\n<p>This is initialised to <code>new System.Object()</code> in the only constructor. You might as well inline it. As a matter of style, I believe it's generally preferred to use the keywords for core types:</p>\n\n<pre><code>private object dataSyncObject_ = new object();\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> // Class Instantiation requires a Callback routine\n private NotifyVector() { }\n</code></pre>\n</blockquote>\n\n<p>So why have the private constructor in the first place? Is it left over from a refactor?</p>\n\n<p>Also, why does the public constructor not check that its argument is non-null?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> // This member fuction invokes the callback routine\n public void Notify()\n {\n if (processing_ == false)\n {\n if (notifyCbr_ != null)\n {\n processing_ = true;\n ar_ = notifyCbr_.BeginInvoke(new AsyncCallback(this.EndNotify), null);\n }\n }\n }\n</code></pre>\n</blockquote>\n\n<p>I consider it bad style to compare to <code>true</code> or <code>false</code>. These nested <code>if</code>s can be reduced to a single condition:</p>\n\n<pre><code> if (!processing_ && notifyCbr_ != null)\n</code></pre>\n\n<p><code>processing_</code> may be volatile, but there's still a race condition. If you want to ensure that only one invocation is in progress at a time then you need to use some synchronisation technique: a separate lock, replacing it with a semaphore, ...</p>\n\n<p>Is <code>ar_</code> necessary? As far as I can see, you don't monitor progress. Remember <a href=\"//en.wikipedia.org/wiki/YAGNI\" rel=\"noreferrer\">YAGNI</a>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> // Function used to implement the Async Notification/Callback\n void EndNotify(IAsyncResult ar)\n {\n // Retrieve the delegate.\n AsyncResult result = (AsyncResult)ar;\n NotifyCBR caller = (NotifyCBR)result.AsyncDelegate;\n\n // Call EndInvoke to complete/cleanup Async call \n caller.EndInvoke(ar_);\n processing_ = false;\n }\n</code></pre>\n</blockquote>\n\n<p>Since you're using VS17 I assume you're also using a recent version of C#. In that case, I'd move <code>EndNotify</code> into <code>Notify</code> to make its scope clear.</p>\n\n<p>Why cast <code>ar</code> to <code>AsyncResult</code>?</p>\n\n<p>With reference to my previous question about whether <code>ar_</code> is necessary, you could replace it here with <code>ar</code>.</p>\n\n<p>Again, the access to <code>processing_</code> needs to be synchronised.</p>\n\n<hr>\n\n<p>The Begin/End style of async has fallen out of favour. On the other hand, in this use case I'm not sure that there's a better way of doing it with <code>async</code>/<code>await</code>. Forcing asynchronous execution of a synchronous method is either longwinded or hacky. E.g. (WARNING: untested code)</p>\n\n<pre><code> public void Notify()\n {\n lock (processingSyncObject_)\n {\n if (!processing_ && notifyCbr_ != null)\n {\n processing_ = true;\n Task.Run(async () =>\n {\n await Task.Delay(TimeSpan.FromTicks(1));\n notifyCbr_();\n }).ContinueWith(result =>\n {\n lock (processingSyncObject_)\n {\n processing_ = false;\n }\n });\n }\n }\n }\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> // Threadsafe pop Objects from vector\n public bool PopObjects(ref System.Collections.Generic.List<T> inlist)\n {\n bool retval = false;\n lock (dataSyncObject_)\n {\n if (vector_.Count() > 0)\n {\n inlist = vector_;\n vector_ = new System.Collections.Generic.List<T>();\n retval = true;\n }\n }\n return retval;\n }\n }\n</code></pre>\n</blockquote>\n\n<p>This looks like an abuse of <code>ref</code>. The in value is unused, so it should be an <code>out</code> parameter.</p>\n\n<p><code>Count()</code> has a special case for lists, but I would still prefer <code>Count</code> for a variable typed as <code>List<></code> or <code>IList<></code>.</p>\n\n<p>I find early returns more readable than single returns and flag Booleans.</p>\n\n<hr>\n\n<p>I don't understand what the point of this class is. It has two completely separate functions: the notification and the list don't interact at all.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T13:17:14.067",
"Id": "419450",
"Score": "0",
"body": "Alright! I have a lot to chew on now. I going to try to respond in order of the questions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T13:52:44.730",
"Id": "419458",
"Score": "1",
"body": "I phrase a lot of feedback on this site in questions, but they're rhetorical. The goal isn't for you to give me an answer, but for you to ask yourself whether you have an answer which satisfies you. At the end of the day, I'm not approving or rejecting your commit. Don't feel any obligation to comment on the answer unless it's unclear."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T14:03:10.430",
"Id": "419461",
"Score": "0",
"body": "Is there any reason not to use System.Action? - I have never used Action. After research...I do not see a use case to notify more than one observer so my class constructor can become NotifyVector(Action cbr). This worked in my tests. What is the procedure for presenting my refactored code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T14:20:52.940",
"Id": "419463",
"Score": "0",
"body": "Why the fully qualified names? / So why have the private constructor in the first place? - I learned to code on punch cards so I am used to explicitly stating what may be obvious. I did learn that default c# constructors are private. Not like c++."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T14:39:25.120",
"Id": "419465",
"Score": "0",
"body": "This looks like an abuse of ref. - ref is used to quickly pass the objects to the consuming thread. I am used to STL and swapping the contents of a vector. Which brings me to the point of the why the class question. The goal is to prevent bottlenecks from network IO and efficient blocking to pass the data. The object(s) of interest can change while sitting in the vector between Notifications. The notification is only for a change in the collection object since the last time it was consumed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T16:15:20.577",
"Id": "419477",
"Score": "0",
"body": "[Options for presenting your refactored code](//codereview.meta.stackexchange.com/a/1765/1402). The question with fully qualified names is more about the inconsistency: a couple of them are fully qualified, but most are not. It's not the case that default C# constructors are private: *if* there is a default constructor, it's public, but there's only a default constructor if there's no explicit constructor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T16:17:28.880",
"Id": "419478",
"Score": "0",
"body": "Perhaps I should rephrase my question about the point of the class: why is this one class rather than two? I would understand it being one class if `AddObject(T)` called `Notify()`, but as it stands it seems to do two completely independent things."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T10:27:38.353",
"Id": "216853",
"ParentId": "216803",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "216853",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T17:59:33.093",
"Id": "216803",
"Score": "6",
"Tags": [
"c#",
"asynchronous",
"thread-safety",
"callback"
],
"Title": "C# asynchronous notification vector"
} | 216803 |
<p>The task:</p>
<blockquote>
<p>Given a string, return the first recurring character in it, or null if
there is no recurring character.</p>
<p>For example, given the string "acbbac", return "b". Given the string
"abcdef", return null.</p>
</blockquote>
<p>My imperative solution:</p>
<pre><code>function getFirstRecurringChar(str) {
let i = 0;
const len = str.length;
const letters = {};
while(i < len && !letters[str[i]]) { letters[str[i++]] = true; }
return i < len ? str[i] : null;
};
console.log(getFirstRecurringChar("acbbac"));
</code></pre>
<p>My functional solution:</p>
<pre><code>const getFirstRecurringChar2 = str => {
const letters = {};
let lastLetter;
return Array.from(str).some(x => {
if(letters[x]) {
lastLetter = x;
return true;
}
letters[x] = true;
return false;
}) ? lastLetter : null;
};
console.log(getFirstRecurringChar2("abcdef"));
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T09:17:30.300",
"Id": "419425",
"Score": "2",
"body": "The requirement \"first recurring character\" isn't clear. In your example `acbbac` the answer could also be \"a\", because it's the first character that recurs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T13:40:19.417",
"Id": "419457",
"Score": "1",
"body": "As I mentioned in an earlier comment: I think it's the character that reoccurs first. (at least I solved it like this and it would be consistent with the given example in the task description)"
}
] | [
{
"body": "<p>The problem is similar to your other \"two of something\" problems, such as <a href=\"https://codereview.stackexchange.com/questions/216795/determine-whether-any-permutation-of-a-string-is-a-palindrome/216828#216828\">Palindrome</a> and <a href=\"https://codereview.stackexchange.com/questions/216468/find-the-elements-that-appear-only-once/216502\">Find the elements that appear only once</a>. As in those problems, a Set is the appropriate data structure.</p>\n\n<p>The main difference is that early exit is possible (when two of something is found) so we'd rather not be inside of a <code>reduce</code>. </p>\n\n<pre><code>const firstRepeated = s => {\n const seen=new Set();\n for (var c of s) {\n if (seen.has(c)) return c; \n else seen.add(c); \n }\n return null;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T08:56:05.093",
"Id": "419423",
"Score": "1",
"body": "Your regular expression doesn't match the original requirement. It only matches duplicate characters that immediately follow each other (e.g. `bb`) but not ones with other characters in between (e.g. `bxb`). It should be `/(.).*\\1/`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T09:16:00.027",
"Id": "419424",
"Score": "1",
"body": "I just realized, that my regexp won't work like expected either. I think the requirement is not clear. What is the \"first\" recurring character? Is the the first character that recurs or the character who's recurrence is first?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T13:37:29.423",
"Id": "419454",
"Score": "0",
"body": "@RoToRa I think it's the latter. (at least I solved it like this and it would be consistent with the given example in the task description)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T19:26:10.883",
"Id": "419496",
"Score": "1",
"body": "Though `Set` is a very useful construct and I like this solution from a code readability standpoint, it is worth pointing out that is would likely not perform as well as map type of approach as used in original solutions, if that is what matters most (like you need to process REALLY long strings)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T19:43:21.417",
"Id": "419500",
"Score": "0",
"body": "@MikeBrant I believe that's incorrect; do you have a source? See for example [Set vs. Object benchmarks](https://github.com/anvaka/set-vs-object) that finds Set is about twice as fast as a plain object. (which is what the original solution used—a Map is something else again)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T19:54:06.440",
"Id": "419502",
"Score": "1",
"body": "@MikeBrant note also that strings can't be longer than character set without having a duplicate (and exiting early). Unicode has under 300k assigned code points. ASCII and Latin-1 of course have far fewer."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T21:05:00.127",
"Id": "216816",
"ParentId": "216804",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216816",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T18:07:01.637",
"Id": "216804",
"Score": "5",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"functional-programming"
],
"Title": "Return the first recurring character in a string"
} | 216804 |
<p>Bit of a complicated one for me.</p>
<p>I have a database full of hundreds of thousands of records, many of which are duplicated.</p>
<p>I need to get all records within the last year but making sure every instance of that record is within the last year, e.g. if a record is duplicated and one is older than a year this shouldn't be included.</p>
<p>So far I have the below...</p>
<p>Step 1 - find out earliest date for each record</p>
<pre><code>SELECT MIN(CreateDate) AS Date, Email FROM Results R
WHERE (R.Email IS NOT NULL AND R.Email <> '')
GROUP BY R.Email
</code></pre>
<p>I created this as a view and called it <code>[EarliestInteraction]</code></p>
<p>Step 2 - grab all within the last year</p>
<p>Note: I need records within the last year but they also need to be in a log table also. So all records within the last year that are also present in some log tables.</p>
<p>So far I have done this...</p>
<pre><code>SELECT * FROM EarliestInteraction ECI
WHERE ( CAST(ECI.Date AS DATE) >= CAST(GETDATE() - 365 AS DATE) )
AND (
EXISTS (
SELECT Id FROM LOG1 R
WHERE Source = 'LOGGED'
AND R.Email = ECI.Email
)
OR
EXISTS (
SELECT Id FROM LOG2 R WHERE (R.Email IS NOT NULL AND R.Email <> '')
AND R.Email = ECI.Email
AND R.EventType IN (
'LOGGED'
))
)
</code></pre>
<p>My question is, is this a good way of doing this and accurate?</p>
<p>Or am I missing something that would bring back earlier duplicates...</p>
<p>Any thoughts on if this is accurate or achieves the brief would be great.</p>
| [] | [
{
"body": "<h1>The following are a few suggestions on how I'd write your view.</h1>\n<p><strong>Source Control</strong></p>\n<p>If you don't already have a <a href=\"https://docs.microsoft.com/en-us/previous-versions/sql/sql-server-data-tools/hh272677(v=vs.103)\" rel=\"nofollow noreferrer\">database project</a>, create one in <a href=\"https://visualstudio.microsoft.com/\" rel=\"nofollow noreferrer\">Visual Studio</a>. Then check it in to source control. <a href=\"https://azure.microsoft.com/en-au/services/devops/\" rel=\"nofollow noreferrer\">Microsoft Azure DevOps Services</a> is free & private for teams of 5 or less (this is per project, so 5 developers per project). Then you'll be able to track changes you make to your stored procedures, views, tables, etc.</p>\n<p><strong>Formatting</strong></p>\n<p>I would download the following tool for SSMS and Visual Studio, <a href=\"https://marketplace.visualstudio.com/items?itemName=TaoKlerks.PoorMansT-SqlFormatterSSMSVSExtension\" rel=\"nofollow noreferrer\">Poor Man's T-Sql Formatter</a> and on <a href=\"https://github.com/TaoK/PoorMansTSqlFormatter\" rel=\"nofollow noreferrer\">GitHub</a>. I use it when I have to edit other developer's code. It's a great way to standardize your SQL. I find it does most of the formatting for me, but I'll still make a few changes after.</p>\n<p>Here are the settings I used:</p>\n<p><a href=\"https://i.stack.imgur.com/aBD8y.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aBD8y.png\" alt=\"screenshot\" /></a></p>\n<p><strong>Commas</strong></p>\n<p>I would put the commas in front to clearly define new columns. Versus code wrapped in multiple lines. It also makes trouble-shooting code easier.</p>\n<p><strong>Where Clause</strong></p>\n<p>If you put <code>1=1</code> at the top of a <code>WHERE</code> condition, it enables you to freely change the rest of the conditions when debugging a query. The SQL query engine will end up ignoring the <code>1=1</code> so it should have no performance impact. <a href=\"https://stackoverflow.com/q/242822/9059424\">Reference</a></p>\n<p><strong>Common Table Expressions (CTE)</strong></p>\n<p><a href=\"https://docs.microsoft.com/en-us/sql/t-sql/queries/with-common-table-expression-transact-sql?view=sql-server-2017\" rel=\"nofollow noreferrer\">CTE's</a> in your SQL help with documentation. The expression name can then let other developers know why you used that expression e.g. <code>current_suppliers</code> or <code>active_projects</code>.</p>\n<p><strong>Schema Names</strong></p>\n<p>Always reference the schema when selecting an object e.g. <code>[dbo].[SalesTable]</code>.</p>\n<p><strong>Estimated Execution Plan</strong></p>\n<p>It's a good idea to check the <a href=\"https://docs.microsoft.com/en-us/sql/relational-databases/performance/display-the-estimated-execution-plan?view=sql-server-2017\" rel=\"nofollow noreferrer\">Estimated Execution Plan</a>. The shortcut in Microsoft SQL Server Management Studio (SSMS) is <kbd>Ctrl</kbd> + <kbd>L</kbd>. You can even run 2 queries in the same tab to compare the plans.</p>\n<p><strong>Keywords</strong></p>\n<p>Avoid using keywords as object names. <a href=\"https://docs.microsoft.com/en-us/sql/t-sql/language-elements/reserved-keywords-transact-sql?view=sql-server-2017\" rel=\"nofollow noreferrer\">Microsoft Reference</a></p>\n<ul>\n<li>Also check out the book <a href=\"https://rads.stackoverflow.com/amzn/click/0132350882\" rel=\"nofollow noreferrer\"><em>Clean Code</em></a>. It will change the way you think about naming conventions.</li>\n</ul>\n<hr />\n<p><strong>Revised SQL</strong></p>\n<p>Without table definitions and sample records I was unable to test this, but it should give you a good start.</p>\n<pre><code>WITH\nearliest_interaction\nAS\n(\n SELECT \n [min_createdate] = CAST(MIN(r.[CreateDate]) AS DATE)\n , r.[Email]\n FROM \n [dbo].[Results] AS r\n WHERE \n 1=1\n AND (r.[Email] IS NOT NULL AND r.[Email] != '')\n GROUP BY \n r.[Email]\n)\n,\nlog_files\nAS\n(\n SELECT [Email] FROM [dbo].[LOG1] WHERE [Source] = 'LOGGED'\n UNION\n SELECT [Email] FROM [dbo].[LOG2] WHERE [Source] = 'LOGGED'\n)\nSELECT \n ei.[min_createdate]\n , ei.[Email]\nFROM \n earliest_interaction AS ei\n INNER JOIN log_files AS lf ON lf.[Email] = ei.[Email]\nWHERE \n 1=1\n AND (ei.[min_createdate] >= DATEADD(YEAR, -1, GETDATE()))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T05:10:51.760",
"Id": "219339",
"ParentId": "216805",
"Score": "2"
}
},
{
"body": "<p>Your view does not filter on the most recent year.</p>\n\n<blockquote>\n<pre><code>SELECT MIN(CreateDate) AS Date, Email FROM Results R\nWHERE (R.Email IS NOT NULL AND R.Email <> '')\nGROUP BY R.Email\n</code></pre>\n</blockquote>\n\n<p>This filter does not change that because your view has already grouped results taking into account data older than 1 year.</p>\n\n<blockquote>\n<pre><code>SELECT * FROM EarliestInteraction ECI\nWHERE ( CAST(ECI.Date AS DATE) >= CAST(GETDATE() - 365 AS DATE) )\n..\n</code></pre>\n</blockquote>\n\n<p>You don't need a view, just a CTE.</p>\n\n<pre><code>with (SELECT MIN(CreateDate) AS Date, Email \n FROM Results R\n WHERE (R.Email IS NOT NULL AND R.Email <> '')\n -- add the filter before the GroupBy !\n AND ( CAST(CreateDate AS DATE) >= Cast(DATEADD(year,-1,GETDATE()) as Date) )\n GROUP BY R.Email) as ECI\nselect *\nfrom ECI\nwhere (\n EXISTS (\n SELECT Id FROM LOG1 R\n WHERE Source = 'LOGGED'\n AND R.Email = ECI.Email\n )\n OR\n EXISTS (\n SELECT Id FROM LOG2 R WHERE (R.Email IS NOT NULL AND R.Email <> '')\n AND R.Email = ECI.Email\n AND R.EventType IN (\n 'LOGGED'\n ))\n);\n</code></pre>\n\n<p>Or in short</p>\n\n<pre><code> with (SELECT MIN(CreateDate) AS Date, Email \n FROM Results R\n WHERE (R.Email IS NOT NULL AND R.Email <> '')\n -- add the filter before the GroupBy !\n AND ( CAST(CreateDate AS DATE) >= Cast(DATEADD(year,-1,GETDATE()) as Date) )\n GROUP BY R.Email) as ECI\n select *\n from ECI\n inner join LOG1 r1 on r1.Email = ECI.Email and r1.Source = 'LOGGED'\n inner join LOG2 r2 on r2.Email = ECI.Email and r2.Source = 'LOGGED'\n ;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T06:15:37.517",
"Id": "221240",
"ParentId": "216805",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T18:07:21.777",
"Id": "216805",
"Score": "3",
"Tags": [
"sql",
"sql-server",
"t-sql"
],
"Title": "SQL Query - records within the last year"
} | 216805 |
<p>I know that this question has been asked many times over many years and I have read every one of them but I wanted to get a modern solution since software has changed and <code>String_Split</code> has been introduced in SQL Server 2016.</p>
<p>I have a stored procedure that splits a comma-separated string and inserts the values into a table after it deletes the value if it is already there. The code works but sometimes I write code that is totally convoluted.</p>
<pre><code>ALTER PROCEDURE [dbo].[Admin_Save_PMIDS]
@MemberID INT,
@PMIDList VARCHAR(MAX)
AS
BEGIN
SELECT Split.a.value('.', 'VARCHAR(100)') AS PMID
INTO #pmids
FROM
(SELECT
CAST('<M>' + REPLACE(@PMIDList, ',', '</M><M>') + '</M>' AS XML) AS String) AS A
CROSS APPLY
String.nodes('/M') AS Split (a)
DELETE FROM [dbo].[PublicationTable]
WHERE (MemberID = @MemberID)
AND PMID IN (SELECT PMID FROM #pmids)
INSERT INTO [dbo].[PublicationTable] (PersonID, PMID, MemberID)
SELECT
@MemberID, PMID, @MemberID
FROM
[#pmids]
WHERE
(LEN(PMID) > 0)
DROP TABLE #pmids
END
</code></pre>
<p>As you can see I'm creating a temporary table and using an XML structure as a cross apply. The code works but since I'm doing a lot of updating in the application I figured I'd get some current opinions.</p>
| [] | [
{
"body": "<p>The following are a few suggestions on how I'd write the stored procedure.</p>\n\n<p><strong>Source Control</strong> </p>\n\n<p>If you don't already have a <a href=\"https://docs.microsoft.com/en-us/previous-versions/sql/sql-server-data-tools/hh272677(v=vs.103)\" rel=\"nofollow noreferrer\">database project</a>, create one in <a href=\"https://visualstudio.microsoft.com/\" rel=\"nofollow noreferrer\">Visual Studio</a>. Then check it in to source control. <a href=\"https://azure.microsoft.com/en-au/services/devops/\" rel=\"nofollow noreferrer\">Microsoft Azure DevOps Services</a> is free & private for teams of 5 or less (this is per project, so 5 developers per project). Then you'll be able to track changes you make to your stored procedures, views, tables, etc.</p>\n\n<p><strong>Error Handling</strong></p>\n\n<p>Use <a href=\"https://docs.microsoft.com/en-us/sql/t-sql/language-elements/try-catch-transact-sql?view=sql-server-2017\" rel=\"nofollow noreferrer\">Try, Catch</a> blocks to handle your errors. You can then write them to a log file or table.</p>\n\n<p><strong>Tranactions</strong></p>\n\n<p>Use <a href=\"https://docs.microsoft.com/en-us/sql/t-sql/language-elements/transactions-transact-sql?view=sql-server-2017\" rel=\"nofollow noreferrer\">transactions</a> for rolling back your queries during testing. If a transaction is successful, all of the data modifications made during the transaction are committed and become a permanent part of the database. If a transaction encounters errors and must be cancelled or rolled back, then all of the data modifications are erased.</p>\n\n<p><strong>Common Table Expressions (CTE)</strong></p>\n\n<p><a href=\"https://docs.microsoft.com/en-us/sql/t-sql/queries/with-common-table-expression-transact-sql?view=sql-server-2017\" rel=\"nofollow noreferrer\">CTE's</a> in your SQL help with documentation. The expression name can then let other developers know why you used that expression e.g. <code>current_suppliers</code> or <code>active_projects</code>.</p>\n\n<p><strong>Merge</strong></p>\n\n<p>If I need to perform more than one DML query on a table, I usually will use a <a href=\"https://docs.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql?view=sql-server-2017\" rel=\"nofollow noreferrer\">MERGE</a> statement.</p>\n\n<p><strong>Formatting</strong></p>\n\n<p>I would download the following tool for SSMS and Visual Studio, <a href=\"https://marketplace.visualstudio.com/items?itemName=TaoKlerks.PoorMansT-SqlFormatterSSMSVSExtension\" rel=\"nofollow noreferrer\">Poor Man's T-Sql Formatter</a> and on <a href=\"https://github.com/TaoK/PoorMansTSqlFormatter\" rel=\"nofollow noreferrer\">GitHub</a>. I use it when I have to edit other developer's code. It's a great way to standardize your SQL. I find it does most of the formatting for me, but I'll still make a few changes after.</p>\n\n<p>Here are the settings I used:</p>\n\n<p><a href=\"https://i.stack.imgur.com/aBD8y.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aBD8y.png\" alt=\"screenshot\"></a></p>\n\n<p><strong>Commas</strong></p>\n\n<p>I would put the commas in front to clearly define new columns. Versus code wrapped in multiple lines. It also makes trouble-shooting code easier. </p>\n\n<p>e.g. <code>, S.[PersonID]</code></p>\n\n<p><strong>Estimated Execution Plan</strong></p>\n\n<p>It's a good idea to check the <a href=\"https://docs.microsoft.com/en-us/sql/relational-databases/performance/display-the-estimated-execution-plan?view=sql-server-2017\" rel=\"nofollow noreferrer\">Estimated Execution Plan</a>. The shortcut in Microsoft SQL Server Management Studio (SSMS) is <kbd>Ctrl</kbd> + <kbd>L</kbd>. You can even run 2 queries in the same tab to compare the plans. Then you can see differences in the query plans using <a href=\"https://docs.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql?view=sql-server-2017\" rel=\"nofollow noreferrer\">STRING_SPLIT</a>.</p>\n\n<hr>\n\n<p><strong>Revised SQL</strong></p>\n\n<p>Without table definitions and sample records I was unable to test this, but it should give you a good start. </p>\n\n<pre><code>ALTER PROCEDURE [dbo].[Admin_Save_PMIDS] \n @MemberID INT\n , @PMIDList VARCHAR(MAX)\nAS\nBEGIN\n\n BEGIN TRY\n\n SET XACT_ABORT ON;\n BEGIN TRANSACTION;\n\n WITH\n pm_ids\n AS\n (\n SELECT \n [PMID] = Split.a.value('.', 'VARCHAR(100)')\n , [PersonID] = @MemberID\n , [MemberID] = @MemberID\n FROM \n (\n SELECT CAST('<M>' + REPLACE(@PMIDList, ',', '</M><M>') + '</M>' AS XML) AS String\n ) AS A\n CROSS APPLY String.nodes('/M') AS Split(a)\n )\n MERGE [dbo].[PublicationTable] AS T\n USING pm_ids AS S\n ON T.[PMID] = S.[PMID] AND T.[MemberID] = S.[MemberID] --< Update the join to the correct unique key for the table\n WHEN NOT MATCHED BY TARGET\n THEN INSERT\n (\n [PMID]\n , [PersonID]\n , [MemberID]\n )\n VALUES\n (\n S.[PMID]\n , S.[PersonID]\n , S.[MemberID]\n )\n WHEN NOT MATCHED BY SOURCE --< You may want to add a WHERE clause here\n THEN DELETE\n --OUTPUT @@SERVERNAME AS [ServerName], DB_NAME() AS [DatabaseName], $action, inserted.*, deleted.* --< show the changed records here\n ;\n\n ROLLBACK TRANSACTION; --< use the rollback for testing\n --COMMIT TRANSACTION; --< use the commit for production\n\n END TRY\n BEGIN CATCH\n --you can write this to a log table \n SELECT \n [ServerName] = @@SERVERNAME\n , [DatabaseName] = DB_NAME()\n , [ErrorProcedure] = ERROR_PROCEDURE()\n , [ErrorNumber] = ERROR_NUMBER()\n , [ErrorSeverity] = ERROR_SEVERITY()\n , [ErrorState] = ERROR_STATE()\n , [ErrorLine] = ERROR_LINE()\n , [ErrorMessage] = ERROR_MESSAGE()\n , [ErrorDateTime] = GETDATE();\n\n -- Test whether the transaction is uncommittable. \n IF (XACT_STATE()) = -1 \n BEGIN \n PRINT \n N'The transaction is in an uncommittable state.' + 'Rolling back transaction.';\n ROLLBACK TRANSACTION; \n END; \n\n -- Test whether the transaction is committable. \n IF (XACT_STATE()) = 1 \n BEGIN \n PRINT \n N'The transaction is committable.' + 'Committing transaction.';\n COMMIT TRANSACTION; \n END; \n\n END CATCH\n\nEND\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T03:21:55.090",
"Id": "217919",
"ParentId": "216810",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T19:12:09.970",
"Id": "216810",
"Score": "1",
"Tags": [
"sql",
"csv",
"sql-server",
"stored-procedure"
],
"Title": "Read comma separated values and insert in SQL Server 2016 table using String_Split"
} | 216810 |
<p>I have written an algorithm to do consecutive word match in a dataset</p>
<p>The input is a <code>dataset</code> (list of textlines) and I want to scan that and return repeated word(s) in the dataset along with some metadata like the strings (lines) they matched at. </p>
<p>I am having hard time to wrap my mind around a better approach to hand the consecutive words match. What I have so far is:</p>
<ul>
<li><code>hashtable</code> datastructure </li>
<li><p>I compute the permutations of each sentence's words. So complexity is n+ (n*avg words count). e.g: <code>abc def gg ww</code> will produce the following permutations</p>
<p>-- <code>abc def</code><br>
-- <code>abc def gg</code><br>
-- <code>abc def gg ww</code><br>
-- <code>def gg</code><br>
-- <code>def gg ww</code><br>
-- <code>gg ww</code> </p></li>
<li>I store every possible word combination from each sentence in a dictionary with value of 1 </li>
<li>if a word combination exists in the dictionary, I increase the value by 1</li>
<li>using stringBuilder to avoid string immutability</li>
<li>I refine my dictionary at the end to remove any items that has value of 1 </li>
</ul>
<p>I am curios if:<br>
1) this can be improved<br>
2) are there any other datastructures/algo I can use to do the consecutive word matching on a text blob</p>
<p>It is C# now, but we are considering python or Go as well.</p>
<pre><code>public Dictionary<string, List<string>> ConsecutiveMatches { get; set; }
public void Load(List<string> dataset)
{
for (int i = 0; i < dataset.Count; i++)
{
var sentence = dataset[i];
var words = sentence.Split(" ", StringSplitOptions.RemoveEmptyEntries);
BuildConsecutiveMatches(words, sentence);
}
RefineConsecutiveMatches();
}
private void BuildConsecutiveMatches(string[] words, string sentence)
{
BuildConsecutiveMatchesRecursive(words, 0, sentence);
}
private void BuildConsecutiveMatchesRecursive(string[] words, int index, string sentence)
{
if (index >= words.Length - 1)
{
return;
}
var builder = new StringBuilder(words[index]);
builder.Append(' ');
for (int i = index + 1; i < words.Length; i++)
{
builder.Append(words[i]);
var permutation = builder.ToString();
if (ConsecutiveMatches.TryGetValue(permutation, out var matches))
{
ConsecutiveMatches[permutation].Add(sentence);
}
else
{
ConsecutiveMatches.Add(permutation, new List<string> { sentence });
}
builder.Append(' ');
}
BuildConsecutiveMatchesRecursive(words, ++index, sentence);
}
private void RefineConsecutiveMatches()
{
ConsecutiveMatches = ConsecutiveMatches.Where(pair => pair.Value.Count >= 2)
.ToDictionary(pair => pair.Key,
pair => pair.Value);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T10:11:07.860",
"Id": "419666",
"Score": "0",
"body": "Are you sure this works because this line `var words = sentence.Split(\" \", StringSplitOptions.RemoveEmptyEntries);` appears to be invalid."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T15:28:35.767",
"Id": "420028",
"Score": "0",
"body": "which part? i am on netcore2.1 fyi"
}
] | [
{
"body": "<p>The data structure you want is called a trie. It's often used with letters in the nodes, for doing word search (finding anagrams and so on); in your case the keys would be words and the values would be sub-tries and arrays of line numbers or other metadata.</p>\n\n<p>Given this input:</p>\n\n<pre><code>cat dog pig\ndog pig cow\n</code></pre>\n\n<p>You'd make a structure like:</p>\n\n<pre><code>{\n cat: {\n dog: {\n pig: { \"#\": [ 1 ] },\n \"#\": [ 1 ]\n },\n \"#\": [ 1 ]\n },\n dog: {\n pig: { \n cow: { \"#\": [ 2 ] },\n \"#\": [ 1, 2 ]\n },\n \"#\": [ 1, 2 ]\n },\n pig: { \n cow: { \"#\": [ 2 ] },\n \"#\": [ 1, 2 ]\n },\n cow: { \"#\": [ 2 ] },\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T15:27:33.663",
"Id": "420027",
"Score": "0",
"body": "i am trying to wrap my head around how is this more performant than the hashtable implementation? also, in line 11 how were you able to determine that pig appeared in sentence #1 without traversing the trie?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T17:17:40.810",
"Id": "420048",
"Score": "0",
"body": "It's not more performant. The point is that it's equal performance with \\$O(n^2)\\$ storage while the hash uses \\$O(n^3)\\$ storage. `pig` is added to the trie as you traverse the text."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T23:44:46.960",
"Id": "216823",
"ParentId": "216811",
"Score": "2"
}
},
{
"body": "<blockquote>\n<pre><code>public Dictionary<string, List<string>> ConsecutiveMatches { get; set; } = new Dictionary<string, List<string>>();\n</code></pre>\n</blockquote>\n\n<p>I wouldn't allow public access to the result in this way, because I wouldn't want clients to be able to manipulate the result of the search directly. Instead I would make this result data be private and then expose it via a public read only method or property either as an <code>IEnumerable<></code> or as an <code>IReadOnlyDictionary<></code>: </p>\n\n<pre><code>private Dictionary<string, List<string>> matches = new Dictionary<string, List<string>>();\n\npublic IReadOnlyDictionary<string, List<string>> GetResult()\n{\n return new ReadOnlyDictionary<string, List<string>>(matches.Where(m => m.Value.Count > 1).ToDictionary(kvp => kvp.Key, kvp => kvp.Value));\n}\n</code></pre>\n\n<p>In this way you ensure that the result is valid and consistent if you need it to be used more than once.</p>\n\n<p>Another common way could be to implement <code>IEnumerable<T></code>, but here that is IMO wrong because of the call to <code>Load(...)</code>. A pattern like (for the different naming see below):</p>\n\n<pre><code> ConsecutiveMatcher matcher = new ConsecutiveMatcher();\n matcher.Search(data);\n foreach (var result in matcher.GetResult())\n {\n ...\n }\n</code></pre>\n\n<p>is more intuitive than:</p>\n\n<pre><code> ConsecutiveMatcher matcher = new ConsecutiveMatcher();\n matcher.Search(data);\n foreach (var result in matcher)\n {\n ...\n }\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>public void Load(List<string> dataset)\n{\n</code></pre>\n</blockquote>\n\n<p>If this method is called more than once, you'll have to have a flag to indicate if the new data is to be appended to existing data or the cache should be reset:</p>\n\n<pre><code>public void Search(List<string> dataset, bool append = false)\n{\n if (dataset == null || dataset.Count == 0) return; // Or throw?\n\n if (!append) matches.Clear();\n</code></pre>\n\n<p>and as shown, you should validate the input.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> var words = sentence.Split(new[] { \" \" }, StringSplitOptions.RemoveEmptyEntries);\n</code></pre>\n</blockquote>\n\n<p>You have to refine the way you split into words:</p>\n\n<p>In this sentence <code>\"this world in this world.\"</code> the two <code>\"this world\"</code> occurrences are not matched by your way to split into words because of the punctuation.</p>\n\n<p>On the other hand are <code>\"Hello World\"</code> <code>\"Hello. World\"</code> to be regarded as consecutively equal? </p>\n\n<p>Depending on how you define a word and \"consecutive\", you could use a <code>regex</code> pattern like:</p>\n\n<pre><code> string pattern = @\"(?<word>\\b\\w+\\b)(?<space>[\\W]*)\";\n</code></pre>\n\n<p>and then split the string by a <code>Regex</code> match:</p>\n\n<pre><code> var words = Regex.Matches(sentence, pattern).Cast<Match>().Select(m => m.Groups[\"word\"].Value).ToArray();\n</code></pre>\n\n<p>Whether the above pattern is suitable for your culture or needs you'll have to decide, but it could be a place to start.</p>\n\n<hr>\n\n<blockquote>\n <p><code>permutation</code></p>\n</blockquote>\n\n<p>strictly speaking the strings you are building are not permutations but \n <code>sub strings</code> or <code>prefix strings</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if (ConsecutiveMatches.TryGetValue(permutation, out var matches))\n {\n ConsecutiveMatches[permutation].Add(sentence);\n }\n else\n {\n ConsecutiveMatches.Add(permutation, new List<string> { sentence });\n }\n</code></pre>\n</blockquote>\n\n<p>This is a little awkward construct. Why not use the maybe found <code>matches</code>:</p>\n\n<pre><code> if (!ConsecutiveMatches.TryGetValue(permutation, out var matches))\n {\n matches= new List<string>();\n ConsecutiveMatches[permutation] = matches;\n }\n\n matches.Add(sentence);\n</code></pre>\n\n<hr>\n\n<p>All in all it's not a bad implementation, but there is a major problem in that it builds up a large dictionary of strings with large data sets and the deconstruct - reconstruct of prefix strings is time expensive. As \"Oh My Goodness\" states, a <code>trie</code> as data structure is more efficient in respect to memory and probably also time wise - for large data sets at least.</p>\n\n<hr>\n\n<p>Below is an edition of your code with the above comments implemented. I've also renamed things a little bit in my flavor:</p>\n\n<pre><code> class ConsecutiveWordMatcher\n {\n private Dictionary<string, List<string>> matches = new Dictionary<string, List<string>>();\n\n public void Search(List<string> dataset, bool append = false)\n {\n if (dataset == null || dataset.Count == 0) return;\n\n if (!append) matches.Clear();\n\n string pattern = @\"(?<word>\\b\\w+\\b)(?<space>[\\W]*)\";\n\n for (int i = 0; i < dataset.Count; i++)\n {\n var sentence = dataset[i];\n if (string.IsNullOrWhiteSpace(sentence)) continue;\n\n var words = Regex.Matches(sentence, pattern).Cast<Match>().Select(m => m.Groups[\"word\"].Value).ToArray();\n\n BuildConsecutiveMatches(words, sentence);\n }\n }\n\n private void BuildConsecutiveMatches(string[] words, string sentence)\n {\n BuildConsecutiveMatchesRecursive(words, 0, sentence);\n }\n\n private void BuildConsecutiveMatchesRecursive(string[] words, int index, string sentence)\n {\n if (index >= words.Length - 1)\n {\n return;\n }\n\n StringBuilder builder = new StringBuilder(words[index]);\n builder.Append(' ');\n\n foreach (string word in words.Skip(index + 1))\n {\n builder.Append(word);\n var subString = builder.ToString();\n\n if (!matches.TryGetValue(subString, out var sources))\n {\n sources = new List<string>();\n matches[subString] = sources;\n }\n\n sources.Add(sentence);\n\n builder.Append(' ');\n }\n\n BuildConsecutiveMatchesRecursive(words, ++index, sentence);\n }\n\n\n public IReadOnlyDictionary<string, List<string>> GetResult(int minOccurrences)\n {\n return new ReadOnlyDictionary<string, List<string>>(matches.Where(m => m.Value.Count >= minOccurrences).ToDictionary(kvp => kvp.Key, kvp => kvp.Value));\n }\n }\n</code></pre>\n\n<hr>\n\n<p>Just for fun and inspiration the below is an implementation using a trie like data structure:</p>\n\n<pre><code> public class SentenceInfo\n {\n public int Count { get; set; }\n public string Sentence { get; set; }\n public List<string> Sources { get; set; }\n }\n\n // A trie implementation\n public class ConsecutiveWordMatcher\n {\n class Node\n {\n private Dictionary<string, Node> m_children = new Dictionary<string, Node>();\n private List<string> m_sources = new List<string>();\n\n public Node(string word)\n {\n Word = word;\n }\n\n public string Word { get; }\n public Dictionary<string, Node> Children => m_children;\n public int Count { get; private set; }\n\n public void AddChild(Node child)\n {\n m_children[child.Word] = child;\n }\n\n public IEnumerable<string> Sentences\n {\n get\n {\n if (m_children.Count == 0)\n {\n yield return Word;\n }\n else\n {\n foreach (Node child in m_children.Values)\n {\n foreach (string substring in child.Sentences)\n {\n yield return $\"{Word} {substring}\";\n }\n }\n }\n }\n }\n\n public IEnumerable<SentenceInfo> GetMatches(int wordCount, int minOccurrences)\n {\n return GetMatches(wordCount, minOccurrences, 1);\n }\n\n private IEnumerable<SentenceInfo> GetMatches(int wordCount, int minOccurrences, int level)\n {\n if (Count >= minOccurrences)\n {\n if (level >= wordCount)\n yield return new SentenceInfo { Count = 1, Sentence = Word, Sources = m_sources };\n\n foreach (Node child in m_children.Where(kvp => kvp.Value.Count >= wordCount).Select(kvp => kvp.Value))\n {\n foreach (SentenceInfo info in child.GetMatches(wordCount, minOccurrences, level + 1))\n {\n info.Count++;\n info.Sentence = $\"{Word} {info.Sentence}\";\n yield return info;\n }\n }\n }\n }\n\n internal bool TryGetNode(string word, out Node node)\n {\n return m_children.TryGetValue(word, out node);\n }\n\n internal void AddSequence(string[] sequence, int index, string source)\n {\n if (sequence.Length == 0 || index >= sequence.Length) return;\n\n Count++;\n string word = sequence[index];\n\n if (word != Word) throw new InvalidOperationException($\"'{word}' doesn't match '{Word}'\");\n\n if (!m_sources.Contains(source))\n {\n m_sources.Add(source);\n }\n\n if (index < sequence.Length - 1)\n {\n string nextWord = sequence[index + 1];\n if (!m_children.TryGetValue(nextWord, out Node childNode))\n {\n childNode = new Node(nextWord);\n m_children[nextWord] = childNode;\n }\n\n childNode.AddSequence(sequence, index + 1, source);\n }\n }\n\n public override string ToString()\n {\n return Word;\n }\n\n internal void Clear()\n {\n m_children.Clear();\n m_sources.Clear();\n }\n }\n\n private readonly Node m_root = new Node(\"\");\n\n public ConsecutiveWordMatcher()\n {\n }\n\n public void Search(List<string> dataset, bool append = false)\n {\n if (dataset == null || dataset.Count == 0) return;\n\n if (!append)\n m_root.Clear();\n\n string pattern = @\"(?<word>\\b\\w+\\b)(?<space>[\\W]*)\";\n\n foreach (string data in dataset)\n {\n if (string.IsNullOrWhiteSpace(data)) continue;\n\n string line = data;\n MatchCollection matches = Regex.Matches(line, pattern);\n if (matches.Count > 0)\n {\n string[] sequence = matches.Cast<Match>().Select(m => m.Groups[\"word\"].Value).ToArray();\n\n for (int i = 0; i < matches.Count; i++)\n {\n HandleWord(sequence, i, data);\n }\n }\n }\n }\n\n private void HandleWord(string[] sequence, int index, string source)\n {\n string word = sequence[index];\n\n if (!m_root.TryGetNode(word, out Node node))\n {\n node = new Node(word);\n m_root.AddChild(node);\n }\n\n node.AddSequence(sequence, index, source);\n }\n\n public IEnumerable<SentenceInfo> GetResult(int wordCount = 2, int minOccurrences = 2)\n {\n return m_root.Children.Values.SelectMany(n => n.GetMatches(wordCount, minOccurrences));\n }\n }\n</code></pre>\n\n<p>As a bonus I've added the possibility to change both how many consecutive words and how many occurrences to search for.</p>\n\n<p>It isn't that well tested, so don't hang me, if...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T15:36:39.340",
"Id": "420029",
"Score": "0",
"body": "Great feedback. I will have to give your trie implementation a try and get back to you. I have a trie implemented for prefix match (char) but not for a word!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T05:42:25.823",
"Id": "216965",
"ParentId": "216811",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T19:58:55.273",
"Id": "216811",
"Score": "2",
"Tags": [
"c#",
"algorithm",
"strings",
"hash-map"
],
"Title": "Consecutive words match in a dataset"
} | 216811 |
<p>I initially posted a <a href="https://stackoverflow.com/q/55468376/5675288">question</a> on SO. I have come up with an answer for the same. Basically, given two dicts of models and parameters, user can create an object, and get the report in 5 steps.</p>
<p>Following is the code.</p>
<pre><code>import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.metrics import f1_score, roc_auc_score, recall_score, precision_score
from sklearn import datasets
from sklearn.pipeline import Pipeline
from sklearn.base import BaseEstimator
import warnings
warnings.filterwarnings('ignore')
cancer = datasets.load_breast_cancer()
df = pd.DataFrame(cancer.data, columns=cancer.feature_names)
df['target'] = cancer.target
target = df['target']
X_train, X_test, y_train, y_test = train_test_split(df.drop(columns='target', axis=1), target, test_size=0.4, random_state=13, stratify=target)
class ClfSwitcher(BaseEstimator):
def __init__(self, model=RandomForestClassifier()):
"""
A Custom BaseEstimator that can switch between classifiers.
:param estimator: sklearn object - The classifier
"""
self.model = model
def fit(self, X, y=None, **kwargs):
self.model.fit(X, y)
return self
def predict(self, X, y=None):
return self.model.predict(X)
def predict_proba(self, X):
return self.model.predict_proba(X)
def score(self, X, y):
return self.estimator.score(X, y)
class report(ClfSwitcher):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.grid = None
self.full_report = None
self.concise_report = None
self.scoring_metrics = {
'precision': precision_score,
'recall': recall_score,
'f1': f1_score,
'roc_auc': roc_auc_score
}
def griddy(self, pipeLine, parameters, **kwargs):
self.grid = GridSearchCV(pipeLine, parameters, scoring='accuracy', n_jobs=-1)
def fit_grid(self, X_train, y_train=None, **kwargs):
self.grid.fit(X_train, y_train)
def make_grid_report(self):
self.full_report = pd.DataFrame(self.grid.cv_results_)
@staticmethod
def get_names(col):
return col.__class__.__name__
@staticmethod
def calc_score(col, metric):
return round(metric(y_test, col.fit(X_train, y_train).predict(X_test)), 4)
def make_concise_report(self):
self.concise_report = pd.DataFrame(self.grid.cv_results_)
self.concise_report['model_names'] = self.concise_report['param_cst__model'].apply(self.get_names)
self.concise_report = self.concise_report.sort_values(['model_names', 'rank_test_score'], ascending=[True, False]) \
.groupby(['model_names']).head(1)[['param_cst__model', 'model_names']] \
.reset_index(drop=True)
for metric_name, metric_func in self.scoring_metrics.items():
self.concise_report[metric_name] = self.concise_report['param_cst__model'].apply(self.calc_score, metric=metric_func)
self.concise_report = self.concise_report[['model_names', 'precision', 'recall', 'f1', 'roc_auc', 'param_cst__model']]
pipeline = Pipeline([
('cst', ClfSwitcher()),
])
parameters = [
{
'cst__model': [RandomForestClassifier()],
'cst__model__n_estimators': [10, 20],
'cst__model__max_depth': [5, 10],
'cst__model__criterion': ['gini', 'entropy']
},
{
'cst__model': [SVC()],
'cst__model__C': [10, 20],
'cst__model__kernel': ['linear'],
'cst__model__gamma': [0.0001, 0.001]
},
{
'cst__model': [LogisticRegression()],
'cst__model__C': [13, 17],
'cst__model__penalty': ['l1', 'l2']
},
{
'cst__model': [GradientBoostingClassifier()],
'cst__model__n_estimators': [10, 50],
'cst__model__max_depth': [3, 5],
'cst__model__min_samples_leaf': [1, 2]
}
]
my_report = report()
my_report.griddy(pipeline, parameters, scoring='f1')
my_report.fit_grid(X_train, y_train)
my_report.make_concise_report()
my_report.concise_report
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T01:22:09.580",
"Id": "419395",
"Score": "0",
"body": "After pip install sklearn (as I didn't have it), when I run your code I get `TypeError: drop() got an unexpected keyword argument 'columns'`. Does your code run with a specific version of sklearn?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T06:42:51.220",
"Id": "419409",
"Score": "0",
"body": "Can you please post traceback? I'm guessing this has to do with `pandas` ? `drop()` is a part of that only."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T07:04:36.783",
"Id": "419413",
"Score": "0",
"body": "This is what I have: `Traceback (most recent call last):\n File \"20190404a.py\", line 19, in <module>\n X_train, X_test, y_train, y_test = train_test_split(df.drop(columns='target', axis=1), target, test_size=0.4, random_state=13, stratify=target)\nTypeError: drop() got an unexpected keyword argument 'columns'`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T07:33:33.960",
"Id": "419418",
"Score": "0",
"body": "`pd.__version__ 0.24.1\nnp.__version__ 1.15.4\nsklearn.__version__ 0.20.2` These are the versions installed in my system."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T20:04:59.413",
"Id": "216812",
"Score": "1",
"Tags": [
"python",
"machine-learning"
],
"Title": "Modified and created a new python class for generating a report of metrics for machine learning"
} | 216812 |
<p>I'm working on the following problem: I've got a dictionary like this one:</p>
<pre><code>dic={0:[0,1,2],1:[3,4,5]}
</code></pre>
<p>And I want to reverse it so it looks like this:</p>
<pre><code>dic2={0:0,1:0,2:0,3:1,4:1,5:1}
</code></pre>
<p>I managed to make it, but doing this:</p>
<pre><code>dic2={}
for i in dic:
for j in dic[i]:
dic2[j]=i
</code></pre>
<p>I know about list and dict comprehensions and this code reeks of it, but I'm not good at them when there are nested <code>for</code> and <code>dicts</code>. How would you make it more efficiently?</p>
| [] | [
{
"body": "<p>There's really not much to say about this code, it is straightforward.</p>\n\n<h3>Style</h3>\n\n<p>These are only nitpicks.</p>\n\n<ul>\n<li>Generic dictionary keys are typically named <code>k</code> instead of <code>i</code> or <code>j</code>, but in a specific application a more descriptive name would be even better.</li>\n<li>Collections should be named by their purpose in the application, not their type.</li>\n<li>By convention, assignments and other binary operators should be surrounded by spaces: <code>a = b</code>, not <code>a=b</code>. See <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP 8</a> for reference, if you're not already aware of it. Following this style guide makes your code easier to read for others.</li>\n</ul>\n\n<h3>Code improvements</h3>\n\n<p>When iterating over the keys and values of a dictionary at the same time, you can use </p>\n\n<pre><code>for k, v in dic.items():\n # ... use k, v ...\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>for k in dic:\n v = dic[k]\n # ...\n</code></pre>\n\n<p>The nested loop can be transformed to a dictionary comprehension like this:</p>\n\n<pre><code>dic2 = {v: k for k, values in dic.items() for v in values}\n</code></pre>\n\n<p>You can remember that the order of <code>for</code> clauses in the comprehension is the same as the order of corresponding nested <code>for</code> loops.</p>\n\n<h3>Potential pitfalls</h3>\n\n<p>You should be aware that this transformation from a dictionary of lists to a reverse dictionary only works if all items in the original lists are unique. Counterexample:</p>\n\n<pre><code>>>> dic = {0: [1, 2], 1: [2, 3]}\n>>> {v: k for k, values in dic.items() for v in values}\n{1: 0, 2: 1, 3: 1} # missing 2: 0\n</code></pre>\n\n<p>To correct this, the output dictionary should have the same format as the input, namely mapping each of the items in the input lists to a <em>list</em> of corresponding keys.</p>\n\n<p>If the input represents a directed graph (mapping nodes to lists of neighbours), this corresponds to computing the <em>transposed</em> or <em>reversed</em> graph. It can be done by using a <a href=\"https://docs.python.org/3/library/collections.html#collections.defaultdict\" rel=\"noreferrer\"><code>collections.defaultdict</code></a>. I don't see an easy way to write it as a comprehension in this case.</p>\n\n<pre><code>from collections import defaultdict\n\ngraph = {0: [1, 2], 1: [2, 3]}\n\ntransposed_graph = defaultdict(list)\nfor node, neighbours in graph.items():\n for neighbour in neighbours:\n transposed_graph[neighbour].append(node)\n\n# {1: [0], 2: [0, 1], 3: [1]}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T03:54:15.580",
"Id": "419400",
"Score": "1",
"body": "Also, it's important to use an entry point in Python - the classic `if __name__ == \"__main__\":` because tools like Sphinx which auto-document code will **load** the code to reflect what properties and methods each object has. Having the entry point separates the execution of the code, from the code itself (does that make sense?). The code in the current form will always execute, as opposed to having something like `do_transpose(graph)` after the entry point responsible for execution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T15:16:19.773",
"Id": "419471",
"Score": "0",
"body": "Way better answer than what I was expecting and just what I need. I don't come from a programming career, so I'm learning the conventions as I go, so this was really helpful. Thanks a lot to both of you !"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T21:02:17.083",
"Id": "216815",
"ParentId": "216814",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "216815",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T20:06:43.897",
"Id": "216814",
"Score": "4",
"Tags": [
"python",
"hash-map"
],
"Title": "Reverse dictionary where values are lists"
} | 216814 |
<p>I'm writing a <a href="https://en.wikipedia.org/wiki/Diffusion-limited_aggregation" rel="nofollow noreferrer">Diffusion-limited aggregation</a> simulation, and need to pick a random point along the edge of an area defined by a dimension pair of <code>[width, height]</code>. The point shouldn't be deep within the area; it should always be on the border of one of the sides. This is the intended behavior:</p>
<pre><code>(let [rand-gen (Random.)
dims [21 11]]
(dotimes [_ 25]
; I'm casting to int so the output is legible
; I actually need doubles
(println
(mapv int (random-edge-coord dims rand-gen)))))
[13 0]
[0 8]
[15 10]
[8 10]
[20 0]
[0 6]
[20 2]
[0 5]
[7 10]
[0 7]
[0 10]
[20 1]
[6 0]
[20 0]
[0 2]
[20 10]
[15 0]
[14 0]
[7 0]
[0 7]
[12 0]
[20 7]
[20 4]
[20 8]
[20 4]
</code></pre>
<p>This is the mess I came up with:</p>
<pre><code>; These two functions are just for the sake of a MCVE
(defn- random-boolean [^Random rand-gen]
(.nextBoolean rand-gen))
(defn- random-double [min, max, ^Random rand-gen]
(let [r (.nextDouble rand-gen)
spread (- max min)
rand (* spread r)]
(+ rand min)))
(defn random-edge-coord [dimensions, ^Random rand-gen]
(let [[w h] dimensions
vertical? (random-boolean rand-gen)
start? (random-boolean rand-gen)
x (if vertical?
; Pick either the left or right edge
(if start?
0
(dec w))
; Else, pick a random point along the top/bottom egde
(random-double 0 w rand-gen))
y (if vertical?
(random-double 0 h rand-gen)
(if start?
0
(dec h)))]
[x y]))
</code></pre>
<p>The redundancy is killing me though. I can't think of how to clean it up. I feel like this should be fairly straightforward to generalize, but I'm stuck. I figured I could clean it up introducing some anonymous functions:</p>
<pre><code>(defn random-edge-coord [dimensions rand-gen]
(let [[w h] dimensions
vertical? (g/random-boolean rand-gen)
start? (g/random-boolean rand-gen)
edge #(if start? 0 (dec %))
rand-edge #(g/random-double 0 % rand-gen)
x (if vertical?
(edge w)
(rand-edge w))
y (if vertical?
(rand-edge h)
(edge h))]
[x y]))
</code></pre>
<p>But that's not a huge gain.</p>
<p>Any input here would be appreciated.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T02:34:17.883",
"Id": "419397",
"Score": "0",
"body": "Is this just some random rectangle?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T02:56:14.183",
"Id": "419398",
"Score": "0",
"body": "@AlanThompson It's just a rectangle, yes. The bounds start from 0, and extend to the width/height of the rectangle."
}
] | [
{
"body": "<p>Easy-peasy. Just imagine walking around the rectangle starting at the origin in a counter-clockwise direction, and keeping track of the length traversed:</p>\n\n<pre><code>(defn random-edge-coord\n [width height]\n (let [len-1 width\n len-2 (+ width height)\n len-3 (+ (* 2 width) height)\n len-4 (* 2 (+ width height))\n pos (rand len-4)]\n (cond\n (< pos len-1) [pos 0]\n (< pos len-2) [width (- pos len-1)]\n (< pos len-3) [(- len-3 pos) height]\n :else [0 (- len-4 pos)])))\n\n(defn print-1 [[x y]]\n (printf \"[%3.1f %3.1f] \\n\" (double x) (double y)) )\n\n(dotest\n (nl)\n (dotimes [i 10]\n (print-1 (random-edge-coord 2 3))))\n</code></pre>\n\n<p>with result:</p>\n\n<pre><code>[1.4 3.0] \n[0.0 0.2] \n[2.0 2.1] \n[1.2 0.0] \n[2.0 1.4] \n[1.7 0.0] \n[1.5 3.0] \n[1.5 3.0] \n[2.0 0.7] \n[1.0 3.0] \n</code></pre>\n\n<p>and</p>\n\n<pre><code>[1.0 0.0] \n[1.4 0.0] \n[1.4 3.0] \n[0.5 0.0] \n[0.0 2.6] \n[2.0 2.7] \n[0.0 1.5] \n[2.0 2.8] \n[0.9 3.0] \n[1.1 3.0] \n</code></pre>\n\n<p>For a more general shape, you could calculate the length breakpoints in a loop and use a loop to search them in order instead of a <code>cond</code>. You could also use generalized line-segments, then interpolate so you don't depend on simply vertical/horizontal coordinates.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T03:19:45.110",
"Id": "216830",
"ParentId": "216819",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216830",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T21:52:06.663",
"Id": "216819",
"Score": "2",
"Tags": [
"clojure",
"fractals"
],
"Title": "Picking a random point along the edge of an area"
} | 216819 |
<p>The below code works however it takes several minutes to run. Is there a way to optimise performance so that it can be completed in a shorter amount of time?</p>
<p>My code is designed to look at the "Standard Roster" worksheet and use information in that worksheet of start and end times of a 14 day roster and compare that to the current worksheet and put the appropriate label into the 30 minute blocks over the whole month for the appropriate staff member.</p>
<p>This is Current Sheet and it continues by 30 minute blocks until the end of the month.</p>
<p><a href="https://i.stack.imgur.com/2aNuz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2aNuz.png" alt="This is Current Sheet and it continues by 30 minute blocks until the end of the month"></a></p>
<p>This is the "Standard Roster" Sheet. It has a total of 150 names:</p>
<p><a href="https://i.stack.imgur.com/Llk0r.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Llk0r.png" alt="This is the "Standard Roster" Sheet. It has a total of 150 names"></a></p>
<p>Code:</p>
<pre><code> Sub FillStandardHours()
'
' FillStandardHours Macro
'
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
Dim CurrentSheet As Worksheet
Dim StandRosSheet As Worksheet
Dim CurrentSheetLastColumn As Integer
Dim CurrentSheetLastRow As Integer
Dim StandRosLastColumn As Integer
Dim StandRosLastRow As Integer
Dim a As Integer
Dim b As Integer
Dim c As Integer
Dim d As Integer
Dim DayNum As Integer
Dim EndLoop1 As Boolean
Dim EndLoop2 As Boolean
Dim StaffActualTime As Date
Dim RosterActualStartTime As Date
Dim RosterActualEndTime As Date
Set CurrentSheet = Sheets(ActiveSheet.Name)
CurrentSheetLastColumn = CurrentSheet.Cells.SpecialCells(xlCellTypeLastCell).Column
CurrentSheetLastRow = CurrentSheet.Cells.SpecialCells(xlCellTypeLastCell).Row
Set StandRosSheet = Sheets("Standard Roster")
StandRosLastColumn = StandRosSheet.Cells.SpecialCells(xlCellTypeLastCell).Column
StandRosLastRow = StandRosSheet.Cells.SpecialCells(xlCellTypeLastCell).Row
CurrentSheet.DisplayPageBreaks = False
StandRosSheet.DisplayPageBreaks = False
a = 8
Do Until a = CurrentSheetLastRow + 1 'Go through every name on CurrentSheet
b = 8
EndLoop1 = False
Do Until b = StandRosLastRow + 1 Or EndLoop1 = True 'For every name on CurrentSheet, go through every name on Standard Roster
If StandRosSheet.Cells(b, 3).Value = CurrentSheet.Cells(a, 3).Value Then
c = 7
Do Until c = CurrentSheetLastColumn + 1
d = 8
DayNum = CurrentSheet.Cells(6, c).Value
Do Until StandRosSheet.Cells(7, d).Value = DayNum Or d = 22
If StandRosSheet.Cells(7, d).Value <> DayNum Then
d = d + 1
End If
If d = 22 Then
MsgBox "Error: " & DayNum & " in " & CurrentSheet.Name & " worksheet does not correspond to the Standard Roster", vbOKOnly, "Error Filling " & CurrentSheet.Name & " with Standard Roster"
Exit Sub
End If
Loop
If CurrentSheet.Cells(7, c).Value + "Total" Then
c = c + 1
Else:
StaffActualTime = TimeValue(CurrentSheet.Cells(7, c).Text)
If StandRosSheet.Cells(b, d).Offset(1, 0).Text = vbNullString Or StandRosSheet.Cells(b, d).Offset(2, 0).Text = vbNullString Then
CurrentSheet.Cells(a, c).Value = "NR"
Else:
RosterActualStartTime = Format((Round(StandRosSheet.Cells(b, d).Offset(1, 0).Value * 48, 0) / 48), "hh:mm AM/PM")
RosterActualEndTime = Format((Round(StandRosSheet.Cells(b, d).Offset(2, 0).Value * 48, 0) / 48), "hh:mm AM/PM")
If StaffActualTime < RosterActualStartTime Or StaffActualTime > RosterActualEndTime Then
CurrentSheet.Cells(a, c).Value = "NR"
ElseIf StandRosSheet.Cells(b, d).Offset(4, 0).Value = "WFH" Then
CurrentSheet.Cells(a, c).Value = "WFH"
Else: CurrentSheet.Cells(a, c).Value = "STD"
End If
End If
c = c + 1
End If
Loop
EndLoop1 = True
End If
Loop
a = a + 1
Loop
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
'
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T00:55:24.027",
"Id": "419392",
"Score": "1",
"body": "Welcome to CR! Please take a moment to [edit] your post to tell reviewers about your code, about its purpose; what these loops do and what's in all these cells you're interacting with - the more you give to reviewers, the more reviewers give to you! Know that [Rubberduck](https://github.com/rubberduck-vba/Rubberduck) inspections would raise a number of inspection results that reviewers will definitely point out - e.g. `Dim a, b As Long` declares `b` as a `Long`, and leaves `a` as an implicit `Variant`. Disclaimer: I contribute to the Rubberduck open-source project."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T01:11:49.207",
"Id": "419393",
"Score": "0",
"body": "Thanks Mathieu, I have updated the description with the objectives of the code. Does that make sense or should I go into further detail?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T01:23:50.937",
"Id": "419396",
"Score": "0",
"body": "Thanks! Feel free to add as much information as you want - up to 60K characters! =)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T12:30:15.633",
"Id": "419550",
"Score": "1",
"body": "Can you show an example of your standard roster sheet and the \"current\" sheet with data?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T01:58:11.630",
"Id": "419936",
"Score": "0",
"body": "Hi Peter, I have updated my description with some screenshots of the standard roster sheet and current sheet."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T00:12:31.147",
"Id": "216825",
"Score": "3",
"Tags": [
"vba"
],
"Title": "Comparing times of two worksheets"
} | 216825 |
<p>I have put together a piece of what can be a much larger frontend in Reactjs.</p>
<p>I just put together the component that renders to the user a list of airports and hotels as well as a header component.</p>
<p>I feel confident about the JavaScript implementation, but what I would like some feedback is on my use of SCSS. I installed <code>node-sass</code> and this is how I implemented it.</p>
<p><code>LocationList.js</code>:</p>
<pre><code>renderLocation() {
const filteredLocations = this.props.locations.filter(location => {
return !location.name.match(/[A-Z0-9]+$/);
});
return filteredLocations.map(location => {
if (location.airport_code) {
return (
<div key={location.id}>
<div className="location">
<h1>
{location.name} ({location.airport_code})
</h1>
<div className="location-secondary-info">
<span>
<i className="material-icons">airplanemode_active</i>
{location.description}
</span>
</div>
</div>
</div>
);
} else {
return (
<div key={location.id}>
<div className="location">
<h1>{location.name}</h1>
<div className="location-secondary-info">
<span>
<i className="material-icons">location_city</i>
{location.description}
</span>
</div>
</div>
</div>
);
}
});
}
render() {
return <div className="locations-container">{this.renderLocation()}</div>;
}
}
</code></pre>
<p><code>Header.js</code>:</p>
<pre><code>const Header = () => {
return (
<header className="App-header">
<div>
<div>
<section>
<i className="material-icons">menu</i>
<Link to="/" className="anchor">
Silvercar
</Link>
</section>
<div className="account">
<section>
<aside className="account">
<Link to="/" className="pill anchor">
Sign Up | Login
</Link>
<Link to="/" className="help">
Help
</Link>
</aside>
</section>
</div>
</div>
</div>
</header>
);
};
</code></pre>
<p><code>App.scss</code>:</p>
<pre><code>@import "../variables.scss";
body {
font-size: 14px;
}
.anchor {
color: $link-color;
text-decoration: none;
font-weight: 500;
font-size: 0.85em;
text-transform: uppercase;
}
.App {
display: flex;
height: 100vh;
}
.App-header {
border-bottom: 1px solid #eee;
}
.App-header div {
max-width: 1200px;
}
.App-header div div {
padding: 16px 8px;
}
.App-header div div section {
flex: 1 1;
display: flex;
align-items: center;
}
section i {
padding-right: 5px;
}
.App-header div div section .anchor {
flex: 1 1;
}
.App-header div .account,
.App-header div div {
display: flex;
align-items: center;
}
.help {
font-size: 1em;
text-decoration: none;
color: #6a6767;
font-weight: 400;
margin: 0 1em;
white-space: nowrap;
}
.locations-container {
display: flex;
height: 200px;
overflow-y: scroll;
flex-wrap: wrap;
}
.locations-container div {
display: flex;
flex: 1 1 30%;
flex-flow: wrap;
}
.location {
border-left: 2px solid $location-color;
padding: 14px;
margin: 12px 0;
flex: 1 1;
min-width: 275px;
max-width: 355px;
}
.location h1 {
padding: 0;
margin: 0;
width: 296px;
font-family: sans-serif;
font-weight: 500;
font-size: 20px;
color: #454545;
text-transform: uppercase;
}
.location span {
font-family: "Roboto", sans-serif;
font-size: 12px;
color: #a3a3a3;
width: 296px;
font-weight: 400;
}
.location-secondary-info {
display: flex;
align-items: center;
}
.location-secondary-info span i {
padding-right: 5px;
}
.location:hover {
background-color: $location-color;
}
.location:hover h1 {
color: $hover-color;
}
.location:hover span {
color: $hover-color;
}
main {
display: flex;
flex-flow: column;
flex: 1 1;
}
.pill {
margin: 0 1em;
border-radius: 100px;
border: 1px solid $link-color;
padding: 15px;
}
</code></pre>
<p><code>variables.scss</code>:</p>
<pre><code>$location-color: #49aaca;
$link-color: #333;
$hover-color: #fff;
</code></pre>
<p>The implementation inside of <code>LocationList.js</code> was the required task, the SCSS preprocessor is the extra credit. Using latest EcmaScript syntax is also extra credit, which I believe I have done. No duplicating of code is also extra credit, but I feel like my if conditional inside of <code>LocationList</code> component is duplicating code, but not sure how else that could have been done.</p>
| [] | [
{
"body": "<p>There’s no real harm in displaying an empty string when there is no airport code. Write the Jsx once and the line where you try to display the location.airport_code, just check if it exists and display it in that case only. With React, ternary operator is your friend: </p>\n\n<p>I believe you can do this like:</p>\n\n<pre><code>renderLocation() {\n const filteredLocations = this.props.locations.filter(location => {\n return !location.name.match(/[A-Z0-9]+$/);\n });\n\n return filteredLocations.map(location => {\n return (\n <div key={location.id}>\n <div className=\"location\">\n <h1>\n {location.name} {location.airport_code ? location.airport_code : ''}\n </h1>\n <div className=\"location-secondary-info\">\n <span>\n {location.airport_code ? \n <i className=\"material-icons\">airplanemode_active</i> :\n <i className=\"material-icons\">location_city</i>\n } \n {location.description}\n </span>\n </div>\n </div>\n </div>\n );\n</code></pre>\n\n<p>and remove the if statement entirely. That will remove your duplication. My only critique of the sass is that you didn’t really utilize any nesting which could have made your code a bit cleaner, but some people are against heavy nesting anyways. An example of utilizing nesting would be like </p>\n\n<pre><code>.location {\n &:hover {\n ....\n },\n h1 { \n ...\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T16:56:47.243",
"Id": "420298",
"Score": "0",
"body": "Thank you for providing me with feedback. My concern in implementing the ternary expression would be, how would I handle the fact that there are two different icons in each condition? So with the `location.airport_code` I need one type of `material-icons` and with just the hotels, that is no `location.airport_code` I would need a different type of `material-icons` to be displayed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T18:50:42.830",
"Id": "420316",
"Score": "0",
"body": "@Daniel, same thing can be achieved with the ternary. I've updated my answer to show this"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T19:28:18.463",
"Id": "217097",
"ParentId": "216826",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "217097",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T00:24:41.623",
"Id": "216826",
"Score": "3",
"Tags": [
"css",
"react.js",
"sass"
],
"Title": "Sass styling with React components"
} | 216826 |
<p>I am searching for the global minimum of a certain function and trying to use its gradient (here same as Jacobin) to guide the step counter. However, my <code>x</code> is fix and so is my gradient. I am also trying to retrieve the fastest way possible the first <code>x</code> for which <code>f(x)<1</code>, therefore I am using a constraint.</p>
<ul>
<li>How can I update the <code>x</code> input and the Jacobin ? </li>
<li>My <code>f(x)<1</code> is not being very effective, so is there any alternative to achieve my requirement?</li>
</ul>
<p>This is my code (more or less):</p>
<pre><code>class MyBounds(object):
def __init__(self, xmax=[2*np.pi, 2*np.pi, 2*np.pi, 2*np.pi, 1.2, 1.2, 1.2, 1.2], xmin=[0, 0, 0, 0, 0, 0, 0, 0] ):
self.xmax = np.array(xmax)
self.xmin = np.array(xmin)
def __call__(self, **kwargs):
x = kwargs["x_new"]
tmax = bool(np.all(x <= self.xmax))
tmin = bool(np.all(x >= self.xmin))
return tmax and tmin
class MyTakeStep(object):
def __init__(self, stepsize=1):
self.stepsize = stepsize
def compute_step(self, jacobi_matrix, x, i):
if jacobi_matrix[i] < 0: r = np.random.uniform(0, 2*np.pi-x[i])
elif jacobi_matrix[i] > 0: r = np.random.uniform(0-x[i], 0)
else : r = 0
return r
def __call__(self, x):
print("ENTERING fROM CALL")
print("THIS IS X: ", x)
jacobi_matrix = jacobian(x)
print("x : ", x)
print("jacobi: ", jacobi_matrix)
x[0] += self.compute_step(jacobi_matrix, x, 0)
x[1] += self.compute_step(jacobi_matrix, x, 1)
x[2] += self.compute_step(jacobi_matrix, x, 2)
x[3] += self.compute_step(jacobi_matrix, x, 3)
x[4] += self.compute_step(jacobi_matrix, x, 4)
x[5] += self.compute_step(jacobi_matrix, x, 5)
x[6] += self.compute_step(jacobi_matrix, x, 6)
x[7] += self.compute_step(jacobi_matrix, x, 7)
print("newx : ", x)
return x
def f(x):
# objective function componenets
result = g1
result += g2
result += g3
return result
def jacobian(x):
print("input_list in Jacobi: ", x)
# define full derivatives
dG_dphi = dg1_dphi + dg2_dphi + dg3_dphi
dG_dr = dg1_dr + dg2_dr + dg3_dr
gradient = np.hstack((dG_dphi, dG_dr))
print("G: ", gradient.shape, gradient, " \n")
return gradient
def callback(x, f, accept):
print("x: %65s | f: %5s | accept: %5s" % (str([round(e,3) for e in x]), str(round(f, 3)), accept))
def hopping_solver(min_f, min_x, input_excitation):
# define bounds
mybounds = MyBounds()
mytakestep = MyTakeStep()
comb = [deg2rad(phi) for phi in input_excitation[:4]] + input_excitation[4:]
print("comb: ", comb)
min_f = 10
tol = 0
cons = {'type':'ineq','fun': lambda x: 1-f(x)}
k = {"method":'Nelder-Mead', 'constraints': cons, 'jac': jacobian, 'tol': tol}
optimal_c = optimize.basinhopping(f,
x0 = comb,
niter = 1000000,
T = 8,
stepsize = 1,
minimizer_kwargs = k,
take_step = mytakestep,
accept_test = mybounds,
callback = callback,
interval = 100000,
disp = True,
niter_success = None)
print(optimal_c)
min_x, min_f = optimal_c['x'], optimal_c['fun']
comb = min_x
sol = np.array(list([np.rad2deg(phi) for phi in list(optimal_c['x'][:4])]) + list(optimal_c['x'][4:]))
min_x = sol
return min_x, min_f
</code></pre>
<p>Any help is much appreciated, thank you in advance.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T00:36:25.503",
"Id": "216827",
"Score": "1",
"Tags": [
"python",
"performance",
"scipy"
],
"Title": "Scipy basinhopping custom step update and constrained looping"
} | 216827 |
<p>I'm currently self-teaching myself C++, using a <a href="https://www.dummies.com/store/product/C-All-in-One-For-Dummies-3rd-Edition.productCd-1118823788.html" rel="noreferrer">C++ For Dummies</a> book that I bought a couple months ago. To practice, I've created a Bank class that holds usernames and passwords, and that has a login/logout system. IT also implements a failsafe if there are too many failed login attempts. I'm looking for advice that can help make this code better, i.e more efficient, more compact, and more up-to-date with todays C++ standards. Any and all help is appreciated and considered.</p>
<p><strong>bank.cpp</strong></p>
<pre><code>//Include Statements
#include <iostream>
#include <vector>
#include <string>
//Class Body
class Bank {
std::vector<std::string> usernames;
std::vector<std::string> passwords;
std::string user;
int attempts;
bool lockedOut;
public:
bool login(std::string username, std::string password);
void logout();
std::string getCurrentUser();
//Constructor
Bank() {
generateTestAccounts();
attempts = 0;
lockedOut = false;
}
private:
void generateTestAccounts();
};
//Class Functions
/*
* Checks if a user is not logged in, and if not, checks to see if
* the passed username and password match any in the Bank
*/
bool Bank::login(std::string username, std::string password) {
if(!lockedOut) {
if(user.empty()) {
for(int i = 0; i < usernames.size(); i++) {
if(usernames[i].compare(username) == 0) {
user = username;
return true;
}
}
}
attempts += 1;
if(attempts == 3) {
lockedOut = true;
}
}
return false;
}
/*
* Logs out the current user by clearing the string value from `user`
*/
void Bank::logout() {
user.clear(); //basically null
}
/*
* Returns the currently logged in user
*/
std::string Bank::getCurrentUser() {
return user;
};
/*
* Generates test accounts that can be used to make sure the
* `login` method works
*/
void Bank::generateTestAccounts() {
for(int i = 0; i < 5; i++) {
usernames.push_back("user" + std::to_string(i));
passwords.push_back("pass" + std::to_string(i));
}
}
/*
* main method for testing bank class
*/
int main() {
Bank bank;
std::string us = "user1";
std::string pw = "pass1";
if(bank.login(us, pw)) {
std::cout << "Logged in as " + us << std::endl;
}
}
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p>You don't check for the password in the <code>login</code> member function. This is the least secure user credential system I've ever seen :)</p></li>\n<li><p>You have some unnecessarily verbose comments in your code, e.g.</p>\n\n<pre><code>//Include Statements\n//Class Body\n//Constructor\n//Class Functions\nuser.clear(); //basically null\n</code></pre>\n\n<p>Just remove them. Comments are hard to maintain and should be used with care, i.e., only when a piece of code is too hard to understand from the code structure and naming of variables, types and functions. </p></li>\n<li><p>You define the constructor <code>Bank::Bank()</code> inside the class definition, but all other member functions outside of the class. Not that this is a severe issue, but I don't think there is a reason for treating the special member function differently with this regard, so consider unifying this.</p></li>\n<li><p>Use in-class member initializers, this is an approach that works consistently across constructor overloads and is blessed by the core guidelines <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c48-prefer-in-class-initializers-to-member-initializers-in-constructors-for-constant-initializers\" rel=\"noreferrer\">C.48</a>.</p>\n\n<pre><code>class Bank {\n int attempts = 0;\n bool lockedOut = false;\n\n // ...\n};\n</code></pre>\n\n<p>Definitely don't assign them in the constructor body, see also Item 4 in Scott Meyer's Effective C++ (\"Make sure that objects are initialized before they're used\").</p></li>\n<li><p>Try to avoid the use of getter member functions like <code>getCurrentUser()</code> if possible. If you do need one, prefer <code>const</code>-qualified member functions that return a <code>const</code> reference or something similar to avoid unnecessary copies. If C++17 is available, e.g.</p>\n\n<pre><code>std::string_view getCurrentUser() const;\n</code></pre></li>\n<li><p>The state that no user is currently logged in is represented by an empty user name, you hence rely on some <code>null</code>-like state of a type. This is possible, but consider replacing it with something more expressive, e.g.</p>\n\n<pre><code>bool hasCurrentUser() const;\n</code></pre>\n\n<p>or (again, with C++17)</p>\n\n<pre><code>std::optional<std::string_view> getCurrentUser() const;\n</code></pre></li>\n<li><p>You also have unnecessary copies here:</p>\n\n<pre><code>bool login(std::string username, std::string password);\n</code></pre>\n\n<p>Pass <code>const std::string&</code> or <code>std::string_view</code> instead.</p></li>\n<li><p>Prefer returning early from a function if you need to check a precondition at the top of it:</p>\n\n<pre><code>bool Bank::login(std::string username, std::string password) {\n if(lockedOut)\n return;\n\n // The rest...\n}\n</code></pre>\n\n<p>This is more readable and requires less indentation.</p></li>\n<li><p>Consider replacing <code>attempts += 1;</code> by <code>++attemps;</code>. This is clearly not a severe issue, but it's a good attitude to minimize the number of magic numbers in your code (<code>1</code> isn't that magic, but still...).</p></li>\n<li><p>This definitely comes closer to a magic number:</p>\n\n<pre><code>if(attempts == 3)\n</code></pre>\n\n<p>Prefer adding a <code>static constexpr maxLoginAttempts = 3;</code> to your class. In addition, <code>if (attempts > maxLoginAttempts)</code> seems a bit more robust to me if you change some implementation details afterwards.</p></li>\n<li><p>Avoid too many level of nested branches, in my opinion, this is already too much:</p>\n\n<pre><code>if(!lockedOut) {\n if(user.empty()) {\n for(int i = 0; i < usernames.size(); i++)\n // ...\n\n // ...\n }\n\n // ...\n}\n</code></pre>\n\n<p>You can easily fix this by moving parts of a member function into a new member function.</p></li>\n<li><p>Use standard <code><algorithm></code>s when appropriate. Looking for a <code>std::string</code> in a <code>std::vector<std::string></code> is a prime example for when it's appropriate:</p>\n\n<pre><code>if (std::find(usernames.cbegin(), usernames.cend(), username) != usernames.cend()) {\n user = username;\n return true;\n}\n</code></pre></li>\n<li><p>Only one user is able to login to your bank at a time, and the only way to add new users that are able to login is to modify the internals of the <code>Bank</code> class. Also, passwords are stored in plain text, and if the number of users grow, a <code>std::vector</code> might not be the best choice for looking up hash-able user identification tokens (like the username). I am aware that this is an exercise, just as a hint where you could go from here.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T13:37:44.537",
"Id": "419455",
"Score": "0",
"body": "Whoops! Totally forgot to add the password part haha! Thanks for the excellent and in-depth answer!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T07:56:09.157",
"Id": "216839",
"ParentId": "216829",
"Score": "6"
}
},
{
"body": "<p>This is a quick review to cover an important issue not already mentioned.</p>\n\n<h2>Fix the bug</h2>\n\n<p>When a user logs out, shouldn’t <code>attempts</code> be reset to 0? Otherwise a single user can effectively lock out the entire bank. There are other circumstances that should also reset <code>attempts</code> so you should think carefully about where those are.</p>\n\n<h2>Rethink the class operation</h2>\n\n<p>Does it really make sense to lock the entire bank in response to excessive failed login attempts? Or would it make more sense to lock the single account? Also, the username and password are closely associated but in two separate data structures. I’d be inclined to define an <code>Account</code> class and have a vector of those.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T08:12:40.783",
"Id": "216840",
"ParentId": "216829",
"Score": "3"
}
},
{
"body": "<h3>Use a <code>std::map</code> to store user name and password</h3>\n\n<p>Use of</p>\n\n<pre><code>std::vector<std::string> usernames;\nstd::vector<std::string> passwords;\n</code></pre>\n\n<p>for storing user names and corresponding passwords is not good. It's easy to add the same user name multiple times. I think it will be bette to use a map.</p>\n\n<pre><code>// Key is user\n// Value is password\nstd::map<std::string, std::string> users;\n</code></pre>\n\n<h3>Add a function to add a user</h3>\n\n<p>Add a function to add a user. In the function, make sure the user name is not already used before adding it to the map.</p>\n\n<pre><code>bool addUser(std::string const& name, std::string const& pass)\n{\n if ( users.find(name) != user.end() )\n {\n std::cerr << \"User '\" << name << \"' already exists.\\n\";\n return false;\n }\n\n user[name] = pass;\n return true;\n}\n</code></pre>\n\n<h3>Update <code>generateTestAccounts</code></h3>\n\n<p>Update <code>generateTestAccounts</code> to use <code>addUser</code>.</p>\n\n<pre><code>void Bank::generateTestAccounts() {\n for(int i = 0; i < 5; i++) {\n addUser(\"user\" + std::to_string(i), \"pass\" + std::to_string(i));\n }\n}\n</code></pre>\n\n<h3>Update <code>login</code> to use the map</h3>\n\n<pre><code>bool Bank::login(std::string const& username, std::string const& password) {\n if(lockedOut)\n {\n return false;\n }\n\n if ( users.find(username) == users.end() )\n {\n std::cerr << \"Unknown user: '\" << username << \"'\\n\";\n return false;\n }\n\n if ( users[username] == password )\n {\n user = username;\n return true;\n }\n\n attempts += 1;\n if(attempts == 3)\n {\n lockedOut = true;\n }\n\n return false; \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T18:29:38.343",
"Id": "216881",
"ParentId": "216829",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216839",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T01:57:28.590",
"Id": "216829",
"Score": "8",
"Tags": [
"c++"
],
"Title": "C++ Banking Class"
} | 216829 |
<p>I am working on <a href="https://leetcode.com/problems/word-ladder/" rel="nofollow noreferrer">Word Ladder - LeetCode</a></p>
<blockquote>
<p>Given two words (<em>beginWord</em> and <em>endWord</em>), and a dictionary's word list, find the length of shortest transformation sequence from <em>beginWord</em> to <em>endWord</em>, such that:</p>
<ol>
<li>Only one letter can be changed at a time.</li>
<li>Each transformed word must exist in the word list. Note that <em>beginWord</em> is <em>not</em> a transformed word.</li>
</ol>
<p><strong>Note:</strong></p>
<ul>
<li>Return 0 if there is no such transformation sequence.</li>
<li>All words have the same length.</li>
<li>All words contain only lowercase alphabetic characters.</li>
<li>You may assume no duplicates in the word list.</li>
<li>You may assume <em>beginWord</em> and <em>endWord</em> are non-empty and are not the same.</li>
</ul>
<p><strong>Example 1:</strong></p>
<pre><code>Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]
Output: 5
Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.
</code></pre>
<p><strong>Example 2:</strong></p>
<pre><code>Input:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
Output: 0
Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
</code></pre>
</blockquote>
<p>Approach 1: Breadth First Search</p>
<pre class="lang-py prettyprint-override"><code>
class Solution1:
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype step: int
"""
visited = set()
wordSet = set(wordList)
queue = [(beginWord, 1)]
while len(queue) > 0: #queue is not empty
word, step = queue.pop(0)
#logging.debug(f"word: {word}, step:{step}")
#base case
if word == endWord:
return step #get the result.
if word in visited: #better than multiple conditions later.
continue
#visited.add(word) # paint word as visited
#traverse all the variants
for i in range(len(word)):
for j in range(0, 26):
ordinal = ord('a') + j
next_word = word[0:i] + chr(ordinal) + word[i + 1:]
#logging.debug(f"changed_word: {next_word}")
if next_word in wordSet:
queue.append((next_word, step + 1)) #contiue next stretch
visited.add(word) # paint word as visited
return 0
</code></pre>
<blockquote>
<p>Runtime: 740 ms, faster than 22.79% of Python3 online submissions for Word Ladder.</p>
<p>Memory Usage: 15.9 MB, less than 13.09% of Python3 online submissions for Word Ladder.</p>
</blockquote>
<p>Approach 2: Bidirectional Breadth First Search</p>
<pre class="lang-py prettyprint-override"><code>
class Solution2(object):
def ladderLength(self, beginWord, endWord, wordList):
#base case
if (endWord not in wordList) or (not endWord) or (not beginWord) or (not wordList):
return 0
size = len(beginWord)
word_set = set(wordList)
forwards, backwards = {beginWord}, {endWord}
visited = set()
step = 0
while forwards and backwards:
step += 1 #treat the first word as step 1
if len(forwards) > len(backwards):
forwards, backwards = backwards, forwards #switch process
#logging.debug(f"step: {step}, forwards: {forwards}, backwords: {backwards}")
neighbors= set()
for word in forwards:#visit words on this level
if word in visited: continue
for i in range(size):
for c in 'abcdefghijklmnopqrstuvwxyz':
next_word = word[:i] + c + word[i+1:]
if next_word in backwards: return step + 1 #terminating case
if next_word in word_set: neighbors.add(next_word)
#logging.debug(f"next_word{next_word}, step: {step}")
visited.add(word) #add visited word as the final step
forwards = neighbors
#logging.debug(f"final: {step}")
return 0
</code></pre>
<blockquote>
<p>Runtime: 80 ms, faster than 98.38% of Python3 online submissions for Word Ladder.</p>
<p>Memory Usage: 13.6 MB, less than 28.37% of Python3 online submissions for Word Ladder.</p>
</blockquote>
<p>TestCase</p>
<pre><code>class MyCase(unittest.TestCase):
def setUp(self):
self.solution = Solution2()
def test_1(self):
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
#logging.debug(f"beginWord: {beginWord}\nendword:{endWord}\nwordList{wordList}")
check = self.solution.ladderLength(beginWord, endWord, wordList)
answer = 5
self.assertEqual(check, answer)
def test_2(self):
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
check = self.solution.ladderLength(beginWord, endWord, wordList)
answer = 0
self.assertEqual(check, answer)
</code></pre>
<p>The memory usage in both solution is bad.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T04:29:41.707",
"Id": "216831",
"Score": "4",
"Tags": [
"python",
"programming-challenge",
"comparative-review",
"graph",
"memory-optimization"
],
"Title": "Two solutions to leetcode 127.wordLadder"
} | 216831 |
<p>I am trying to learn how to correctly structure my projects and write a good, clean code. I would also like to learn how to write good tests. Can you please review it and give me some tips and tricks how to make that better?</p>
<p>The application is calculating the exchange from the bill for lemonade. Lemonade costs 5$ and client may pay with 5$, 10$ or 20$. At the beginning there is no change available.</p>
<h2>Project structure</h2>
<p>My project structure is as follows:</p>
<p>LemonadeChange (project) with src package and 4 packages inside:</p>
<ul>
<li>app (contains Main)</li>
<li>calculatorImp (contains CalculatorLongImp and CalculatorShortImp)</li>
<li>calculatorInterface (contains CalculatorInterface)</li>
<li>test (contains CalculatorTest)</li>
</ul>
<h2>Classes</h2>
<p>Main</p>
<pre><code>public class Main {
public static void main(int[] args) {
CalculatorInterface calc = new CalculatorLongImp();
calc.lemonadeChange(args);
}
}
</code></pre>
<p>CalculatorInterface</p>
<pre><code>public interface CalculatorInterface {
public boolean lemonadeChange(int[] bills);
}
</code></pre>
<p>CalculatorLongImp</p>
<pre><code>public class CalculatorLongImp implements CalculatorInterface {
private int five = 0;
private int ten = 0;
int acc = 0;
public boolean lemonadeChange(int[] bills) {
for (int bill : bills) {
if(bill == 5) {
five++;
}
else if(bill == 10) {
five--;
ten++;
}
else {
if(ten >= 1 && five >= 1) {
ten--;
five--;
}
else if (five >= 3) {
five -= 3;
}
else {
acc++;
}
}
}
if(acc == 0) {
return true;
}
else {
return false;
}
}
}
</code></pre>
<p>CalculatorTest</p>
<pre><code>public class CalculatorTest {
@Test
public void testAllChangeShouldBePossibleToGive() {
int[] bills = {5,5,5,10,20};
CalculatorInterface calc = new CalculatorLongImp();
assertTrue(calc.lemonadeChange(bills));
calc = new CalculatorShortImp();
assertTrue(calc.lemonadeChange(bills));
}
@Test
public void testAllChangeShouldNotBePossibleToGive() {
int[] bills = {20};
CalculatorInterface calc = new CalculatorLongImp();
assertFalse(calc.lemonadeChange(bills));
calc = new CalculatorShortImp();
assertFalse(calc.lemonadeChange(bills));
}
@Test
public void testAllChangeShouldNotBePossibleToGiveSecond() {
int[] bills = {10, 20};
CalculatorInterface calc = new CalculatorLongImp();
assertFalse(calc.lemonadeChange(bills));
calc = new CalculatorShortImp();
assertFalse(calc.lemonadeChange(bills));
}
@Test
public void testAllChangeShouldBePossibleToGiveSecond() {
int[] bills = {5, 5, 10, 20};
CalculatorInterface calc = new CalculatorLongImp();
assertTrue(calc.lemonadeChange(bills));
calc = new CalculatorShortImp();
assertTrue(calc.lemonadeChange(bills));
}
@Test
public void testAllChangeShouldNotBePossibleToGiveThird() {
int[] bills = {10, 20, 5, 5};
CalculatorInterface calc = new CalculatorLongImp();
assertFalse(calc.lemonadeChange(bills));
calc = new CalculatorShortImp();
assertFalse(calc.lemonadeChange(bills));
}
@Test
public void testAllChangeShouldBePossibleToGiveThird() {
int[] bills = {5,5,5,5,20};
CalculatorInterface calc = new CalculatorLongImp();
assertTrue(calc.lemonadeChange(bills));
calc = new CalculatorShortImp();
assertTrue(calc.lemonadeChange(bills));
}
}
</code></pre>
<p>How would you improve that? Any tips and tricks welcomed!</p>
<p>Please let me know if you want to see the task that it solves - that is one of the tasks on LeetCode, so I can post it if that makes review easier.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T06:23:30.380",
"Id": "419404",
"Score": "1",
"body": "Yes, please include the task description in the question. Also, what is `CalculatorShortImp`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T17:48:28.903",
"Id": "419486",
"Score": "0",
"body": "Here you have the task itself:\nhttps://leetcode.com/problems/lemonade-change/\n\nThe CalculatorShortImp contains the implementation of calculator that was prepared by someone else."
}
] | [
{
"body": "<p>First off, the implementation of lemonadeChange is pretty complicated. I get worried whenever I see a bunch of nested if statements - these always lead to bugs. Indeed, try adding another test case where you only pass $10 bills, I think it will erroneously return true. It's generally a good idea to limit the complexity of any individual function, take a look at the concept of Cyclomatic Complexity: <a href=\"https://help.semmle.com/wiki/plugins/servlet/mobile?contentId=29393453#content/view/29393453\" rel=\"nofollow noreferrer\">https://help.semmle.com/wiki/plugins/servlet/mobile?contentId=29393453#content/view/29393453</a></p>\n\n<p>Also, if you call lemonadeChange more than once on the same instance of CalculatorLongImp then the values of five/ten/acc will persist between calls, giving you odd results. Generally, you'd say this function has \"side effects\", and it's often a good idea to avoid these where possible. </p>\n\n<p>It's good that you've included tests. I would separate these out so each test only covers a single implementation - specific tests covering a single function on a single class make it easier to see exactly what's broken. </p>\n\n<p>Finally, I find the naming a bit confusing. What does acc do? What's the difference between CalculatorLongImp and CalculatorShortImp? Imagine someone else will be reading your code tomorrow and trying to understand what it does. Naming things clearly will make it much easier for someone else (or yourself in the future!) to read and understand your code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T17:56:49.237",
"Id": "419488",
"Score": "1",
"body": "Hi!\n\nThank you a lot for your comment! \n\nI agree that naming can be a bit confusing as CalculatorLongImp stands for Calculator Long Implementation - the one prepared by me, which is longer than prepared by my friend (CalculatorShortImp). But that is something that only I know, so for sure should be changed.\n\nI will try to make the code shorter by mysel - I can see how to improve code by removing acc variable now. I used that as a flag for the case when it is possible to give the change or not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T17:56:53.600",
"Id": "419489",
"Score": "0",
"body": "Regarding tests - that what you say is that I should create separate test classes for the two implementations that I have?\n\nAlso - is the structure of packages correct and clear? \nShould I publish the code once again here once I am done with the refactoring that you suggested?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T20:14:52.790",
"Id": "419503",
"Score": "0",
"body": "@Marcin Codereview tends to view the improved code as a side show. The main event is the review/feedback discussion here in the answers and comments. Thus, muddling the question with an update of new code tends to confuse other users and could attract downvotes. I would recommend publishing a 'self-answer' with the improved code, rather than an update to the question. Just keep in mind not to accept it as the answer final answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T22:22:05.697",
"Id": "419631",
"Score": "0",
"body": "@DapperDan, thanks! I will add the comment with the final version of the code tomorrow!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T06:48:47.467",
"Id": "216835",
"ParentId": "216834",
"Score": "4"
}
},
{
"body": "<p>Hello and welcome to Code Review! I'll dive right in:</p>\n\n<hr>\n\n<h3>Project Structure</h3>\n\n<p>Java projects <strong>tend</strong> to have a following structure:</p>\n\n<pre>\nModule\n^-src\n ^-main\n ^-java\n ^-Your applications top level package\n ^-your application\n ^-resources\n ^-property files and such\n ^-test\n ^-java\n ^-Your applications test packages\n ^-your applicationtests\n ^-resources\n ^-property files for tests\n</pre>\n\n<p>Your applications top level package should have a reasonably unique name. The convention in most cases is to reverse the domain where it is hosted.For example, if you were writing an applet hosted at codereview.stackexchange.com, convention says your package inside the main/java directory would be something like</p>\n\n<pre>\n^-com\n ^-stackexchange\n ^-codereview\n ^-appName\n</pre>\n\n<p><hr>\nI see you are coding to an interface! Good, this is commonly held as a best practice. However, the package structure around this type of coding is very opinion based.\nYou could keep each interface and implementation alone in there own directory like so:</p>\n\n<pre>\nappName\n^-sub1\n ^-interface1\n ^-impl1\n^-sub2\n...\n</pre>\n\n<p>and some choose to make a second \"impl\" subdirectory:</p>\n\n<pre>\n^-sub1\n ^-impl\n ^-impl1\n ^-interface1\n</pre>\n\n<p>These are just examples of common use</p>\n\n<hr>\n\n<p>On to actual code ~</p>\n\n<hr>\n\n<h3>CalculatorLongImp</h3>\n\n<p><strong>I noticed you don't track how many 20s you receive</strong>, is this intentional?</p>\n\n<p>The method lemonadeChange breaks convention: the method returns a boolean true/false based on where or not the bills passed could make a valid transaction. For readability, convention here is to make such Boolean methods a true/false question. A name more in line with convention would be isValid, or IMHO, isValidTransaction</p>\n\n<p>Also, as @herdistheword commented, 'acc' isnt a very descriptive name. To write good code means to write code that others could maintain. Do you think another developer could look at that name and know what it is? if not, consider renaming it.</p>\n\n<p>SPEAKING OF ACC: At the end of your method, you check if acc is 0 or not, and then return a true or false. I would recommend making acc a <code>boolean</code>, replacing <code>acc = 0</code> with <code>acc = true</code>, replacing <code>acc++</code> with <code>acc = false</code>, and then finally replacing your last <code>if(){}else{}</code> block with a simple <code>return acc</code>. Same results, less work.</p>\n\n<hr>\n\n<h3>Writing Tests</h3>\n\n<p>The bests tests are tests that have been in mind since the inception of the project. One approach to better tests is to <strong>design your code based on the tests it needs to pass</strong>. This way, you know upfront what you need to test, and what tests your code must pass to meet requirements.</p>\n\n<blockquote>\n <p>The application is calculating the exchange from the bill for lemonade. Lemonade costs 5$ and client may pay with 5$, 10$ or 20$. At the beginning there is no change available.</p>\n</blockquote>\n\n<p>From the above, you have a guideline for what to test:</p>\n\n<blockquote>\n <p>The application is calculating the exchange from the bill for lemonade. Lemonade costs 5$</p>\n</blockquote>\n\n<p>Your first test should be proof that it correctly calculates the necessary change for a test case</p>\n\n<blockquote>\n <p>Clients may pay with 5$, 10$ or 20$</p>\n</blockquote>\n\n<p>That's three cases, each one should return true in a test(In some of these you will need to 'initialize' your change before your assert test)</p>\n\n<blockquote>\n <p>At the beginning there is no change available</p>\n</blockquote>\n\n<p>So test use with a 10 or 20 as the first transaction should return false</p>\n\n<p>That's 5 good tests just from your requirements statement, and its easy to see that code that can pass all 5 tests is at least adjacent to done\n<hr>\nMy last suggestion is to look at your tests. I mentioned above,</p>\n\n<blockquote>\n <p>(In some of these you will need to 'initialize' your change before your assert test)</p>\n</blockquote>\n\n<p>If you keep in mind that every time you call new Calculator, you reset your 5s/10s/20s to zero, you will see that some of your tests are expecting money to be there when it is not.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T22:27:40.457",
"Id": "419633",
"Score": "0",
"body": "Amazing explanation with some small tricks and tips for making code better :)\n\nI have to say that I prefer keeping interfaces in a separate package, so I will keep that convention.\n\nAs I can see there are some changes that I need to do, so I will add a comment with a final version of code tomorrow.\n\nThank you especially for a tip how to write the tests, I was just picking some random values and wondering what result that should return. Now it will be much better structured. Better structure - better understanding as you really have to know what do you want to test, not only put random."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T23:00:14.303",
"Id": "419636",
"Score": "0",
"body": "Happy to be of service! Please accept my answer if you found it helpful :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T20:10:25.033",
"Id": "216887",
"ParentId": "216834",
"Score": "4"
}
},
{
"body": "<p>[EDIT - adding explanations what was changed in the code]</p>\n\n<p>Here is my final version of a code:</p>\n\n<p>Project structure:</p>\n\n<pre><code>Module\n^-src\n ^-app\n Main.java\n ^-calculatorImp\n CalculatorImp.java\n ^-calculatorInterface\n CalculatorInterface.java\n ^-test\n CalculatorTest.java\n</code></pre>\n\n<p>And the final version of the classes:</p>\n\n<p><strong>Main</strong></p>\n\n<pre><code>public class Main {\n\n public static void main(int[] args) {\n CalculatorInterface calc = new CalculatorImp();\n calc.lemonadeChange(args);\n }}\n</code></pre>\n\n<p><strong>CalculatorImp</strong></p>\n\n<p>Removed acc variable, changed the last if else statement to true or false on the basis of number of fives and tens instead of value of acc variable</p>\n\n<pre><code>public class CalculatorImp implements CalculatorInterface {\n private int five;\n private int ten;\n\n @Override\n public boolean lemonadeChange(int[] bills) {\n five = 0;\n ten = 0;\n\n for (int bill : bills) {\n if (bill == 5) {\n five++;\n } else if (bill == 10) {\n five--;\n ten++;\n } else {\n if (ten >= 1 && five >= 1) {\n ten--;\n five--;\n } else if (five >= 3) {\n five -= 3;\n } else {\n return false;\n }\n }\n }\n\n if(five >= 0 && ten >= 0) {\n return true;\n } else {\n return false;\n }\n }}\n</code></pre>\n\n<p><strong>CalculatorTest</strong></p>\n\n<p>Added several test cases - starting from the most basic ones, so the change for 5$, 10$ and 20$ and then the combinations of that.</p>\n\n<pre><code>public class CalculatorTest {\n\n @Test\n public void testChangeShouldBePossibleToGiveFor5$Transaction() {\n int[] bills = {5};\n CalculatorInterface calc = new CalculatorImp();\n assertTrue(calc.lemonadeChange(bills));\n }\n\n @Test\n public void testChangeShouldNotBePossibleToGiveFor10$Transaction() {\n int[] bills = {10};\n CalculatorInterface calc = new CalculatorImp();\n assertFalse(calc.lemonadeChange(bills));\n }\n\n @Test\n public void testChangeShouldNotBePossibleToGiveFor20$Transaction() {\n int[] bills = {20};\n CalculatorInterface calc = new CalculatorImp();\n assertFalse(calc.lemonadeChange(bills));\n }\n\n @Test\n public void testChangeShouldBePossibleToGiveForFirstTransaction5$() {\n int[] bills = {5,10,20};\n CalculatorInterface calc = new CalculatorImp();\n assertFalse(calc.lemonadeChange(bills));\n }\n\n @Test\n public void testChangeShouldNotBePossibleToGiveForFirstTransaction10$() {\n int[] bills = {10,20,5};\n CalculatorInterface calc = new CalculatorImp();\n assertFalse(calc.lemonadeChange(bills));\n }\n\n @Test\n public void testChangeShouldNotBePossibleToGiveForFirstTransaction20$() {\n int[] bills = {20,5,10};\n CalculatorInterface calc = new CalculatorImp();\n assertFalse(calc.lemonadeChange(bills));\n }\n\n @Test\n public void testAllChangeShouldBePossibleToGiveForMultipleTransactions() {\n int[] bills = {5,5,5,10,20};\n CalculatorInterface calc = new CalculatorImp();\n assertTrue(calc.lemonadeChange(bills));\n }\n\n @Test\n public void testAllChangeShouldNotBePossibleToGiveForMultipleTransactions() {\n int[] bills = {20};\n CalculatorInterface calc = new CalculatorImp();\n assertFalse(calc.lemonadeChange(bills));\n }\n\n @Test\n public void testAllChangeShouldNotBePossibleToGiveForMultipleTransactions2() {\n int[] bills = {10, 20};\n CalculatorInterface calc = new CalculatorImp();\n assertFalse(calc.lemonadeChange(bills));\n }\n\n @Test\n public void testAllChangeShouldBePossibleToGiveForMultipleTransactions2() {\n int[] bills = {5, 5, 10, 20};\n CalculatorInterface calc = new CalculatorImp();\n assertTrue(calc.lemonadeChange(bills));\n }\n\n @Test\n public void testAllChangeShouldNotBePossibleToGiveForMultipleTransactions3() {\n int[] bills = {10, 20, 5, 5};\n CalculatorInterface calc = new CalculatorImp();\n assertFalse(calc.lemonadeChange(bills)); \n }\n\n @Test\n public void testAllChangeShouldBePossibleToGiveForMultipleTransactions3() {\n int[] bills = {5,5,5,5,20};\n CalculatorInterface calc = new CalculatorImp();\n assertTrue(calc.lemonadeChange(bills));\n }}\n</code></pre>\n\n<p><strong>CalculatorInterface</strong></p>\n\n<pre><code>public interface CalculatorInterface {\n\n public boolean lemonadeChange(int[] bills);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T16:59:27.480",
"Id": "419693",
"Score": "0",
"body": "Cyclomatic complexity of lemonadeChange method can be reduced. \nI have just found another very clever solution on the internet (in LeetCode discussions), but as I implemented it this way I will leave the algorithm as it is.\n\nThank you all for your help!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T17:55:09.933",
"Id": "419702",
"Score": "0",
"body": "You must also specify what has been revised in this version."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T12:21:18.233",
"Id": "419735",
"Score": "0",
"body": "Sorry, I cannot find in Help tab, YouTube or in questions how to write the code comparison here side-by-side. Can you give me a tip how to do that so that we can close this topic?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T15:11:23.557",
"Id": "419746",
"Score": "0",
"body": "You just need to mention what changes you've made, such as at the top of the post. I'm not quite sure how else to explain it."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T16:57:04.923",
"Id": "216983",
"ParentId": "216834",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "216887",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T06:13:33.450",
"Id": "216834",
"Score": "2",
"Tags": [
"java",
"algorithm",
"calculator"
],
"Title": "Simple exchange calculator in Java - structure and tests"
} | 216834 |
<p>I have two tables as below</p>
<h3>ACCOUNTS:</h3>
<pre><code>+--------------+----------------+----------------------+-----------+
| BANK_ID (PK) | BRANCH_ID (PK) | ACCOUNT_NUM (PK) | CURRENCY |
+--------------+----------------+----------------------+-----------+
| 20 | 621 | 1001 | ILS |
| 20 | 623 | 1002 | USD |
| 20 | 90 | 1003 | GBP |
+--------------+----------------+----------------------+-----------+
</code></pre>
<h3>AMOUNTS:</h3>
<pre><code>+-----------------+--------+-----+
| ACCOUNT_REC(PK) | AMOUNT | |
+-----------------+--------+-----+
| 20 621 1001 | 10000 | |
| 20 623 1002 | 20000 | |
| 20 90 1003 | 30000 | |
+-----------------+--------+-----+
</code></pre>
<p>and I want the result to be a simple join between the primary keys (without ACCOUNT_REC), i.e:</p>
<pre><code>+---------+-----------+-------------+----------+--------+
| BANK_ID | BRANCH_ID | ACCOUNT_NUM | CURRENCY | AMOUNT |
+---------+-----------+-------------+----------+--------+
| 20 | 621 | 1001 | ILS | 10000 |
| 20 | 623 | 1002 | USD | 20000 |
| 20 | 90 | 1003 | GBP | 30000 |
+---------+-----------+-------------+----------+--------+
</code></pre>
<p>My query is: </p>
<pre><code>FROM [ACCOUNTS]
JOIN [AMOUNTS]
ON (REPLACE( CAST ([BANK_ID] as nchar(2)) + ' '
+ CAST ([BRANCH_ID] as nchar(3)) + ' '
+ CAST ([ACCOUNT_NUM] as nchar(4)) ,' ', '') = REPLACE([ACCOUNT_REC], ' ', ''))
</code></pre>
<p>What I made to create a format that suits both tables
<code>[BANK_ID][BRANCH_ID][ACCOUNT_NUM]</code> with no spaces between </p>
<p>I want to if there's any way to improve my query and if there's a better approach to this problem?</p>
<p>P.S: I cannot change the table structure </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T15:02:56.347",
"Id": "419470",
"Score": "2",
"body": "Aside from firing the database admin, I noticed you add spaces&remove them using REPLACE on both sides."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T18:16:55.903",
"Id": "419492",
"Score": "1",
"body": "The only good approach is to split the `amounts.account_rec` column into three separate columns."
}
] | [
{
"body": "<p>You should probably fire the Database Admin.</p>\n\n<p>But seriously, a problem in your query arises if you have duplicate, but different (bank_id + branch_id)'s. For example, (22 + 202) and (2 + 2202) both equal the same thing.</p>\n\n<p>Change your query to include the space, instead of replacing it on both sides.</p>\n\n<p>Here's a SQL Fiddle demonstrating the issue:\n<a href=\"http://sqlfiddle.com/#!18/3a6b9/2\" rel=\"nofollow noreferrer\">http://sqlfiddle.com/#!18/3a6b9/2</a></p>\n\n<p>Example query to match exactly, don't remove the spaces (Note won't work on SQL fiddle as I used different lengths for the colunmns):</p>\n\n<pre><code>SELECT BANK_ID, BRANCH_ID, ACCOUNT_NUM, CURRENCY, AMOUNT\nFROM [ACCOUNTS] \n JOIN [AMOUNTS] \n ON (\n CAST(\n CAST ([BANK_ID] as nchar(2)) + ' '\n + CAST ([BRANCH_ID] as nchar(3)) + ' '\n + CAST ([ACCOUNT_NUM] as nchar(4)) \n AS varchar(255)\n ) \n LIKE\n CAST ([AMOUNTS].[ACCOUNT_REC] AS varchar(255))\n )\n</code></pre>\n\n<p><strong>Update, since you mentioned more about your schema:</strong> </p>\n\n<p><a href=\"https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=f8c037b9cc9afc2e2de850011031020d\" rel=\"nofollow noreferrer\">https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=f8c037b9cc9afc2e2de850011031020d</a></p>\n\n<pre><code>SELECT * FROM ACCOUNTS JOIN AMOUNTS ON (\n CONCAT(CONVERT(VARCHAR(255), [BANK_ID]), ' ')\n + CONCAT(CONVERT(VARCHAR(255), [BRANCH_ID]), ' ')\n + CONVERT(VARCHAR(255), [ACCOUNT_NUM])\n ) LIKE ([AMOUNTS].[ACCOUNT_REC] )\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T05:41:34.667",
"Id": "420617",
"Score": "0",
"body": "Your query returns an empty set"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T07:41:22.667",
"Id": "420637",
"Score": "0",
"body": "@styx as mentioned, you may need to change the values inside 'nchar(x)' to match your database."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T07:48:24.423",
"Id": "420639",
"Score": "0",
"body": "all but ACCOUNT_REC are defined as INT"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T08:17:19.920",
"Id": "420640",
"Score": "0",
"body": "@styx updated my answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T08:39:15.487",
"Id": "420641",
"Score": "0",
"body": "your fiddle is correct, but still, for some reason, i get an empty result"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T08:49:24.277",
"Id": "420642",
"Score": "0",
"body": "@styx what's your schema look like? What version of sql-server are you using?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T09:15:46.003",
"Id": "420643",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/92417/discussion-between-styx-and-dustytrash)."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T15:21:03.513",
"Id": "216872",
"ParentId": "216838",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T07:53:43.590",
"Id": "216838",
"Score": "2",
"Tags": [
"sql",
"sql-server",
"join"
],
"Title": "Simple join between 2 tables with unusual structure"
} | 216838 |
<p>I am using an <code>array_count_values</code> function since I have translated the code from php to javascript and javascript does not have this function, but not sure on the performance of it. I'm sure it can be faster. It currently takes 50ms for 32000 iterations each time it is called.</p>
<p>I have one that returns a simple array:</p>
<pre><code>function array_count_values(arr) {//returns array
let a = [], prev;
arr.sort();
for ( let i = 0; i < arr.length; i++ ) {
if ( arr[i] !== prev ) {
a.push(1)
} else {
a[a.length-1]++;
}
prev = arr[i];
}
return a;
}
</code></pre>
<p>And another that returns an object:</p>
<pre><code>function array_cnt_values(arr) {//returns object
let a = [], prev;
arr.sort();
for ( let i = 0; i < arr.length; i++ ) {
if ( arr[i] !== prev ) {
a[arr[i]] = 1
} else {
a[arr[i]]++;
}
prev = arr[i];
}
return a;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T12:53:24.017",
"Id": "421047",
"Score": "0",
"body": "What do you need it to return? What's the problem description that this code solves?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-19T05:19:46.187",
"Id": "421257",
"Score": "0",
"body": "The function of the code does not need to change, they do what is needed. My question is how to improve the performance of these two pieces of code."
}
] | [
{
"body": "<p>Your first function just gives an array of counts, without anyway to tell what each of them are counting.</p>\n\n<p>Your second function is better, as the index shows what's being counted. You can use the index to see if it already exists, which means you don't have to sort your array.</p>\n\n<pre><code>if( a[arr[i]] )\n</code></pre>\n\n<p>This works fine if all values are positive integers. But what if you had strings? It would still work, but you couldn't loop through the result easily. You might also run into problems if you have values equal to existing array properties like <code>length</code>.</p>\n\n<p>Instead you can use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"nofollow noreferrer\">Map</a>, which is similar to the associative array in php.</p>\n\n<pre><code>function array_count_values(arr) {\n let a = new Map();\n for ( let i = 0; i < arr.length; i++ ) {\n if ( a.has(arr[i]) ) {\n a.set(arr[i], a.get(arr[i])+1)\n } else {\n a.set(arr[i], 1)\n }\n }\n return a;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-19T05:25:00.313",
"Id": "421259",
"Score": "0",
"body": "Yes I need both of the functions, they serve purposes for different things. But I need to optimise the performance of them."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T09:48:02.943",
"Id": "216849",
"ParentId": "216842",
"Score": "1"
}
},
{
"body": "<p>I'll talk about the second implementation first.</p>\n\n<hr>\n\n<p>The name isn't well chosen. I'm aware it's supposed to mirror the PHP name, but in JavaScript it is convention to use camelCase names and not snake_case. I'd choose <code>countArrayValues</code>.</p>\n\n<p>Also don't use unnecessary short and undescriptive variable names. In your case <code>arr</code> and <code>a</code> are easily confused. Better names would be, for example, <code>input</code> and <code>result</code>.</p>\n\n<hr>\n\n<p>You are initializing <code>a</code> as an empty array. Unlike PHP in JavaScript arrays and objects are two different things (although an array is also an object, which is why is still works). An empty object in JavaScript is denoted with <code>{}</code>.</p>\n\n<hr>\n\n<p>It's bad form to have a function like this to mutate its input. A user may not expect that their array is suddenly sorted. </p>\n\n<p>Additionally it's not even needed to sort the array in this case, so leaving it out will speed it up considerably. Instead of comparing with the \"previous\" value, just check if the value is already in the result.</p>\n\n<pre><code>function countArrayValues(input) {//returns object\n let result = {};\n for ( let i = 0; i < input.length; i++ ) {\n // result[input[i]] will either result in `undefined` which is \n // interpreted as `false`, or as the current count, which as \n // a positive integer will be considered `true`\n if ( result[input[i]] ) {\n result[input[i]]++;\n } else {\n result[input[i]] = 1\n }\n }\n return result;\n}\n</code></pre>\n\n<hr>\n\n<p>Regarding the first implemention: I'm not quite sure about the use case, because just a array of numbers without any reference to the original values seems a bit pointless to me. If it's needed I'd base it's implementation on the result of the second version.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T10:09:04.953",
"Id": "419431",
"Score": "0",
"body": "Thanks for your tips about naming conventions, it's a personal project so I just named it whatever I preferred but incidentally all my other functions are named with camel case. The point of the other count value function is to return an array which can be easily sorted. The other use is for an object with specific key names that does not need to be sorted. Hence the two separate functions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T09:55:50.430",
"Id": "216850",
"ParentId": "216842",
"Score": "1"
}
},
{
"body": "<h2>Depends of the data</h2>\n\n<p>The best solution to the problem will depend on the data you are processing. As you have given no indication as to what the data contains I can but guess.</p>\n\n<h2>Small range</h2>\n\n<p>If the values are a small set within a known range then the optimal solutions is to create an array that will fit all the values before the loop, fill it with zero and then count each index.</p>\n\n<h3>Example A</h3>\n\n<p><code>values</code> is array of integers in the range of 0-<code>setSize</code></p>\n\n<pre><code>function countValuesA(values, setSize) { // example A\n const counts = new Array(setSize);\n counts.fill(0);\n var i;\n for (i = 0; i < values.length; i++) { counts[values[i]]++ }\n return counts;\n}\n</code></pre>\n\n<h2>Limited</h2>\n\n<p>This only works for values that are integers >= 0. The following solutions will work for any type of values. But as you can see in the benchmarking the above method can provide a huge advantage, So much so that is worth upstream modification to bring small range sets into an integer range.</p>\n\n<h2>Unknown set with small range</h2>\n\n<p>If the set of values is unknown but small then you know that each iteration is more likely to find an existing value to count. Thus you can write the function to favor that situation.</p>\n\n<p>When using a Map, either as <code>count = new Map</code>, or <code>counts = {}</code> there is a cost each time you access a key. This is the cost of converting the key to a hash. </p>\n\n<p>So avoiding the hash calculation when possible gives an advantage.</p>\n\n<h3>Example B</h3>\n\n<p>When the set of values is small (compared to the number of values) but the range of the values is unknown</p>\n\n<pre><code>function countValuesB(values) { // example B\n const counts = new Map();\n var i,count;\n for (i = 0; i < values.length; i++) {\n count = counts.get(values[i]);\n if (count) { count[0]++ }\n else { counts.set(values[i], [1]) }\n }\n return counts;\n}\n</code></pre>\n\n<h2>Unknown set with large range</h2>\n\n<p>If the set of values is large (near or greater than the length of the array) then the above example is at a disadvantage, as each new value found require that a new array is created. The new array has a higher cost than calculating the hash, so we can put the advantage to adding new items in the map of counts</p>\n\n<h3>Example C</h3>\n\n<p>When the set of values is large or the range is unknown </p>\n\n<pre><code>function countValuesC(values) { // example C\n const counts = new Map();\n var i;\n for (i = 0; i < values.length; i++) {\n const num = values[i];\n if (counts.has(num)) { counts.set(num, counts.get(num) + 1) }\n else { counts.set(num, 1) }\n }\n return counts;\n}\n</code></pre>\n\n<h2>Bench-marking</h2>\n\n<p>To get a flavor as to how each performs we must benchmark the performance for different types of data. To define the data I have used the following</p>\n\n<pre><code>const data = (length, min, max) => setOf(length, () => randI(min, max));\n</code></pre>\n\n<p>Where <code>setOf</code> creates an array of <code>length</code>. The array contains random integers from <code>min</code> to <code>max-1</code></p>\n\n<p>If we benchmark the three example A,B,C. The values are linear metrics denoting time taken, with lower values faster. </p>\n\n<h3>Performance comparisons</h3>\n\n<pre><code> length | min | max || A | B | C | ~ perf Best Worst \n ------------------------- ---------------------------------------------\n 32000 | 0 | 1000 || 0.205 | 1.472 | 2.159 | A 10 times faster C\n 32000 | 10000 | 11000 || 2.091 | 1.554 | 2.249 | B 30% faster C\n 32000 | 10000 |1000000 || 8.888 | 4.541 | 4.003 | C 2 times faster A\n</code></pre>\n\n<p><em><sub><strong>Note</strong> Function A uses max as its second argument.</sub></em></p>\n\n<p>From the best of the worst (last line C) to the best of the best (first line A) processing 32000 items can have a performance difference of 2000% simply by taking advantage of the type, distribution, and range of the items being processed.</p>\n\n<h2>Ternary</h2>\n\n<p>In JavaScript ternary expression always tend to be slightly quicker than statements. In my view ternaries are easier to read.</p>\n\n<p>The two examples B,and C can be written with ternary and give both function a 3% performance increase. The benefit is marginal, but it is good practice to favor a performant and readable style over any other.</p>\n\n<h3>Example B ternary</h3>\n\n<pre><code>function countValuesBT(values) {\n const counts = new Map();\n var i, c;\n for (i = 0; i < values.length; i++) {\n (c = counts.get(values[i])) ? c[0]++ : counts.set(values[i], [1]);\n }\n return counts;\n}\n</code></pre>\n\n<h3>Example C ternary</h3>\n\n<pre><code>function countValuesCT(values) { \n const counts = new Map();\n var i, num;\n for (i = 0; i < values.length; i++) {\n counts.has(num = values[i]) ?\n counts.set(num, counts.get(num) + 1) :\n counts.set(num, 1);\n }\n return counts;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T14:06:47.383",
"Id": "419462",
"Score": "0",
"body": "My god, this is a comprehensive answer! Looking through it all now. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T14:49:42.573",
"Id": "419466",
"Score": "0",
"body": "Don't these all return objects though? I needed one to return a simple array like `1,2,2,1,1' because it's easy to sort. I searched but couldn't find any way to sort an object unless the keys were the same. The keys here would all be different since it's counting each different type."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T15:33:31.607",
"Id": "419475",
"Score": "0",
"body": "@Hasen Info on Map https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T13:23:18.140",
"Id": "216864",
"ParentId": "216842",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T08:25:07.640",
"Id": "216842",
"Score": "1",
"Tags": [
"javascript",
"node.js"
],
"Title": "Javascript array_count_values function"
} | 216842 |
<p>I tried to solve the <a href="https://leetcode.com/problems/super-pow/" rel="nofollow noreferrer">Super Pow - LeetCode</a></p>
<blockquote>
<ol start="372">
<li>Super Pow</li>
</ol>
<p>Medium</p>
<p>Your task is to calculate <em>a</em><sup><em>b</em></sup> mod 1337 where <em>a</em> is a positive integer and <em>b</em> is an extremely large positive integer given in the form of an array.</p>
<p><strong>Example 1:</strong></p>
<pre><code>Input: a = 2, b = [3]
Output: 8
</code></pre>
<p><strong>Example 2:</strong></p>
<pre><code>Input: a = 2, b = [1,0]
Output: 1024
</code></pre>
</blockquote>
<p>My solution </p>
<pre class="lang-py prettyprint-override"><code>import unittest
import logging
logging.basicConfig(level=logging.DEBUG, format="%(levelname)s %(message)s")
class Solution(object):
def superPow(self, a, b):
"""
:type a: int
:type b: List[int]
:rtype: int
"""
digit = int("".join(map(str, b)))
product = a ** digit
res = product % 1337
return res
class MyCase(unittest.TestCase):
def setUp(self):
self.solution = Solution()
def test_1(self):
a = 2
b = [1, 0]
answer = 1024
check = self.solution.superPow(a, b)
self.assertEqual(answer, check)
unittest.main()
</code></pre>
<p>The solution exceeded the time limit.</p>
<p>How could I improve my solution?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T10:18:03.550",
"Id": "419533",
"Score": "0",
"body": "*an extremely large positive integer given in the form of an array*\" is far too vague for a specification."
}
] | [
{
"body": "<p>Python's built-in <a href=\"https://docs.python.org/3/library/functions.html#pow\" rel=\"nofollow noreferrer\"><code>pow</code></a> already has this functionality.</p>\n\n<pre><code>class Solution(object):\n def superPow(self, a, b):\n \"\"\"\n :type a: int\n :type b: List[int]\n :rtype: int\n \"\"\"\n digit = int(\"\".join(map(str, b)))\n return pow(a, digit, 1337)\n</code></pre>\n\n<p>The bottleneck then might be parsing the list of digits into the integer. To remedy that, you can try to use the fact that</p>\n\n<p><span class=\"math-container\">\\$\n\\begin{align}\na^{123} ~\\text{mod}~ 1337 &= (a^{100}\\cdot a^{20}\\cdot a^3)~\\text{mod}~ 1337& \\\\\n &= (a^{100}~\\text{mod}~ 1337 \\cdot a^{20}~\\text{mod}~ 1337\\cdot a^3 ~\\text{mod}~ 1337) ~\\text{mod}~ 1337& \\\\\n\\end{align}\\$</span></p>\n\n<pre><code>class Solution(object):\n def superPow(self, a, b):\n \"\"\"\n :type a: int\n :type b: List[int]\n :rtype: int\n \"\"\"\n ret = 1\n for i, digit in enumerate(reversed(b)):\n ret = (ret * pow(a, digit * 10**i, 1337)) % 1337\n return ret\n</code></pre>\n\n<hr>\n\n<p>And here are some timings for inputs of increasing length (from 1 to 10 digits, because your function would take way too long otherwise), with <code>a = 2</code> and where <code>super_pow_op</code> is your function, <code>super_pow_built_in</code> is my first function and <code>super_pow_expanded</code> is my second function.</p>\n\n<p><a href=\"https://i.stack.imgur.com/Ei9vK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Ei9vK.png\" alt=\"enter image description here\"></a></p>\n\n<p>And here for 3 to 1000 digits, but only with my two functions:</p>\n\n<p><a href=\"https://i.stack.imgur.com/kNZ9W.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kNZ9W.png\" alt=\"enter image description here\"></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T09:57:39.273",
"Id": "419429",
"Score": "0",
"body": "amazing, do you mind if I ask what' the tool you use to analyze the performance?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T09:58:35.963",
"Id": "419430",
"Score": "1",
"body": "@Alice: I used the code in [my question here](https://codereview.stackexchange.com/questions/165245/plot-timings-for-a-range-of-inputs), plus the answer given there."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T09:17:44.227",
"Id": "216846",
"ParentId": "216845",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216846",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T09:11:20.960",
"Id": "216845",
"Score": "1",
"Tags": [
"python",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Exceeded time limit to solve super pow"
} | 216845 |
<p>I'm learning design patterns and I thought that it would be a good idea to make my examples of each pattern. This is <a href="https://github.com/NovaBG03/DesignPatternsExamples/tree/master/StrategyPatternExamples/Example1" rel="nofollow noreferrer">my example</a> of the Strategy Pattern. Can you tell me is it good and what to improve?</p>
<p>This is the Gallery class</p>
<pre><code> public class PhotoGallery
{
private ICollection<string> photosNames;
private IShareStrategy shareStrategy;
public PhotoGallery()
{
this.photosNames = new List<string>();
}
public void AddPhoto(string photoName)
{
this.photosNames.Add(photoName);
}
private void SetShareStrategy(ShareStrategy strategy)
{
switch (strategy)
{
case ShareStrategy.onFacebook:
this.shareStrategy = new ShareOnFacebook();
break;
case ShareStrategy.onInstagram:
this.shareStrategy = new ShareOnInstagram();
break;
case ShareStrategy.onTwitter:
this.shareStrategy = new ShareOnTwitter();
break;
}
}
public void SharePhoto(string photoName, ShareStrategy strategy)
{
if (!this.photosNames.Contains(photoName))
{
Console.WriteLine("Invalid photo name.");
return;
}
this.SetShareStrategy(strategy);
shareStrategy.Share(photoName);
}
}
</code></pre>
<p>This is The Share Strategy Enum</p>
<pre><code>public enum ShareStrategy
{
onFacebook,
onInstagram,
onTwitter
}
</code></pre>
<p>And the Strategies classes</p>
<pre><code>public class ShareOnFacebook : IShareStrategy
{
public void Share(string photoName)
{
Console.WriteLine($"You shared {photoName} on Facebook.");
}
}
public class ShareOnInstagram : IShareStrategy
{
public void Share(string photoName)
{
Console.WriteLine($"You shared {photoName} on Instagram.");
}
}
public class ShareOnTwitter : IShareStrategy
{
public void Share(string photoName)
{
Console.WriteLine($"You shared {photoName} on Twitter.");
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T10:36:11.760",
"Id": "419434",
"Score": "4",
"body": "We cannot review just the pattern alone. You have use it with some _real-world_ application. I see you have one so please [edit] your question and add a description about what it is doing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T00:15:19.473",
"Id": "420072",
"Score": "1",
"body": "Looks more like Factory rather than Strategy"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T00:20:53.200",
"Id": "420073",
"Score": "1",
"body": "Here's a more trustworthy example from wikipedia https://en.wikipedia.org/wiki/Strategy_pattern#C#"
}
] | [
{
"body": "<p>I would use dependency injection. Something like</p>\n\n<pre><code>serviceCollection\n .AddTransient<IShareStrategy, ShareOnFacebook>()\n .AddTransient<IShareStrategy, ShareOnTwitter>()\n .AddTransient<IShareStrategyProvider, ShareStrategyProvider>();\n\npublic class ShareStrategyProvider : IShareStrategyProvider\n{\n private readonly IEnumerable<IShareStrategy> _strategies;\n public ShareStrategyProvider(IEnumerable<IShareStrategy> strategies) \n {\n _strategies = strategies;\n }\n\n public GetStrategy(ShareStrategy sharingStrategy);\n {\n return _strategies.Single(s => s.SharingStrategy == sharingStrategy);\n }\n}\n</code></pre>\n\n<p>edit: Read up on open/closed principle, its related</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T10:04:37.770",
"Id": "216851",
"ParentId": "216847",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216851",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T09:32:51.147",
"Id": "216847",
"Score": "3",
"Tags": [
"c#",
"object-oriented",
"design-patterns"
],
"Title": "Implementation of Strategy Pattern (photo gallery example)"
} | 216847 |
<p>I'm a beginner as you can see and I would like to know how I can improve my code. Studying for 6 months now. Thank you.</p>
<pre><code>roman_dict = {1: 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L', 90: 'XC', 100: 'C', 400: 'CD',
500: 'D', 900: 'CM', 1000: 'M'}
divide_list = [1000, 100, 10, 1]
def not_in_dict(fixed_decimal, divide_num):
sub_count = 0
sub_roman_multi = roman_dict[divide_num]
temp_decimal = fixed_decimal
while temp_decimal not in roman_dict:
temp_decimal -= divide_num
sub_count += 1
return roman_dict[temp_decimal]+(sub_count*sub_roman_multi)
def decimal_to_roman(decimal):
original_decimal = decimal
roman = ""
for divide_num in divide_list:
if decimal >= divide_num:
reminder = decimal//divide_num
if(reminder >= 1) and ((reminder*divide_num) in roman_dict):
roman += roman_dict[(reminder*divide_num)]
decimal -= reminder*divide_num
else:
roman += not_in_dict(reminder*divide_num, divide_num)
decimal -= (reminder*divide_num)
return str(original_decimal)+' = '+roman
</code></pre>
| [] | [
{
"body": "<p>If you use a list of tuples instead of a dictionary and reverse the order, you can simply iterate over it. Your <code>while</code> loop also becomes a lot easier to understand and there is no longer any need to outsource it to another function that returns the literal and its count.</p>\n\n<p>Instead of manually adding strings (<a href=\"https://www.python.org/dev/peps/pep-0008/#programming-recommendations\" rel=\"noreferrer\">something you should basically never do in in Python</a>), use <code>str.join</code>.</p>\n\n<pre><code>ROMAN_LITERALS = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'),\n (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'),\n (5, 'V'), (4, 'IV'), (1, 'I')]\n\ndef decimal_to_roman(x):\n out = []\n for value, literal in ROMAN_LITERALS:\n while x >= value:\n x -= value\n out.append(literal)\n return \"\".join(out)\n</code></pre>\n\n<p>Instead of the <code>while</code> loop you can also use integer division like you did:</p>\n\n<pre><code>def decimal_to_roman(x):\n out = []\n for value, literal in ROMAN_LITERALS:\n n = x // value # will be 0 if value is too large\n out.extend([literal] * n) # will not do anything if n == 0\n x -= n * value # will also not do anything if n == 0\n return \"\".join(out)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T13:36:04.307",
"Id": "419453",
"Score": "0",
"body": "wow. looks so easy now, thank you. that's great."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T14:01:34.113",
"Id": "419460",
"Score": "1",
"body": "@Ofeks: If this helped you, consider accepting it as the correct answer (by clicking the checkmark to the left of the answer). It is customary to wait about 24 hours, though, to give everyon on the globe a chance to answer and not discourage other people from commenting."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T12:01:48.310",
"Id": "216860",
"ParentId": "216852",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "216860",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T10:23:42.617",
"Id": "216852",
"Score": "6",
"Tags": [
"python",
"roman-numerals"
],
"Title": "Decimal to roman python"
} | 216852 |
<p>I am working on an easy math question Happy number <a href="https://leetcode.com/problems/happy-number/" rel="nofollow noreferrer">Happy Number - LeetCode</a></p>
<blockquote>
<ol start="202">
<li>Happy Number</li>
</ol>
<p>Write an algorithm to determine if a number is "happy".</p>
<p>A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.</p>
<p><strong>Example:</strong> </p>
<pre><code>Input: 19
Output: true
Explanation:
1² + 9² = 82
8² + 2² = 68
6² + 8² = 100
1² + 0² + 0² = 1
</code></pre>
</blockquote>
<p>My solutions</p>
<ul>
<li><p>Solution 1, 28ms 12.1mb</p>
<ul>
<li>string operations</li>
</ul></li>
</ul>
<pre class="lang-py prettyprint-override"><code>class Solution1:
def isHappy(self, n):
s = set()
while n != 1:
if n in s: return False
s.add(n)
n = sum([int(i) ** 2 for i in str(n)])
else:
return True
</code></pre>
<ul>
<li>Solution 2, 24ms, 12.3mb</li>
</ul>
<pre class="lang-py prettyprint-override"><code>class Solution2:
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
s = set()
while n != 1:
if n in s: return False
s.add(n)
_sum = 0
while n:
_sum += (n % 10) ** 2
n //= 10
n = _sum
return n == 1
</code></pre>
<ul>
<li>Solution 3 the save as solution 2 minor changes (24ms, 12.3mb)</li>
</ul>
<pre class="lang-py prettyprint-override"><code>class Solution3:
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
s = set()
while n:
if 1 in s:
return True
if n in s:
return False
s.add(n)
_sum = 0
while n:
_sum += (n%10)**2 #leave unit digit
n //= 10 #remvoe unit digit
n = _sum
</code></pre>
<ul>
<li>Solution 4 without extra space(24ms, 12.3mb)</li>
</ul>
<pre class="lang-py prettyprint-override"><code>class Solution4:
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
while n != 1 and n != 4:
_sum = 0
while n :
_sum += (n % 10) * (n % 10)
n //= 10
n = _sum
return n == 1
</code></pre>
<p>TestCase</p>
<pre><code>class MyCase(unittest.TestCase):
def setUp(self):
self.solution = Solution3()
def test_1(self):
n = 19
check = self.solution.isHappy(n)
self.assertTrue(check)
</code></pre>
<p>It's interesting that the last 3 solutions shared the same performance, though try best possibility to improve it.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T18:29:49.390",
"Id": "419494",
"Score": "1",
"body": "In general, you should never be using a benchmark that takes less than a second. Timings below that are way too variable."
}
] | [
{
"body": "<p>Solution #2:</p>\n\n<pre><code>class Solution2:\n def isHappy(self, n):\n # ...\n while n != 1:\n if n in s: return False\n # ...\n\n return n == 1\n</code></pre>\n\n<p>You are looping while <code>n != 1</code>, without any <code>break</code> statements. There is no need to test <code>n == 1</code> at the return statement at the end. Just <code>return True</code>.</p>\n\n<hr>\n\n<p>Solution #3 returns <code>None</code> if 0 is given as input, instead of returning <code>True</code> or <code>False</code>.</p>\n\n<hr>\n\n<p>Solution #4 becomes an endless loop if 0 is given as input.</p>\n\n<p>Are there any other stopping conditions other that <code>n == 0</code>, <code>n == 1</code> or <code>n == 4</code>? It isn't clear that all unhappy numbers result in a loop containing the value <code>4</code>, so the validity of this approach is in question.</p>\n\n<p><strong>Update</strong>: Actually <a href=\"https://en.wikipedia.org/wiki/Happy_number#Sequence_behavior\" rel=\"nofollow noreferrer\">Wikipedia</a> provides a clear argument that unhappy numbers will arrive in a loop containing the value <code>4</code>, so this approach is valid, but should included a comment with a link to that proof.</p>\n\n<hr>\n\n<p>In all your solutions, your loop is testing at least two conditions, such as both <code>n != 1</code> and <code>n is s</code>. Why not initialize <code>s</code> to contain a <code>1</code> (or even just leave it as an empty set), and then only test <code>n in s</code>. No special cases.</p>\n\n<pre><code>def is_happy(n):\n s = { 1 }\n\n while n not in s:\n s.add(n)\n n = sum(i * i for i in map(int, str(n)))\n\n return n == 1\n</code></pre>\n\n<p><strong>Update</strong>:</p>\n\n<p>Since <a href=\"https://en.wikipedia.org/wiki/Happy_number#Sequence_behavior\" rel=\"nofollow noreferrer\">Wikipedea</a> has <em>proof</em> that all positive unhappy numbers end in the sequence <code>4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 → ...</code>, and happy numbers end in the sequence <code>1 → 1 → ...</code>, you can create a set of these termination values (including <code>0 → 0 → ...</code>), and no longer needed to maintain the set of \"seen\" values. By using all numbers in the unhappy loop, we can terminate the search up to 8 iterations earlier over just checking for <code>n == 1</code> and <code>n == 4</code>.</p>\n\n<pre><code>def is_happy(num):\n # See https://en.wikipedia.org/wiki/Happy_number#Sequence_behavior\n terminal = { 0, 1, 4, 16, 20, 37, 42, 58, 89, 145 }\n\n while num not in terminal:\n num = sum(i * i for i in map(int, str(num)))\n\n return n == 1\n</code></pre>\n\n<hr>\n\n<p>Finally:</p>\n\n<ul>\n<li>follow the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a> standards (avoid mixedCase function/method names),</li>\n<li><a href=\"https://www.youtube.com/watch?v=o9pEzgHorH0\" rel=\"nofollow noreferrer\">Stop writing classes</a>!</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T22:41:59.017",
"Id": "216892",
"ParentId": "216856",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216892",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T11:24:06.377",
"Id": "216856",
"Score": "4",
"Tags": [
"python",
"performance",
"programming-challenge",
"comparative-review"
],
"Title": "4 solutions to leetcode 202. Happy Number have almost same performance"
} | 216856 |
<p>Intersection of two sorted vectors in C++ - can this be written any better?</p>
<pre><code>vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
vector<int> result;
int l = 0, r = 0;
while(l < nums1.size() && r < nums2.size()){
int left = nums1[l], right = nums2[r];
if(left == right){
result.push_back(right);
while(l < nums1.size() && nums1[l] == left )l++;
while(r < nums2.size() && nums2[r] == right )r++;
continue;
}
if(left < right){
while(l < nums1.size() && nums1[l] == left )l++;
}else while( r < nums2.size() && nums2[r] == right )r++;
}
return result;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T14:30:38.560",
"Id": "419464",
"Score": "5",
"body": "Do you know about `std::set_intersection()`? Reference and example implementations: https://en.cppreference.com/w/cpp/algorithm/set_intersection"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T14:57:49.687",
"Id": "419467",
"Score": "3",
"body": "@user673679 yes I did, and didn't want to use it;"
}
] | [
{
"body": "<ul>\n<li><p>Indentation</p>\n\n<p>Your indentation is not consistent. This makes the code hard to read and maintain. It should be fixed so you don't give other people headaches.</p>\n\n<pre><code> if(left < right){\n while(l < nums1.size() && nums1[l] == left )l++;\n }else while( r < nums2.size() && nums2[r] == right )r++;\n</code></pre>\n\n<p>That is basically unreadable giberish (opinion of Martin).</p></li>\n<li><p>Using namespace <code>std;</code> is super bad</p>\n\n<p>This is mention in nearly every C++ review. There is a large article on the subject here: <em><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Why is “using namespace std” considered bad practice?</a></em>. The second answer is the best in my opinion (Martin) <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice/1453605#1453605\">see</a></p></li>\n<li><p>Multiple declarations in one is bad (thanks to terrible syntax binding rules)</p>\n\n<p>The one declaration per line has been written about adnausium in best practice guides. Please for the sake of your reader declare one variable per line with its own exact type.</p>\n\n<p>The syntax binding rules alluded to above is:</p>\n\n<pre><code>int* x, y; // Here x is int* and y in int\n // confusing to a reader. Did you really mean to make y an int?\n // Avoid this problem be declaring one variable per line\n</code></pre></li>\n<li><p>Typically, functions like this would be based on iterators to work on any container</p>\n\n<p>Here your code is limited to only using vectors. But the algorithm you are using could be used by any container type with only small modifications. As a result your function could provide much more utility being written to use iterators.</p>\n\n<p>The standard library was written such that iterators are the glue between algorithms and container.</p></li>\n<li><p>It would be a lot simpler, if not necessarily more efficient at runtime, to just use some hash sets.</p></li>\n<li>This function could be generic in T rather than assuming <code>int</code>.</li>\n<li>The repeated conditions make me feel like there's simplification waiting here, although exactly what that is eludes me in the two minutes I'm spending on this.</li>\n<li>Should take by <code>const</code> ref, not ref, so that you can operate on temporaries.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T13:53:30.477",
"Id": "419459",
"Score": "1",
"body": "You caught the problems and I voted you up, but you could improve your answer by explaining what the issue for the first 4 bullet items."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T16:55:22.110",
"Id": "419480",
"Score": "2",
"body": "@pacmaninbw: Added some context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T08:10:26.760",
"Id": "419526",
"Score": "0",
"body": "@MartinYork wow! whose answer is it, anyway? :) :) /intended in a positive way/"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T12:44:50.960",
"Id": "216863",
"ParentId": "216861",
"Score": "13"
}
},
{
"body": "<p>I invite you to review <a href=\"https://codereview.stackexchange.com/a/216863/8999\">@DeadMG's answer</a>.</p>\n\n<p>Rewriting following (most of) his advice, you'd get something like:</p>\n\n<pre><code>#include <cassert>\n#include <algorithm>\n#include <vector>\n\nstd::vector<T> intersection(std::vector<T> const& left_vector, std::vector<T> const& right_vector) {\n auto left = left_vector.begin();\n auto left_end = left_vector.end();\n auto right = right_vector.begin();\n auto right_end = right_vector.end();\n\n assert(std::is_sorted(left, left_end));\n assert(std::is_sorted(right, right_end));\n\n std::vector<T> result;\n\n while (left != left_end && right != right_end) {\n if (*left == *right) {\n result.push_back(*left);\n ++left;\n ++right;\n continue;\n }\n\n if (*left < *right) {\n ++left;\n continue;\n }\n\n assert(*left > *right);\n ++right;\n }\n\n return result;\n}\n</code></pre>\n\n<p>I've always found taking pairs of iterators awkward, so I would not recommend such an interface. Instead, you could take simply take any \"iterable\", they need not even have the same value type, so long as they are comparable:</p>\n\n<pre><code>template <typename Left, typename Right>\nstd::vector<typename Left::value_type> intersection(Left const& left_c, Right const& right_c);\n</code></pre>\n\n<p>Also, note that I've included some <code>assert</code> to validate the pre-conditions of the methods (the collections must be sorted) as well as internal invariants (if <code>*left</code> is neither equal nor strictly less than <code>*right</code> then it must be strictly greater).</p>\n\n<p>I encourage you to use <code>assert</code> liberally:</p>\n\n<ul>\n<li>They document intentions: pre-conditions, invariants, etc...</li>\n<li>They check that those intentions hold.</li>\n</ul>\n\n<p>Documentation & Bug detection rolled in one, with no run-time (Release) cost.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T16:59:19.717",
"Id": "419481",
"Score": "1",
"body": "Why don't you post that as its own questions. There are some improvements even if we don't move to iterators like using template template types."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T17:10:59.537",
"Id": "419482",
"Score": "1",
"body": "@MartinYork: I generally don't find \"template template\" to be an improvement, they're quite awkward to use, and tend to constrain the inputs more than intended."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T08:29:52.500",
"Id": "419527",
"Score": "0",
"body": "Accepting iterable types is a good idea, and certainly the direction of modern C++ (Ranges, etc). If I were writing it, I'd probably provide the iterator-pair interface for the rare occasions that the caller needs more control, and provide the range interface as a thin adapter. Also, consider the Standard Library pattern of passing an output iterator - that can similarly be wrapped with an adaptor if a vector result is needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T08:35:41.070",
"Id": "419528",
"Score": "0",
"body": "@TobySpeight: If you want two pairs of iterators as input and an output iterator as output... well, that's `set_intersection` :) Another nice trick, rather than taking an output iterator as argument, would be to create an \"intersecting range\" which can be consumed lazily and us *that* to initialize whatever collection you want... haven't played much with ranges yet but it seems doable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T08:40:32.550",
"Id": "419530",
"Score": "0",
"body": "I've haven't played with ranges myself, but that does sound like a worthwhile exercise; I'll put that on the list of fun things to do when I get around to it (probably when I need light relief from maintaining C++03 code)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T18:34:39.880",
"Id": "419775",
"Score": "0",
"body": "@MatthieuM. Because your implementation will fail when there are duplicates."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T07:00:16.250",
"Id": "419833",
"Score": "0",
"body": "@Rick: Thanks for clarifying; I used the specifications of [`set_intersection`](https://en.cppreference.com/w/cpp/algorithm/set_intersection) as a basis. Adding duplicate-filtering is easy, however I am not sure this is the right call; it seems to be an orthogonal issue, which can be solved by first filtering the input, so that only inputs which do contain duplicates pay the cost for the detection."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T23:00:28.173",
"Id": "419929",
"Score": "0",
"body": "@MatthieuM.How can I generalize this approach to work with vectors of doubles rather than ints?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T06:35:03.880",
"Id": "419951",
"Score": "0",
"body": "@Seth: The approach I presented here is already generalized, since it takes `T` instead of `int`. If you pass it a `std::vector<double>` it will work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T13:26:15.973",
"Id": "420002",
"Score": "0",
"body": "@MatthieuM. How would I specify the tolerance when a = b?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T14:33:50.053",
"Id": "420015",
"Score": "0",
"body": "@Seth: Ah! I see. In this case, I would advise following the lead of the standard library => pass a 3rd argument which is a comparison predicate (default is `std::less<T>`), and replace all comparisons with uses of the predicate. This allows the user to provide a \"fuzzy\" comparator."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T16:55:11.220",
"Id": "216880",
"ParentId": "216861",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "216863",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T12:38:18.530",
"Id": "216861",
"Score": "7",
"Tags": [
"c++",
"reinventing-the-wheel"
],
"Title": "Intersection of two sorted vectors in C++"
} | 216861 |
<p>I could use some help refactoring my component and service. I have a lot of nested logic and wasn't sure what I could do to improve this. I'm new to Angular 7 and their piping syntax. I suspect this is what I could use in this example to improve my code? Also, I have an issue where the drawPoll() function is being called before the forEach iteration is done so I manually added a 3 second setTimeout() for the time being. I think that refactoring these subscriptions to not be so nested and also be synchronous might fix this issue.</p>
<p><strong>poll.component.ts</strong></p>
<pre><code>import { Component, OnInit } from '@angular/core';
import * as Chart from 'chart.js';
import { Observable } from 'rxjs';
import { FirebaseService } from '../services/firebase.service';
import { Input, Output, EventEmitter } from '@angular/core';
import { CardModule } from 'primeng/card';
@Component({
selector: 'app-poll',
templateUrl: './poll.component.html',
styleUrls: ['./poll.component.scss']
})
export class PollComponent implements OnInit {
chart:any;
poll:any;
votes:[] = [];
labels:string[] = [];
title:string = "";
isDrawn:boolean = false;
inputChoices:any = [];
@Input()
pollKey: string;
@Output()
editEvent = new EventEmitter<string>();
@Output()
deleteEvent = new EventEmitter<string>();
constructor(private firebaseService: FirebaseService) { }
ngOnInit() {
this.firebaseService.getPoll(this.pollKey).subscribe(pollDoc => {
// ToDo: draw poll choices on create without breaking vote listener
console.log("details?", pollDoc);
// Return if subscription was triggered due to poll deletion
if (!pollDoc.payload.exists) {
return;
}
const pollData:any = pollDoc.payload.data();
this.poll = {
id: pollDoc.payload.id,
helperText: pollData.helperText,
pollType: pollData.pollType,
scoringType: pollData.scoringType,
user: pollData.user
};
this.title = this.poll.pollType == 1 ? "Title 1" : "Title 2"
this.firebaseService.getChoices(this.pollKey).subscribe(choices => {
this.poll.choices = [];
choices.forEach(choice => {
const choiceData:any = choice.payload.doc.data();
const choiceKey:any = choice.payload.doc.id;
this.firebaseService.getVotes(choiceKey).subscribe((votes: any) => {
console.log("does this get hit on a vote removal?", votes.length);
this.poll.choices.push({
id: choiceKey,
text: choiceData.text,
votes: votes.length
});
})
});
setTimeout(() => {
this.drawPoll();
}, 3000);
});
});
}
drawPoll() {
if (this.isDrawn) {
this.chart.data.datasets[0].data = this.poll.choices.map(choice => choice.votes);
this.chart.data.datasets[0].label = this.poll.choices.map(choice => choice.text);
this.chart.update()
}
if (!this.isDrawn) {
this.inputChoices = this.poll.choices;
var canvas = <HTMLCanvasElement> document.getElementById(this.pollKey);
var ctx = canvas.getContext("2d");
this.chart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: this.poll.choices.map(choice => choice.text),
datasets: [{
label: this.title,
data: this.poll.choices.map(choice => choice.votes),
fill: false,
backgroundColor: [
"rgba(255, 99, 132, 0.2)",
"rgba(255, 159, 64, 0.2)",
"rgba(255, 205, 86, 0.2)",
"rgba(75, 192, 192, 0.2)",
"rgba(54, 162, 235, 0.2)",
"rgba(153, 102, 255, 0.2)",
"rgba(201, 203, 207, 0.2)"
],
borderColor: [
"rgb(255, 99, 132)",
"rgb(255, 159, 64)",
"rgb(255, 205, 86)",
"rgb(75, 192, 192)",
"rgb(54, 162, 235)",
"rgb(153, 102, 255)",
"rgb(201, 203, 207)"
],
borderWidth: 1
}]
},
options: {
events: ["touchend", "click", "mouseout"],
onClick: function(e) {
console.log("clicked!", e);
},
tooltips: {
enabled: true
},
title: {
display: true,
text: this.title,
fontSize: 14,
fontColor: '#666'
},
legend: {
display: false
},
maintainAspectRatio: true,
responsive: true,
scales: {
xAxes: [{
ticks: {
beginAtZero: true,
precision: 0
}
}]
}
}
});
this.isDrawn = true;
}
}
vote(choiceId) {
if (choiceId) {
const choiceInput:any = document.getElementById(choiceId);
const checked = choiceInput.checked;
if (checked) this.firebaseService.incrementChoice(choiceId);
if (!checked) this.firebaseService.decrementChoice(choiceId);
this.poll.choices.forEach(choice => {
const choiceEl:any = document.getElementById(choice.id);
if (choiceId !== choiceEl.id && checked) choiceEl.disabled = true;
if (!checked) choiceEl.disabled = false;
});
}
}
}
</code></pre>
<p><strong>firebase.service.ts</strong></p>
<pre><code>import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';
import { map, switchMap, first } from 'rxjs/operators';
import { Observable, from } from 'rxjs';
import * as firebase from 'firebase';
import { AngularFireAuth } from '@angular/fire/auth';
@Injectable({
providedIn: 'root'
})
export class FirebaseService {
// Source: https://github.com/AngularTemplates/angular-firebase-crud/blob/master/src/app/services/firebase.service.ts
constructor(public db: AngularFirestore, private afAuth: AngularFireAuth) { }
getPoll(pollKey) {
return this.db.collection('polls').doc(pollKey).snapshotChanges();
}
getChoices(pollKey) {
return this.db.collection('choices', ref => ref.where('poll', '==', pollKey)).snapshotChanges();
}
incrementChoice(choiceKey) {
const userId = this.afAuth.auth.currentUser.uid;
const choiceDoc:any = this.db.collection('choices').doc(choiceKey);
// Check if user voted already
choiceDoc.ref.get().then(choice => {
let pollKey = choice.data().poll
this.db.collection('votes').snapshotChanges().pipe(first()).subscribe((votes:any) => {
let filteredVote = votes.filter((vote) => {
const searchedPollKey = vote.payload.doc._document.proto.fields.poll.stringValue;
const searchedChoiceKey = vote.payload.doc._document.proto.fields.choice.stringValue;
const searchedUserKey = vote.payload.doc._document.proto.fields.user.stringValue;
return (searchedPollKey == pollKey && searchedChoiceKey == choiceKey && searchedUserKey == userId);
});
if (filteredVote.length) {
// This person aleady voted
return false;
} else {
let votes = choice.data().votes
choiceDoc.update({
votes: ++votes
});
const userDoc:any = this.db.collection('users').doc(userId);
userDoc.ref.get().then(user => {
let points = user.data().points
userDoc.update({
points: ++points
});
});
this.createVote({
choiceKey: choiceKey,
pollKey: pollKey,
userKey: userId
});
}
});
});
}
decrementChoice(choiceKey) {
const choiceDoc:any = this.db.collection('choices').doc(choiceKey);
const userId = this.afAuth.auth.currentUser.uid;
choiceDoc.ref.get().then(choice => {
let pollKey = choice.data().poll
let votes = choice.data().votes
choiceDoc.update({
votes: --votes
});
const userDoc:any = this.db.collection('users').doc(userId);
userDoc.ref.get().then(user => {
let points = user.data().points
userDoc.update({
points: --points
});
});
// Find & delete vote
this.db.collection('votes').snapshotChanges().pipe(first()).subscribe((votes:any) => {
let filteredVote = votes.filter((vote) => {
const searchedPollKey = vote.payload.doc._document.proto.fields.poll.stringValue;
const searchedChoiceKey = vote.payload.doc._document.proto.fields.choice.stringValue;
const searchedUserKey = vote.payload.doc._document.proto.fields.user.stringValue;
return (searchedPollKey == pollKey && searchedChoiceKey == choiceKey && searchedUserKey == userId);
});
this.deleteVote(filteredVote[0].payload.doc.id);
});
});
}
createVote(value) {
this.db.collection('votes').add({
choice: value.choiceKey,
poll: value.pollKey,
user: value.userKey
}).then(vote => {
console.log("Vote created successfully", vote);
}).catch(err => {
console.log("Error creating vote", err);
});
}
deleteVote(voteKey) {
this.db.collection('votes').doc(voteKey).delete().then((vote) => {
console.log("Vote deleted successfully");
}).catch(err => {
console.log("Error deleting vote", err);
});
}
getVotes(choiceKey) {
return this.db.collection('votes', ref => ref.where('choice', '==', choiceKey)).snapshotChanges().pipe(first());
}
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T13:41:55.510",
"Id": "216865",
"Score": "2",
"Tags": [
"typescript",
"data-visualization",
"angular-2+",
"firebase"
],
"Title": "Angular polling and plotting component using Firebase"
} | 216865 |
<p>What will be the best practice to create an efficient error handler in object class in VBA? Creating some for Outlook (used later in both, Excel and Access) and trying to get the most efficient and well-built handler.
My concern here is that I have multiple Functions returning an object which makes bubble structure harder to implement. </p>
<p>In Class</p>
<pre><code> Public sOutClassErrStr As String
Private Function OutMain() As Object
On Error Resume Next
Set OutMain = GetObject(, "Outlook.Application")
If Err.Number = 429 Then
Set OutMain = CreateObject("Outlook.Application") 'Handled error - no reason to raise.
ElseIf Err.Number <> 0 And Err.Number <> 429 Then
sOutClassErrStr = sOutClassErrStr & Err.Number & ";" & Err.Description & ";" & "cOutlookFunctions.OutMain" & ";" & Date & " " & Time & "|"
End If
End Function
Private Function OutNmspc() As Object
On Error Resume Next
Set OutNmspc = OutMain.GetNamespace("MAPI") 'Outlook.Namespace -- only MAPI is available, at least MS Docs say so
If Err.Number <> 0 Then sOutClassErrStr = sOutClassErrStr & Err.Number & ";" & Err.Description & ";" & "cOutlookFunctions.OutNmspc" & ";" & Date & " " & Time & "|"
End Function
Private Function OutRecip(ByVal sUserResolve As String) As Object
On Error Resume Next
Set OutRecip = OutMain.session.CreateRecipient(sUserResolve)
OutRecip.Resolve
If Err.Number <> 0 Then sOutClassErrStr = sOutClassErrStr & Err.Number & ";" & Err.Description & ";" & "cOutlookFunctions.OutRecip" & ";" & Date & " " & Time & "|"
If Not OutRecip.Resolved Then sOutClassErrStr = sOutClassErrStr & "1" & ";" & "Recipient not resolved." & ";" & "cOutlookFunctions.OutRecip" & ";" & Date & " " & Time & "|" 'custom error - raise by dev
End Function
Private Function GetFolderObject(ptyFolder As enOutFolder, Optional ByVal sUserName As String = "", Optional ByVal sShareMB As String = "") As Object
If sShareMB <> "" Then
On Error Resume Next
Set GetFolderObject = OutMain.GetNamespace("MAPI").Folders(sShareMB).Folders("Inbox")
If Err.Number <> 0 Then
MsgBox "You don't have an access/mapped " & sShareMB & " mailbox.", vbExclamation
Exit Function
End If
End If
If sUserName <> "" Then
'To add err handling when username not exist like 'asdasda.dasdasdd'
Set GetFolderObject = OutNmspc.GetSharedDefaultFolder(OutRecip(sUserName), ptyFolder).Items
Exit Function
End If
Set GetFolderObject = OutNmspc.GetDefaultFolder(ptyFolder).Items
End Function
</code></pre>
<p>First, even though it's widely criticized, thanks for that.<br>
To clarify a couple of things though. In the end, I want to use this class in, as mentioned, only in Excel/Access projects. I did not copy the whole class into the code, but just a sample how I want to refer inside/outside of it.<br>
There are public Sub's like <code>SendEmail, AddAppointemt, ShareCalendar</code> etc. Mentioned functions are the 'guts' of the publics. This string, though not sure whether it should be public, as I'm thinking of it now, is displayed in ErrHandler UDF created separately. And, in the end, I want to display it - of course, delimited to columns - whenever something goes wrong atop.<br>
At the same time want to avoid raising too many errors while the reason is one i.e.</p>
<pre><code>Private Function App As Object
On Error Resume Next
Set App = GetObject(,SomeApp)
If Err.Number <> 0 Then strErr = strErr & Err.Desc & "|"
End Function
Private Function ChildApp As Object
On Error Resume Next
If strErr <> "" Then Exit Fucntion
Set ChildApp = App.Items
If Err.Number <> 0 Then strErr = strErr & Err.Desc & "|"
End Function
Public Sub DisplayNoOfItems
If strErr <> "" Then frmErrHandler(strErr).Show
MsgBox "There are " & ChildAp.Count & " items."
End Sub
</code></pre>
<p>Where in this form code will be terminated after errors are being handled. Don't want to receive info about errors in both of the Priv Functions as, which is obvious, in most cases, if one function throws an error, the second one also won't be working fine.</p>
<p>About naming convention - you're right, I've just shortened Hungarian notation --> I'm referring to sSomeString or cSomeClass. It's easier for me. The same goes for adding 'Out' in the begining of my Outlook priv function. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T17:11:38.793",
"Id": "419483",
"Score": "1",
"body": "At a quick glance: `If Err.Number = 429 Then ... ElseIf Err.Number <> 0 And Err.Number <> 429 Then ...` there's no need to check that `Err.Number <> 429` in the `ElseIf`. You'll never get to the `ElseIf` if it does = 429 - that'll be handled in the `If`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T18:10:51.880",
"Id": "419490",
"Score": "0",
"body": "Welcome to CR! Can you [edit] your post to include example usage of this class? How is your program instantiating it, and how is it using `sOutClassErrStr`? Also, unclear how this relates to \"bubbling\", given `On Error Resume Next` and no `Err.Raise` going on anywhere..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T13:01:36.953",
"Id": "419999",
"Score": "0",
"body": "When I dumped your first block into a Class module and second into a Standard module I get a compile error \"User-defined type not defined\" at `Private Function GetFolderObject(ptyFolder As enOutFolder, Optional ByVal sUserName As String = \"\", Optional ByVal sShareMB As String = \"\") As Object`. Am I missing something?"
}
] | [
{
"body": "<p>I don't think this should be a class: it's a collection of <em>very</em> loosely related functions (they all do something with Outlook... beyond that...), but the only instance-level piece of data is this <code>Public sOutClassErrStr</code> string, which is constantly being appended to.</p>\n\n<p>This is not a good <em>or</em> idiomatic approach to sane error handling, and is mixing concerns - conflating things like logging (presumably that's what that string is for?) and providing user feedback (<code>MsgBox</code>), and not bubbling any errors in the process.</p>\n\n<p>No matter what you do, error state is going to be global, with <code>Err.Description</code> giving you the description for the current error, wherever you are in the project: exception made of <a href=\"https://www.everythingaccess.com/vbwatchdog.asp\" rel=\"nofollow noreferrer\">vbWatchDog</a> (no affiliation, but its author did contribute to <a href=\"http://www.github.com/rubberduck-vba/Rubberduck\" rel=\"nofollow noreferrer\">Rubberduck</a>, an open-source VBIDE add-in project I contribute to), every single attempt ever made at changing how error handling works in VBA (or VB6), has been doomed, cumbersome, bug-prone, confusing, and/or just plain wrong.</p>\n\n<p>The function names are unclear and confusing. What is \"out main\" supposed to be doing? Looks like it's essentially a <em>factory method</em> to get/create an <code>Outlook.Application</code> instance. But, if this code is used in Outlook, then the global-scope <code>Application</code> identifier <em>already</em> holds a reference to that very object we're trying to get. Why the <code>Out</code> prefix though? Because \"Outlook\"? The class is already named <code>cOutlookFunctions</code>, so why have every single one of its members remind us \"this is for Outlook!\" ...if we didn't want Outlook functions, we wouldn't be using an <code>cOutlookFunctions</code> class in the first place!</p>\n\n<p>That said, consider using <code>TypeName(Me)</code> to get the name of the current class, rather than hard-coding it.</p>\n\n<p>Rule of thumb, avoid prefixes. They are useless and clutter up the code, making it harder to read than necessary. <code>c</code>-for-class serves no purpose, <code>s</code>-for-string either. Avoid disemvoweling, too. There is no reason to turn <code>Namespace</code> into <code>Nmspc</code>, other than to make it impossible to pronounce. Worse, if you don't code against the Outlook object model all that often, you might not even remember what it stands for when you get back to that code 6 months from now -- be it you, or your successor.</p>\n\n<p>The effect of returning <code>Nothing</code> instead of bubbling errors up, is that you're taking the real source of the error, burying it in some string (whose value is lost forever once execution ends), and then forcing the caller to immediately check whether it got <code>Nothing</code>, otherwise they might very well be throwing error 91 at a completely unrelated place, well further down the execution path, far away from the source of the problem.</p>\n\n<p>What you're trying to do, is much better handled with a \"try\" pattern.</p>\n\n<pre><code>Public Function TryGetSomething(ByVal thing As String, ByRef outResult As Object) As Boolean\n\n Dim result As Boolean\n On Error GoTo TryFailed\n\n Set outResult = Things(thing)\n result = True\n\nCleanExit:\n TryGetSomething = result\n Exit Function\n\nTryFailed:\n result = False\n Set outResult = Nothing\n Resume CleanExit\nEnd Function\n</code></pre>\n\n<p>Note the <code>out</code> prefix stands for \"output\" and <em>is</em> meaningful in this case - unlike an \"out\" prefix meaning \"outlook\", which is redundant. Structured like this, the client code can intuitively do:</p>\n\n<pre><code>Dim something As Object\nIf TryGetSomething(\"thing\", outResult:=something) Then\n 'try succeeded: [something] holds the object reference we needed.\nElse\n 'try failed: write to log, pop MsgBox, etc.\nEnd If\n</code></pre>\n\n<p>But, I'd probably move all these <code>TryXxxxx</code> functions to a standard module - there's no need to have a class to only hold methods that don't work with any instance state, especially if the class is meant to be a single-instance object.</p>\n\n<p>As for the <code>sOutClassErrStr</code> \"log\" string, I'd remove it entirely, and use an actual <a href=\"https://codereview.stackexchange.com/q/64109/23788\">logger</a> class instead, so that the logs are actually persisted or at least output to the immediate pane as soon as the entries are written - that way the information won't be lost if the host application crashes or execution is accidentally ended.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T20:07:18.243",
"Id": "216885",
"ParentId": "216869",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T14:52:30.037",
"Id": "216869",
"Score": "1",
"Tags": [
"vba",
"error-handling"
],
"Title": "VBA Function Error Bubbling"
} | 216869 |
<p>The code below does what I need it too but it is ugly and clunky. If I could set the list of cells I want to retreive data from as an array that is declared somewhere, then I could loop through that array rather than declaring each individual cell.</p>
<p>As you can see below, I have had to declare each of the cells I want informatino from at the end of the ThisWorkbook lines. Except for the For Count loop where there are 13 cells in a column that I need information from.</p>
<p>Does anyone know how I could do this?</p>
<pre><code>Sub InfoExtract()
Dim xPath As String
Dim xWb As Workbook
Dim xWs As Worksheet
Dim file As String
Dim i As Integer, j As Integer, k As Integer
xPath = "T:\PROJECTS\***\"
Application.ScreenUpdating = False
Application.DisplayAlerts = False
file = Dir(xPath)
i = 1
Do While file <> ""
i = i + 1
j = 3
Cells(i, 2) = file
Workbooks.Open (xPath & file)
Set xWb = ActiveWorkbook
ThisWorkbook.Worksheets(2).Cells(i, j).Value = Cells(7, 4).Value
j = j + 1
ThisWorkbook.Worksheets(2).Cells(i, j).Value = Cells(8, 4).Value
j = j + 1
k = 11
For Count = 1 To 13
ThisWorkbook.Worksheets(2).Cells(i, j).Value = Cells(k, 5).Value
j = j + 1
k = k + 1
Next Count
'Captures the comments
ThisWorkbook.Worksheets(2).Cells(i, j).Value = Cells(24, 4).Value
j = j + 1
ThisWorkbook.Worksheets(2).Cells(i, j).Value = Cells(25, 3).Value
j = j + 1
ThisWorkbook.Worksheets(2).Cells(i, j).Value = Cells(26, 3).Value
j = j + 1
ThisWorkbook.Worksheets(2).Cells(i, j).Value = Cells(27, 3).Value
j = j + 1
ThisWorkbook.Worksheets(2).Cells(i, j).Value = Cells(28, 4).Value
j = j + 1
ThisWorkbook.Worksheets(2).Cells(i, j).Value = Cells(29, 3).Value
j = j + 1
ThisWorkbook.Worksheets(2).Cells(i, j).Value = Cells(30, 3).Value
j = j + 1
ThisWorkbook.Worksheets(2).Cells(i, j).Value = Cells(31, 3).Value
j = j + 1
ThisWorkbook.Worksheets(2).Cells(i, j).Value = Cells(32, 4).Value
j = j + 1
ThisWorkbook.Worksheets(2).Cells(i, j).Value = Cells(33, 3).Value
j = j + 1
ThisWorkbook.Worksheets(2).Cells(i, j).Value = Cells(34, 3).Value
j = j + 1
ThisWorkbook.Worksheets(2).Cells(i, j).Value = Cells(35, 3).Value
j = j + 1
xWb.Close
file = Dir
Loop
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T17:54:47.873",
"Id": "419487",
"Score": "1",
"body": "Welcome to CR! As it stands, your post reads like your code doesn't do exactly what it needs to be doing, which means it's probably too early to get your code peer reviewed - reviewers point out edge case bugs, readability, maintainability, extensibility issues and yes, better ways to do things -- but reviewers don't help with implementing the required functionality. Please [edit] your post to clarify, or come back later with the working code to get feedback on any/all aspects of the code. Cheers!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T18:17:48.770",
"Id": "419493",
"Score": "1",
"body": "Welcome to Code Review! The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T10:36:39.340",
"Id": "419535",
"Score": "0",
"body": "@MathieuGuindon Thanks Mathieu. I was told by those over at Stack Overflow that I should post my question here as they thought it was more like a code review issue. Thanks"
}
] | [
{
"body": "<p>The simple things:</p>\n\n<p>I'm assuming you don't have <code>Option Explicit</code> turned on. That's found in the menu under Tools>Code Settings>Require Variable Declaration. Turn that on it will add <code>Option Explicit</code> to the top of any new code modules, you'll need to retroactively add it to any existing modules. Once you've done that from the menu open Debug>Compile {ProjectName} and you'll be alerted to the fact that your variable <code>Count</code> isn't declared anywhere. A prime example of why it's best to turn it on.</p>\n\n<p>Any sub that doesn't have an access modifier is implicitly <code>Public</code>. Add that to your code <code>Public Sub InfoExtract()</code> to explicitly show you do want it to be public.</p>\n\n<p>Your Do ... Loop is using <code>\"\"</code> which is better replaced with <code>vbNullString</code>. This lets you know that your code is intentionally using a string without any contents instead of <code>\"Foo\"</code> where Foo was removed but the string quotes weren't.</p>\n\n<p>I personally find having variables declared just before their use, rather than at the top, makes my code more readable. You have <code>xWS</code> declared but it's never used in your code... This is an example of why a wall of variable declarations at the top makes it easy to miss an unused variable.</p>\n\n<p>Your variable names can be improved. Intead of <code>xPath</code>, <code>xWB</code> and <code>xWS</code> try <code>externalPath</code>, <code>externalWorkbook</code>, and <code>externalWorksheet</code>. <code>i</code>, <code>j</code>, and <code>k</code> don't tell you what they're used for. <code>i</code> --> <code>populationRow</code>, <code>j</code> --> <code>populationColumn</code> makes your code more descriptive as to what it's doing. Converting <code>ThisWorkbook.Worksheets(2)</code> to a descriptive variable name like <code>destinationSheet</code> will make your code more maintainable.</p>\n\n<p>Usage of <code>Cells(7, 4).Value</code> is implicitly using the <code>Activesheet</code>. This can introduce unintended bugs without realizing it. If you do indeed want to use the Activesheet then qualify with <code>Activesheet.Cells()</code> avoiding any ambiguity. At the point in your code where you open a new workbook you can reference it with a variable <code>externalWorksheet</code> like so <code>Set externalWorksheet = externalWorkbook.ActiveSheet</code>. Now when populating <code>destinationSheet.Cells(populationRow, populationColumn).Value = externalWorksheet.Cells(7, 4).Value</code> you have fully qualified references doing just what they say they're doing.</p>\n\n<hr />\n\n<p>Not so simple things:</p>\n\n<p>Your use of the <code>For ... Next</code> statement is essentially transposing a single column vertical range of cells into a single row. </p>\n\n<pre><code>k = 11\nDim count As Long\nFor count = 1 To 13\n ThisWorkbook.Worksheets(2).Cells(i, j).Value = Cells(k, 5).Value\n j = j + 1\n k = k + 1\nNext count\n\n</code></pre>\n\n<p><a href=\"https://docs.microsoft.com/en-us/office/vba/api/excel.range.pastespecial\" rel=\"nofollow noreferrer\">Range.PasteSpecial</a> takes care of that as shown below.</p>\n\n<pre><code>Dim transposeSourceArea As Range\nSet transposeSourceArea = externalWorksheet.Cells(11, 5).Resize(RowSize:=13)\ntransposeSourceArea.Copy\n\nDim transposeDestinationArea As Range\nSet transposeDestinationArea = destinationSheet.Cells(populationRow, populationColumn + 2).Resize(ColumnSize:=transposeSourceArea.Rows.count)\ntransposeDestinationArea.PasteSpecial XlPasteType.xlPasteValues, Transpose:=True\n</code></pre>\n\n<hr />\n\n<p>Your use of a comment \"Captures the comments\" is an indication that a dedicated sub is hiding right in front of you. Create a sub that describes what it's doing and has descriptive parameters.</p>\n\n<pre><code>Private Sub CaptureComments(ByVal sourceSheet As Worksheet, ByVal populationSheet As Worksheet, ByVal inputRow As Long, ByVal inputColumn As Long)\n</code></pre>\n\n<p>Use that function by providing it arguments when you call it <code>CaptureComments destinationSheet, externalWorksheet, populationRow, populationColumn + 15</code> Within the body of the Sub procedure you can copy all of your code and begin to update it. Your original code is populating a cell then incrementing <code>j</code>. Instead of incrementing it after every cell population change it to be something like below and you'll see that you want it to span across a column.</p>\n\n<pre><code>populationSheet.Cells(i, j).Value = ...\npopulationSheet.Cells(i, j + 1).Value = ...\n...\npopulationSheet.Cells(i, j + 11).Value = ...\n</code></pre>\n\n<p>Since population is in a contiguous range you can use an array to do this. You'll need to pull the source values from their cells to populate the array. The static values of 3 and 4 are replaced with constants for maintainability. You'll need to come up with a descriptive name for them.</p>\n\n<pre><code>Const thirdColumn As Long = 3\nConst fourthColumn As Long = 4\n\nDim comments(0 To 11) As String\ncomments(0) = sourceSheet.Cells(24, fourthColumn).Value\ncomments(1) = sourceSheet.Cells(25, thirdColumn).Value\n...\ncomments(11) = ...\n</code></pre>\n\n<p>The final population is done via <code>populationSheet.Cells(inputRow, inputColumn).Resize(ColumnSize:=UBound(comments) - LBound(comments) + 1).Value = comments</code></p>\n\n<hr />\n\n<p>Putting everything together. I may have missed a number or two but this should give you an idea. There's likely a better way to deal with the varying rows/columns in <code>CaptureComments</code> using a named range or three but without seeing the data I can only guess what they'd be called.</p>\n\n<pre><code>Public Sub InfoExtract()\n Dim externalPath As String\n externalPath = \"T:\\PROJECTS\\***\\\"\n\n Application.ScreenUpdating = False\n Application.DisplayAlerts = False\n\n Dim file As String\n file = Dir(externalPath)\n Dim populationRow As Long\n populationRow = 2\n Do While file <> vbNullString\n Const populationColumn As Long = 3\n ActiveSheet.Cells(populationRow, 2).Value2 = file\n\n Workbooks.Open (externalPath & file)\n Dim externalWorkbook As Workbook\n Set externalWorkbook = ActiveWorkbook\n\n Dim externalWorksheet As Worksheet\n Set externalWorksheet = externalWorkbook.ActiveSheet\n\n Dim destinationSheet As Worksheet\n Set destinationSheet = ThisWorkbook.Worksheets(2)\n\n destinationSheet.Cells(populationRow, populationColumn).Value = externalWorksheet.Cells(7, 4).Value\n destinationSheet.Cells(populationRow, populationColumn + 1).Value = externalWorksheet.Cells(8, 4).Value\n\n Dim transposeSourceArea As Range\n Set transposeSourceArea = externalWorksheet.Cells(11, 5).Resize(RowSize:=13)\n transposeSourceArea.Copy\n\n Dim transposeDestinationArea As Range\n Set transposeDestinationArea = destinationSheet.Cells(populationRow, populationColumn + 2).Resize(ColumnSize:=transposeSourceArea.Rows.count)\n transposeDestinationArea.PasteSpecial XlPasteType.xlPasteValues, Transpose:=True\n\n CaptureComments destinationSheet, externalWorksheet, populationRow, populationColumn + 15\n\n externalWorkbook.Close\n file = Dir\n\n populationRow = populationRow + 1\n Loop\n\n Application.DisplayAlerts = True\n Application.ScreenUpdating = True\nEnd Sub\n\nPrivate Sub CaptureComments(ByVal sourceSheet As Worksheet, _\n ByVal populationSheet As Worksheet, _\n ByVal inputRow As Long, _\n ByVal inputColumn As Long)\n Const thirdColumn As Long = 3\n Const fourthColumn As Long = 4\n\n Dim comments(0 To 11) As String\n comments(0) = sourceSheet.Cells(24, fourthColumn).Value\n comments(1) = sourceSheet.Cells(25, thirdColumn).Value\n comments(2) = sourceSheet.Cells(26, thirdColumn).Value\n comments(3) = sourceSheet.Cells(27, thirdColumn).Value\n\n comments(4) = sourceSheet.Cells(28, fourthColumn).Value\n comments(5) = sourceSheet.Cells(29, thirdColumn).Value\n comments(6) = sourceSheet.Cells(30, thirdColumn).Value\n comments(7) = sourceSheet.Cells(31, thirdColumn).Value\n\n comments(8) = sourceSheet.Cells(32, fourthColumn).Value\n comments(9) = sourceSheet.Cells(33, thirdColumn).Value\n comments(10) = sourceSheet.Cells(34, thirdColumn).Value\n comments(11) = sourceSheet.Cells(35, thirdColumn).Value\n\n populationSheet.Cells(inputRow, inputColumn).Resize(ColumnSize:=UBound(comments) - LBound(comments) + 1).Value = comments\nEnd Sub\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T20:10:09.647",
"Id": "216886",
"ParentId": "216871",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "216886",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T15:16:49.933",
"Id": "216871",
"Score": "-1",
"Tags": [
"vba",
"excel"
],
"Title": "How to return cell values of a non-sequential set of cells from multiple closed spreadsheets? Code condensing/simplification"
} | 216871 |
<p>This is the code that I'm submitting for the "Good vs Evil" Kata on CodeWars:</p>
<p><a href="https://www.codewars.com/kata/good-vs-evil/train/javascript" rel="nofollow noreferrer">https://www.codewars.com/kata/good-vs-evil/train/javascript</a></p>
<pre><code>function goodVsEvil(good, evil) {
good = good.split(' ');
evil = evil.split(' ');
//hobbits, men, elves, etc
let goodWorth = [1, 2, 3, 3, 4, 10];
//orcs, men, wargs, etc
let evilWorth = [1, 2, 2, 2, 3, 5, 10];
let goodArmyPoints = [];
//multiply goodWorth by type:
for (let i = 0; i < goodWorth.length; i++) {
goodArmyPoints.push(good[i] * goodWorth[i]);
}
goodArmyPoints = goodArmyPoints.reduce(function (sum, value) {
return sum + value;
});
let evilArmyPoints = [];
for (let j = 0; j < evilWorth.length; j++) {
evilArmyPoints.push(evil[j] * evilWorth[j]);
}
evilArmyPoints = evilArmyPoints.reduce(function (sum, value) {
return sum + value;
});
if (evilArmyPoints < goodArmyPoints) {
return "Battle Result: Good triumphs over Evil";
} else if (evilArmyPoints > goodArmyPoints) {
return "Battle Result: Evil eradicates all trace of Good";
} else {
return "Battle Result: No victor on this battle field";
}
}
</code></pre>
<p>But I'm not sure what:</p>
<pre><code>goodArmyPoints = goodArmyPoints.reduce(function (sum, value) {
return sum + value;
});
</code></pre>
<p>is doing exactly. </p>
<p>I see that <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce" rel="nofollow noreferrer">reduce</a> "executes a reducer function (which I've provided?) on each member of the array, resulting in a single output value".</p>
<p>But can someone please walk me through what <code>.reduce(function (sum, value)</code> is doing, exactly? Where is this function coming from? What are <code>sum</code> and <code>value</code>? </p>
<p>I'm still learning JavaScript and this is new to me. Thanks.</p>
| [] | [
{
"body": "<p>Look at this example</p>\n\n<pre><code>var numbers = [65, 44, 12, 4];\n\nfunction getSum(total, num) {\n return total + num;\n}\n\nfunction myFunction(item) {\n document.getElementById(\"demo\").innerHTML = numbers.reduce(getSum);\n}\n</code></pre>\n\n<p>Given a function and an array, reduce will keep iterating the next element of the array in the function. Also, the funcion returns a value, which is being passed each time.</p>\n\n<p>So, sum is the output of the function until that moment, value is the array element of that iteration</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T15:52:18.817",
"Id": "216876",
"ParentId": "216875",
"Score": "0"
}
},
{
"body": "<p>I see at least two things about your code that could be improved.</p>\n\n<pre><code> let goodArmyPoints = [];\n //multiply goodWorth by type:\n for (let i = 0; i < goodWorth.length; i++) {\n goodArmyPoints.push(good[i] * goodWorth[i]);\n }\n\n goodArmyPoints = goodArmyPoints.reduce(function (sum, value) {\n return sum + value;\n });\n</code></pre>\n\n<p>Here you allocate a whole <em>array</em> to store the results of multiplications, and then reduce over it. This extra array is wasteful. It would be much clearer and cleaner (and faster) to write simply</p>\n\n<pre><code> let goodArmyPoints = 0;\n for (let i = 0; i < goodWorth.length; ++i) {\n goodArmyPoints += good[i] * goodWorth[i];\n }\n</code></pre>\n\n<hr>\n\n<p>Another confusing thing about your original code is that in the line</p>\n\n<pre><code> goodArmyPoints = goodArmyPoints.reduce(...);\n</code></pre>\n\n<p>you are <em>assigning over</em> <code>goodArmyPoints</code>. And not just assigning over its <em>value</em>, but actually changing its <em>type</em> — from \"array of numbers\" to \"just a single number.\"</p>\n\n<p>Since a variable's name usually reflects what's stored in it, and what's stored in it is usually a function of its <em>type</em>, it follows that variables of different types rarely end up with the same name. For example, if I had two variables, one that stored an array of point-values and one that stored a single point-value, I would probably name them <code>goodScores</code> and <code>goodScore</code>, or <code>goodPartialScores</code> and <code>goodTotal</code>, or something like that. But I definitely would not give them the <em>same exact</em> name!</p>\n\n<p>By giving each variable a unique name, and never changing the type of an existing variable, we increase the understandability of the code. Because now, when the reader asks, \"What is the type of variable <code>goodArmyPoints</code>?\", we can actually give an answer! In your original code, if the reader asks \"What is the type of variable <code>goodArmyPoints</code>?\", all we can do is hedge: \"Well, at this point in the code it's an array, but when we use it two lines later, it's a number...\" That's a more complicated and confusing answer, which is just another way of saying that your original code is more complicated and confusing than the simplified code above.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T16:13:16.727",
"Id": "216878",
"ParentId": "216875",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T15:34:57.517",
"Id": "216875",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Good Vs. Evil - Battle For Middle Earth - CodeWars"
} | 216875 |
<p>Here is a simple heap implementation that allows the heap arity to be chosen at compile time, including the degenerate case where n=1 and the heap is effectively a sorted array with a terrible repair strategy.</p>
<p>The heap implementation class, broadly speaking, has two repair strategies: making swaps in the direction of the leaves and making swaps in the direction of the root.</p>
<p>The prototypical use case for a <code>leafward_heapify</code> is when we construct a new heap from a vector. In that case, we start iterating over indices backwards (which starts at the leaves) and swap big items down (aka a <code>leafward_heapify</code>).</p>
<p><code>heapify_rootward</code> is used when we insert a new item of unknown size at the bottom right corner of the heap.</p>
<p>This heap is not thread-safe and is not meant to be thread-safe.</p>
<p>The <code>heap</code>-class is meant to be the public-facing API.</p>
<p>The <code>detail::heap_impl</code> heap does all the work, but its API isn't bounds-checked when <code>NDEBUG</code> is defined, it doesn't have any <code>const</code> methods, and its methods and members are all public.</p>
<p>The <code>heap</code> class does have <code>const</code> and non-<code>const</code> versions of each <code>const</code> method.</p>
<p><em>My main concern is that I've done a lot of things that are weird or non-idiomatic and I'd like to know how rewrite this code to be less weird.</em></p>
<p>Also, I've tried to make sure that I'm only taking copies of small, trivially copyable things, except where it's unavoidable (such as the constructor taking a std::vector) and have tried to implement things on top of <code>swap</code> as much as possible, but I'm not sure that's a good idea.</p>
<pre><code>#ifndef DARY_HEAP_HPP
#define DARY_HEAP_HPP 1
#include <algorithm>
#include <exception>
#include <utility>
#include <vector>
namespace dary_heap {
using std::vector;
namespace detail {
template <class T, int ARITY> class heap_impl {
public:
static_assert(ARITY > 0, "ARITY must be at least 1");
vector<T> storage;
using ssize_type = std::ptrdiff_t;
using iterator = decltype(storage.begin());
using const_iterator = decltype(storage.cbegin());
heap_impl() noexcept = default;
heap_impl(heap_impl &&) noexcept = default;
heap_impl(std::vector<T> vs) {
swap(vs, storage);
for (auto i = -1 + ssize(); i >= 0; i--) {
heapify_leafwards(i);
}
}
constexpr ssize_type ssize() const noexcept {
return static_cast<ssize_type>(storage.size());
}
constexpr ssize_type last() const noexcept { return ssize() - 1; }
constexpr ssize_type first() const noexcept { return 0; }
T get(ssize_type i) noexcept {
assert(i < ssize());
assert(i >= 0);
return storage[i];
}
std::pair<bool, ssize_type> get_parent(ssize_type i) {
if (i == 0) {
return {false, 0};
}
auto idx = i;
idx -= 1;
idx /= ARITY;
assert(idx < i);
return {true, idx};
}
std::pair<bool, ssize_type> get_first_child(ssize_type i) {
auto idx = i;
idx *= ARITY;
idx += 1;
if (idx >= ssize()) {
return {false, 0};
}
return {true, idx};
}
std::pair<bool, ssize_type> get_last_child(ssize_type i) {
auto p = get_first_child(i);
if (!p.first) {
return {false, 0};
}
auto idx = p.second + ARITY - 1;
return {true, std::min<decltype(idx)>(idx, last())};
}
void swap_indices(ssize_type i, ssize_type j) {
assert(i >= 0);
assert(i < ssize());
assert(j >= 0);
assert(j <= ssize());
iter_swap(storage.begin() + i, storage.begin() + j);
return;
}
std::pair<bool, ssize_type> get_smallest_child(ssize_type i) {
auto p1 = get_first_child(i);
if (!p1.first) {
return {false, 0};
}
auto start = p1.second;
auto stop = get_last_child(i).second;
assert(start <= stop);
ssize_type argmin = start;
for (auto jj = start + 1; jj <= stop; jj++) {
if (storage[jj] < storage[argmin]) {
argmin = jj;
}
}
assert(argmin > i);
assert(argmin < ssize());
return {true, argmin};
}
void push_back(T u) noexcept(false) {
storage.push_back(u);
heapify_rootwards(last());
return;
}
T at(ssize_type i) noexcept(false) {
if (i < 0) {
throw std::runtime_error("index cannot be negative");
}
if (i >= ssize()) {
throw std::runtime_error("index out of bounds");
}
return storage[i];
}
// when we are given an initially not-in-heap-order
// std::vector, we need to potentially make swaps
// to enforce the heap invariant.
// under the assumption that our child subheaps are all min-heaps
// we swap with the smallest child and then check the location
// that we just swapped into.
std::pair<bool, ssize_type> heapify_leafwards_step(ssize_type i) {
auto p = get_smallest_child(i);
if (!p.first) {
return {false, 0};
}
auto smallest = p.second;
if (storage[smallest] < storage[i]) {
swap_indices(smallest, i);
return {true, smallest};
} else {
return {false, 0};
}
}
void heapify_leafwards(ssize_type i) {
auto cur = i;
while (true) {
auto p = heapify_leafwards_step(cur);
if (!p.first) {
return;
} else {
assert(p.second > cur);
cur = p.second;
}
}
}
// when we have a heap that is completely in heap order except
// for a single item (because it was inserted, for instance).
// we repair the heap by
std::pair<bool, ssize_type> heapify_rootwards_step(ssize_type i) {
auto p = get_parent(i);
if (!p.first) {
return {false, 0};
}
auto root_i = p.second;
assert(i > 0);
assert(root_i < i);
if (storage[i] < storage[root_i]) {
swap_indices(i, root_i);
return {true, root_i};
}
return {false, 0};
}
void heapify_rootwards(ssize_type i) {
ssize_type cur = i;
while (true) {
auto p = heapify_rootwards_step(cur);
if (!p.first) {
return;
} else {
assert(p.second < cur);
cur = p.second;
}
}
}
// always succeeds!
void remove_last() noexcept {
auto usize = storage.size();
if (usize != 0) {
storage.resize(usize - 1);
}
}
void remove(ssize_type i) noexcept {
assert(i >= 0);
assert(i < ssize());
swap_indices(i, last());
remove_last();
// if the item is the biggest in the heap
// we need to push it into the leaves.
// in pathological cases where the last item
// happens to be relatively small, we also heapify
// towards the root.
heapify_leafwards(i);
heapify_rootwards(i);
}
iterator begin() noexcept { return storage.begin(); }
iterator end() noexcept { return storage.end(); }
const_iterator cbegin() noexcept { return storage.cbegin(); }
const_iterator cend() noexcept { return storage.cend(); }
};
} // namespace detail
template <class T, int ARITY> class heap {
private:
mutable detail::heap_impl<T, ARITY> impl;
public:
using ssize_type = typename decltype(impl)::ssize_type;
using iterator = typename decltype(impl)::iterator;
;
using const_iterator = typename decltype(impl)::const_iterator;
heap() noexcept = default;
heap(heap &&) noexcept = default;
heap(std::vector<T> v) : impl(v) {}
void push_back(T u) noexcept(false) { impl.push_back(u); }
T at(ssize_type i) noexcept(false) { return impl.at(i); }
T at(ssize_type i) const noexcept(false) { return impl.at(i); }
constexpr ssize_type ssize() const noexcept { return impl.ssize(); }
void remove(ssize_type i) noexcept(false) {
if (i < 0) {
throw std::runtime_error("index cannot be negative");
}
if (i >= ssize()) {
throw std::runtime_error("index too large");
}
impl.remove(i);
}
iterator begin() { return impl.begin(); }
iterator end() { return impl.end(); }
const_iterator cbegin() { return impl.cbegin(); }
const_iterator cbegin() const { return impl.cbegin(); }
const_iterator cend() { return impl.cend(); }
const_iterator cend() const { return impl.cend(); }
};
} // namespace dary_heap
#endif // DARY_HEAP_HPP
</code></pre>
<p>And here's the test code, just called <code>dary_heap.cpp</code>.</p>
<pre><code>#define BOOST_TEST_MAIN 1
#define BOOST_TEST_DYN_LINK 1
#define BOOST_TEST_MODULE dary_heap
#include <boost/test/unit_test.hpp>
#include "dary_heap.hpp"
#include <cstdio>
BOOST_AUTO_TEST_SUITE(heap)
BOOST_AUTO_TEST_CASE(empty_heap) {
using namespace dary_heap;
heap<float, 4> h;
const heap<float, 4> &c_h = h;
BOOST_CHECK(h.ssize() == 0);
BOOST_CHECK(h.begin() == h.end());
BOOST_CHECK(h.cbegin() == h.cend());
BOOST_CHECK(c_h.cbegin() == c_h.cend());
BOOST_CHECK_THROW(h.at(0), std::runtime_error);
}
BOOST_AUTO_TEST_CASE(singleton_heap) {
using namespace dary_heap;
heap<float, 4> h;
const heap<float, 4> &c_h = h;
h.push_back(7.0f);
BOOST_CHECK(h.ssize() == 1);
BOOST_CHECK(1 + h.begin() == h.end());
BOOST_CHECK(1 + h.cbegin() == h.cend());
BOOST_CHECK(1 + c_h.cbegin() == c_h.cend());
BOOST_CHECK(h.at(0) == 7.0f);
BOOST_CHECK_THROW(h.at(1), std::runtime_error);
}
BOOST_AUTO_TEST_CASE(singleton_heap_from_vector) {
using namespace dary_heap;
std::vector<float> v{7.0f};
heap<float, 4> h(v);
const heap<float, 4> &c_h = h;
BOOST_CHECK(h.ssize() == 1);
BOOST_CHECK(1 + h.begin() == h.end());
BOOST_CHECK(1 + h.cbegin() == h.cend());
BOOST_CHECK(1 + c_h.cbegin() == c_h.cend());
BOOST_CHECK(h.at(0) == 7.0f);
BOOST_CHECK_THROW(h.at(1), std::runtime_error);
}
BOOST_AUTO_TEST_CASE(two_element_heap) {
using namespace dary_heap;
heap<float, 4> h;
// push elements in the "wrong" order
h.push_back(7.0f);
h.push_back(1.0f);
BOOST_CHECK(h.at(0) == 1.0f);
BOOST_CHECK(h.at(1) == 7.0f);
BOOST_CHECK(h.ssize() == 2);
}
BOOST_AUTO_TEST_CASE(binary_heap_remove_min) {
using namespace dary_heap;
heap<float, 2> h;
h.push_back(4.0f);
h.push_back(7.0f);
h.push_back(8.0f);
BOOST_CHECK(h.at(0) == 4.0f);
BOOST_CHECK(h.at(1) == 7.0f);
BOOST_CHECK(h.at(2) == 8.0f);
BOOST_CHECK_NO_THROW(h.remove(0));
BOOST_CHECK(h.at(0) == 7.0f);
BOOST_CHECK(h.at(1) == 8.0f);
BOOST_CHECK_THROW(h.at(2), std::runtime_error);
}
BOOST_AUTO_TEST_CASE(unary_heap_remove_middle) {
using namespace dary_heap;
std::vector<int> v{0, 1, 2, 3, 4, 5, 6, 7};
heap<int, 1> h(v);
BOOST_CHECK(h.at(0) == 0);
BOOST_CHECK(h.at(1) == 1);
BOOST_CHECK(h.at(2) == 2);
BOOST_CHECK(h.at(3) == 3);
BOOST_CHECK(h.at(4) == 4);
BOOST_CHECK(h.at(5) == 5);
BOOST_CHECK(h.at(6) == 6);
BOOST_CHECK(h.at(7) == 7);
h.remove(3);
BOOST_CHECK(h.at(0) == 0);
BOOST_CHECK(h.at(1) == 1);
BOOST_CHECK(h.at(2) == 2);
BOOST_CHECK(h.at(3) == 4);
BOOST_CHECK(h.at(4) == 5);
BOOST_CHECK(h.at(5) == 6);
BOOST_CHECK(h.at(6) == 7);
BOOST_CHECK_THROW(h.at(7), std::runtime_error);
}
BOOST_AUTO_TEST_SUITE_END()
</code></pre>
<p>Since there are only two files, a shell script suffices for the build:</p>
<pre><code>#!/bin/sh
PROGNAME=program.exe
LIBS=
LIBS+="-lboost_unit_test_framework"
${CXX:-clang++} -o "${PROGNAME:-x}" *.cpp -I. -std=c++11 "$@" ${LIBS}
</code></pre>
| [] | [
{
"body": "<p>First, thumbs-up for providing a test suit, although I couldn't make it work (copy-and-paste on <a href=\"http://wandbox.org\" rel=\"nofollow noreferrer\">wandbox</a>, it might be the reason why).</p>\n\n<p>Now on to the not so good:</p>\n\n<ul>\n<li>Your code is quite long; the longer it is, the harder it is to read. That's why you must always try to be as concise as possible. In this case I strongly believe that you could have cut out a lot. It isn't even hard to do: let me give you a very trivial example:</li>\n</ul>\n\n<p>Ex:</p>\n\n<pre><code>// original code\nauto idx = i;\nidx *= ARITY;\nidx += 1;\nif (idx >= ssize()) {\n return {false, 0};\n}\nreturn {true, idx};\n\n// concise version:\nauto index = i * ARITY + 1;\nreturn index < ssize() ? { true, index } : { false, 0 };\n\n// or with C++17, localized variable\nif (auto index = i * ARITY + 1; index < ssize())\n return { true, index };\nelse return { false, 0 };\n</code></pre>\n\n<ul>\n<li>Your code is cluttered with variables that have short, more or less obscure or arbitrary names (<code>i</code>, <code>j</code>, <code>jj</code>, <code>vs</code>, etc.). Variable names introduce meaning, it's a great way to document your code and make it easier to read and understand:</li>\n</ul>\n\n<p>Ex (continued):</p>\n\n<pre><code>// now we know what it is the index of\nif (auto child_index = parent_index * ARITY + 1; child_index < ssize())\n return { true, child_index };\nelse return { false, 0 };\n</code></pre>\n\n<ul>\n<li><p>Another reason why your code is too long for what it does is that it is overly defensive. I assume you thought that <code>assert</code>s are free because they can be toggled off. But they're not because it can obscure your error-handling strategy: why are there <code>assert</code>s in some places, <code>if</code> clauses in others, or even exceptions? I can't give you a hard rule about this, but generally it's good to check the error as locally as possible, and handle it as centrally as possible. It's not good to do it everywhere.</p></li>\n<li><p>Your \"signed size\" gymnastic is dangerous. I understand where it comes from, but look where it goes to:</p></li>\n</ul>\n\n<p><em>How dangerous is:</em></p>\n\n<pre><code>constexpr ssize_type ssize() const noexcept {\n return static_cast<ssize_type>(storage.size());\n}\n</code></pre>\n\n<p>Well, tell me what happens if <code>storage.size()</code> is greater than <code>std::numeric_limits<ssize_type>::max()</code>? Well, you've got a negative size (I don't consider the theoretically possible case where the overflow could lead to a positive but false size -> good luck finding the bug). And your code full of asserts doesn't even check this!!</p>\n\n<ul>\n<li><p>returning a <code>std::pair<bool, index></code> is a bit cumbersome. Depending on the version of C++ you can use, you can return a <code>std::optional</code> or simply an iterator (when an iterator points past the last element, it indicates failure). NB: if you have access to C++17, structured bindings make for a more elegant syntax when assigning a pair: <code>auto [success, child_index] = get_smallest_child(parent_index);</code></p></li>\n<li><p>the distinction between the implementation and the \"front\" class is weird. What did you want to achieve with this? If it's about re-compilation and the \"pimpl idiom\", then you need to use a pointer to <code>heap_impl</code> inside <code>heap</code>. A pointer allows you to refer to an incomplete type, and define the type somewhere else.</p></li>\n<li><p>do you really want to provide random access to the elements of your heap? There might be scenarios where you need this (or are there? heaps aren't completely sorted, the children of a given parent can be in any order, so why would you get the 3rd, and not the 2nd or the 4th?), but you generally use heaps as a kind of priority queue. You only need to provide access to the \"top\" element. It will simplify your code and get you closer to the principle: make an interface that is easy to use and hard to misuse (out of bond access is harder this way).</p></li>\n<li><p>your <code>noexcept</code> policy is incoherent and a bit tedious also. You tag almost everything but not <code>begin()</code> or <code>end()</code>, for some reason. <code>noexcept(false)</code> isn't really necessary, in the sense that no one (neither compiler nor client) will expect to be protected from exceptions unless there's a <code>noexcept</code> tag at the end of the signature.</p></li>\n<li><p>I think you should have offered to customize the comparison operator. It's really useful when the element doesn't provide a comparison operator, of if you want to compare the elements in a different order, or a projection of the elements.</p></li>\n<li><p>there are probably other little things that can be improved, but I feel like they'll become more obvious when you work further on the initial code. With that in mind, here's a quick, more modern, iterator based implementation of a heap to give you a comparison point and some hints:</p></li>\n</ul>\n\n<p>Ex:</p>\n\n<pre><code>#include <vector>\n#include <functional>\n#include <optional>\n#include <iostream>\n\ntemplate <typename T, typename Pred = std::less<T>, std::size_t ARITY = 2>\nclass heap {\n\n using Iterator = std::vector<T>::iterator;\n\n public: std::vector<T> storage; private: // for testing purpose\n Iterator root = storage.begin();\n Iterator last_element = root;\n\n Pred predicate;\n\n Iterator get_parent(Iterator child) {\n const auto parent_index = (std::distance(root, child) - 1) / ARITY;\n return std::next(root, parent_index);\n }\n\n std::pair<Iterator, Iterator> get_children(Iterator parent) {\n const auto children_index = std::distance(root, parent) * ARITY + 1;\n if (children_index >= storage.size()) return { last_element, last_element };\n const auto children_number = std::min(storage.size() - children_index, ARITY);\n return { std::next(root, children_index), std::next(root, children_index + children_number) };\n }\n\n void restore_up(Iterator child);\n void restore_down(Iterator parent);\n\n public:\n\n heap() = default;\n\n template <typename Iter>\n heap(Iter first, Iter last);\n\n std::optional<T> pop() { // simplification. You need to provide both T top() and void pop() to be exception safe\n if (storage.empty()) return {};\n auto result = std::exchange(*root, *last_element--);\n storage.pop_back();\n restore_down(root);\n return result;\n }\n\n};\n\ntemplate <typename T, typename Pred, std::size_t ARITY>\nvoid heap<T, Pred, ARITY>::restore_up(Iterator child) {\n while (child != root) {\n auto parent = get_parent(child);\n if (!predicate(*child, *parent)) return;\n std::iter_swap(child, parent);\n child = parent;\n }\n}\n\ntemplate <typename T, typename Pred, std::size_t ARITY>\nvoid heap<T, Pred, ARITY>::restore_down(Iterator parent) {\n while (true) {\n auto [first, last] = get_children(parent);\n if (first == last) return;\n auto top_child = std::min_element(first, last, predicate);\n if (!predicate(*top_child, *parent)) return;\n std::iter_swap(top_child, parent);\n parent = top_child;\n }\n}\n\ntemplate <typename T, typename Pred, std::size_t ARITY>\ntemplate <typename Iter>\nheap<T, Pred, ARITY>::heap(Iter first, Iter last) \n : storage(first, last) {\n if (first == last) return;\n last_element = std::prev(storage.end());\n auto last_parent = get_parent(last_element);\n do {\n restore_down(last_parent);\n } while (last_parent-- != root);\n}\n\nint main() {\n std::vector<int> data {3,5,7,9,4,1,6,8};\n heap<int, std::greater<int>> test(data.begin(), data.end());\n for (auto i : test.storage) std::cout << i << ' ';\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T12:31:03.057",
"Id": "217132",
"ParentId": "216888",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217132",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T20:44:54.237",
"Id": "216888",
"Score": "5",
"Tags": [
"c++",
"heap"
],
"Title": "C++11 min-heap with configurable arity"
} | 216888 |
<p>I've created a Python script that tries to properly indent and dedent ASP code. Similar to <a href="http://www.aspindent.com/" rel="nofollow noreferrer">http://www.aspindent.com/</a> </p>
<p>Since I've began using it I've noticed some edge cases that I hadn't anticipated. The reason these edge-cases appear is because of the fact that I'm not parsing straight ASP code. There are instances of HTML and Javascript in the file, thus, some of this is causing indentations to occur sporadically throughout the final output. I realize that part of the problem stems from my regex use. I'm here to see if there is a cleaner way to go about this.</p>
<pre><code>import re, sys
class Indenter:
def __init__(self, string):
self.space = 0
self.count = 0
self.string = string
def print_ln(self, string):
sys.stdout.write(" " * self.space + str(string))
sys.stdout.flush()
def indent(self):
self.print_ln(self.string[self.count])
self.space += 4
def dedent(self):
self.space -= 4
self.print_ln(self.string[self.count])
def dedent_indent(self):
self.space -= 4
self.print_ln(self.string[self.count])
self.space += 4
def main(self):
while self.count < len(self.string):
if re.search("^\s*if.*then", str(self.string[self.count]), re.IGNORECASE):
self.indent()
elif re.search("^\s*for", str(self.string[self.count]), re.IGNORECASE):
self.indent()
elif re.search("^\s*with", str(self.string[self.count]), re.IGNORECASE):
self.indent()
elif re.search("^\s*do until", str(self.string[self.count]), re.IGNORECASE):
self.indent()
elif re.search("^\s*do$", str(self.string[self.count]), re.IGNORECASE):
self.indent()
elif re.search("^\s*Select Case", str(self.string[self.count]), re.IGNORECASE):
self.indent()
elif re.search("^\s*End Select", str(self.string[self.count]), re.IGNORECASE):
self.dedent()
elif re.search("^\s*loop", str(self.string[self.count]), re.IGNORECASE):
self.dedent()
elif re.search("^\s*end with", str(self.string[self.count]), re.IGNORECASE):
self.dedent()
elif re.search("^\s*end if", str(self.string[self.count]), re.IGNORECASE):
self.dedent()
elif re.search("^\s*next", str(self.string[self.count]), re.IGNORECASE):
self.dedent()
elif re.search("^\s*Case", str(self.string[self.count]), re.IGNORECASE):
self.dedent_indent()
elif re.search("^\s*else", str(self.string[self.count]), re.IGNORECASE):
self.dedent_indent()
elif re.search("^\s*elseif.*then", str(self.string[self.count]), re.IGNORECASE):
self.dedent_indent()
else:
self.print_ln(self.string[self.count])
self.count += 1
with open("scratch.html") as s:
ind = Indenter(s.readlines())
ind.main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T05:29:44.080",
"Id": "419515",
"Score": "2",
"body": "Could you give an example of that kind of edge case and the desired output?"
}
] | [
{
"body": "<p>You should always write the main program protected within a <code>if __name__ == '__main__':</code> block, so that you can import the file in another program without automatically executing code. Eg)</p>\n\n<pre><code>if __name__ == '__main__':\n ind = Indenter(s.readlines())\n ind.main()\n</code></pre>\n\n<hr>\n\n<p>Don't write classes where you create the class object just to call one instance method of the object. See the video <a href=\"https://www.youtube.com/watch?v=o9pEzgHorH0\" rel=\"nofollow noreferrer\">Stop Writing Classes</a>.</p>\n\n<hr>\n\n<p>Your code has:</p>\n\n<pre><code>ind = Indenter(s.readlines())\n</code></pre>\n\n<p>which reads every single line of the file into memory, and stores it in a list. Then, you call the <code>Indenter.main()</code> function which executes ...</p>\n\n<pre><code>while self.count < len(self.string):\n # ... many lines of code omitted ...\n self.count += 1\n</code></pre>\n\n<p>... sequentially loops through every element of the list (line of the file) for processing one at a time. Each member function, including this <code>main()</code> function, uses <code>self.string[self.count]</code> to reference the current line. This must have been maddening to write, having to type (or copy/paste) the same code over and over. It is frightening to read.</p>\n\n<p>Let's clean this up.</p>\n\n<p><code>print_ln(self, string)</code> is structured correctly. It takes the current line <code>string</code> as input. Let's duplicate that in <code>indent()</code>, <code>dedent()</code>, and <code>dedent_indent()</code>, by adding the <code>string</code> argument to them, like:</p>\n\n<pre><code>def indent(self, string):\n self.print_ln(string)\n self.space += 4\n</code></pre>\n\n<p>In the <code>main()</code> function, we now need to pass the line to each function, just like it was passed to <code>self.print_ln(self.string[self.count])</code>. But that is a lot of duplicate <code>self.string[self.count]</code> access, so let's make a temporary variable for it. We can use that temporary variable in the <code>re.search(....)</code> calls too.</p>\n\n<pre><code>while self.count < len(self.string):\n string = self.string[self.count]\n if re.search(\"^\\s*if.*then\", string, re.IGNORECASE):\n self.indent(string)\n elif # ... many lines of code omitted ...\n else:\n self.print_ln(string)\n self.count += 1\n</code></pre>\n\n<p>Note that each <code>string</code> is a string, so the <code>str(...)</code> calls can just be omitted.</p>\n\n<p>Now that <code>self.count</code> is only used in <code>main()</code>, we can make it a local variable, instead of an instance member.</p>\n\n<pre><code>count = 0\nwhile count < len(self.string):\n string = self.string[count]\n # ... many lines of code omitted ...\n count += 1\n</code></pre>\n\n<p>A <code>while</code> loop which counts from 0 up to some limit an be replaced by a <code>for ... in range(...)</code> loop:</p>\n\n<pre><code>for count in range(len(self.string)):\n string = self.string[count]\n # ... many lines of code omitted ...\n</code></pre>\n\n<p>And since <code>count</code> is only ever used to index into the <code>list</code> that we are looping over the indices of, we can omit the indices altogether, and just loop over the list of strings itself.</p>\n\n<pre><code>for string in self.string:\n # ... many lines of code omitted ...\n</code></pre>\n\n<p>Now that we are looping directly over <code>self.string</code>, we don't need to explicitly know that it is a list of strings. It can be any iterable object that returns, one-at-a-time, all the string we are interested in. Like a file object. And that file object can be passed to the <code>main()</code> function.</p>\n\n<pre><code>class Indenter:\n # ... omitted ...\n\n def main(self, lines):\n\n for line in lines:\n if re.search(\"^\\s*if.*then\", line), re.IGNORECASE):\n self.indent(line)\n elif # ... many lines of code omitted ...\n else:\n self.print_ln(line)\n\nif __name__ == '__main__':\n with open('scratch.html') as file:\n ind = Indenter()\n ind.main(file)\n</code></pre>\n\n<p>Now we are no longer reading the entire file into memory. Rather, we are opening the file, and reading it line-by-line, processing each line as it is read in, and then discarding it.</p>\n\n<hr>\n\n<p>What does your code do if it encounters a file which is already indented? It indents it some more!</p>\n\n<p>That is probably undesired behaviour. You probably want to strip off any existing indentation before adding the new indentation.</p>\n\n<pre><code> for line in lines:\n line = line.strip()\n # ... if/elif/else statements omitted ...\n</code></pre>\n\n<p>Note that this removes the newline from the end of the lines as well, so you'll want to add that back in, perhaps by changing the <code>sys.stdout.write(...)</code> \\ <code>sys.stdout.flush()</code> into a simple <code>print(...)</code> statement.</p>\n\n<hr>\n\n<p>With each line stripped of any previous indentation, you can remove the <code>\\s*</code> from the start of all of the reg-ex patterns.</p>\n\n<hr>\n\n<p>There are 6 reg-ex patterns where you want to indent, 5 where you want to dedent, and 3 where you want to do both. You always print. You dedent before printing. You indent after printing.</p>\n\n<p>Instead of writing many lines of code which do the same thing with different patterns, it is much, much easier to write a loop, which loops through the patterns. Let's put the patterns into lists:</p>\n\n<pre><code>indent_patterns = ['^if.*then', '^for', '^with', '^do until', '^do$', '^select case',\n '^case', '^else', '^elseif.*then']\ndedent_patterns = ['^end select', '^loop', '^end with', '^end if', '^next',\n '^case', '^else', '^elseif.*then']\n</code></pre>\n\n<p>Now we can say if the current line matches any of the <code>dedent_patterns</code>, reduce <code>space</code>. Then print the line. Then, if the current line matches any of the <code>indent_patterns</code>, increase <code>space</code>.</p>\n\n<pre><code>if any(re.search(pattern, line, re.IGNORECASE) for pattern in dedent_patterns):\n self.space -= 4\n\nself.print_ln(line)\n\nif any(re.search(pattern, line, re.IGNORECASE) for pattern in indent_patterns):\n self.space += 4\n</code></pre>\n\n<p>... and the <code>indent</code>, <code>dedent</code> and <code>dedent_indent</code> functions just became unnecessary.</p>\n\n<p>Since <code>print_ln()</code> is called in one spot, we can write than inline as well, which eliminates the need for <code>self.space</code> to be a member variable.</p>\n\n<hr>\n\n<p>With no member variables left, the entire class can be replaced with one function.</p>\n\n<pre><code>import re\n\ndef indent(lines, spacing=4):\n\n indent_patterns = ['^if.*then', '^for', '^with', '^do until', '^do$', '^select case',\n '^case', '^else', '^elseif.*then']\n dedent_patterns = ['^end select', '^loop', '^end with', '^end if', '^next',\n '^case', '^else', '^elseif.*then']\n\n space = 0\n\n for line in lines:\n line = line.strip()\n\n if any(re.search(pattern, line, re.IGNORECASE) for pattern in dedent_patterns):\n space -= spacing\n\n print(\" \"*space + line)\n\n if any(re.search(pattern, line, re.IGNORECASE) for pattern in indent_patterns):\n space += spacing\n\nif __name__ == '__main__':\n\n with open('scratch.html') as file:\n indent(file)\n</code></pre>\n\n<p>And like what was said above, stop writing classes.</p>\n\n<hr>\n\n<p>This does not address the sporadic indentation caused by HTML and Javascript in the file, but</p>\n\n<ul>\n<li>this is a Code Review, which only addresses the code you have actually written. This is not a forum where you come to get help writing new code, but to get a review of code you have already written.</li>\n<li>with a cleaner implementation of the indent code, you should have an easier time addressing that issue. When you have finished, feel free to post a follow-up question.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T06:32:57.253",
"Id": "419948",
"Score": "3",
"body": "Excellent analysis! Since the regex patterns are now stored in a single place, it might be worth to throw a [`re.compile`](https://docs.python.org/3/howto/regex.html#compiling-regular-expressions) at them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T14:00:14.587",
"Id": "420010",
"Score": "2",
"body": "@Alex I thought about adding that, but a) it was already 12:30am and I wanted to get to bed; b) Python automatically compiles and caches most recently used regex patterns, so it probably wouldn’t impact the performance much. See [this question](https://stackoverflow.com/questions/7520622/python-re-modules-cache-clearing) for more/related info."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T15:07:53.877",
"Id": "420023",
"Score": "1",
"body": "Well, there is always something to learn :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T16:32:12.337",
"Id": "420039",
"Score": "0",
"body": "Wow! Thank you very much, this is a very succinct explanation!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T16:33:54.773",
"Id": "420040",
"Score": "0",
"body": "In regards to the sporadic indentation, I was able to remedy this by using an if statement to check for `<%` and `%>` asp tags, and only applying the indentation between those tags."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T16:47:40.020",
"Id": "420045",
"Score": "0",
"body": "Happy to have helped."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T05:35:42.843",
"Id": "217113",
"ParentId": "216891",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "217113",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T22:22:37.717",
"Id": "216891",
"Score": "5",
"Tags": [
"python",
"regex",
"formatting"
],
"Title": "Indenting and dedenting ASP Classic code with Python"
} | 216891 |
<p>I've recently picked up a book that gives various "modern" C++ challenges/solutions. One of the first ones I did was on modeling an IPv4 address in C++. Below is the full implementation; it's also on <a href="https://github.com/DeveloperPaul123/modern-cpp-challenge" rel="noreferrer">Github</a>. Any suggestions? My goal is to make this as modern as possible and I'm not sure if there are some C++17 features I'm not taking advantage of. </p>
<p><code>ip_address.h</code></p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include <array>
#include <string>
#include <string_view>
#include <stdint.h>
namespace ip
{
/**
* @brief Thrown when there is an invalid ip address passed via
* string.
*/
class invalid_format_exception : public std::exception
{
std::string invalid_format_;
public:
invalid_format_exception(const std::string &invalid_format);
char const* what() const override;
};
/**
* Class that models a IPv4 address.
*/
class address
{
public:
#pragma region Type definitions
using value_type = uint8_t;
using reference = value_type & ;
using pointer = value_type * ;
using iterator = std::array<value_type, 4>::iterator;
using const_iterator = std::array<value_type, 4>::const_iterator;
using reverse_iterator = std::array<value_type, 4>::reverse_iterator;
using const_reverse_iterator = std::array<value_type, 4>::const_reverse_iterator;
using size_type = std::array<value_type, 4>::size_type;
#pragma endregion
/**
* @brief Create an IP address representation from the
* four parts of the address definition.
* @param first the first part of the address
* @param second the second part of the address
* @param third the third part of the address.
* @param fourth the fourth part of the address.
* @details Example:
* @code
* ip::address addr(127, 0, 0, 1);
* @endcode
*/
address(const value_type& first, const value_type &second,
const value_type &third, const value_type& fourth);
/**
* @brief Create an IP address representaiton from an
* array.
* @param data the data array.
* @details Example:
* @code
* ip::address addr = {127, 0, 0, 1};
* @endcode
*/
address(const std::array<unsigned char, 4> &data);
/**
* @brief Create an IP adderss representation from a
* unsigned 32 bit integer.
* @param value the integer representation of an IP address.
*/
explicit address(const uint32_t &value);
/**
* @brief Implicit conversion to an unsigned 32 bit integer.
*/
uint32_t operator()() const;
/**
* @brief Access operator.
* @param index the index to access.
*/
reference operator[](const int &index) noexcept(false);
/**
* @brief Const version of the access operator.
*/
value_type operator[](const int &index) const noexcept(false);
/**
* @brief Prefix increment operator.
*/
void operator++();
/**
* @brief Postfix increment operator.
*/
::ip::address& operator++(int);
/**
* @brief Prefix decrement operator.
*/
void operator--();
/**
* @brief Prefix decrement operator.
*/
::ip::address& operator--(int);
iterator begin();
iterator end();
const_iterator begin() const;
const_iterator end() const;
private:
std::array<value_type, 4> data_;
};
bool operator<(const ip::address &first, const ip::address &second);
bool operator==(const ip::address &first, const ip::address &second);
std::ostream& operator<<(std::ostream& output, const ip::address &address);
address from_string(const std::string &view);
std::string to_string(const address& address);
}
</code></pre>
<p><code>ip_address.cpp</code></p>
<pre class="lang-cpp prettyprint-override"><code>#include <ip_address.h>
#include <iterator>
#include <iostream>
#include <sstream>
#include <regex>
#include <vector>
#include <string>
#pragma region Utilities
template<typename Output>
void split(const std::string &s, char delim, Output result) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
*(result++) = item;
}
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, std::back_inserter(elems));
return elems;
}
#pragma endregion
ip::invalid_format_exception::invalid_format_exception(const std::string& invalid_format)
: invalid_format_(invalid_format)
{
}
char const* ip::invalid_format_exception::what() const
{
std::ostringstream oss;
oss << "Invalid IP address format: " << invalid_format_;
return oss.str().c_str();
}
ip::address::address(const value_type & first, const value_type & second, const value_type & third, const value_type & fourth)
{
data_[0] = first;
data_[1] = second;
data_[2] = third;
data_[3] = fourth;
}
ip::address::address(const std::array<unsigned char, 4>& data)
{
data_ = data;
}
ip::address::address(const uint32_t& value)
{
data_[0] = value >> 24 & 0xFF;
data_[1] = value >> 16 & 0xFF;
data_[2] = value >> 8 & 0xFF;
data_[3] = value & 0xFF;
}
uint32_t ip::address::operator()() const
{
const uint32_t value = data_[0] << 24 | data_[1] << 16 | data_[2] << 8 | data_[3];
return value;
}
ip::address::reference ip::address::operator[](const int& index)
{
return data_.at(index);
}
ip::address::value_type ip::address::operator[](const int& index) const
{
return data_.at(index);
}
void ip::address::operator++()
{
auto location = std::find_if(data_.rbegin(), data_.rend(), [](const unsigned char& data)
{
return data < 255;
});
if(location != std::rend(data_))
{
const auto r_index = std::distance(data_.rbegin(), location);
auto index = 4 - r_index - 1;
data_[index]++;
}
}
::ip::address& ip::address::operator++(int)
{
auto result(*this);
++(*this);
return result;
}
void ip::address::operator--()
{
auto location = std::find_if(data_.rbegin(), data_.rend(), [](const unsigned char& data)
{
return data < 255;
});
if (location != std::rend(data_))
{
const auto r_index = std::distance(data_.rbegin(), location);
auto index = 4 - r_index - 1;
data_[index]--;
}
}
::ip::address& ip::address::operator--(int)
{
auto result(*this);
--(*this);
return result;
}
ip::address::iterator ip::address::begin()
{
return data_.begin();
}
ip::address::const_iterator ip::address::end() const
{
return data_.end();
}
bool ip::operator<(const ip::address& first, const ip::address& second)
{
return (uint32_t)first() < (uint32_t)second();
}
bool ip::operator==(const ip::address& first, const ip::address& second)
{
return (uint32_t)first() == (uint32_t) second();
}
ip::address::const_iterator ip::address::begin() const
{
return data_.begin();
}
ip::address::iterator ip::address::end()
{
return data_.end();
}
std::ostream& ip::operator<<(std::ostream& output, const ip::address& address)
{
std::copy(address.begin(), address.end()-1,
std::ostream_iterator<short>(output, "."));
output << +address[3];
return output;
}
ip::address ip::from_string(const std::string &view)
{
auto parts = split(view, '.');
if (parts.size() != 4)
{
throw invalid_format_exception(view);
}
return {
(ip::address::value_type)std::stoi(parts[0]),
(ip::address::value_type)std::stoi(parts[1]),
(ip::address::value_type)std::stoi(parts[2]),
(ip::address::value_type)std::stoi(parts[3])
};
}
std::string ip::to_string(const address& address)
{
std::ostringstream string_stream;
string_stream << address;
return string_stream.str();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T11:41:00.237",
"Id": "419542",
"Score": "1",
"body": "networking-ts has an excellent reference implementation: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/n4771.pdf#page179"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T16:04:32.263",
"Id": "419689",
"Score": "1",
"body": "Mod Note: Please do not use comments for extended conversations. Comments are intended to resolve unclarities about the post. Use [chat] for extended conversations and in-depth discussions. If you want to critique the code presented in the question, please do so in an answer. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T23:50:31.887",
"Id": "419712",
"Score": "0",
"body": "Remember that an ipv4 is not only four numbers separated by 3 dots.\n1 = 0.0.0.1, 1.2=1.0.0.2, 1.2.3 = 1.2.0.3, 192.168.0.1 = 3232235521 = 0xC0A80001"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T15:18:08.243",
"Id": "419747",
"Score": "0",
"body": "@Lenne Yes, but one of the requirements was also that the address be human readable when printed to a stream."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T13:30:13.217",
"Id": "420004",
"Score": "1",
"body": "@DeveloperPaul, All formats are human-readable ;-). Anyway, your should be able to read all the formats, regardless of what format you want to use for output."
}
] | [
{
"body": "<p>You're passing fundamental types by const reference. These are better off just being passed by value. So you'd get things like</p>\n\n<pre><code>explicit address(uint32_t value);\nreference operator[](int index) noexcept(false);\n</code></pre>\n\n<p>Your prefix increment and decrement operators should return a reference to the incremented value.</p>\n\n<pre><code>address &operator++() { /* ... */ return *this; }\naddress &operator--() { /* ... */ return *this; }\n</code></pre>\n\n<p>This will allow expressions like <code>addr = ++other_addr;</code>. (Note that, since you're in the <code>address</code> class, you can just name the class, you don't need to specify scope with <code>::ip::address</code>).</p>\n\n<p>Your postfix increment and decrement operators have a bug, because they return a reference to a local variable. The return types should be a value.</p>\n\n<pre><code>address operator++(int);\naddress operator--(int);\n</code></pre>\n\n<p>For readability and clarity, expressions mixing shifts and bit masking should use parentheses:</p>\n\n<pre><code>data_[0] = (value >> 24) & 0xFF;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T01:07:46.160",
"Id": "216895",
"ParentId": "216894",
"Score": "9"
}
},
{
"body": "<p>You storing the value in <code>std::array<value_type, 4></code> which is fine. But if you change your mind on the storage type you have to change this in like 10 places. To make this easier it is a good idea to abstract the storage type and then use this storage type in all places.</p>\n\n<pre><code> using Storage = std::array<value_type, 4>;\n using iterator = Storage::iterator;\n using const_iterator = Storage::const_iterator;\n using reverse_iterator = Storage::reverse_iterator;\n using const_reverse_iterator = Storage::const_reverse_iterator;\n using size_type = Storage::size_type;\n</code></pre>\n\n<p>Now if you change the underlying storage type you only have to change it in one place.</p>\n\n<hr>\n\n<p>What does it mean to increment/decrement an ip address?</p>\n\n<pre><code> /**\n * @brief Prefix increment operator.\n */\n void operator++();\n</code></pre>\n\n<p>What scenario does this make sense?</p>\n\n<hr>\n\n<p>If there is a test for equality:</p>\n\n<pre><code>bool operator==(const ip::address &first, const ip::address &second);\n</code></pre>\n\n<p>Then I would expect a test for inequality.</p>\n\n<hr>\n\n<p>If there is an output operator:</p>\n\n<pre><code>std::ostream& operator<<(std::ostream& output, const ip::address &address);\n</code></pre>\n\n<p>Then I would expect an input operator.</p>\n\n<hr>\n\n<p>The standard exceptions (except <code>std::exception</code> itself) already implement <code>what()</code>. You should inherit from one of these rather than <code>std::exception</code> (probably <code>std::runtime_error</code>.</p>\n\n<pre><code>class invalid_format_exception : public std::exception\n{\n std::string invalid_format_;\npublic:\n invalid_format_exception(const std::string &invalid_format);\n char const* what() const override;\n};\n</code></pre>\n\n<p>This becomes:</p>\n\n<pre><code>struct invalid_format_exception: std::runtime_error\n{\n using std::runtime_error::runtime_error; // Pull runtime_error constructor into this class.\n};\n</code></pre>\n\n<hr>\n\n<p>Are you sure that the IP address is always stored in big endian form?</p>\n\n<pre><code>data_[0] = value >> 24 & 0xFF;\ndata_[1] = value >> 16 & 0xFF;\ndata_[2] = value >> 8 & 0xFF;\ndata_[3] = value & 0xFF;\n</code></pre>\n\n<p>I would double check and also add a big comment that that is what you expect.</p>\n\n<hr>\n\n<p>The increment operator looks complicated.<br>\nI think it can really be simplified by using some existing functions you have identified.</p>\n\n<pre><code>void ip::address::operator++()\n{\n uint32_t value = (*this); // convert to 32 bit number\n ++value; // Add 1\n (*this) = address(value); // convert back to address and copy/move\n}\n</code></pre>\n\n<hr>\n\n<p>Functions that simply forward calls just put them in the class and forget about them. There is nothing to maintain and it need not take up multiple lines in the source file:</p>\n\n<pre><code>ip::address::iterator ip::address::begin()\n{\n return data_.begin();\n}\n\nip::address::const_iterator ip::address::end() const\n{\n return data_.end();\n}\n\n// I would just do the following the header:\n\n\n iterator begin() {return data_.begin();}\n iterator end() {return data_.end();}\n const_iterator begin() const {return data_.begin();}\n const_iterator end() const {return data_.end();}\n</code></pre>\n\n<p>You are of course missing a few:</p>\n\n<pre><code> const_iterator cbegin() const {return data_.cbegin();}\n reverse_iterator rbegin() {return data_.rbegin();}\n\n // You can add the end() versions.\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T12:06:10.233",
"Id": "419547",
"Score": "0",
"body": "\"What does it mean to increment/decrement an ip address?\" It means exactly what it sounds like, no? The main purpose was to be able to enumerate a number of addresses in a given range. I didn't mention this in the OP, but it was another part of the challenge. Good point about the storage type, that will definitely be useful. As far as putting the defs of `begin()`, `end()` and the like in the header I disagree with that sentiment. I do not like mixing and matching where functions are defined. They will either be all in the header, or all in the source file; not both."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T16:42:26.470",
"Id": "419584",
"Score": "1",
"body": "@DeveloperPaul: It should not matter were the definitions are. All good development tools will automatically jump to definition when asked. I use `vi` and it still jumps to the function definition when I ask without me knowing where the file is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T16:43:47.517",
"Id": "419586",
"Score": "1",
"body": "`It means exactly what it sounds like, no?` Sure but why. This is not a property of an address. Consecutive addresses have no relationship. So this should not be in the address class. You could put it in a helper class that allows you to scan addresses but it should not be part of the address class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T18:06:14.480",
"Id": "419596",
"Score": "0",
"body": "I see your point now. Seems like I've included quite a bit in the address class that doesn't need to be there."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T01:36:46.993",
"Id": "216896",
"ParentId": "216894",
"Score": "13"
}
},
{
"body": "<p>I think it's very strange that you provide iterators and an <code>operator[]</code> for an <strong><em>IP address.</em></strong> Generally speaking, IP addresses are not considered to be \"iterable\"; an IP address is just a <em>single</em> address. If you were modeling a subnet mask, like <code>127.0.0.0/8</code>, then it might make sense to model it as a <em>range</em> of addresses; but if you're modeling just a single address, I don't think it is appropriate at all to model it as a <em>range</em> of <em>octets</em>. What benefit do you gain from that? IMHO: none. <a href=\"https://www.youtube.com/watch?v=46kXH6GGtT0\" rel=\"noreferrer\">None benefit.</a></p>\n\n<hr>\n\n<p>As 1201ProgramAlarm already said, your increment and decrement operators' signatures are a bit screwed up (essentially, backwards). Plus:</p>\n\n<pre><code>::ip::address& ip::address::operator++(int)\n{\n auto result(*this);\n ++(*this);\n return result;\n}\n</code></pre>\n\n<p>This one should also have given you a compiler warning (assuming you use any mainstream compiler, such as GCC, Clang, or MSVC). Step number one when writing C++ is always to <strong>compile with <code>-W -Wall -Wextra</code></strong> and <strong>fix all the warnings</strong> prior to publishing your code. The compiler warnings are usually telling you about bugs in your code; and even when they're not technically bugs, you should still fix the warnings, so that none of your coworkers have to read the warnings ever again. Clean code is friendly code!</p>\n\n<hr>\n\n<pre><code>ip::address::iterator ip::address::begin()\n{\n return data_.begin();\n}\n\nip::address::const_iterator ip::address::end() const\n{\n return data_.end();\n}\n</code></pre>\n\n<p>It is super weird to me that you define these member functions in the order \"nonconst <code>begin</code>, const <code>end</code>, const <code>begin</code>, nonconst <code>end</code>.\" That's harmless, but it's just <em>weird</em>. Also, I recommend defining these functions directly in-line in the body of the class. They're one-liners. You waste space (and thus, waste the reader's time) by defining them out-of-line. That is, I'd write:</p>\n\n<pre><code> iterator begin() { return data_.begin(); }\n iterator end() { return data_.end(); }\n const_iterator begin() const { return data_.begin(); }\n const_iterator end() const { return data_.end(); }\nprivate:\n std::array<value_type, 4> data_;\n</code></pre>\n\n<p>Also, all four of these methods should probably be declared <code>noexcept</code>.</p>\n\n<hr>\n\n<p>Overloaded comparison operators should <em>always</em> be defined in-line in the body of the class, using the \"hidden friend\" (a.k.a. \"ADL friend,\" a.k.a. \"Barton-Nackman\") trick. That is, instead of</p>\n\n<pre><code>class address { ... };\n\nbool operator<(const ip::address &first, const ip::address &second);\n\nbool ip::operator<(const ip::address& first, const ip::address& second)\n{\n return (uint32_t)first() < (uint32_t)second();\n}\n</code></pre>\n\n<p>you should write simply</p>\n\n<pre><code>class address {\n // ...\n\n friend bool operator<(const address& a, const address& b) {\n return uint32_t(a()) < uint32_t(b());\n }\n};\n</code></pre>\n\n<p>Notice that I switched your type-casts from C style to constructor-style, a.k.a. \"Python style,\" just for the heck of it. I find the fewer parentheses the easier it is to read. Also, I switched the verbose <code>first</code> and <code>second</code> to simply <code>a</code> and <code>b</code>: we don't need long names for these extremely locally scoped variables.</p>\n\n<p>But wait, there's more! I initially assumed that <code>first()</code> was a typo — but it's not! You actually declared an overloaded <code>operator()</code>:</p>\n\n<pre><code> /**\n * @brief Implicit conversion to an unsigned 32 bit integer.\n */\n uint32_t operator()() const;\n</code></pre>\n\n<p>Why on earth is this an <em>overloaded function-call operator</em> instead of a <em>conversion operator</em>? Worse, why is this any kind of operator at all, when you already went out of your way to declare a free function <code>ip::to_string(const address&)</code>? <strong>Why is the conversion to <code>uint32_t</code> not implemented as <code>ip::to_uint32(const address&)</code>?</strong></p>\n\n<p>Consistency is important. Also, compatibility with the rest of the language is important. When you overload <code>operator()</code>, you're making <code>ip::address</code> \"callable,\" which means you're enabling your clients to write things like</p>\n\n<pre><code>ip::address myAddress(127, 0, 0, 1);\nstd::function<int()> f = myAddress; // !!\nassert(f() == 0x7F000001);\n</code></pre>\n\n<p>Just as with the iterator/range-of-octets business, this functionality strikes me as <em>fundamentally not what an IP address ought to be about.</em> IP addresses aren't ranges, and IP addresses aren't callables. They should be <em>just addresses.</em> To the extent that your <code>ip::address</code> is anything other than <em>just an address</em>, you have actually <em>failed</em> in your stated goal of \"modeling an IP address\"!</p>\n\n<hr>\n\n<p>Your <code>operator<<</code> should also be defined in-line.</p>\n\n<p>Anytime you provide <code>operator==</code>, you should also provide <code>operator!=</code> — the language doesn't (yet) provide it for you automatically.</p>\n\n<p>Anytime you provide <code>operator<</code>, you should also provide <code>operator<=</code>, <code>></code>, and <code>>=</code> — the language doesn't (yet) provide these for you automatically. (But in C++2a you'll have <code>operator<=></code> to play with!)</p>\n\n<hr>\n\n<pre><code>void ip::address::operator++()\n{\n auto location = std::find_if(data_.rbegin(), data_.rend(), [](const unsigned char& data)\n {\n return data < 255;\n });\n\n if(location != std::rend(data_))\n {\n const auto r_index = std::distance(data_.rbegin(), location);\n auto index = 4 - r_index - 1;\n data_[index]++;\n }\n}\n</code></pre>\n\n<p>It's odd that you write <code>data_.rend()</code> in one place and <code>std::rend(data_)</code> in the other. I recommend the former in both cases, simply because it's shorter.</p>\n\n<p>However, doesn't this code \"increment\" <code>address(0, 0, 0, 255)</code> to <code>address(0, 0, 1, 255)</code> instead of to <code>address(0, 0, 1, 0)</code>? If so, oops! IMO the clearest and simplest way to write this \"odometer algorithm\" is simply</p>\n\n<pre><code>address& operator++() noexcept\n{\n if (++data_[3] == 0) {\n if (++data_[2] == 0) {\n if (++data_[1] == 0) {\n ++data_[0];\n }\n }\n }\n return *this;\n}\n</code></pre>\n\n<p>Short and sweet. Arguably it's overly complicated and \"clever\" — but look what it's replacing! What it's replacing uses multiple STL algorithms, is three lines <em>longer</em>, and (AFAICT) <em>doesn't even work</em>. So feel free to reduce the \"cleverness\" of my proposed code even further, if you can; regardless, I claim it's an improvement over the original.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T12:01:39.650",
"Id": "419546",
"Score": "2",
"body": "Good point about compiling with warning and fixing said warnings. Also the order of definition for the \"begin()\" and \"end()\" methods wasn't on purpose. They are supposed to be in the same order as the declaration. Why should \"overloaded comparison operators always be defined in-line in the body of the class\"? This seems like conjecture to me and I don't see the real value in bloating the class with something that can easily be left outside the class. I do agree with creating a `ip::to_uint32t()` function so good point there and I overall agree with your comments about consistency."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T12:12:35.977",
"Id": "419549",
"Score": "0",
"body": "\"_I find the fewer parentheses the easier it is to read_\" — haven't you just increased nesting level of parentheses, leaving total count of them unchanged?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T00:05:16.670",
"Id": "419639",
"Score": "2",
"body": "Something else to consider: An `address` is a small trivial type. Thus, passing by constant reference instead of value is a pessimisation."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T01:43:53.983",
"Id": "216897",
"ParentId": "216894",
"Score": "34"
}
}
] | {
"AcceptedAnswerId": "216897",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T23:47:31.050",
"Id": "216894",
"Score": "15",
"Tags": [
"c++",
"c++11",
"ip-address"
],
"Title": "Modeling an IPv4 Address"
} | 216894 |
<p>Here is a class that stores a single value into the limited cache. If cache is full, it will remove the oldest element to make a space for a new value.
I'm using 2 structures to accomplish this because I need a fast lookup. I'm not very confident this is the best approach.
Cache will contain a small amount of data (lets say 1000 elements).</p>
<pre><code>#include <unordered_set>
#include <queue>
template <class T>
class Cache{
private:
int _maxSize;
std::unordered_set<T> _set;
std::queue<T> _queue;
public:
explicit Cache(int maxSize) : _maxSize(maxSize){}
bool add(T value){
if(_set.find(value) == _set.end()){ // // if not exists in set
if(_set.size() == _maxSize){ // if set is 'full'
_set.erase(_queue.front()); // delete the oldest value from the set
_queue.pop(); // delete oldest value from queue
}
_queue.push(value); // push new value into queue
_set.insert(value); // insert new value into set
return true;
}
return false;
}
int size(){
return static_cast<int>(_set.size());
}
};
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p>Naming of data members: I would avoid duplicating the information that carries with the type. Can you think of something more meaningful?</p></li>\n<li><p>Unsigned vs. signed integer for handling the size: as the maximum size is passed to the contructor as an <code>int</code>, <code>static_cast<int>(_set.size())</code> should be safe. However, when it's foreseeable that you'll implement the class template using containers from the standard library (they all use <code>std::size_t</code> for their sizes), why not go with <code>std::size_t</code> for <code>Cache</code>, too?</p></li>\n<li><p>Related to the above: always compile with warnings enabled. <code>clang++ -Wall -pedantic -Wsign-conversion -Wextra -std=c++11</code> gives me</p>\n\n<blockquote>\n <p>warning: comparison of integers of different signs [...]</p>\n\n<pre><code>if(_set.size() == _maxSize){ // if set is 'full'\n</code></pre>\n</blockquote>\n\n<p>Again, as <code>_maxSize</code> is an <code>int</code>, this can be considered a non-issue in practice, but it's still somewhat brittle, if you change some implementation details later on.</p></li>\n<li><p>You can only instantiate the <code>Cache</code> template when <code>T</code> mets the standard hash container requirements (i.e., a <code>std::hash</code> specialization is available as well as a comparison operator). To make your class template more reusable, consider adding template parameters that can be passed to <code>std::unordered_set</code>. If they have sensible defaults, you don't need to specify them most of the time.</p>\n\n<pre><code>template <class T, class Hash = std::hash<T>, class EqualTo = std::equal_to<T>>\nclass Cache {\n std::unordered_set<T, Hash, EqualTo> _set;\n // ...\n};\n</code></pre></li>\n<li><p>When caching an object, you save it twice, one in <code>_queue</code> and once in <code>_set</code>. For small objects, the duplication might be acceptable, but what if <code>T</code> is large? Remember that <code>std::unordered_map</code> doesn't invalidate iterators/pointers upon insertion and removal of entries. Consider a <code>std::queue</code> of iterators into <code>_set</code>.</p></li>\n<li><p>Passing <code>T</code> by value in <code>bool add(T value)</code> can be a reasonable choice as long as you <code>std::move</code> it when it's used the last time and <code>T</code> supports move semantics. In your case:</p>\n\n<pre><code>bool add(T value) {\n // ...\n _queue.push(value); // Don't move here\n _set.insert(std::move(value)); // ... but here!\n}\n</code></pre>\n\n<p>You could also consider an overload set <code>bool add(const T&)</code> and <code>bool add(T&&)</code> instead as <code>std::vector::push_back</code> does for example.</p></li>\n<li><p>When you worry about performance and you have varying max. cache sizes known at compile time, consider adding a non-type <code>std::size_t</code> template parameter to <code>Cache</code>. This way, you could specialize on smaller caches to e.g. use <code>std::vector</code> instead of <code>std::unordered_map</code>, which can be faster due fewer cache (ha!) misses. You need to do some benchmarking first though, and take different <code>sizeof(T)</code> into account.</p></li>\n<li><p>A last note on performance: <code>std::unordered_set</code> was designed as a drop-in replacement for <code>std::set</code>. That's why it doesn't invalidate iterators/pointers into an instance, but that's also why it's not the fastest hash set. Of course, make sure to benchmark this properly, but you might want to have a look at some open address hash set, e.g. the one provided by abseil could be an option.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T07:45:39.360",
"Id": "216910",
"ParentId": "216898",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T02:01:01.723",
"Id": "216898",
"Score": "2",
"Tags": [
"c++",
"performance",
"c++11",
"cache"
],
"Title": "Cache with limited size; If full remove the oldest"
} | 216898 |
AutoIt v3 is a freeware BASIC-like scripting language designed for automating the Windows GUI and general scripting. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T02:33:42.813",
"Id": "216900",
"Score": "0",
"Tags": null,
"Title": null
} | 216900 |
<p>Im trying to teach myself some computer science (and c++). I am relatively new to this (and to code review).</p>
<p>I have attempted to implement a queue. I have copied the code below for reference.</p>
<hr>
<p><strong>QUESTIONS:</strong></p>
<ol>
<li><p>I have used assertions in many instances: I assert that the size must be non-zero when accessing the front or the back and when popping (or, dequeueing in my case); I assert that an index must be between 0 and one less than the size when implementing the function </p>
<pre><code> T const & at(size_t index)
</code></pre>
<p>and I assert that "this != other" in the copy constructor. <strong>Are these appropriate uses of assertion? Should I throw exceptions instead? Or should I do things differently? What is the standard practice with respect to error checking? Should I simply allow for undefined behavior?</strong></p></li>
<li><p><strong>Would you implement the copy constructor and the destructor differently?</strong></p>
<pre><code> Queue(Queue const & other) : m_front(nullptr),
m_back(nullptr),
m_size(0),
{
assert(this != &other);
this->enqueue(other);
}
~Queue()
{
this->clear();
}
</code></pre></li>
<li><p>I noticed that cppreference mentioned something about an "Allocator." <strong>Would it be difficult to incorporate into my code? Is it only for array-based implementations? I have implemented queues via arrays. If it is not difficult to incorporate, how would I go about doing so?</strong></p></li>
<li><p>Is there any way to pass a generic "Container" object into the constructor to to initialize the queue? So, for example, the user has the option of passing in an array, or a vector, to have the values in that container copied into the queue.</p></li>
</ol>
<p>The following questions are welcome. However, I realize they are non specific, and if I should remove them, please let me know. I will do so, and restrict the code I posted to reflect <em>only</em> my questions prior.</p>
<ol start="5">
<li><p>Should I have implemented anything differently?</p></li>
<li><p>Any stylistic advice?</p></li>
</ol>
<p><strong>MY CODE (FOR REFERENCE):</strong></p>
<p><strong>Queue.h:</strong></p>
<pre><code> #ifndef QUEUE_H
#define QUEUE_H
#include <algorithm>
#include <climits>
template <class T>
class Queue
{
private:
struct QueueItem
{
T val;
QueueItem *next;
QueueItem() : next(nullptr) {}
QueueItem(T const & val, QueueItem *next) : val(val), next(next) {}
QueueItem(T const & val) : val(val), next(nullptr) {}
QueueItem(QueueItem *next) : next(next) {}
};
QueueItem *m_front;
QueueItem *m_back;
size_t m_size;
public:
//friends
friend void swap(Queue & a, Queue & b)
{
using std::swap;
swap(a.m_front, b.m_front);
swap(a.m_back, b.m_back);
swap(a.m_size, b.m_size);
}
friend void concatenate(Queue & a, Queue & b)
{
a.m_back->next = b.m_front;
a.m_back = b.m_back;
}
//constructors and deconstructor
Queue() : m_front(nullptr), m_back(nullptr), m_size(0) {}
Queue(Queue const & other) : m_front(nullptr), m_back(nullptr), m_size(0)
{
assert(this != &other);
this->enqueue(other);
}
~Queue()
{
this->clear();
}
//capacity
size_t const size() const;
bool const empty() const;
//element access
T & front();
T const & front() const;
T & back();
T const & back() const;
bool const has(T const & val) const;
T const * const data() const;
//modifiers
T const dequeue();
void enqueue(T const & val);
void enqueue(T && val);
void enqueue(Queue const & other);
T const deenqueue(T const & val);
T const deenqueue(T && val);
void reverse();
void clear();
Queue & operator + (Queue const & other);
Queue & operator += (Queue const & other);
Queue & operator = (Queue const other);
//comparators
bool const operator == (Queue const & other);
bool const operator != (Queue const & other);
};
#include "Queue.hpp"
#endif // QUEUE_H
</code></pre>
<p><strong>List.hpp</strong></p>
<pre><code> #ifndef QUEUE_HPP
#define QUEUE_HPP
//capacity
template <class T>
size_t const Queue<T>::size() const
{
return m_size;
}
template <class T>
bool const Queue<T>::empty() const
{
return m_size == 0;
}
//element access
template <class T>
T & Queue<T>::front()
{
assert(m_size > 0);
return m_front->val;
}
template <class T>
T const & Queue<T>::front() const
{
assert(m_size > 0);
return m_front->val;
}
template <class T>
T & Queue<T>::back()
{
assert(m_size > 0);
return m_back->val;
}
template <class T>
T const & Queue<T>::back() const
{
assert(m_size > 0);
return m_back->val;
}
template <class T>
bool const Queue<T>::has(T const & val) const
{
QueueItem *item = m_front;
while(item)
{
if(item->val == val)
return true;
item = item->next;
}
return false;
}
template <class T>
T const * const Queue<T>::data() const
{
if(m_size == 0)
return nullptr;
T const * const data = new T[m_size];
QueueItem *item = m_front;
for(size_t i = 0; item; item = item->next)
data[i++] = item->val;
return data;
}
//modifiers
template <class T>
T const Queue<T>::dequeue()
{
assert(m_size > 0);
T const give = m_front->val;
QueueItem *item = m_front->next;
delete m_front;
m_front = item;
--m_size;
if(m_size == 0)
m_back = nullptr;
return give;
}
template <class T>
void Queue<T>::enqueue(T const & val)
{
QueueItem *item = new QueueItem(val);
if(m_size == 0)
m_front = m_back = item;
else
{
m_back->next = item;
m_back = item;
}
++m_size;
}
template <class T>
void Queue<T>::enqueue(T && val)
{
QueueItem *item = new QueueItem(val);
if(m_size == 0)
m_front = m_back = item;
else
{
m_back->next = item;
m_back = item;
}
++m_size;
}
template <class T>
void Queue<T>::enqueue(Queue<T> const & other)
{
QueueItem *item = other.m_front;
while(item)
{
this->enqueue(item->val);
item = item->next;
}
}
template <class T>
T const Queue<T>::deenqueue(T const & val)
{
T const give = dequeue();
QueueItem *item = new QueueItem(val);
if(m_size == 0)
m_front = m_back = item;
else
{
m_back->next = item;
m_back = item;
}
++m_size;
return give;
}
template <class T>
T const Queue<T>::deenqueue(T && val)
{
T const give = dequeue();
QueueItem *item = new QueueItem(val);
if(m_size == 0)
m_front = m_back = item;
else
{
m_back->next = item;
m_back = item;
}
++m_size;
return give;
}
template <class T>
void Queue<T>::reverse()
{
using std::swap;
QueueItem *first = nullptr,
*second = m_front,
*save;
while(second)
{
save = second->next;
second->next = first;
first = second;
second = save;
}
swap(m_front, m_back);
}
template <class T>
void Queue<T>::clear()
{
while(m_front)
{
QueueItem *item = m_front->next;
delete m_front;
m_front = item;
}
m_back = nullptr;
m_size = 0;
}
template <class T>
Queue<T> & Queue<T>::operator + (Queue<T> const & other)
{
this->enqueue(other);
return *this;
}
template <class T>
Queue<T> & Queue<T>::operator += (Queue<T> const & other)
{
this->enqueue(other);
return *this;
}
template <class T>
Queue<T> & Queue<T>::operator = (Queue<T> const other)
{
swap(*this, other);
return *this;
}
//comparators
template <class T>
bool const Queue<T>::operator == (Queue<T> const & other)
{
if(m_size != other.m_size)
return false;
QueueItem *thsitem = m_front,
*othitem = other.m_front;
while(thsitem)
{
if(thsitem->val != othitem->val)
return false;
thsitem = thsitem->next;
othitem = othitem->next;
}
return true;
}
template <class T>
bool const Queue<T>::operator != (Queue<T> const & other)
{
return !(*this == other);
}
#endif // QUEUE_HPP
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T07:39:41.520",
"Id": "419728",
"Score": "1",
"body": "Welcome to Code Review. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. If you believe that your changes was made without invalidating the current answer, please let me know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T15:59:55.943",
"Id": "419754",
"Score": "0",
"body": "Hey, Simon. I did make a change to my code, by it doesn't reflect answers to my questions. Let me know if you need me to do anything on my end! And thanks for informing me. Moving on, I will keep that rule in mind."
}
] | [
{
"body": "<p>At first sight, your code looks consistent and readable. Congrats!</p>\n\n<p>That said, I'll jump into your questions. The assertions are used correctly. Often you'll see them written as <code>assert(I > 0 && \"Valid index needed\");</code> That allows adding a comment to it. Especially useful if the code itself ain't 100% understandable from the callers point of view.</p>\n\n<p>You're preconditions are also a very good example of the contracts extensions of C++20 and make them part of your API instead. For now, I would document them at class level.</p>\n\n<p>Jumping into the assert of the copy constructor, that one is useless as you can't ever trigger it. It does make sense in copy assignment, although, it's better to handle that case and return early.</p>\n\n<p>The implementation of queue looks good to me, it leverages existing methods instead of writing it from scratch. Perfect coding on my side.</p>\n\n<p>You do want to consider initializing the members in the class definition, as it is less error prone.</p>\n\n<p>Adding the allocator is adding an extra template argument and member and replacing all new/delete. </p>\n\n<p>I like the east const, however, adding const to the return value if by value doesn't make much sense. I would remove it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T07:47:43.147",
"Id": "216970",
"ParentId": "216902",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216970",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T04:31:13.647",
"Id": "216902",
"Score": "6",
"Tags": [
"c++",
"object-oriented",
"c++11",
"queue"
],
"Title": "Implementing a queue: questions and clarification"
} | 216902 |
<p>Im trying to make a SFML code that takes my code i already have to make a star with a convex shape and put it into a circle of stars surrounding the point the user chooses. The User is also able to choose the amount of stars in the circle.</p>
<p>Here is my code for making a star</p>
<pre><code>#include <iostream>
#include <SFML/Graphics.hpp>
#include <stdlib.h>
#include <time.h>
#include <math.h>
using namespace std;
using namespace sf;
int main()
{
double x;
double y;
double width;
double p = 3.14*4;
double r = width;
cout<<"Enter x"<<endl;
cin>>x;
cout<<"Enter y"<<endl;
cin>>y;
cout<<"Enter a width"<<endl;
cin >>width;
RenderWindow window(VideoMode(800,800),"My Window");
window.setFramerateLimit(60);
ConvexShape convex;
convex.setPointCount(5);
convex.setPoint(0,Vector2f(width*cos(p/5)+x,width*sin(p/5)+y));
convex.setPoint(1,Vector2f(width*cos(p/5*2)+x, width*sin(p/5*2)+y));
convex.setPoint(2,Vector2f(width*cos(p/5*3)+x, width*sin(p/5*3)+y));
convex.setPoint(3,Vector2f(width*cos(p/5*4)+x, width*sin(p/5*4)+y));
convex.setPoint(4,Vector2f(width*cos(p/5*5)+x, width*sin(p/5*5)+y));
convex.setFillColor(Color(0,0,255));
while (window.isOpen())
{
Event event;
while (window.pollEvent(event))
{
if (event.type == Event::Closed)
window.close();
}
window.clear();
window.draw(convex);
window.display();
}
return 0 ;
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T05:10:36.750",
"Id": "216904",
"Score": "1",
"Tags": [
"c++",
"sfml"
],
"Title": "SFML Circle of Stars"
} | 216904 |
<p>Imagine simple game:</p>
<pre><code>type Combatant = {
hp : int
attack : int
}
type CombatantGroup = Combatant list
type CombatantGroups = CombatantGroup list
type Battle = {
combatantGroups : CombatantGroups
}
</code></pre>
<p>there is some battle, in which some amount groups participate. In each group there is several combatants. Now I want to implement a function for one combatant to attack another. Due to immutability, I have to replace whole attacked target, and whole group and whole battle. If the battle was just between two participants, I could write code like this:</p>
<pre><code>if target = battle.combatant1 then
{ battle with combatant1 = { battle.combatant1 with hp = battle.combatant1.hp - attacker.attack }}
else
{ battle with combatant2 = { battle.combatant2 with hp = battle.combatant2.hp - attacker.attack }}
</code></pre>
<p>which is also terrible code, I would appreciate any advice on it. But with nested collections it gets even more complicated, and event doesn't look functional to me anymore:</p>
<pre><code>let containsTarget = List.contains target
let transformCombatant combatant = if combatant = target then { combatant with hp = combatant.hp - attacker.attack } else combatant
let transformGroup = List.map transformCombatant
let checkGroup group =
if group |> containsTarget then
group |> transformGroup
else
group
let transformGroups = List.map checkGroup
{ battle with combatantGroups = transformGroups battle.combatantGroups }
</code></pre>
<p>Can you please give me advise on how can I use features of F# and functional programming, to make given code more pretty and concise?</p>
| [] | [
{
"body": "<ul>\n<li>I think you need an <code>id</code> field to be sure that you're updating the correct combatant. I assume it's possible to have multiple combatants with the same <code>hp</code> and <code>attack</code>.</li>\n<li>And in that case it makes sense to store a group as a Map of id to combatant. This makes it really simple to update a value by id and there's no need to check for existence first. See the <code>tryUpdateCombatantById</code> function below.</li>\n<li>You can add small helper functions to update specific record fields with a function that is passed in.</li>\n</ul>\n\n<p>Here's the code with all of those changes:</p>\n\n<pre><code>type Combatant = {\n id : int\n hp : int\n attack : int\n}\n\ntype Battle = { combatantGroups : Map<int, Combatant> list }\n\nlet updateHp f combatant = { combatant with hp = f combatant.hp }\nlet removeHp attack = updateHp (fun hp -> hp - attack)\n\nlet tryUpdateCombatantById combatantId f group =\n group\n |> Map.tryFind combatantId\n |> Option.map (fun c -> group |> Map.add c.id (f c))\n |> Option.defaultValue group\n\nlet applyAttack targetId attacker battle =\n { battle with\n combatantGroups =\n battle.combatantGroups\n |> List.map (tryUpdateCombatantById targetId (removeHp attacker.attack)) }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T20:23:42.610",
"Id": "419918",
"Score": "0",
"body": "`Option.map` in combination with `Option.defaultValue` seems like a very good pattern that I was not aware of, but I think your code actually adds new combat participant, instead of apdating an existing one, isn't it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T22:04:12.927",
"Id": "419925",
"Score": "1",
"body": "`Map.add` adds a value or replaces an existing one and in this case we're only adding values when the key already exists. An F# map is like a dictionary or hash table but immutable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T06:34:53.347",
"Id": "419950",
"Score": "0",
"body": "Oh, right, that's a map, and not a list, thx for clarification"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T12:31:00.553",
"Id": "217011",
"ParentId": "216909",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "217011",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T06:54:11.673",
"Id": "216909",
"Score": "3",
"Tags": [
".net",
"functional-programming",
"f#"
],
"Title": "Concise way of \"updating\" element in nested collections"
} | 216909 |
<p>I've just written a <strong>Producer / Consumer</strong> pattern templatized that should work in multi threads environment (IE producer(s) and consumer(s) in separate threads).</p>
<p>The original use case is one producer and one consumer in separate thread with a limit of container size.</p>
<p>It should work for a multi producers / consumers case though.</p>
<p><strong><em>[EDIT 1]</strong>: it appears to not working at all with multi consumers</em></p>
<p>Standard used is <strong>C++ 14</strong></p>
<p>My question is about the correctness of the <code>std::unique_lock<std::mutex></code> instructions and <code>synchronizer.wait</code> ones.</p>
<p>I have also a question about the forward declaration of templates, is there a way to avoid it without having a compiler error in the linking step ?</p>
<p>And last question about the handle of the container (the list), it must become the owner of the elements and handle its life time so what's the method signature I have to use (<code>const T &e</code>, <code>T e</code>, <code>T &&e</code>, ...) ? Or even <code>std::move</code> and implementation of perfect forwarding, I don't know.</p>
<p><strong>ProducerConsumer.hpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#ifndef CUDA_HARDWARE_VIDEO_READER_PRODUCERCONSUMER_HPP
#define CUDA_HARDWARE_VIDEO_READER_PRODUCERCONSUMER_HPP
#include <condition_variable>
#include <mutex>
#include <thread>
#include <queue>
template<typename T> class ProducerConsumer
{
public:
explicit ProducerConsumer(ulong maxSizeInBytes);
void produce(const T &element);
T consume();
void producerIsOver();
bool isFinished();
private:
std::queue<T> queue;
std::condition_variable synchronizer;
std::mutex mutex;
bool producerOver;
ulong maxSizeInBytes;
};
#endif //CUDA_HARDWARE_VIDEO_READER_PRODUCERCONSUMER_HPP
</code></pre>
<p><strong>ProducerConsumer.cpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#include "ProducerConsumer.hpp"
/**
* @brief Constructor
*
* @tparam T - The type of element's container
* @param maxSizeInMB - The maximum size the container can have in bytes
*/
template<typename T> ProducerConsumer<T>::ProducerConsumer(ulong maxSizeInBytes): maxSizeInBytes(maxSizeInBytes), producerOver(false) { }
/**
* @brief Producer - add element in the list
*
* @tparam T - The type of the element
* @param element - The element to add
*/
template<typename T> void ProducerConsumer<T>::produce(const T &element)
{
std::unique_lock<std::mutex> lock(mutex);
// Block the thread until the size of the queue allows to add more elements in it
if (sizeof(T) * (queue.size() + 1) > maxSizeInBytes) {
synchronizer.wait(lock, [&]() {
return sizeof(T) * (queue.size() + 1) <= maxSizeInBytes;
});
}
queue.push(element);
synchronizer.notify_one();
}
/**
* @brief Consumer - Get an element of the list and wait for it if the list is empty
*
* @tparam T - The type of the element
*
* @return The element
*/
template<typename T> T ProducerConsumer<T>::consume()
{
std::unique_lock<std::mutex> lock(mutex);
// Block the thread until the queue is empty and the producer has finished to fill the queue
if (queue.empty() && !producerOver) {
synchronizer.wait(lock, [&]() {
return !queue.empty() || producerOver;
});
}
T element = queue.front();
queue.pop();
// Wake up the producer if he's waiting
synchronizer.notify_all();
return element;
}
/**
* @brief Tells the producer has finished to fill the container
*
* @tparam T - The type of element's container
*/
template<typename T> void ProducerConsumer<T>::producerIsOver()
{
// @todo Useless ?
std::unique_lock<std::mutex> lock(mutex);
producerOver = true;
}
/**
* @brief Tells if the whole process is over (IE producer has finished to fill the container and the container is empty)
*
* @tparam T - The type of element's container
*
* @return True if the whole process is over, false otherwise
*/
template<typename T> bool ProducerConsumer<T>::isFinished()
{
std::unique_lock<std::mutex> lock(mutex);
return producerOver && queue.empty();
}
// @todo Annoying forward declaration there ...
template class ProducerConsumer<long double>;
</code></pre>
<p><strong>main.cpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <random>
#include <ctime>
#include <unistd.h>
#include "ProducerConsumer.hpp"
/**
* @brief Test the producer / consumer pattern that preserves order and is limited in size
* Required output is :
* Consume 1,
* Consume 2,
* Consume 3,
* ...,
* Consume 20
*
* @return EXIT_SUCCESS if no error occurred
*/
int main()
{
ProducerConsumer<long double> container(sizeof(long double));
std::random_device randomDevice;
std::mt19937 randomGenerator(randomDevice());
std::uniform_int_distribution<uint32_t> distribution(10000, 1000000);
randomGenerator.seed(std::time(nullptr));
std::thread producer([&]() {
for (int i = 1; i < 21; ++i) {
usleep(distribution(randomGenerator));
container.produce(i);
}
container.producerIsOver();
});
std::thread consumer([&]() {
do {
usleep(distribution(randomGenerator));
std::cout << "Consume " << container.consume() << std::endl;
} while (!container.isFinished());
});
producer.join();
consumer.join();
return EXIT_SUCCESS;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T12:41:30.190",
"Id": "419555",
"Score": "1",
"body": "Welcome to Code Review! Your edit places the question on the edge of what is considered [on-topic](https://codereview.stackexchange.com/help/on-topic) here, since it seems like the code is not working as intended. Against this background, pleace check if your code is ready to be reviewed in full here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T14:04:30.293",
"Id": "419572",
"Score": "1",
"body": "@Alex Hello, actually my code is working for the primary job I stated. You can execute the main and it is working as intended. I thought it would work for a larger scope but it is not. This point is \"on topic\" because: _Questions about improving scalability are allowable, as long as your code works for small inputs._"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T08:53:20.563",
"Id": "216912",
"Score": "3",
"Tags": [
"c++",
"multithreading",
"c++14",
"producer-consumer"
],
"Title": "C++ Producer / Consumer multi threads pattern with maximum container size"
} | 216912 |
<p>I employed the conventional Kadane's algorithms to solve a maximum subarray problem in leetcode <a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock/" rel="nofollow noreferrer">Best Time to Buy and Sell Stock - LeetCode</a></p>
<h1>Description</h1>
<blockquote>
<ol start="121">
<li>Best Time to Buy and Sell Stock</li>
</ol>
<p>Say you have an array for which the <em>i</em>th element is the price of a given stock on day <em>i</em>.</p>
<p>If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.</p>
<p>Note that you cannot sell a stock before you buy one.</p>
<p><strong>Example 1:</strong></p>
<pre><code>Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
</code></pre>
<p><strong>Example 2:</strong></p>
<pre><code>Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
</code></pre>
</blockquote>
<h1>My solution</h1>
<pre class="lang-py prettyprint-override"><code>class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
local_max = global_max = 0
gains = [prices[i]-prices[i-1] for i in range(1, len(prices))]
for cur in gains:
local_max = max(local_max + cur, cur)
global_max = max(global_max, local_max)
return global_max
</code></pre>
<blockquote>
<p>Runtime: 64 ms, faster than 14.96% of Python3 online submissions for Best Time to Buy and Sell Stock.</p>
<p>Memory Usage: 14 MB, less than 5.08% of Python3 online submissions for Best Time to Buy and Sell Stock</p>
</blockquote>
<pre class="lang-py prettyprint-override"><code>class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
loc = glo = 0
for i in range(1, len(prices)):
loc = max(loc+prices[i]-prices[i-1], prices[i]-prices[i-1])
glo = max(glo, loc)
return glo
</code></pre>
<blockquote>
<p>Runtime: 48 ms, faster than 53.38% of Python3 online submissions for Best Time to Buy and Sell Stock.</p>
<p>Memory Usage: 13.8 MB, less than 5.08% of Python3 online submissions for Best Time to Buy and Sell Stock</p>
</blockquote>
<h1>TestCase</h1>
<pre><code>class MyCase(unittest.TestCase):
def setUp(self):
self.solution = Solution3()
def test_a(self):
prices = [7,1,5,3,6,4]
answer = 5
check = self.solution.maxProfit(prices)
self.assertEqual(answer, check)
def test_b(self):
prices = [1,2,3,4,5]
answer = 4
check = self.solution.maxProfit(prices)
self.assertEqual(answer, check)
def test_c(self):
prices = [7,6,4,3,1]
answer = 0
check = self.solution.maxProfit(prices)
self.assertEqual(answer, check)
unittest.main()
</code></pre>
<p>The memory usage ranks very low.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T09:15:13.417",
"Id": "216913",
"Score": "3",
"Tags": [
"python",
"algorithm",
"programming-challenge",
"comparative-review",
"memory-optimization"
],
"Title": "Kadane's algorithms to leetcode \"121 Best Time to Buy and Sell Stock\""
} | 216913 |
<p>This is a function which aims to convert an amount of milliseconds to a more human-interpretable <strong>Day(s) Hour(s) Minute(s) Second(s)</strong> format:</p>
<pre><code>function dhms(t) {
d = Math.floor(t / (1000 * 60 * 60 * 24)),
h = Math.floor((t % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
m = Math.floor((t % (1000 * 60 * 60)) / (1000 * 60)),
s = Math.floor((t % (1000 * 60)) / 1000);
return d + 'Day(s) ' + h + 'Hour(s) ' + m + 'Minute(s) ' + s + 'Second(s)'
}
</code></pre>
<p>So for getting the variables values I have for now something quite verbose:</p>
<pre><code>d = Math.floor(t / (1000 * 60 * 60 * 24)),
h = Math.floor((t % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
m = Math.floor((t % (1000 * 60 * 60)) / (1000 * 60)),
s = Math.floor((t % (1000 * 60)) / 1000);
</code></pre>
<p>Is it the way to go? Or should I go with:</p>
<pre><code>d = Math.floor(t / 86400000),
h = Math.floor(t % 86400000 / 3600000),
m = Math.floor(t % 3600000 / 60000),
s = Math.floor(t % 60000 / 1000);
</code></pre>
<p>Or even with:</p>
<pre><code>d = Math.floor(t / 864e5),
h = Math.floor(t % 864e5 / 36e5),
m = Math.floor(t % 36e5 / 6e4),
s = Math.floor(t % 6e4 / 1e3);
</code></pre>
<p>Or another way? How is it recommended to assign time values?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T10:55:47.063",
"Id": "419538",
"Score": "3",
"body": "To me this feels like stub code, and lacks sufficient context. I have no clue what this code is supposed to achieve and I wouldn't be surprised that there are better ways to achieve its goals by using built-in functionality, but the lack of context prevents us knowing. (What is `t`?) See also https://codereview.meta.stackexchange.com/questions/3649/my-question-was-closed-as-being-off-topic-what-are-my-options/3652#3652"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T11:51:09.493",
"Id": "419543",
"Score": "1",
"body": "@BCdotWEB is it really that hard to figure out what `t` is? Strong clue: he's dividing it by `1000*60*60*24` and assigning the result to a variable named `d`, in a language that dispenses timestamps in milliseconds."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T12:47:54.627",
"Id": "419557",
"Score": "2",
"body": "Even though the context might be easy to guess in this specific example, the request for context exists for a good reason. Since your just presenting your solution but not the actual problem, it's hard to say if there might be a more appropriate solution. See also this [SO meta post](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T13:48:07.220",
"Id": "419571",
"Score": "1",
"body": "FYI https://github.com/moment/moment/blob/develop/moment.js has the following comment in their library: `//using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978`, so are you sure all three implementations are correct and result in the same output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T16:42:43.513",
"Id": "419585",
"Score": "0",
"body": "@BCdotWEB The fp error is not in the format 35e5 it is in the number `360000` eg `2.3 * (1000*60*60) === 2.3 * 36e5`, `2.3*1000*60*60 !== 2.3 * 36e5`, `2.3*3600000 !== 2.3*1000*60*60`, `2.3*1000*60*60 !== 60*60*1000*2.3` and `1000*60*60 === 36e5` are all `true`. The Op does not multiply, making the point mute."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T16:59:19.480",
"Id": "419590",
"Score": "0",
"body": "What `t` is in in the title and first line of the question. What the function does is also in the title."
}
] | [
{
"body": "<h2>The Decimal Point</h2>\n\n<p>Exponential notation is by far the better for large numbers.</p>\n\n<p>However when writing numbers in this format the convention is to have the decimal point after the first digit, as the exponent represents the magnitude of the value which is obscured if you have to locate the decimal point.</p>\n\n<pre><code>d = Math.floor(t / 8.64e7), \nh = Math.floor(t % 8.64e7 / 3.6e6), \nm = Math.floor(t % 3.6e6 / 6e4), \ns = Math.floor(t % 6e4 / 1e3);\n</code></pre>\n\n<h2>As constants</h2>\n\n<p>But.. These are magic numbers, and you repeat some of them several times, which is prone to error. Also assuming that this function would be part of a set of such functions declaring these constants as named variables would be much better.</p>\n\n<pre><code>DAY_MS = 8.64e7;\nHOUR_MS = 3.6e6;\nMIN_MS = 6e4;\nSEC_MS = 1e3;\n</code></pre>\n\n<h2>Derived values</h2>\n\n<p>As they are derived from each other you can then write it as</p>\n\n<pre><code>SEC_MS = 1e3;\nMIN_MS = SEC_MS * 60;\nHOUR_MS = MIN_MS * 60;\nDAY_MS = HOUR_MS * 24;\n</code></pre>\n\n<h2>Encapsulate</h2>\n\n<p>If you then encapsulate them you can drop the _MS and your function would look like.</p>\n\n<pre><code>\"use strict\";\nconst dhms = (()=>{\n const SEC = 1e3;\n const MIN = SEC * 60;\n const HOUR = MIN * 60;\n const DAY = HOUR * 24;\n return time => {\n const ms = Math.abs(time);\n const d = ms / DAY | 0;\n const h = ms % DAY / HOUR | 0;\n const m = ms % HOUR / MIN | 0;\n const s = ms % MIN / SEC | 0;\n return `${time < 0 ? \"-\" : \"\"}${d}Day(s) ${h}Hour(s) ${m}Minute(s) ${s}Second(s)`;\n };\n})();\n</code></pre>\n\n<p>Notes</p>\n\n<ol>\n<li><p>That <code>t</code> is made positive <code>ms</code> to avoid a negative sign on each number. This also lets you use the shorter and quicker <code>| 0</code> (<a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#(Bitwise_OR)\" rel=\"nofollow noreferrer\">bit-wise OR</a> 0) to floor the values, which you should only use for positive integers.</p></li>\n<li><p>The use of a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals\" rel=\"nofollow noreferrer\">template string</a> to format the output.</p></li>\n<li><p>You could also define it as a module and thus avoid the need to encapsulate the constants as a module has its own local scope.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T16:14:57.497",
"Id": "216932",
"ParentId": "216914",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216932",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T09:40:58.137",
"Id": "216914",
"Score": "0",
"Tags": [
"javascript",
"datetime",
"comparative-review",
"formatting"
],
"Title": "Formatting milliseconds as days, hours, minutes, and seconds"
} | 216914 |
<p>I am allowing user to <strong>upload images & drag uploaded image</strong> once user click on mask images, also gave an option to <strong>Edit the text</strong>....</p>
<p>I am fetching mask images and text from <strong>json</strong> file....</p>
<p>I am uploading each mask images in single canvas & using absolute positing....</p>
<p>But now its getting very difficult to do any code changes because the code structure looks very bad, i have no idea how to improve the look and feel of code structure , need help.....</p>
<p><a href="https://i.stack.imgur.com/3uqug.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3uqug.png" alt="enter image description here"></a></p>
<p>JSfiddle : <a href="https://jsfiddle.net/kidsdial1/rhowf7dn/" rel="nofollow noreferrer">https://jsfiddle.net/kidsdial1/rhowf7dn/</a></p>
<p>pen : <a href="https://codepen.io/kidsdial/pen/rbeRZK" rel="nofollow noreferrer">https://codepen.io/kidsdial/pen/rbeRZK</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>function closePopUp(el) {
el.style.display = 'none';
openID = null
}
function openPopUp(el) {
///console.log(" open is called ",id)
if (openID != null) {
closePopUp(openID)
}
el.style.display = 'block';
openID = el;
}
let openID = null;
var target;
var imageUrl = "https://i.imgur.com/RzEm1WK.png";
let jsonData = {
"layers" : [
{
"x" : 0,
"height" : 600,
"layers" : [
{
"x" : 20,
"height" : 788,
"src" : "ax0HVTs.png",
"y" : 70,
"width" : 650,
"type" : "image",
"name" : "shape_1"
},
{
"x" : 40,
"height" : 140,
"src" : "iEA642D.jpg",
"y" : 360,
"width" : 430,
"type" : "image",
"name" : "shape_2"
},
{
"font" : "ArchivoNarrow-Bold",
"x" : 19,
"y" : 17,
"width" : 211,
"src" : "611aa93612da8fde1b17d87368355d1f_Font83.otf",
"type" : "text",
"text" : "VALENTINES DAY ",
"size" : 27,
"height" : 22,
"name" : "edit_sale"
}
],
"y" : 0,
"width" : 600,
"type" : "group",
"name" : "fb_post_5"
}
]
};
$(document).ready(function() {
// below code will upload image onclick mask image
$('.container').click(function(e) {
// filtering out non-canvas clicks
if (e.target.tagName !== 'CANVAS') return;
// getting absolute points relative to container
const absX = e.offsetX + e.target.parentNode.offsetLeft + e.currentTarget.offsetLeft;
const absY = e.offsetY + e.target.parentNode.offsetTop + e.currentTarget.offsetTop;
const $canvasList = $(this).find('canvas');
// moving all canvas parents on the same z-index
$canvasList.parent().css({
zIndex: 0
});
$canvasList.filter(function() { // filtering only applicable canvases
const bbox = this.getBoundingClientRect();
const canvasTop = bbox.top + window.scrollY;
const canvasLeft = bbox.left + window.scrollX;
return (
absX >= canvasLeft && absX <= canvasLeft + bbox.width &&
absY >= canvasTop && absY <= canvasTop + bbox.height)
}).each(function() { // checking white in a click position
const x = absX - this.parentNode.offsetLeft - e.currentTarget.offsetLeft;
const y = absY - this.parentNode.offsetTop - e.currentTarget.offsetTop;
const pixel = this.getContext('2d').getImageData(x, y, 1, 1).data;
if (pixel[3] === 255) {
$(this).parent().css({
zIndex: 2
})
target = this.id;
console.log(target);
setTimeout(() => {
$('#fileup').click();
}, 20);
}
})
});
// Below code will fetch mask images from json file
function getAllSrc(layers) {
let arr = [];
layers.forEach(layer => {
if (layer.src) {
arr.push({
src: layer.src,
x: layer.x,
y: layer.y,
name: layer.name
});
} else if (layer.layers) {
let newArr = getAllSrc(layer.layers);
if (newArr.length > 0) {
newArr.forEach(({
src,
x,
y,
name
}) => {
arr.push({
src,
x: (layer.x + x),
y: (layer.y + y),
name: (name)
});
});
}
}
});
return arr;
}
function json(data)
{
var width = 0;
var height = 0;
let arr = getAllSrc(data.layers);
let layer1 = data.layers;
width = layer1[0].width;
height = layer1[0].height;
let counter = 0;
let table = [];
for (let {
src,
x,
y,
name
} of arr) {
$(".container").css('width', width + "px").css('height', height + "px").addClass('temp');
if (name.indexOf('mask_') !== -1) {
var imageUrl1 = imageUrl;
} else {
var imageUrl1 = '';
}
var mask = $(".container").mask({
imageUrl: imageUrl1,
maskImageUrl: 'https://i.imgur.com/' + src,
onMaskImageCreate: function(img) {
img.css({
"position": "absolute",
"left": x + "px",
"top": y + "px"
});
},
id: counter
});
table.push(mask);
fileup.onchange = function() {
let mask2 = table[target];
const newImageLoadedId = mask2.loadImage(URL.createObjectURL(fileup.files[0]));
document.getElementById('fileup').value = "";
// Edit image
$("<span class=\"pip\">" +
"<br/><a onclick='document.getElementById(\"light\").style.display=\"block\";'><span class=\"edit\" >Edit </span>" +
'<div id=\'light\' class=\'white_content\'>content <a href=\"javascript:void(0)\" onclick=\"document.getElementById(\'light\').style.display=\'none\';">Close</a></div> ' +
"</span>").insertAfter("#fileup");
// Edit image code end here....
// Remove image
$("<br/><span id=\"" + newImageLoadedId + "\" class=\"remove\">Remove image</span>").insertAfter("#fileup");
$(".remove").click(function(event) {
const canvasId = "canvas#" + event.currentTarget.id;
// Delete the image
const ctx = $("canvas")[event.currentTarget.id].getContext("2d");
ctx.fillStyle = "white"
ctx.fillRect(0, 0, 500, 500)
// Delete the button
$(this).remove();
});
// Remove image code end here....
};
counter++;
}
drawText(data);
}
json(jsonData);
}); // end of document ready
const fonts = []; // caching duplicate fonts
function drawText(layer) {
if (layer.type === 'image') return;
if (!layer.type || layer.type === 'group') {
return layer.layers.forEach(drawText)
}
if (layer.type === 'text') {
const url = 'http://piccellsapp.com:1337/parse/files/PfAppId/' + layer.src;
if (!fonts.includes(url)) {
fonts.push(url);
$("style").prepend("@font-face {\n" +
"\tfont-family: \"" + layer.font + "\";\n" +
"\tsrc: url(" + url + ") format('truetype');\n" +
"}");
}
// Below is POP UP Code
const lightId = 'light' + layer.name
const lightIdString = '#' + lightId
$('.container').append(
'<a id ="' + layer.name + '" onclick="openPopUp(' + lightId + ')"' +
'<div class="txtContainer" contenteditable="true" ' +
'style="' +
'left: ' + layer.x + 'px; ' +
'top: ' + layer.y + 'px; ' +
'font-size: ' + layer.size + 'px; ' +
'">' + layer.text + '</div></a>' +
'<div id="light' + layer.name + '" class="white_content" style="' +
'left: ' + layer.x + 'px; ' +
'top: ' + layer.y + 'px; ' + '"> content <a href="javascript:void(0)" ' +
'onclick="closePopUp(' + lightId + ')">Close</a></div> <div>'
);
document.getElementById(lightId).style.left = layer.x + document.getElementById(layer.name).offsetWidth + 'px'
// Above is POP UP Code
}
}
// extempl code end
// jq plugin
(function($) {
var JQmasks = [];
$.fn.mask = function(options) {
// This is the easiest way to have default options.
var settings = $.extend({
// These are the defaults.
maskImageUrl: undefined,
imageUrl: undefined,
scale: 1,
id: new Date().getUTCMilliseconds().toString(),
x: 0, // image start position
y: 0, // image start position
onMaskImageCreate: function(div) {},
}, options);
var container = $(this);
let prevX = 0,
prevY = 0,
draggable = false,
img,
canvas,
context,
image,
timeout,
initImage = false,
startX = settings.x,
startY = settings.y,
div;
container.mousePosition = function(event) {
return {
x: event.pageX || event.offsetX,
y: event.pageY || event.offsetY
};
}
container.selected = function(ev) {
var pos = container.mousePosition(ev);
var item = $(".masked-img canvas").filter(function() {
var offset = $(this).offset()
var x = pos.x - offset.left;
var y = pos.y - offset.top;
var d = this.getContext('2d').getImageData(x, y, 1, 1).data;
return d[0] > 0
});
JQmasks.forEach(function(el) {
var id = item.length > 0 ? $(item).attr("id") : "";
if (el.id == id)
el.item.enable();
else el.item.disable();
});
};
container.enable = function() {
draggable = true;
$(canvas).attr("active", "true");
div.css({
"z-index": 2
});
}
container.disable = function() {
draggable = false;
$(canvas).attr("active", "false");
div.css({
"z-index": 1
});
}
container.onDragStart = function(evt) {
if (evt.target.getContext) {
var pixel = evt.target.getContext('2d').getImageData(evt.offsetX, evt.offsetY, 1, 1).data;
$(canvas).attr("active", "true");
container.selected(evt);
prevX = evt.clientX;
prevY = evt.clientY;
var img = new Image();
evt.originalEvent.dataTransfer.setDragImage(img, 10, 10);
evt.originalEvent.dataTransfer.setData('text/plain', 'anything');
}
};
container.getImagePosition = function() {
return {
x: settings.x,
y: settings.y,
scale: settings.scale
};
};
container.onDragOver = function(evt) {
if (evt.target.getContext) {
var pixel = evt.target.getContext('2d').getImageData(evt.offsetX, evt.offsetY, 1, 1).data;
if (pixel[3] === 255) {
if (draggable && $(canvas).attr("active") === "true") {
var x = settings.x + evt.clientX - prevX;
var y = settings.y + evt.clientY - prevY;
if (x == settings.x && y == settings.y)
return; // position has not changed
settings.x += evt.clientX - prevX;
settings.y += evt.clientY - prevY;
prevX = evt.clientX;
prevY = evt.clientY;
clearTimeout(timeout);
timeout = setTimeout(function() {
container.updateStyle();
renderInnerImage();
}, 20);
}
} else {
evt.stopPropagation();
return false;
}
}
};
container.updateStyle = function() {
return new Promise((resolve, reject) => {
context.beginPath();
context.globalCompositeOperation = "source-over";
image = new Image();
image.setAttribute('crossOrigin', 'anonymous');
image.src = settings.maskImageUrl;
image.onload = function() {
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0, image.width, image.height);
div.css({
"width": image.width,
"height": image.height
});
resolve();
};
});
};
function renderInnerImage() {
img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = settings.imageUrl;
img.onload = function() {
settings.x = settings.x == 0 && initImage ? (canvas.width - (img.width * settings.scale)) / 2 : settings.x;
settings.y = settings.y == 0 && initImage ? (canvas.height - (img.height * settings.scale)) / 2 : settings.y;
context.globalCompositeOperation = 'source-atop';
context.drawImage(img, settings.x, settings.y, img.width * settings.scale, img.height * settings.scale);
initImage = false;
};
}
// change the draggable image
container.loadImage = function(imageUrl) {
console.log("load");
//if (img)
// img.remove();
// reset the code.
settings.y = startY;
settings.x = startX;
prevX = prevY = 0;
settings.imageUrl = imageUrl;
initImage = true;
container.updateStyle().then(renderInnerImage);
// sirpepole Add this
return settings.id;
};
// change the masked Image
container.loadMaskImage = function(imageUrl, from) {
canvas = document.createElement("canvas");
context = canvas.getContext('2d');
canvas.setAttribute("draggable", "true");
canvas.setAttribute("id", settings.id);
settings.maskImageUrl = imageUrl;
div = $("<div/>", {
"class": "masked-img"
}).append(canvas);
// div.find("canvas").on('touchstart mousedown', function(event)
div.find("canvas").on('dragstart', function(event) {
if (event.handled === false) return;
event.handled = true;
container.onDragStart(event);
});
div.find("canvas").on('touchend mouseup', function(event) {
if (event.handled === false) return;
event.handled = true;
container.selected(event);
});
div.find("canvas").bind("dragover", container.onDragOver);
container.append(div);
if (settings.onMaskImageCreate)
settings.onMaskImageCreate(div);
container.loadImage(settings.imageUrl);
};
container.loadMaskImage(settings.maskImageUrl);
JQmasks.push({
item: container,
id: settings.id
})
return container;
};
}(jQuery));</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.temp {}
.container {
background: silver;
position: relative;
}
.container img {
position:absolute;
top:0;
bottom:250px;
left:0;
right:0;
margin:auto;
z-index:999;
}
.masked-img {
overflow: hidden;
position: relative;
}
.txtContainer{ position:absolute; text-align:center; color:#FFF}
.txtContainer:hover {
background: red;
padding: 1px;
border-style: dotted;
}
.pip {
display: inline-block;
margin: 10px 10px 0 0;
}
.remove {
display: block;
background: #444;
border: 1px solid black;
color: white;
text-align: center;
cursor: pointer;
}
.remove:hover {
background: white;
color: black;
}
.edit {
display: block;
background: #444;
border: 1px solid black;
color: white;
text-align: center;
cursor: pointer;
}
.edit:hover {
background: white;
color: black;
}
.white_content {
display: none;
position: absolute;
top: 25%;
left: 25%;
width: 50%;
height: 50%;
padding: 16px;
border: 16px solid orange;
background-color: white;
z-index: 1002;
overflow: auto;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="fileup" name="fileup" type="file" style="display:none" >
<div class="container">
</div></code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T07:04:02.847",
"Id": "420208",
"Score": "0",
"body": "it will be really helpfull if someone give codepen...."
}
] | [
{
"body": "<p>It looks like this code is very similar to <a href=\"https://codereview.stackexchange.com/q/214525/120114\">the code you posted last month</a>, and in that review <a href=\"https://codereview.stackexchange.com/a/214574/120114\">blindman67 recommended you consider eliminating the jQuery code</a>. While it isn't imperative that you do so it would perhaps simplify some code and decrease page load times - not that it would likely be a dramatic change but could be less.</p>\n\n<p>You could consider moving anonymous/lambda functions/closures out to named functions - this would allow decreasing the nesting levels.</p>\n\n<p>If you keep the jQuery code, perhaps the suggestions below will be helpful.</p>\n\n<p>While that syntax of <code>$(document).ready()</code> still works with the latest jQuery version (i.e. 3.3.1 at the time of typing), but is deprecated and the recommended syntax is simply <code>$(function() {})</code><sup><a href=\"https://api.jquery.com/ready/\" rel=\"nofollow noreferrer\">1</a></sup>.</p>\n\n<hr>\n\n<p>I see this variable declaration:</p>\n\n<blockquote>\n<pre><code>var imageUrl = \"https://i.imgur.com/RzEm1WK.png\";\n</code></pre>\n</blockquote>\n\n<p>That value is never re-assigned, so it could be declared with the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\"><code>const</code></a> keyword and a common convention among developers is to name constants in all capital letters and separate words with underscores. Additionally that name is somewhat vague. Maybe a better name would be <code>DEFAULT_IMAGE_URL</code> or <code>FALLBACK_IMAGE_URL</code>.</p>\n\n<hr>\n\n<p>It is wise to cache DOM elements in variables instead of repeatedly querying the DOM<sup><a href=\"https://www.sitepoint.com/jquery-performance-dom-caching/\" rel=\"nofollow noreferrer\">2</a></sup> - e.g. </p>\n\n<pre><code>const containerElement = $('.container');\n</code></pre>\n\n<p>If that element is the only container on the page, perhaps it would be appropriate to use an <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id\" rel=\"nofollow noreferrer\"><em>id</em></a> attribute </p>\n\n<pre><code><div id=\"container\"></div> <!-- could still also have class=\"container\" -->\n</code></pre>\n\n<p>and then select it in JavaScript with the <a href=\"https://api.jquery.com/id-selector/\" rel=\"nofollow noreferrer\">id selector</a>:</p>\n\n<pre><code>const containerElement = $('#container');\n</code></pre>\n\n<p>Then that can be referenced later in the code - e.g.</p>\n\n<pre><code>// below code will upload image onclick mask image\n\ncontainerElement.click(function(e) {\n // filtering out non-canvas clicks\n</code></pre>\n\n<p>and </p>\n\n<pre><code>containerElement.css('width', width + \"px\").css('height', height + \"px\").addClass('temp');\nif (name.indexOf('mask_') !== -1) {\n var imageUrl1 = imageUrl;\n } else {\n var imageUrl1 = '';\n }\n var mask = containerElement.mask({...});\n</code></pre>\n\n<p>In order to use that in <code>drawText()</code> the scope would need to be widened (e.g. outside of the DOM-ready callback, or have that function moved).</p>\n\n<p>Other elements used frequently that can be cached are <code>$('#fileup')</code>, <code>$(\".container\")</code>, etc.</p>\n\n<hr>\n\n<p>In function <code>json()</code> I see a <code>for</code> loop that starts like this:</p>\n\n<blockquote>\n<pre><code>for (let {\n src,\n x,\n y,\n name\n } of arr) {\n $(\".container\").css('width', width + \"px\").css('height', height + \"px\").addClass('temp');\n</code></pre>\n</blockquote>\n\n<p>That first line inside the block will be updating the css of the container element once for each iteration of <code>arr</code>. It would be better to move that call outside the <code>for</code> loop in order to avoid excess function calls.</p>\n\n<hr>\n\n<p>Lower in function <code>json()</code> I see this line:</p>\n\n<pre><code>fileup.onchange = function() {\n</code></pre>\n\n<p>But I don't see <code>fileup</code> declared as a variable, local to this code or function, which means this is utilizing a global variable. As <a href=\"https://stackoverflow.com/a/25325330/1575353\">joews explains in this answer</a> to <a href=\"https://stackoverflow.com/q/25325221/1575353\"><em>Why don't we just use element IDs as identifiers in JavaScript?</em></a> the <a href=\"http://w3c.github.io/html/browsers.html#named-access-on-the-window-object\" rel=\"nofollow noreferrer\">HTML5 spec</a> advises against using Named access.</p>\n\n<blockquote>\n <p><strong><em><code>window</code></em><code>[</code><em><code>name</code></em><code>]</code></strong><br><br>\n Returns the indicated element or collection of elements.<br>\n As a general rule, relying on this will lead to brittle code. Which IDs end up mapping to this API can vary over time, as new features are added to the Web platform, for example. Instead of this, use <a href=\"https://dom.spec.whatwg.org/#dom-nonelementparentnode-getelementbyid\" rel=\"nofollow noreferrer\"><code>document.getElementById()</code></a> or <code>document.querySelector()</code>.<sup><a href=\"http://w3c.github.io/html/browsers.html#named-access-on-the-window-object\" rel=\"nofollow noreferrer\">3</a></sup></p>\n</blockquote>\n\n<p>Additionally, setting the <code>onchange</code> property of an element would overwrite any previous onchange handler. If there was a need to have multiple events then you can use <a href=\"https://developer.mozilla.org/en/docs/Web/API/EventTarget/addEventListener\" rel=\"nofollow noreferrer\"><code>Event.addEventListener()</code></a></p>\n\n<hr>\n\n<p>At the end of the first click handler on <code>$('.container')</code> I see:</p>\n\n<blockquote>\n<pre><code>setTimeout(() => {\n $('#fileup').click();\n}, 20);\n</code></pre>\n</blockquote>\n\n<p>This could be simplified using a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Creating_a_bound_function\" rel=\"nofollow noreferrer\">Bound function</a>:</p>\n\n<pre><code>const fileUp = $('#fileup'); //can be moved to top of DOM ready callback\nsetTimeout(fileUp.click.bind(fileUp), 20);\n</code></pre>\n\n<hr>\n\n<p>The CSS has a few peculiar aspects. First, I see an empty ruleset for <code>.temp</code>. Also, some of the lines have unique indentation levels- some have tabs while others have two spaces, yet the majority have four spaces</p>\n\n<blockquote>\n<pre><code>.container {\n background: silver;\n position: relative;\n\n}\n.container img {\n position:absolute;\n top:0;\n bottom:250px;\n left:0;\n right:0;\n margin:auto;\n z-index:999;\n}\n</code></pre>\n</blockquote>\n\n<p>It would improve readability to make all indentation spacing uniform.</p>\n\n<hr>\n\n<p>In your review <a href=\"https://codereview.stackexchange.com/q/216247/120114\"><em>Edit and delete uploaded images code inside script tag</em>\n</a>, which also has very similar code to the code here, <a href=\"https://codereview.stackexchange.com/a/216251/120114\">x539 recommended using template tags</a> and <a href=\"https://codereview.stackexchange.com/questions/216247/edit-and-delete-uploaded-images-code-inside-script-tag#comment419569_216251\">you asked in comments how to make the styles change</a>. That can be done with JavaScript after the template is cloned - similar to the <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template#Examples\" rel=\"nofollow noreferrer\">MDN example that modifies contents after cloning</a>. </p>\n\n<p>Instead of inserting the cloned element immediately:</p>\n\n<blockquote>\n<pre><code>$('#demoTemplate').clone().insertAfter('#fileup');\n</code></pre>\n</blockquote>\n\n<p>modify the sub-elements in-between. Use a traversal function like <a href=\"http://api.jquery.com/find/\" rel=\"nofollow noreferrer\"><code>.find()</code></a> to locate the elements to alter.</p>\n\n<pre><code>const clone = $('#demoTemplate').clone();\nclone.find('.edit').css({left: '3px'});\nclone.id = layer.name; //make unique\nclone.show(); //remove style=\"display: none\"\nclone.insertAfter('#fileup');\n</code></pre>\n\n<p><sup>1</sup><sub><a href=\"https://api.jquery.com/ready/\" rel=\"nofollow noreferrer\">https://api.jquery.com/ready/</a></sub></p>\n\n<p><sup>2</sup><sub><a href=\"https://www.sitepoint.com/jquery-performance-dom-caching/\" rel=\"nofollow noreferrer\">https://www.sitepoint.com/jquery-performance-dom-caching/</a></sub></p>\n\n<p><sup>3</sup><sub><a href=\"http://w3c.github.io/html/browsers.html#named-access-on-the-window-object\" rel=\"nofollow noreferrer\">http://w3c.github.io/html/browsers.html#named-access-on-the-window-object</a></sub></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T09:42:15.710",
"Id": "420103",
"Score": "0",
"body": "Thanks for your valuable time, you spent lot of time on this.... you guys deserved lot, ..... not just thanks or upvotes...."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T07:03:03.560",
"Id": "420207",
"Score": "0",
"body": "i used `const containerElement = $('#container');` in code : https://codepen.io/kidsdial/pen/gyWwZJ , images loaded , but not displaying in page, please check when you get free time...."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T05:38:44.067",
"Id": "420737",
"Score": "0",
"body": "Darn My original statements were too vague and I didn’t explicitly state that the container `<div>` would need to have an `id` attribute (e.g. `<div id=\"container\"></div>`) in order for that to work. I have updated this answer"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T22:06:37.507",
"Id": "217162",
"ParentId": "216915",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "217162",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T10:22:25.110",
"Id": "216915",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"ecmascript-6",
"html5"
],
"Title": "User upload & Drag image and update text"
} | 216915 |
<p>I've been reading about pure methods and immutability in Java. I have a current application and want to convert all the methods to pure methods. </p>
<p>My app takes payment from users. I first create a payment in the DB:</p>
<pre><code>Payment payment = new Payment();
payment = createPayment(orderId, status, address1, address2, country, state, price);
// createPayment() creates a row in the database table, saving orderId, status, address1, address2, country, state, price
// state is the inital state of the payment, in this cased INITIATED
createPayment() returns a Payment model
// make the payment with the payment processor
PaymentResult paymentResult = paymentService.pay(payment);
</code></pre>
<p><code>PaymentResult</code> contains properties such as <code>authCode</code>, <code>pspReference</code>, <code>resultCode</code>, <code>refusalReason</code>.</p>
<p>The Payment model also contains <code>authCode</code> etc. properties. I now want to update my Payment model, including its status. I currently have:</p>
<pre><code>paymentService.updatePaymentFromPaymentResultOnAuthorise(paymentResult, payment);
</code></pre>
<p>And <code>updatePaymentFromPaymentResultOnAuthorise</code> is:</p>
<pre><code>public void updatePaymentFromPaymentResultOnAuthorise(PaymentResult paymentResult, Payment payment) throws PaymentException {
try {
boolean success = !isNullOrEmpty(paymentResult.getAuthCode());
if (success) {
payment.setLastStatus(payment.getStatus());
payment.setStatus(PaymentStatus.PAID);
}
payment.setPspReference(paymentResult.getPspReference());
payment.setAuthCode(paymentResult.getAuthCode());
payment.setResultCode(String.valueOf(paymentResult.getResultCode()));
payment.setRefusalReason(paymentResult.getRefusalReason());
paymentDAO.updatePayment(payment);
} catch (Exception e) {
throw new PaymentException(String.format("there was an error updating the payment with paymentId %s", payment.getId()));
}
}
</code></pre>
<p>As you can see, <code>updatePaymentFromPaymentResultOnAuthorise</code> is not a pure method as it changes the argument <code>payment</code>. This pattern is repeated throughout the app. </p>
<p>Is the only way to make this method pure to create a copy of <code>payment</code> within <code>updatePaymentFromPaymentResultOnAuthorise</code> and return this new object? This seems expensive and it will need to be done in many places throughout my app. But is that my only option?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T11:17:59.493",
"Id": "419541",
"Score": "1",
"body": "Let's start with the reasons why you want to make a major change to the APIs in your system. What is wrong with the current implementation and what problem will you solve by changing everything to pure methods?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T12:31:36.087",
"Id": "419551",
"Score": "1",
"body": "@TorbenPutkonen The current implementation works fine. I want to move towards pure functions as it's cleaner, easier to test and less bug prone."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T12:40:36.003",
"Id": "419554",
"Score": "0",
"body": "You have to consider that the pattern you have copies the pattern in the underlying persistence layer (EJB3). It's ok to change the pattern in order to hide the persistence layer but on the other hand if your developers are accustomed to EJB3 and are expecting your API to behave likewise, changing to pure methods is going to cause problems."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T12:44:56.633",
"Id": "419556",
"Score": "0",
"body": "It's more a case of getting into the habit of following Java good practices. My current implementation work, but changing argument properties isn't a great idea, and makes things hard to test"
}
] | [
{
"body": "<p>The biggest problem I see is that the objects you pass around in EJB3 are part of the transaction. If you try to reload the payment again from the EntityManager, you will get back the exact same instance you are trying to avoid changing. You will have to jump through hoops in order to reload the payment as a completely new object and that pretty much negates anything that makes pure methods less error prone.</p>\n\n<p>Following best practises is a valid reason but in this case I get the feeling that the baby gets thrown out with the bath water. Don't feel bad, though. EJB3 transaction model is not intuitive at all, needs very good project documentation and guidelines and it still needs constant care taking anyway.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T12:47:27.323",
"Id": "216924",
"ParentId": "216916",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216924",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T10:25:57.657",
"Id": "216916",
"Score": "0",
"Tags": [
"java",
"functional-programming"
],
"Title": "Pure methods for updating java objects"
} | 216916 |
<p>I'm trying to find a way to create a test table from golden and input files.</p>
<p>I have the following dir structure:</p>
<pre><code>pkg
|
| mypackage/
| testdata/
| file1.input
| file1.golden
| file2.input
| file2.golden
| mypackage_test.go
| ...
</code></pre>
<p>I'm trying to find an efficient way to create a test table from a pair of input and golden files:</p>
<pre><code>type test struct {
input,
expected string
}
func getFiles() test {
input, _ := ioutil.ReadFile(filepath.Join("testdata", fmt.Sprintf("%s.%s", filename, "input")))
expected, := ioutil.ReadFile(filepath.Join("testdata", fmt.Sprintf("%s.%s", filename, "golden")))
return {string(input), string(expected)}
}
func getTable() []test {
return []test{getFiles("file1"), getFiles("file2"), getFiles("file3")}
}
func TestInputs(t *testing.T) {
table := getTable()
for _, tt := range table {
// perform the test
}
}
</code></pre>
<p>I'm not really the best at writting tests, and the code above seems a bit hacky. Is there a better way to do what I'm trying?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T12:08:26.443",
"Id": "216919",
"Score": "1",
"Tags": [
"go"
],
"Title": "Transforming golden and input files in test table"
} | 216919 |
<p>I wrote scripts that sums up the students and their grades. It uses four csv files.</p>
<ul>
<li><a href="https://drive.google.com/open?id=1Z6f1TLdXuqg-wItsuIVWwCsAzWWYA62r" rel="nofollow noreferrer">students</a></li>
<li><a href="https://drive.google.com/open?id=1Jx4CPkkLzZOXK4f6SGn03WhYQCeNfe35" rel="nofollow noreferrer">marks</a></li>
<li><a href="https://drive.google.com/open?id=1pIi2hWO3L9ng9PCzzsfg76PD8JwT55N_" rel="nofollow noreferrer">tests</a></li>
<li><a href="https://drive.google.com/open?id=1zVSxuIINwoFyDhErYlxk4sQ03LFx7IiQ" rel="nofollow noreferrer">courses</a></li>
</ul>
<p>.</p>
<pre><code># main
import pandas
from statistics import mean
if __name__ == "__main__":
students_df = pandas.read_csv("students.csv")
marks_df = pandas.read_csv("marks.csv")
tests_df = pandas.read_csv("tests.csv")
courses_df = pandas.read_csv("courses.csv")
marks_tests = pandas.merge(marks_df, tests_df, left_on="test_id", right_on="id")
student_courses = marks_tests.groupby(by="student_id")['course_id'].apply(set)
students_dict = students_df.set_index("id").to_dict(orient="index")
courses_dict = courses_df.set_index("id").to_dict(orient="index")
for student_id, course_ids in student_courses.iteritems():
print("Student id: {}, name: {name}".format(student_id, **students_dict[student_id]))
final_grades = []
for course_id in course_ids:
marks = marks_tests.loc[(marks_tests['course_id'] == course_id) & (marks_tests['student_id'] == student_id)]
final_grades.append(sum(marks['mark']*(marks['weight']/100.0)))
print("Total Average: {:.2f}%".format(mean(final_grades)))
for course_id in course_ids:
print(" Course: {name}, Teacher: {teacher}".format(**courses_dict[course_id]))
marks = marks_tests.loc[(marks_tests['course_id'] == course_id) & (marks_tests['student_id'] == student_id)]
final_grade = sum(marks['mark']*(marks['weight']/100.0))
print(" Final Grade: {:.2f}%".format(final_grade))
</code></pre>
<p>It works very well but I don't know if it is optimized. For instance I have two loops that do almost the same thing : the first one to get the total Average which is mean of the final grades for each topic and the second one to get the final grade for each topics.</p>
<p>Furthermore it would have been better if I added some testing to it such has </p>
<ul>
<li>if the sum of the weights of the tests a student has taken in a topic are equal to 0 (the student took every tests)</li>
<li>or go over 100.</li>
</ul>
| [] | [
{
"body": "<p>The main part of programming is writing code so that it makes sense to others, and the biggest part of that is slicing your code into functions (Single Responsibility) which do only one thing.<br>\nIf I was changing your code, the first thing I would do is move everything under your entry point (<code>if __name__</code>... - good BTW, always have an entry point) into functions, and have the main communicate what the code is doing. For instance:</p>\n\n<pre><code>if __name__ == \"__main__\":\n load_student_files_into_data_frames()\n merge_test_marks()\n group_students()\n print_students_and_course_results()\n</code></pre>\n\n<p>Now I understand the purpose of your code without having to look for a README.txt or spending 5-10 minutes reading or stepping through your code. This is also a good technique for understanding program flow before you actually write code inside the functions (and lends itself to TDD, but that's another topic for another day). </p>\n\n<p>Of course, doing that with your code as it currently is, breaks all operations. \nEven if we update the load process to return each data frame, it starts to look messy:</p>\n\n<pre><code>def load_student_files_into_data_frames():\n students_df = pandas.read_csv(\"students.csv\")\n marks_df = pandas.read_csv(\"marks.csv\")\n tests_df = pandas.read_csv(\"tests.csv\")\n courses_df = pandas.read_csv(\"courses.csv\")\n return students_df, marks_df, tests_df, courses_df\n\nif __name__ == \"__main__\":\n students_df, marks_df, tests_df, courses_df = load_student_files_into_data_frames()\n</code></pre>\n\n<p>Now we've encountered the DRY (Don't Repeat Yourself) code smell - performing the same operation multiple times. Let's extract out the CSV read into a separate function like this:</p>\n\n<pre><code>def read_csv(filename):\n return pandas.read_csv(filename)\n\ndef load_student_files_into_data_frames():\n file_names = [\"students.csv\", \"marks.csv\", \"tests.csv\", \"courses.csv\"]\n return map(read_csv, file_names)\n</code></pre>\n\n<p>However, now we violated the Open/Close Principle - which is that code should be closed for modification but open for enhancement. For example, if you need to add another CSV, you'd have to open the code up, edit it and put the new CSV in, correct? Or if the CSV comes from an external company, and they change its name (for whatever reason), you'd need to edit the code to make it work again, yes? This is true for magic numbers and anything else which can change.<br>\nSo, the best method is to have the file names in an external .ini file, and use ConfigParser to load the names - but this is a small script, so we'll just define them in the <code>__main__</code>.</p>\n\n<pre><code>def load_student_files_into_data_frames(filename_list):\n return map(read_csv, filename_list)\n\nif __name__ == \"__main__\":\n filename_list = [\"students.csv\", \"marks.csv\", \"tests.csv\", \"courses.csv\"]\n students_df, marks_df, tests_df, courses_df = load_student_files_into_data_frames(filename_list)\n</code></pre>\n\n<p>That's much cleaner, and now we're starting to write our functions in a functional programming style - which is we pass data in, get it modified, and get it passed out again. Nice and clean, and we know exactly what happens to the data where, making it very easy to narrow down bugs. </p>\n\n<p>For instance, the <code>merge_test_marks()</code> function becomes:</p>\n\n<pre><code>def merge_test_marks(marks_df, tests_df):\n return pandas.merge(marks_df, tests_df, left_on=\"test_id\", right_on=\"id\")\n</code></pre>\n\n<p>and if there were any issues with the merging of those two data frames, you know exactly which function was responsible for the bug (rather than having to laboriously step through the code with a debugger to understand where the variable's data state changed wrongly).</p>\n\n<p>So here would be the final version, and whilst I haven't done anything to clean up the <code>print_students_and_course_results</code> function - as we have two internal loops that should be shuffled off to a separate function - I'll leave that as an exercise for you to attempt. Hope this was helpful, here is the final code (PEP8 formatted except I removed the extra line between functions to make it visually shorter):</p>\n\n<pre><code>import pandas\nfrom statistics import mean\n\ndef read_csv(filename):\n return pandas.read_csv(filename)\n\ndef load_student_files_into_data_frames(filename_list):\n return map(read_csv, filename_list)\n\ndef merge_test_marks(marks_df, tests_df):\n return pandas.merge(marks_df, tests_df, left_on=\"test_id\", right_on=\"id\")\n\ndef group_students(marks_tests, students_df, courses_df):\n student_courses = marks_tests.groupby(by=\"student_id\")['course_id'].apply(set)\n students_dict = students_df.set_index(\"id\").to_dict(orient=\"index\")\n courses_dict = courses_df.set_index(\"id\").to_dict(orient=\"index\")\n return student_courses, students_dict, courses_dict\n\ndef print_students_and_course_results(student_courses, students_dict, marks_tests, courses_dict):\n for student_id, course_ids in student_courses.iteritems():\n print(\"Student id: {}, name: {name}\".format(student_id, **students_dict[student_id]))\n final_grades = []\n for course_id in course_ids:\n marks = marks_tests.loc[(marks_tests['course_id'] == course_id) & (marks_tests['student_id'] == student_id)]\n final_grades.append(sum(marks['mark'] * (marks['weight'] / 100.0)))\n\n print(\"Total Average: {:.2f}%\".format(mean(final_grades)))\n for course_id in course_ids:\n print(\" Course: {name}, Teacher: {teacher}\".format(**courses_dict[course_id]))\n marks = marks_tests.loc[(marks_tests['course_id'] == course_id) & (marks_tests['student_id'] == student_id)]\n final_grade = sum(marks['mark'] * (marks['weight'] / 100.0))\n print(\" Final Grade: {:.2f}%\".format(final_grade))\n\nif __name__ == \"__main__\":\n filename_list = [\"students.csv\", \"marks.csv\", \"tests.csv\", \"courses.csv\"]\n students_df, marks_df, tests_df, courses_df = load_student_files_into_data_frames(filename_list)\n marks_tests = merge_test_marks(marks_df, tests_df)\n student_courses, students_dict, courses_dict = group_students(marks_tests, students_df, courses_df)\n print_students_and_course_results(student_courses, students_dict, marks_tests, courses_dict)\n</code></pre>\n\n<p>Keep up the coding and Good Luck!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T05:15:00.710",
"Id": "216964",
"ParentId": "216921",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T12:18:33.337",
"Id": "216921",
"Score": "4",
"Tags": [
"python",
"performance"
],
"Title": "Summing up students by the topics they studied and the marks they got"
} | 216921 |
<p>Here is the problem.</p>
<blockquote>
<p>In a town, there are N people labelled from 1 to N. There is a rumor
that one of these people is secretly the town judge.</p>
<p>If the town judge exists, then:</p>
<p>The town judge trusts nobody.</p>
<p>Everybody (except for the town judge) trusts the town judge.</p>
<p>There is exactly one person that satisfies properties 1 and 2.</p>
<p>You are given trust, an array of pairs trust[i] = [a, b] representing
that the person labelled a trusts the person labelled b.</p>
<p>If the town judge exists and can be identified, return the label of
the town judge. Otherwise, return -1.</p>
<ul>
<li><p>Example 1:</p>
<p>Input: N = 2, trust = [[1,2]]
Output: 2</p></li>
<li><p>Example 2:</p>
<p>Input: N = 3, trust = [[1,3],[2,3]]
Output: 3</p></li>
<li><p>Example 3:</p>
<p>Input: N = 3, trust = [[1,3],[2,3],[3,1]]
Output: -1</p></li>
<li><p>Example 4:</p>
<p>Input: N = 3, trust = [[1,2],[2,3]]
Output: -1</p></li>
<li><p>Example 5:</p>
<p>Input: N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]]
Output: 3</p></li>
</ul>
<p>Note:</p>
<ul>
<li>1 <= N <= 1000</li>
<li>trust.length <= 10000</li>
<li>trust[i] are all different</li>
<li>trust[i][0] != trust[i][1]</li>
<li>1 <= trust[i][0], trust[i][1] <= N</li>
</ul>
</blockquote>
<p>And here is my solution. </p>
<p>(Logic :- Check the degree of every node, +1 for incoming and -1 for outgoing. If any node is having degree as N-1 then that is the node.)</p>
<pre><code>public int findJudge(int N, int[][] trust) {
// Create graph of N and then check degree, should be N-1
final int NOT_FOUND = -1;
final int trustArrayLength = trust.length;
// Degree array should have value starting from 1 to N+1
final int[] degreeArray = new int[N + 1];
for (int i = 0; i < trustArrayLength; i++) {
int[] itemInTrustArray = trust[i];
// Since its outbound connection, decrease the degree by 1.
degreeArray[itemInTrustArray[0]]--;
// Since its inbound connection, increase the degree by 1.
degreeArray[itemInTrustArray[1]]++;
}
// Now iterate though the degreeArray to find the index having degree as N-1.
for (int i = 1; i <= N; i++) {
if (degreeArray[i] == N - 1) {
return i;
}
}
return NOT_FOUND;
}
</code></pre>
<p>Pleae let me know, the area of improvement.</p>
| [] | [
{
"body": "<p>This is a wonderfully succinct solution. I will make one point:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>final int[] degreeArray = new int[N + 1];\n</code></pre>\n\n<p>This creates a never-used int at degreeArray[0]. I understand that this was a choice so as to be able to use a simple access by value of the trustees:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>degreeArray[itemInTrustArray[0]]--;\n</code></pre>\n\n<p>In the interest of creating the minimum number of objects necessary, and thus using the least memory possible, I would recommend initializing degreeArray to length N</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>final int[] degreeArray = new int[N];\n</code></pre>\n\n<p>And then left shifting your insert by value statements</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>degreeArray[itemInTrustArray[0]--]--;\ndegreeArray[itemInTrustArray[1]--]++;\n</code></pre>\n\n<p>and finally updating your final for loop to account for this change to the zero-based indexing inherent to arrays</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>// Now iterate though the degreeArray to find the index having degree as N-1.\nfor (int i = 0; i < N; i++) {\n</code></pre>\n\n<p>Since you are working with int primitives, the math operators here would add only a near-vanishing amount to overall runtime, if that is a concern.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T16:33:53.780",
"Id": "419691",
"Score": "0",
"body": "Thank you, it was really helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-11T14:15:27.213",
"Id": "471382",
"Score": "0",
"body": "Great!! solution as I wondering why everyone is initializing it as N+1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-11T14:30:39.970",
"Id": "471383",
"Score": "0",
"body": "Great!! but this doesn't work, can you please share full code"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T15:50:53.107",
"Id": "216930",
"ParentId": "216926",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216930",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T14:14:25.383",
"Id": "216926",
"Score": "2",
"Tags": [
"java",
"algorithm",
"programming-challenge",
"graph"
],
"Title": "Leetcode online Find the judge, graph with highest degree"
} | 216926 |
<p>I have the following tables in my database:</p>
<pre><code>people: phones:
+----+------+ +-----------+------------+-------------+
| id | name | | person_id | number | description |
+----+------+ +-----------+------------+-------------+
| 1 | Jade | | 1 | 1234567890 | home |
| 2 | Ben | | 1 | 987654321 | office |
+----+------+ +-----------+------------+-------------+
</code></pre>
<p>I use a query with <code>INNER JOIN</code> to select the name and phone numbers for each person:</p>
<pre><code>SELECT
id,
name,
group_concat(
concat(
number,
' (',
description,
')'
) ORDER BY description SEPARATOR ','
) AS phones
FROM people INNER JOIN phones
ON person_id = id
GROUP BY id;
</code></pre>
<p>Results from the above query:</p>
<pre><code>+----+------+--------------------------------------+
| id | name | phones |
+----+------+--------------------------------------+
| 1 | Jade | 1234567890 (home),987654321 (office) |
+----+------+--------------------------------------+
</code></pre>
<p>But I want to use this query to go through all the people in my database and not just the ones with phone numbers, so I added the following row to the phones table:</p>
<pre><code>INSERT INTO phones VALUES (0, 0, NULL);
</code></pre>
<p>And then modified the <code>ON</code> statement of the query to:</p>
<pre><code>ON person_id = id OR person_id = 0
</code></pre>
<p>That way every person gets selected even if he has no phone numbers registered in the database:</p>
<pre><code>+----+------+--------------------------------------+
| id | name | phones |
+----+------+--------------------------------------+
| 1 | Jade | 1234567890 (home),987654321 (office) |
| 2 | Ben | NULL |
+----+------+--------------------------------------+
</code></pre>
<p>Is this a proper way to achieve this? I don't really like the idea of having to make sure that the <code>0, 0, NULL</code> row will always stay in the database in order to ensure the queries will work as intended. (since the company I develop this for might decide to clear the database)</p>
<p>This implementation requires calling an <code>ensureNullRow()</code> function every time before using this query, is this a good solution or would you do it differently?</p>
| [] | [
{
"body": "<p>What you are describing is known as<code>LEFT OUTER JOIN</code></p>\n\n<pre><code>SELECT\n id,\n name, \n group_concat(\n concat(\n number,\n ' (',\n description,\n ')'\n ) ORDER BY description SEPARATOR ','\n ) AS phones\nFROM people LEFT OUTER JOIN phones\nON person_id = id\nGROUP BY id;\n</code></pre>\n\n<p><code>inner join</code> => give me only rows with records in both tables<br>\n<code>left outer join</code> => give me all rows of from the left table along with any matching rows in the right..</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T14:41:30.563",
"Id": "216928",
"ParentId": "216927",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216928",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T14:23:36.157",
"Id": "216927",
"Score": "1",
"Tags": [
"sql",
"join"
],
"Title": "Listing people with their phone numbers (if any)"
} | 216927 |
<p>This is my first question here and this is my working Body Mass Index Swing Calculator.
Any improvement or recommendation is welcome.</p>
<pre><code>// Metric units
// Weight in kg
// Height in meters
import javax.swing.*;
import java.awt.*;
public class MainProgram {
public static void calculateIMC(DataPanel in){
String salida = in.weight.getText();
System.out.print(salida);
}
public static void main(String[] args) {
JFrame frame = new JFrame("BMI");
DataPanel in = new DataPanel();
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setBounds(150,150,500,400);
frame.setLayout(new GridLayout(0,2));
// frame.pack();
frame.add(in);
System.out.println(Grade.getGrade(33.4));
}
}
</code></pre>
<p>This is an enum example</p>
<pre><code>public enum Grade {
INS("Insuficient Weight",18.5),
NRM("Normal Wight",24.9),
SBR1("Overweight Grade 1",26.9),
SBR2("Overweight Grade 2: Probesity",29.9),
OBS1("Obesity Grade 1",34.9),
OBS2("Obesity Grade 2",3.9),
OBS3("Obesity Grade 3: Morbid",49.9),
OBS4("Obesity Grade 4: Extreme",50);
private final String title;
private final double lim;
public String getTitle() {
return title;
}
public double getLim() {
return lim;
}
Grade(String s, double i) {
title = s;
lim = i;
}
public static String getGrade(double value){
for (int i=0; i < Grade.values().length;i++){
if(value > Grade.OBS4.getLim()){
return Grade.OBS4.getTitle();
} else if(value < Grade.INS.getLim()){
return Grade.INS.getTitle();
} else if(value > Grade.values()[i].getLim() && value < Grade.values()[i+1].getLim()){
return Grade.values()[i+1].getTitle();
}
}
return null;
}
}
</code></pre>
<p>And the Panel</p>
<pre><code>import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class DataPanel extends JPanel {
JTextField weight = new JTextField(10);
JTextField height = new JTextField(10);
JButton calculate = new JButton("Calculate");
DataPanel(){
initialize();
}
private void initialize() {
add(new JLabel("Weight: "));
add(weight);
add(new JLabel("Height: "));
add(height);
add(calculate);
calculate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
double w=Double.parseDouble(weight.getText());
double h=Double.parseDouble(height.getText());
double bmi=w/(h*h);
JOptionPane.showMessageDialog(null,"Your BMI is: "+String.format("%.2f",bmi));
JOptionPane.showMessageDialog(null,"Your Grade is: "+Grade.getGrade(bmi));
}
});
setVisible(true);
setBorder(BorderFactory.createTitledBorder("BMI"));
// setBounds();
// setLayout(new GridLayout(0,2));
setMaximumSize(new Dimension(30,100));
}
}
</code></pre>
| [] | [
{
"body": "<blockquote>\n<pre><code> for (int i=0; i < Grade.values().length;i++){\n if(value > Grade.OBS4.getLim()){\n return Grade.OBS4.getTitle();\n } else if(value < Grade.INS.getLim()){\n return Grade.INS.getTitle();\n } else if(value > Grade.values()[i].getLim() && value < Grade.values()[i+1].getLim()){\n return Grade.values()[i+1].getTitle();\n }\n }\n</code></pre>\n</blockquote>\n\n<p>You don't need the first two conditions in the <code>for</code> loop. You can instead say </p>\n\n<pre><code> if (value > Grade.OBS4.getLim()) {\n return Grade.OBS4.getTitle();\n }\n\n if (value < Grade.INS.getLim()) {\n return Grade.INS.getTitle();\n }\n\n for (int i = 1; i < Grade.values().length; i++) {\n if (value > Grade.values()[i - 1].getLim() && value < Grade.values()[i].getLim()) {\n return Grade.values()[i].getTitle();\n }\n }\n</code></pre>\n\n<p>This is because those two conditions are invariant relative to the loop. They'll either be true the first time or they will never be true. Since you are returning, an <code>else</code> is unnecessary (although harmless if you prefer it). </p>\n\n<p>We don't need to check <code>i</code> equal to 0, as there is no -1 grade. We instead just check the insufficient grade before the loop. </p>\n\n<p>If the BMI grade is exactly equal to the border marker, you'll fall through to the <code>null</code> case. You should make one of those inequalities \"or equal to\", i.e. <code>>=</code> or <code><=</code>. Which one depends on the exact rules, which you don't include in your question. I'm going to choose <code>>=</code>. </p>\n\n<pre><code> for (Grade grade : Grade.values()) {\n if (value < grade.getLim()) {\n return grade.getTitle();\n }\n }\n\n return Grade.OBS4.getTitle();\n</code></pre>\n\n<p>You may need to change your limits to match. </p>\n\n<p>Now we don't do any checks outside the loop. And we don't need to compare across grades. We know it's greater than or equal to previous grades, as if it were less than, we would already have returned. </p>\n\n<p>If we fall through the loop, we know that the value represents extreme obesity. </p>\n\n<p>I've added some additional whitespace for readability. </p>\n\n<p>I would prefer to replace <code>Lim</code> with <code>Limit</code> for readability. </p>\n\n<p>You can also use a <code>NavigableMap</code> here. See <a href=\"https://codereview.stackexchange.com/a/142752/71574\">here</a> for an example on a similar problem. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T17:22:13.243",
"Id": "216937",
"ParentId": "216933",
"Score": "1"
}
},
{
"body": "<p>In your <code>main()</code> function, you create your <code>JFrame</code> and make it visible, and then proceed to set its bounds, its layout and add content to it. This is dangerous behaviour. Swing requires all GUI interaction to be performed on Swing’s Event Dispatching Thread (EDT).</p>\n\n<p>You can improve the safety by creating the <code>JFrame</code>, setting its bounds, its layout, adding content to it, and finally, only after all other configuration has been done, calling <code>frame.setVisible(true);</code>.</p>\n\n<p>But you really should switch to the EDT, using <code>SwingUtilities.invokeLater(...)</code>.</p>\n\n<pre><code>public class MainProgram {\n public static void main(String[] args) {\n SwingUtilities.invokeLater( new Runnable() {\n @Override\n public void run() {\n // ... your GUI creation code here, ending with ...\n frame.setVisible();\n }\n });\n }\n}\n</code></pre>\n\n<p>Using lambda syntax makes this easier:</p>\n\n<pre><code>public class MainProgram {\n public static void main(String[] args) {\n SwingUtilities.invokeLater(MainProgram::createGUI);\n }\n\n private static void createGUI() {\n // ... your GUI creation code here, ending with ...\n frame.setVisible();\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T06:31:53.763",
"Id": "216999",
"ParentId": "216933",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T16:16:53.783",
"Id": "216933",
"Score": "2",
"Tags": [
"java",
"swing",
"enum"
],
"Title": "Java Swing Exercise: BMI Calculator"
} | 216933 |
<p><a href="https://i.stack.imgur.com/1zLwz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1zLwz.png" alt="enter image description here"></a></p>
<p>This has been my white whale for a while, the idea is convert all the symbols to the goal symbol using <strong>all</strong> the pieces.</p>
<p>I did an algorithm like 5 years ago (now is lost) and reach lvl 48 but got stuck here and drop. After I watch The Imitation Game and see how Turin solve enigma using a Heil Hitler to reduce the space search I decide give it a second try.</p>
<p>I try solve row by row. First you have to see how many flips each row need and then found a set of pieces with enough squares to flip all symbols or a multiple of the symbol cycle (in this case 3)</p>
<p>In the orginal version when I found a set I try to place the pieces on each column to see if can solve the row if that happen then can go to the next row. Now I dont try to solve it but directly try to go to the next row with less pieces. Not sure what is the best aproach.</p>
<p>With those 18 pieces you 6.5E25 combinations to place them on the board (consider engima machine has 15E18). But if you try to solve only the flips on the first row you have 2^18 = 262k set combinations, of those only 84k has the correct amount of flips. That is the biggest prunning I could found.</p>
<p>My hope is there is some algorithm to allow me reduce even more the search space or some optimization I can use to improve the search speed.</p>
<p><strong>How I model the problem:</strong></p>
<p>First I define pieces/shape as an array of how many flips can the piece do for each row. So the first piece (the one looking like a sail boat) has 2 flips in 1st, 2nd and 3rd row. The second piece (machine gun) has 2 flips on 1st row, 4 on second row and 1 on 3rd and 4th.</p>
<p>I convert the board to number of flips for each row. The <code>crown</code> need 2 flips to reach <code>sword</code> (goal) <code>cups</code> need one flip.</p>
<p>I assign to each piece an ID = 2^0, 2^1, 2^2, 2^3, ..... 2^18 </p>
<p>Here is the prunning I came with. I create set of pieces (in total you have 2^18 = 265k combinations of pieces) where the sum of flips on the pieces match the number of flips for the row. </p>
<p>Is possible you can have a solution with the right amount of flips but there isnt possible place them on the board in a way to reach goal for all the row. That testing should be done in a later process rigth now just try to discard solution doesnt even have the right amount of flips.</p>
<p>Of course if you use 0 pieces you can't solve 1st row, and if you use all the pieces on 1st row you wont have pieces to solve the bottom rows. </p>
<p>So lets analyze 1st row: You need a solution with at least 6 flips or (6 + 3*x) flips. If you spend one extra flip on a <code>sword</code> that become <code>crown</code> and then need 2 more to return to <code>sword</code>.</p>
<p>One possible combination with 6 flips is {5,6,9}:</p>
<p><a href="https://i.stack.imgur.com/cM6P4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cM6P4.png" alt="enter image description here"></a></p>
<p>But those pieces can't reach the first crown on the row. One posible solution using pieces {1,3,4} </p>
<p><a href="https://i.stack.imgur.com/z7jEv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z7jEv.png" alt="enter image description here"></a></p>
<p>With the first piece convert the 2 <code>crowns</code> to <code>cups</code> and with the other 2 form a line to convert all 4 to <code>swords</code>. In this case my solution now has <code>id = 2^0 + 2^3 + 2^4 = 25</code></p>
<p>Now we start looking the second row we need 7 flips, but from previous solution we already have 7 flips beign apply to second row so now we start looking for solution for the second row need to have 0 flips or 3*x flips. </p>
<p>I keep adding pieces to each row until I "flip solve" each row. If i reach last row, use all pieces and every row has the right amount of flips then I proced to test each position. ( I didnt reach this point )</p>
<p>Now another filter is if are trying to solve the 6th row and you realize you havent place the 2nd piece (heigh = 4) you know wont be a valid solution because you wont be able to place that piece.</p>
<p>If want you can see the game in action here: <a href="http://www.neopets.com/medieval/shapeshifter.phtml" rel="nofollow noreferrer">http://www.neopets.com/medieval/shapeshifter.phtml</a>, <strong>need create an user</strong> first levels doesnt even need a program you can solve by hand.</p>
<blockquote>
<p><code>Shape</code></p>
</blockquote>
<pre><code>[Serializable()]
public class Shape : ICloneable
{
public int Height { get; set; }
public int Width { get; set; } // I will use Width to test by column later
public int[] Changes { get; set; } // How many flips
public long Id { get; set; }
public int RowPosition { get; set; } // In what Row Im using the piece
public int MaxRow { get; set; } // What is the last row where can fit
public Shape(double id, int[] piece, int height)
{
Changes = piece;
Height = height;
Id = (long)id;
RowPosition = -1;
MaxRow = 8 - height;
}
public object Clone()
{
return this.MemberwiseClone();
}
}
</code></pre>
<blockquote>
<p><code>Solution</code></p>
</blockquote>
<pre><code>[Serializable()]
public class Solution : ICloneable
{
private readonly int[] Game = new int[8] { 3, 8, 6, 7, 7, 8, 9, 7 };
public List<Shape> Pieces { get; set; }
public long Id { get; set; }
public Solution()
{
Pieces = new List<Shape>();
}
// Return a deep clone of an object of type T.
public object DeepClone()
{
using (MemoryStream memory_stream = new MemoryStream())
{
// Serialize the object into the memory stream.
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(memory_stream, this);
// Rewind the stream and use it to create a new object.
memory_stream.Position = 0;
return (Solution)formatter.Deserialize(memory_stream);
}
}
public bool TestRowFlips(int row)
{
int[] Changes = new int[8] { 0, 0, 0, 0, 0, 0, 0, 0 };
foreach (Shape p in Pieces)
{
for (int i = 0; i < p.Height; i++)
{
Changes[ i + p.RowPosition ] += p.Changes[i];
}
}
if ((Changes[row] - Game[row]) % 3 == 0)
{
return true;
}
else
{
return false;
}
}
public bool ExistPiece(long id)
{
return Pieces.Any(x => x.Id == id);
}
}
</code></pre>
<blockquote>
<p><code>Recursive</code></p>
</blockquote>
<pre><code>class Recursive
{
private List<Shape> Pieces { get; set; }
public void Setup()
{
Pieces = new List<Shape>
{
new Shape(Math.Pow( 2, 0 ), new int[5] { 2, 1, 2, 0, 0 }, 3),
new Shape(Math.Pow( 2, 1 ), new int[5] { 2, 1, 0, 0, 0 }, 2),
new Shape(Math.Pow( 2, 2 ), new int[5] { 2, 2, 2, 0, 0 }, 3),
new Shape(Math.Pow( 2, 3 ), new int[5] { 3, 1, 3, 0, 0 }, 3),
new Shape(Math.Pow( 2, 4 ), new int[5] { 4, 3, 3, 3, 0 }, 4),
new Shape(Math.Pow( 2, 5 ), new int[5] { 3, 0, 0, 0, 0 }, 1),
new Shape(Math.Pow( 2, 6 ), new int[5] { 3, 1, 3, 0, 0 }, 3),
new Shape(Math.Pow( 2, 7 ), new int[5] { 3, 4, 1, 2, 2 }, 5),
new Shape(Math.Pow( 2, 8 ), new int[5] { 1, 0, 0, 0, 0 }, 1),
new Shape(Math.Pow( 2, 9 ), new int[5] { 2, 2, 2, 0, 0 }, 3),
new Shape(Math.Pow( 2, 10 ), new int[5] { 2, 3, 4, 0, 0 }, 3),
new Shape(Math.Pow( 2, 11 ), new int[5] { 1, 3, 1, 3, 2 }, 5),
new Shape(Math.Pow( 2, 12 ), new int[5] { 1, 2, 2, 0, 0 }, 3),
new Shape(Math.Pow( 2, 13 ), new int[5] { 2, 4, 1, 1, 0 }, 4),
new Shape(Math.Pow( 2, 14 ), new int[5] { 1, 2, 1, 0, 0 }, 3),
new Shape(Math.Pow( 2, 15 ), new int[5] { 1, 1, 3, 0, 0 }, 3),
new Shape(Math.Pow( 2, 16 ), new int[5] { 3, 2, 3, 1, 0 }, 4),
new Shape(Math.Pow( 2, 17 ), new int[5] { 1, 3, 2, 2, 0 }, 4)
};
// try to solve first row
for (long PieceSet = 0; PieceSet < Math.Pow(2, 18); PieceSet++)
{
Solution solution = new Solution();
foreach (Shape piece in Pieces)
{
if ((piece.Id & PieceSet) > 0)
{
Shape p = (Shape)piece.Clone();
p.RowPosition = 0;
solution.Pieces.Add(p);
}
}
if (solution.TestRowFlips(0))
{
solution.Id = PieceSet;
Solve_Row(solution, 1);
}
}
}
public bool Solve_Row(Solution solution, int rowToSolve)
{
// Check the unused pieces to see if are too big to be used on any other row.
if (Pieces.Any(x => (x.Id & solution.Id) == 0 && x.MaxRow < rowToSolve))
{
return false;
}
for (long pieceSet = 0; pieceSet < Math.Pow(2, 18); pieceSet++)
{
if ((pieceSet & solution.Id) == 0)
{
Solution newSolution = (Solution)solution.DeepClone();
foreach (Shape piece in Pieces.Where(x => (x.Id & pieceSet) > 0)
.ToList())
{
Shape p = (Shape)piece.Clone();
p.RowPosition = rowToSolve;
newSolution.Pieces.Add(p);
}
newSolution.Id = newSolution.Id | pieceSet;
if (newSolution.Id == Pieces.Sum(x => x.Id))
{
Debug.Print("Found a Solution");
return true;
}
if (newSolution.TestRowFlips(rowToSolve))
{
Solve_Row(newSolution, rowToSolve + 1);
}
}
}
return false;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T19:53:06.473",
"Id": "420323",
"Score": "0",
"body": "My main interest is find out if there is an algorithm allowing to reduce the space search so the brute force part can finish in my lifetime. But any suggestion on optimizations are welcome. In the boardgame there is already people finish this game so I know is possible solve it. Also I saw another app where you have to put runes in a monster to improve their stats and the number of combinations is also very big and the app is very fast."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T07:35:41.123",
"Id": "420361",
"Score": "0",
"body": "I'm pretty sure you can calculate how many possible combinations there are and how long it would take to generate them all so let's wait for a math guru to show us how it goes ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T08:42:36.033",
"Id": "420377",
"Score": "0",
"body": "@t3chb0t I Include some numbers in the post 6e25 without prunning. If you test 1 each ms would take 1.9e15 years"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T08:47:43.760",
"Id": "420378",
"Score": "0",
"body": "I don't see an explanation of the task you're trying to solve, which makes it hard to review the code and even harder to suggest algorithmic improvements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T08:48:40.963",
"Id": "420379",
"Score": "0",
"body": "@PeterTaylor do you want more explanation about the puzzle or about the code? I include a description about both but can elaborate"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T08:53:04.723",
"Id": "420380",
"Score": "0",
"body": "I definitely need an explanation of the puzzle. (It's not a case of \"more\": I can't see *any* at present). I don't see any comments explaining the data representation in the code, so that would also be useful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T09:49:22.050",
"Id": "420391",
"Score": "0",
"body": "@PeterTaylor Check again and let me know if is more clear now. Im going to bed for now."
}
] | [
{
"body": "<h2>Shape</h2>\n\n<blockquote>\n<pre><code> [Serializable()]\n</code></pre>\n</blockquote>\n\n<p>The <code>()</code> is unnecessary and it's usual to omit it for readability.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public class Shape : ICloneable\n</code></pre>\n</blockquote>\n\n<p><code>ICloneable</code> is from the very early days of C# before they added generics (for which read \"<em>a half-decent type system</em>\"). I would strongly recommend never using it in new code. Make your own</p>\n\n<pre><code>public interface ICloneable<T>\n{\n T Clone();\n}\n</code></pre>\n\n<p>so that you can avoid all the casts. Or just add the <code>Clone</code> method without a marker interface.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public int Height { get; set; }\n public int Width { get; set; } // I will use Width to test by column later\n public int[] Changes { get; set; } // How many flips \n public long Id { get; set; }\n public int RowPosition { get; set; } // In what Row Im using the piece\n public int MaxRow { get; set; } // What is the last row where can fit \n</code></pre>\n</blockquote>\n\n<p>Why are these all settable? As far as I can see, <code>RowPosition</code> is the only one that is set anywhere outside the constructor, so I think that they should either have <code>private set;</code> or (if you're using a recent enough version of C#) use the <code>public int Height { get; } = height</code> syntax.</p>\n\n<p>Why is <code>Changes</code> an <code>int[]</code>? That allows callers to modify it. I think that <code>IReadOnlyList<int></code> would probably convey the intent more clearly.</p>\n\n<p>I said that <code>RowPosition</code> is the only one of these that is set anywhere outside the constructor. In fact, it's only ever set immediately after cloning. I suggest replacing <code>Clone()</code> with a copy constructor. (This may force using <code>private set</code> or a backing <code>readonly</code> field: I don't think it plays well with <code>{ get; } =</code>).</p>\n\n<p>Alternatively, go for a purer object model: the <code>RowPosition</code> is not strictly a property of the shape. You could factor it out and work with some kind of tuple <code>(Shape, Location)</code> or <code>Dictionary<Shape, Location></code>.</p>\n\n<p><code>Changes</code> and <code>Id</code> could use documentation on their interpretation. If I've understood correctly, both are bitmasks: state that clearly. It might be a good idea to make the constructor validate that <code>Id</code> is a single bit:</p>\n\n<pre><code>if (id == 0 || (id & (id - 1)) != 0) throw new ArgumentOutOfRangeException(nameof(id));\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> public Shape(double id, int[] piece, int height)\n</code></pre>\n</blockquote>\n\n<p><code>id</code> should be a <code>long</code>, not a <code>double</code>.</p>\n\n<hr>\n\n<h2>Solution</h2>\n\n<p>Some previous comments apply.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public long Id { get; set; }\n</code></pre>\n</blockquote>\n\n<p>I think this is a mask indicating which pieces are present. The name should reflect that.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public object DeepClone()\n {\n using (MemoryStream memory_stream = new MemoryStream())\n {\n // Serialize the object into the memory stream.\n BinaryFormatter formatter = new BinaryFormatter();\n formatter.Serialize(memory_stream, this);\n\n // Rewind the stream and use it to create a new object.\n memory_stream.Position = 0;\n return (Solution)formatter.Deserialize(memory_stream);\n }\n }\n</code></pre>\n</blockquote>\n\n<p>This is quite clever and robust to changes, but also slow. Given that time is your biggest enemy, I think it might be better to use a more brittle but faster approach.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if ((Changes[row] - Game[row]) % 3 == 0)\n {\n return true;\n }\n else\n {\n return false;\n }\n</code></pre>\n</blockquote>\n\n<p>This is more readable as</p>\n\n<pre><code> return (Changes[row] - Game[row]) % 3 == 0;\n</code></pre>\n\n<p>Also, this method calculates <code>Changes</code> to then ignore all but <code>Changes[row]</code>. That's an easy place to optimise.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public bool ExistPiece(long id)\n {\n return Pieces.Any(x => x.Id == id);\n }\n</code></pre>\n</blockquote>\n\n<p>I think this should be called <code>ContainsPiece</code>, and I also think that it could be optimised to <code>return (this.Id & id) != 0;</code>, assuming that I've correctly understood the invariants about <code>Solution.Id</code>.</p>\n\n<hr>\n\n<h2>Recursive</h2>\n\n<blockquote>\n<pre><code> new Shape(Math.Pow( 2, 0 ), new int[5] { 2, 1, 2, 0, 0 }, 3),\n</code></pre>\n</blockquote>\n\n<p>(and lots of similar lines). Firstly, don't use <code>Math.Pow</code> unless you're dealing with <code>double</code>s. For bitmasks <code><<</code> and <code>>></code> should be enough. Secondly, why the trailing zeroes and a separate argument to say how long it is? This looks to me like it should be</p>\n\n<pre><code> new Shape(1L << 0, new int[] { 2, 1, 2 }),\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> // try to solve first row\n</code></pre>\n</blockquote>\n\n<p>Is there any reason why this can't be done with a line or two of setup and a call to <code>Solve_Row(solution, 0)</code>?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public bool Solve_Row(Solution solution, int rowToSolve)\n {\n ...\n\n for (long pieceSet = 0; pieceSet < Math.Pow(2, 18); pieceSet++)\n { \n if ((pieceSet & solution.Id) == 0)\n {\n ...\n }\n }\n return false;\n }\n</code></pre>\n</blockquote>\n\n<p>This is extremely inefficient. I suggest that you first create a method <code>public static IEnumerable<IEnumerable<T>> Subsets<T>(IEnumerable<T> elements)</code> which uses a technique like this to generate all subsets of its argument. (Use <code>yield return</code> to keep the memory usage low). Then you can make this loop iterate only over subsets of the pieces which aren't already included. It probably still won't be fast enough, but it will at least be much faster.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> foreach (Shape piece in Pieces.Where(x => (x.Id & pieceSet) > 0)\n .ToList())\n</code></pre>\n</blockquote>\n\n<p>I suggest you factor out a method <code>IEnumerable<Shape> PiecesForMask(int pieceSet)</code>. Then it can be faster by using a <code>Dictionary<long, Shape></code> to map IDs to shapes and using the standard trick that <code>x & -x</code> is the lowest set bit of <code>x</code> to run in time proportional to the number of pieces in <code>pieceSet</code> rather than iterating through all of them.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if (newSolution.Id == Pieces.Sum(x => x.Id))\n</code></pre>\n</blockquote>\n\n<p>This is another easy optimisation: calculate the target mask once and store it. (Or calculate it on the fly as <code>(1L << Pieces.Count) - 1</code>).</p>\n\n<hr>\n\n<p>One big thing that's missing is comments. A simple explanation of what the code is trying to do (which I think is to find a mapping which places every piece in one row such that the sums all add up to desired values modulo 3) would go a long way, along with clear identification of which <code>int</code>s represent counts and which represent bitmasks.</p>\n\n<hr>\n\n<p>Finally, the big question: the algorithm. I suspect that the test applied (<code>(Changes[row] - Game[row]) % 3 == 0</code>) is actually overly optimistic. Probably you also need <code>Changes[row] >= Game[row]</code>. If so, I would look at reformulating the problem as a set multicover and solving it with a variant of <a href=\"https://en.wikipedia.org/wiki/Dancing_Links\" rel=\"noreferrer\">Knuth's Algorithm X</a>. Probably you should first try to understand the basic algorithm for set cover and the formulation of simple puzzles as set cover. Then look at expanding to multicover. The idea would be that a cell which needs to be covered <span class=\"math-container\">\\$a + 3k\\$</span> times (for any <span class=\"math-container\">\\$k \\ge 0\\$</span>) would become an element which needs to be covered <span class=\"math-container\">\\$a + 3K\\$</span> for a suitably large <span class=\"math-container\">\\$K\\$</span> (maybe iterative deepening would be a sensible approach; alternatively, making <span class=\"math-container\">\\$K\\$</span> the number of shapes is definitely sufficiently conservative); also, each shape needs to be covered once (it must be used in exactly one place). The placement of a shape in a position is a row which can be used in the cover: it covers the shape and the board elements (with multiplicity). Then there are some utility rows which cover one element 3 times and take up the slack. If you don't actually need to use all the shapes (I think you have to take them in order when playing, but can you stop early?) then that could be handled with rows which just cover the last <span class=\"math-container\">\\$i\\$</span> shapes and no board elements.</p>\n\n<p>Looking at Knuth's <a href=\"https://www-cs-faculty.stanford.edu/~knuth/programs.html\" rel=\"noreferrer\">downloadable programs</a> starting with DLX I see there are some new variants since I last read the draft of <a href=\"https://www-cs-faculty.stanford.edu/~knuth/fasc5c.ps.gz\" rel=\"noreferrer\">fascicle 4C of the Art of Computer Programming</a>. I strongly recommend you download that and dedicate a good 10 hours to reading and understanding it: it's a very good technique for many kinds of puzzle.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T14:32:20.810",
"Id": "420424",
"Score": "0",
"body": "You need to use all the pieces."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T12:20:20.273",
"Id": "420534",
"Score": "0",
"body": "Eric Lippert had a great series of articles that used Immutable collections to create subsets/permutations/combinations that was extremely fast. I wonder if that could be leveraged here *somehow*"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T12:56:03.153",
"Id": "420539",
"Score": "2",
"body": "@pinkfloydx33, I doubt it. The problem is almost certainly NP-complete, so finding a good heuristic is far more useful than optimising a brute force search."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T12:35:30.200",
"Id": "217321",
"ParentId": "216934",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "217321",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T16:30:01.280",
"Id": "216934",
"Score": "6",
"Tags": [
"c#",
"performance",
"algorithm",
"recursion",
"combinatorics"
],
"Title": "Best way to performance permutations"
} | 216934 |
<p>I created a morse converter from a .txt file.</p>
<p>I'm learning java and I created a simple morse converter. Convert only A to Z and 0 to 9 chars. Space char remain for split words in morse-code.
At the beginning I used a big switch for any letters or number but it was no good.</p>
<pre><code>public static String toMorse(byte[] bytes) {
String text = new String(bytes);
String morseText = "";
text = text.toLowerCase();
String[] morseChar
= {".-",
"-...",
"-.-.",
"-..",
".",
"..-.",
"--.",
"....",
"..",
".---",
"-.-",
".-..",
"--",
"-.",
"---",
".--.",
"--.-",
".-.",
"...",
"-",
"..-",
"...-",
".--",
"-..-",
"-.--",
"--.."};
String[] morseNumber
= {".----",
"..---",
"...--",
"....-",
".....",
"-....",
"--...",
"---..",
"----.",
"-----"};
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) >= 'a' && text.charAt(i) <= 'z') {
morseText = morseText + morseChar[text.charAt(i) - 'a'];
} else if (text.charAt(i) >= '0' && text.charAt(i) <= '9') {
morseText = morseText + morseNumber[text.charAt(i) - '0'];
} else if (text.charAt(i) == ' ') {
morseText = morseText + text.charAt(i);
}
}
return morseText;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T06:06:25.433",
"Id": "419945",
"Score": "0",
"body": "Your mapping for numbers is incorrect, BTW."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T11:13:08.840",
"Id": "419980",
"Score": "0",
"body": "Apart from some inefficiency, pointed out in multiple answers, this code is **incorrect**. Please fix it before the question gets [put on hold](https://codereview.stackexchange.com/help/closed-questions) as off-topic."
}
] | [
{
"body": "<p>Hello and Welcome to Code Review!</p>\n\n<p>Just one suggestion:</p>\n\n<p>Your for loop at the bottom performs the same method calls several times. Its performance could be improved if you slightly retooled your loop like so:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>int charCount = text.length;\nfor (int i = 0; i < charCount; i++) {\n char currentChar = text.charAt(i);\n if (currentChar >= 'a' && currentChar <= 'z') {\n morseText = morseText + morseChar[currentChar - 'a'];\n } else if (currentChar >= '0' && currentChar <= '9') {\n morseText = morseText + morseNumber[currentChar - '0'];\n } else if (currentChar == ' ') {\n morseText = morseText + currentChar;\n }\n }\n}\n</code></pre>\n\n<p>By pulling these method calls up as variables, the number of calls your loop makes is significantly decreased. Your version calls text.length at the top of each iteration of the loop, and text.charAt(i) <s>eight</s> up to 6 times per loop. With this change you would call length once total, and text.charAt only once per loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T18:47:34.480",
"Id": "419599",
"Score": "0",
"body": "Thanks. I improved my code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T09:56:02.157",
"Id": "419966",
"Score": "0",
"body": "Minor correction: the original loop invokes `text.charAt(i)` up to 6 times per iteration, not 8. Those are 5 times per all `if`-s and once in the conditional branch (it will never execute all three branches in a single iteration!) And those 5 only if the analyzed character is not a letter nor a digit. So a text consisting of, say, 70% letters, 10% digits and 20% spaces will require, on average, 3.8 calls to `text.charAt(i)` per character loop. Anyway it's still worth reducing to 1. Upvoted."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T18:34:24.960",
"Id": "216940",
"ParentId": "216938",
"Score": "5"
}
},
{
"body": "<p>I'd suggest adding a comment mentioning how the order of values in the arrays <code>morseChar</code> and <code>morseNumber</code> are important for the conversion.</p>\n\n<p>At first glance I was confused how the conversion was being done.</p>\n\n<p>You should declare <code>morseChar</code> and <code>morseNumber</code> as final class variables so they are easily visible & can be used in other methods.</p>\n\n<p>If you may add symbols to the code, a class or enum containing the MorseCode and english character can be added. This also makes the opposite conversion very easy.</p>\n\n<pre><code> // Note: Simply add numbers and symbols to this enum. \n // The Order does not matters.\n public enum MorseCharacter\n {\n A(\".-\", 'a'),\n B(\"-...\", 'b'),\n C(\"-.-.\", 'c'),\n D(\"-..\", 'd'),\n E(\".\", 'e'),\n F(\"..-.\", 'f'),\n G(\"--.\", 'g'),\n H(\"....\", 'h'),\n I(\"..\", 'i'),\n J(\".---\", 'j'),\n K(\"-.-\", 'k'),\n L(\".-..\", 'l'),\n M(\"--\", 'm'),\n N(\"-.\", 'n'),\n O(\"---\", 'o'),\n P(\".--.\", 'p'),\n Q(\"--.-\", 'q'),\n R(\".-.\", 'r'),\n S(\"...\", 's'),\n T(\"-\", 't'),\n U(\"..-\", 'u'),\n V(\"...-\", 'v'),\n W(\".--\", 'w'),\n X(\"-..-\", 'x'),\n Y(\"-.--\", 'y'),\n Z(\"--..\", 'z');\n\n private final String morseCode;\n private final char character;\n private static final MorseCharacter[] ALL_VALUES = values();\n\n MorseCharacter(String morseCode, char character)\n {\n this.morseCode = morseCode;\n this.character = character;\n }\n\n public String getMorseCode()\n {\n return morseCode;\n }\n\n public char getCharacter()\n {\n return character;\n }\n\n public static MorseCharacter valueOf(char character)\n {\n for (MorseCharacter morseChar : ALL_VALUES)\n {\n if (morseChar.getCharacter() == character)\n {\n return morseChar;\n }\n }\n\n throw new RuntimeException(\"Morse character not found: \" + character);\n }\n }\n\n public static String toMorse(String text) \n {\n String morseText = \"\";\n text = text.toLowerCase();\n\n for (int i = 0; i < text.length(); i++) \n {\n morseText += MorseCharacter.valueOf(text.charAt(i)).getMorseCode();\n }\n return morseText;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T06:27:55.740",
"Id": "419725",
"Score": "0",
"body": "Why the setter methods in an enum? Haven't seen that before."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T14:55:25.757",
"Id": "419745",
"Score": "0",
"body": "@TomG Good point, updated"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T07:11:46.833",
"Id": "419835",
"Score": "2",
"body": "This is fairly inefficient. While finding the morse code is already O(N) the enum.values() creates a clone of the internal array. So you'll be doing a lot of repetitive memory allocation. I would use Map instead or use an array like OP did (but hidden behind a dedicated obect that does error checking)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T08:32:26.457",
"Id": "419843",
"Score": "0",
"body": "Also, naming the field as asciiCharacter is a bit misleading as the value it represents is already a decoded Java character, not an ASCII encoded binary value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T13:04:55.613",
"Id": "419866",
"Score": "0",
"body": "You could create a variable for the values to ensure it's only created once if you're converting massive amounts of text. I'll update the code again"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T05:03:06.597",
"Id": "419939",
"Score": "1",
"body": "You're stil doing O(N) for an O(1) job. How much would you have to extend an enumeration with non-standard functionality to realize an enum is not a good tool for this job?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T10:28:20.500",
"Id": "419975",
"Score": "0",
"body": "Could you, please, specify, what exactly do you expect in _'a comment mentioning how the order of values in the arrays `morseChar` and `morseNumber` are important for the conversion'_...? As far as I can see there is no importance here, except that it allows direct access through indexing instead of through searching. What do I miss?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T12:56:05.103",
"Id": "419998",
"Score": "0",
"body": "@CiaPan was referring to the original post. If you change the order of either array it no longer works."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T14:35:56.493",
"Id": "420017",
"Score": "0",
"body": "@dustytrash Well... I can't see a purpose of such comment. From my experience, in almost all programs almost all data and almost all instructions structure and order is essential for a proper execution of algorithm. So I suppose such comments could be placed in most programs at every single line..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T14:42:28.830",
"Id": "420021",
"Score": "0",
"body": "@CiaPan It only becomes clear that the indexes in the array are part of the algorithm when you see the conversion."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T20:18:32.863",
"Id": "216948",
"ParentId": "216938",
"Score": "1"
}
},
{
"body": "<p>I add comments in the arrays</p>\n\n<pre><code>String[] morseChar\n = {\".-\", //A\n \"-...\", //B\n \"-.-.\", //C\n \"-..\", //D\n \".\", //E\n \"..-.\", //F\n \"--.\", //G\n \"....\", //H\n \"..\", //I\n \".---\", //J\n \"-.-\", //K\n \".-..\", //L\n \"--\", //M\n \"-.\", //N\n \"---\", //O\n \".--.\", //P\n \"--.-\", //Q\n \".-.\", //R\n \"...\", //S\n \"-\", //T\n \"..-\", //U\n \"...-\", //V\n \".--\", //W\n \"-..-\", //X\n \"-.--\", //Y\n \"--..\"};//Z\n String[] morseNumber\n = {\".----\", //0\n \"..---\",//1\n \"...--\",//2\n \"....-\",//3\n \".....\",//4\n \"-....\",//5\n \"--...\",//6\n \"---..\",//7\n \"----.\",//8\n \"-----\"};//9\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T06:05:39.450",
"Id": "419944",
"Score": "0",
"body": "The comments for the numbers are incorrect."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T10:31:31.293",
"Id": "419976",
"Score": "1",
"body": "@TorbenPutkonen The comments are correct, but the data are wrong."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T10:51:50.757",
"Id": "419977",
"Score": "0",
"body": "@CiaPan I don't think that they work like that..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T11:00:43.097",
"Id": "419979",
"Score": "0",
"body": "@TorbenPutkonen Like what?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T21:00:53.520",
"Id": "216952",
"ParentId": "216938",
"Score": "-2"
}
},
{
"body": "<p>One more review, where I'd like to point out two Java pitfalls you should avoid in professional code.</p>\n\n<h2>byte[] array to represent text</h2>\n\n<p>Your <code>public static String toMorse(byte[] bytes) { ... }</code> method signature gets the input as byte array and only internally creates a <code>String</code> out of that array. </p>\n\n<p>That's dangerous, as that <code>String(byte[] bytes)</code> constructor is documented as (emphasis mine):</p>\n\n<blockquote>\n <p><code>public String(byte[] bytes)</code></p>\n \n <p>Constructs a new String by decoding the specified array of bytes <strong>using\n the platform's default charset</strong>. [...]</p>\n</blockquote>\n\n<p>That means that the same byte array will produce different results when running under different operating systems, as even nowadays there are still many different character encodings in use all over the world and all over the various operating systems.</p>\n\n<p>A computational method like your morse converter should have a <code>String</code> argument instead of a <code>byte[]</code> array, then it's run-anywhere reproducible. If necessary, have your file I/O methods handle character encodings.</p>\n\n<p>Rule of thumb: to pass around things that represent text, use <code>String</code>.</p>\n\n<h2>Repeated String appending</h2>\n\n<p>In your loop, you build the output string by repeatedly doing lines like</p>\n\n<pre><code>morseText = morseText + morseChar[text.charAt(i) - 'a'];\n</code></pre>\n\n<p>That's ok if you know the text is rather short, but it will become quite slow for strings with thousands of characters.</p>\n\n<p>Why? Every time the machine executes such a line, it creates a completely new <code>morseText</code> string, copying all the characters from the old morseText, plus the additional morse snippet. So, the first morse snippets get copied over and over and over again. To avoid that, use a single <code>StringBuilder</code>, and in every loop iteration, <code>append()</code> the morse snippet to that <code>StringBuilder</code>, and only after the loop, convert the <code>StringBuilder</code> to the <code>String</code> you want to return.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T19:49:48.760",
"Id": "216988",
"ParentId": "216938",
"Score": "7"
}
},
{
"body": "<p>You have defined the morse code mapping arrays as method variables. This means that they are allocated from stack every time you call the method. This is fairly ineficient. You should move them to class constants:</p>\n\n<pre><code>private static final String[] MORSE_CHAR\n = {\".-\",\n \"-...\",\n ...\n\nprivate static final String[] MORSE_NUMBER\n = {\".----\",\n \"..---\",\n ...\n\n\npublic static String toMorse(byte[] bytes) {\n ...\n}\n</code></pre>\n\n<p>But we can make it better. Morse conversion in this case is fundamentally mapping characters to strings, so why don't we encapsulate the conversion to a separate class to comply with the <em>single responsibility principle</em>? We can take advantage of Unicode being compatible with ASCII and define the mappings as a simple array where the array index represents a ASCII code points and the value in the array represents the Morse code that represents the ASCII character. And look at that, Java has an interface for us... :) We have to make some special cases for word separators, since we are using data types that cannot fully represent the intricacies of Morse code (e.g. space is mapped to space). Ideally we would map to dots, dashes and delays of different lengths (or if we want to split hairs, a dash is just a dot that lasts three times as long, so the mapping would be to sounds and silences of certain lengths).</p>\n\n<p>A really fancy solution would return <code>Optional<String></code> instead of a nullable String.</p>\n\n<pre><code>import java.util.function.IntFunction;\n\n/**\n * Convert Unicode code points to morse code strings.\n * Code points that can not be represented in morse are retuned as\n * null. Space is returned as space.\n */\npublic class CodePointToMorseStringConverter implements IntFunction<String> {\n\n public static final IntFunction<String> INSTANCE = new CodePointToMorseStringConverter();\n\n private static final String[] ASCII_TO_MORSE = {\n null, // 0\n ... // 30 nulls removed for brevity\n null, // 31\n \"\", // 32, space\n \"-.-.--\", // 33, !\n \".-..-.\", // 34, \"\n null, // 35\n null, // 36\n null, // 37\n null, // 38\n \".----.\", // 39, '\n \"-.--.-\", // 40, ( (brackets)\n \"-.--.-\", // 41, ) (brackets)\n null, // 42\n null, // 43\n \"--..--\", // 44, ,\n \"-....-\", // 45, -\n \".-.-.-\", // 46, .\n \"-..-.\", // 47, / (fraction bar)\n \"-----\", // 48, 0\n \".----\",\n \"..---\",\n \"...--\",\n \"....-\",\n \".....\",\n \"-....\",\n \"--...\",\n \"---..\",\n \"----.\", // 57, 9\n \"---...\", // 58, :\n null, // 59\n null, // 60\n \"-...-\", // 61, =\n null, // 62\n \"..--..\", // 63, ?\n \".--.-.\", // 64, @\n \".-\", // 65, A\n \"-...\",\n \"-.-.\",\n \"-..\",\n \".\",\n \"..-.\",\n \"--.\",\n \"....\",\n \"..\",\n \".---\",\n \"-.-\",\n \".-..\",\n \"--\",\n \"-.\",\n \"---\",\n \".--.\",\n \"--.-\",\n \".-.\",\n \"...\",\n \"-\",\n \"..-\",\n \"...-\",\n \".--\",\n \"-..-\",\n \"-.--\",\n \"--..\", // 90, Z\n null, // 91\n null, // 92\n null, // 93\n null, // 94\n null, // 95\n null, // 96\n \".-\", // 97, A\n \"-...\",\n \"-.-.\",\n \"-..\",\n \".\",\n \"..-.\",\n \"--.\",\n \"....\",\n \"..\",\n \".---\",\n \"-.-\",\n \".-..\",\n \"--\",\n \"-.\",\n \"---\",\n \".--.\",\n \"--.-\",\n \".-.\",\n \"...\",\n \"-\",\n \"..-\",\n \"...-\",\n \".--\",\n \"-..-\",\n \"-.--\",\n \"--..\" // 122, Z\n };\n\n @Override\n public String apply(int i) {\n if (i >= 0 && i <= ASCII_TO_MORSE.length) {\n return ASCII_TO_MORSE[i];\n } else {\n return null;\n }\n }\n}\n</code></pre>\n\n<p>Conversion then becomes a stream operation. We can wrap this into a method if we like. Or even make a <code>Function<String, String></code>. But that'll be an exercise for later.</p>\n\n<pre><code>String text = \"Hello world!\";\nString morse = text.codePoints()\n .mapToObj(CodePointToMorseStringConverter.INSTANCE)\n .filter(Objects::nonNull)\n .collect(Collectors.joining(\" \"));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T13:14:51.867",
"Id": "420000",
"Score": "0",
"body": "Could you convert Morse to Text this way?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T00:56:00.953",
"Id": "420074",
"Score": "0",
"body": "Sure. 987654321"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T07:25:31.250",
"Id": "217057",
"ParentId": "216938",
"Score": "-2"
}
},
{
"body": "<p>You might consider using StringBuilder for better performance and call <code>text.charAr(i)</code> only once by making it a local variable. Also, I'd rather change the parameter to String, so you do not run into decoding issues.</p>\n\n<pre><code>public static void main(String[] args) throws IOException {\n String filePath = \"/tmp/test\";\n String text = new String(Files.readAllBytes(Paths.get(filePath)));\n}\n\npublic static String toMorse(String text) {\n StringBuilder morseText = new StringBuilder();\n text = text.toLowerCase();\n String[] morseChar = // see above, didn't check\n String[] morseNumber ={\n \"-----\", //0 has to be the first one. programmers start counting by 0!\n \".----\",\n \"..---\",\n \"...--\",\n \"....-\",\n \".....\",\n \"-....\",\n \"--...\",\n \"---..\",\n \"----.\"};\n\n for (int i = 0; i < text.length(); i++) {\n char character = text.charAt(i);\n if (character >= 'a' && character <= 'z') {\n morseText.append(morseChar[character - 'a']);\n } else if (character >= '0' && character <= '9') {\n morseText.append(morseNumber[character - '0']);\n } else if (character == ' ') {\n morseText.append(character);\n }\n }\n return morseText.toString();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T17:25:33.967",
"Id": "217213",
"ParentId": "216938",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216988",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T17:47:09.157",
"Id": "216938",
"Score": "4",
"Tags": [
"java",
"beginner",
"morse-code"
],
"Title": "Text-to-Morse code converter"
} | 216938 |
<p>The task:</p>
<blockquote>
<p>Find an efficient algorithm to find the smallest distance (measured in
number of words) between any two given words in a string.</p>
<p>For example, given words "hello", and "world" and a text content of
"dog cat hello cat dog dog hello cat world", return 1 because there's
only one word "cat" in between the two words.</p>
</blockquote>
<pre><code>const s = "dog cat hello cat dog dog hello cat world";
</code></pre>
<p>My imperative solution:</p>
<pre><code>function smallestWordDistance2({str, word1, word2}) {
if (!str.match(word1) || !str.match(word2)) { return 0; }
const strArr = str.split(" ");
let iStart, iEnd, min;
let count = 0;
for (let x in strArr) {
if (!iStart) {
if (strArr[x] === word1) {
iStart = word1;
iEnd = word2;
} else if(strArr[x] === word2) {
iStart = word2;
iEnd = word1;
}
} else {
count++;
if (strArr[x] === iStart) {
count = 0;
} else if (strArr[x] === iEnd) {
if (count === 1) { return 0; }
if (!min || min > count) {
min = count;
}
[iStart, iEnd] = [iEnd, iStart];
count = 0;
}
}
}
return min - 1;
}
console.log(smallestWordDistance2({str:s, word1:"hello", word2:"world"}));
</code></pre>
<p>My "functional" solution:</p>
<pre><code>const smallestWordDistance3 = ({str, word1, word2} )=> {
if (!str.match(word1) || !str.match(word2)) { return 0; }
const strArr = str.split(" ");
return strArr.reduce((acc, x, i) => {
if (!acc.iStart) {
if (x === word1) {
acc.iStart = word1;
acc.iEnd = word2;
} else if(x === word2) {
acc.iStart = word2;
acc.iEnd = word1;
}
} else {
acc.count++;
if (x === acc.iStart) {
acc.count = 0;
} else if (x === acc.iEnd) {
if (!acc.min || acc.min > acc.count) {
acc.min = acc.count;
}
[acc.iStart, acc.iEnd] = [acc.iEnd, acc.iStart];
acc.count = 0;
}
}
return acc;
}, {iStart: null, iEnd: null, count: 0, min: null}).min - 1;
};
console.log(smallestWordDistance3({str:s, word1:"hello", word2:"world"}));
</code></pre>
<p>At first I thought this was a good task for a regex solution, but the following code is the best I could do. It works with the given sample string. However a slight variance in the given string would make the code unusable, because it doesn't take into consideration that <code>word1</code> and <code>word2</code> can be swapped (the following code would return <code>2</code> instead of <code>1</code>):</p>
<pre><code>const s = "dog cat hello cat dog dog hello cat dog world dog hello";
const smallestWordDistance = ({str, word1, word2} )=> {
if (!str.match(word1) || !str.match(word2)) { return 0; }
const reg = new RegExp(`.*\\b${word1}\\s+(.*?)\\s+${word2}\\b`);
const match = str.match(reg);
return match ? match[1].split(" ").length : 0;
};
console.log(smallestWordDistance({str:s, word1:"hello", word2:"world"}));
</code></pre>
<p>I'm now not so sure anymore whether regex is the right approach. But if anyone got a good regex (JS flavor) solution, then I'd be very much interested.</p>
| [] | [
{
"body": "<p>How about a single pass through the list of words. Have two variables to record the latest position you saw \"hello\" or \"world\", and when either occurs, compute the absolute difference between the positions, if it's a new record, update the record.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T20:00:32.363",
"Id": "419611",
"Score": "0",
"body": "That's exactly what my \"imperative solution\" is doing."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T19:49:58.507",
"Id": "216943",
"ParentId": "216939",
"Score": "0"
}
},
{
"body": "<p>After staring at your code for some time,</p>\n\n<ul>\n<li>You are using <a href=\"https://en.wikipedia.org/wiki/Hungarian_notation\" rel=\"nofollow noreferrer\">Hungarian notation</a>, that is not a JavaScript practice\n\n<ul>\n<li>Related to that, <code>strArr</code> probably should have been <code>arrStr</code> if the code was consistent</li>\n</ul></li>\n<li>It seems odd that you would return <code>0</code> when either word is not present, <code>0</code> would indicate that the words are neighbours. I would return -1 in that case.</li>\n<li>You seem to track too much state in <code>acc</code>, you can get away with just tracking the last matched word, the location of the last matched word and what the best distance has been thus far</li>\n<li>There are no comments whatsoever, I think your code could have used some</li>\n</ul>\n\n<p>This is my functional approach:</p>\n\n<pre><code>const s = \"dog cat hello cat dog dog hello cat dog world dog hello\";\n\nfunction smallestWordDistance(s, w1, w2) {\n\n function analyze(acc, word, index) {\n\n if (word == w1 || word == w2) {\n\n if (acc.word && acc.word != word) {\n const distance = index - acc.index - 1;\n acc.out = acc.out == -1 ? distance : Math.min(acc.out, distance);\n }\n acc.index = index;\n acc.word = word;\n }\n return acc;\n }\n\n return s.split(' ').reduce(analyze, { out: -1 }).out;\n}\n\nconsole.log(smallestWordDistance(s, \"hello\", \"world\"));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T19:51:33.360",
"Id": "216945",
"ParentId": "216939",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216945",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T17:48:56.473",
"Id": "216939",
"Score": "1",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"functional-programming",
"regex"
],
"Title": "Find the smallest distance between any two given words in a string"
} | 216939 |
<p>For a class that I'm in, we're creating digital Pokemon cards. I'm trying to create elements that are nested within another element and repeated multiple times. For example, I have currently:</p>
<pre><code><div class="columns">
<div class="column">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
</div>
</code></pre>
<p>But, I only want 3 of the box <strong>divs</strong> to be inside the column <strong>div</strong> and then for this model to repeat for every 3 box <strong>divs</strong> so that it looks like this:</p>
<pre><code><div class="columns">
<div class="column">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
</div>
<div class="columns">
<div class="column">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
</div>
<div class="columns">
<div class="column">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
</div>
</code></pre>
<p>And I want that to repeat until all of the box <strong>divs</strong> are filled into a column <strong>div</strong>.</p>
<p>The javascript that I used to make these <strong>divs</strong> is the following:</p>
<pre><code>function createPokeCard(pokeData) {
let scene = document.createElement('div')
let card = document.createElement('div')
scene.className = 'scene'
card.className = 'box'
card.addEventListener( 'click', function() {
card.classList.toggle('is-flipped')
})
card.appendChild(cardFront(pokeData))
card.appendChild(cardBack(pokeData))
mainContainer.appendChild(card)
mainContainer.appendChild(section)
mainContainer.appendChild(columns)
mainContainer.appendChild(column)
section.appendChild(columns)
columns.appendChild(column)
columns.appendChild(card)
column.appendChild(card)
}
</code></pre>
<p>Can you review this code for best coding practices?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T19:33:45.087",
"Id": "419605",
"Score": "1",
"body": "Don't alter the HTML to suit your layout. Layout should be done using CSS."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T20:28:41.407",
"Id": "419619",
"Score": "0",
"body": "Sorry, can you explain a bit more in depth what you mean? I don't quite understand."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T11:09:03.623",
"Id": "419852",
"Score": "0",
"body": "What @200_success means, is that you don't need to use JavaScript to reorder the HTML to create columns, instead you can use CSS, for example grid layout. How exactly depends on how you want it too look. Also, even if you don't want to use CSS, why aren't you generating the original HTML with the separate columns?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T22:23:53.030",
"Id": "419927",
"Score": "0",
"body": "Right, I know that I can use HTML and CSS instead of the Javascript, but I will be having a button that can generate new content using the Javascript, and I want those new elements to fall under that sam structure. Can I do that with only HTML and CSS? Also, if I were to use HTML and CSS then I would still need to assign that HTML and CSS to the javascript content that I am generating from an API so they would still need to be linked somehow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T10:42:34.010",
"Id": "420109",
"Score": "0",
"body": "Welcome to Code Review! I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. Code Review is not the site to ask for help in fixing or changing *what* your code does. Once the code does what you want, we would love to help you do the same thing in a cleaner way! Please see our [help center](/help/on-topic) for more information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T18:24:56.697",
"Id": "420580",
"Score": "0",
"body": "I didn’t realize e that is what it was for, thank you for clarifying! I will not ask again. Have a great day!"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T19:23:53.040",
"Id": "216942",
"Score": "1",
"Tags": [
"javascript",
"html"
],
"Title": "Nesting 3 divs within another div using JavaScript"
} | 216942 |
<p>The first version of my solution was wrong (the usage of <code>compile()</code> function), for details see <a href="https://stackoverflow.com/q/55543832/2913477">Stack Overflow</a>.</p>
<p>The solution has been fixed and now it works correctly. Another approach is used: <code>my_add.__code__</code>. The questions stayed the same.</p>
<p>I am reading the book: <em>Obi Ike-Nwosu. Inside The Python Virtual Machine</em> and have reached the "Code Objects" chapter. This chapter has all code object fields printed out:</p>
<blockquote>
<pre><code>co_argcount = 1
co_cellvars = ()
co_code = b'|\x00d\x01\x16\x00d\x02k\x02r\x1e|\x00d\x03\x16\x00d\x02k\x02r\x1ed\\
x04S\x00n,|\x00d\x01\x16\x00d\x02k\x02r0d\x05S\x00n\x1a|\x00d\x03\x16\x00d\x02k\x02r\
Bd\x06S\x00n\x08t\x00|\x00\x83\x01S\x00d\x00S\x00'
co_consts = (None, 3, 0, 5, 'FizzBuzz', 'Fizz', 'Buzz')
co_filename = /Users/c4obi/projects/python_source/cpython/fizzbuzz.py
co_firstlineno = 6
co_flags = 67
etc...
</code></pre>
</blockquote>
<p>but there is no explanation how this can be done programatically, so I wrote my own code:</p>
<pre><code># The explored function
def my_add(a,b):
first = a
second = b
return first + second
def print_co_obj_fields(code_obj):
# Iterating through all instance attributes
# and calling all having the 'co_' prefix
for name in dir(code_obj):
if name.startswith('co_'):
co_field = getattr(code_obj, name)
print(f'{name:<20} = {co_field}')
# The function code object (__code__) usage
print_co_obj_fields(my_add.__code__)
</code></pre>
<p><strong>Output</strong></p>
<pre class="lang-none prettyprint-override"><code>co_argcount = 2
co_cellvars = ()
co_code = b'|\x00}\x02|\x01}\x03|\x02|\x03\x17\x00S\x00'
co_consts = (None,)
co_filename = ./source.py
co_firstlineno = 17
co_flags = 67
co_freevars = ()
co_kwonlyargcount = 0
co_lnotab = b'\x00\x01\x04\x01\x04\x02'
co_name = my_add
co_names = ()
co_nlocals = 4
co_stacksize = 2
co_varnames = ('a', 'b', 'first', 'second')
</code></pre>
<p>Have I done this the optimal way? How would you solve this problem?</p>
| [] | [
{
"body": "<h1>main guard</h1>\n\n<p>Put the parts of your code that are the ones calling for execution behind a <code>if __name__ == \"__main__\":</code> <a href=\"https://stackoverflow.com/a/419185/1562285\">guard</a></p>\n\n<pre><code>if __name__ == \"__main__\":\n def my_add(a, b):\n first = a\n second = b\n\n return first + second\n print_co_obj_fields(my_add.__code__)\n</code></pre>\n\n<p>This way you can import this python module from other places if you ever want to</p>\n\n<h1>Documentation</h1>\n\n<p>There is a python convention (<code>docstring</code>) to document the behaviour of a method: <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">PEP-257</a></p>\n\n<pre><code>def print_co_obj_fields(code_obj):\n \"\"\"prints all the instance variables of the code object that start with 'co_'\"\"\"\n</code></pre>\n\n<h1>Indentation</h1>\n\n<p>To decrease the levels of indentation, you can reverse the test of <code>startswith</code>, and <code>continue</code> when it fails:</p>\n\n<pre><code>def print_co_obj_fields(code_obj):\n # Iterating through all instance attributes\n # and calling all having the 'co_' prefix\n for name in dir(code_obj):\n if not name.startswith('co_'):\n continue\n co_field = getattr(code_obj, name)\n print(f'{name:<20} = {co_field}')\n</code></pre>\n\n<p>An alternative if using the builtin <code>filter</code>:</p>\n\n<pre><code>def print_co_obj_fields(code_obj):\n # Iterating through all instance attributes\n # and calling all having the 'co_' prefix\n for name in filter(lambda field: field.startswith(\"co_\"), dir(code_obj)):\n co_field = getattr(code_obj, name)\n print(f'{name:<20} = {co_field}')\n</code></pre>\n\n<h1>Presentation</h1>\n\n<p>Separate the generation of the results from the presentation. The easiest way to do this is to have <code>print_co_obj_fields</code> <code>yield</code> the <code>name</code> and <code>co_field</code> instead of printing them</p>\n\n<pre><code>def co_obj_fields(code_obj):\n \"\"\"generator that yields the fields in a code_object and their value\"\"\"\n for name in filter(lambda field: field.startswith(\"co_\"), dir(code_obj)):\n co_field = getattr(code_obj, name)\n yield name, co_field\n\ndef print_co_obj_fields(fields):\n for name, co_field in fields:\n print(f\"{name:<20} = {co_field}\")\n</code></pre>\n\n<p>The <code>main</code> part then changes to:</p>\n\n<pre><code>if __name__ == \"__main__\":\n\n def my_add(a, b):\n first = a\n second = b\n\n return first + second\n\n fields = co_obj_fields(my_add.__code__)\n print_co_obj_fields(fields)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T12:03:01.607",
"Id": "423721",
"Score": "0",
"body": "\"Separate the generation of the results from the presentation.\" But it means, that I should write the presentation part every time I use `co_obj_fields`. It is good from one point of view - I can customize presentation as needed (it is the main purpose of separation, I think), but it is bad when I need the same formatting everywhere, so I will get the duplication in the code. Or in this case it would be better to wrap the presentation part into another function and call it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T13:42:36.280",
"Id": "423736",
"Score": "1",
"body": "It would be better to wrap the presentation part in another function and call that. If you follow Brendan Rhodes' [clean architecture](https://rhodesmill.org/brandon/talks/#clean-architecture-python) you don't have that function call the `co_obj_fields`, but it just receives the results of that call."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T07:25:50.453",
"Id": "219342",
"ParentId": "216944",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "219342",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T19:50:33.790",
"Id": "216944",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"reflection"
],
"Title": "Exploring code objects"
} | 216944 |
<p>My love calculator gives a result from 0 to 100% based on these factors:</p>
<ol>
<li>If the first letters of the names are the same.</li>
<li>If the number of vowels is the same.</li>
<li>If the length of the name is the same.</li>
<li>If the number of consonants is the same.</li>
</ol>
<p>Also, there is an extra boost of 10-50%, so the result is also partially as a result of luck.
Can the coding below be simplified or improved to function more smoothly?:</p>
<p>(Edit 1: By the way, I'm very new at Python - I joined the community only yesterday.)</p>
<p>(Edit 2: I am using Python 3.7.3 for Mac OSX.)</p>
<pre><code>name1 = input("Please type Name 1.\n")
name2 = input("Please type Name 2.\n")
total_vowel1 =0
for i in ['a','e','i','o','u']:
total_vowel1 += name1.count(i)
total_vowel2 =0
for i in ['a','e','i','o','u']:
total_vowel2 += name2.count(i)
love = 0
if(total_vowel1 == total_vowel2):
import random
love +=random.randint(10,30)
consonants1 = 0
consonants2 = 0
CONSONANTS = 'bcdfghjklmnprstvwxyz'
consonants1 = len([letter for letter in name1 if letter.lower() in
CONSONANTS])
consonants2 = len([letter for letter in name2 if letter.lower() in
CONSONANTS])
if(consonants1 == consonants2):
import random
love +=random.randint(20,40)
line1 = name1
line2 = name2
split1 = line1.split()
split2 = line2.split()
fl1 = [word[0] for word in split1]
fl2 = [word[0] for word in split2]
if (fl1 == fl2):
import random
love +=random.randint(10,30)
if (len(name1) == len(name2)):
import random
love+=random.randint(1,10)
import random
love +=random.randint(10,50)
if (love>100):
love = 100
print("Calculating...")
import time
import random
time.sleep(random.randint(1,3))
print("",name1,"and",name2,"have a",love,"% relationship.")
if ((love>90) or (love == 90)):
print("They have an unbreakable relationship that will last
forever.")
if ((love<89) or (love == 89)) and ((love>70) or (love == 70)):
print("They have a strong relationship that will most likely
lead to a marriage.")
if ((love<69) or (love == 69)) and ((love>50) or (love == 50)):
print("They have a good relationship that can lead to a
honeymoon to Paris.")
if ((love<49) or (love == 49)):
print("They have a weak relationship that could have been a
'match made in heaven'.")
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T20:15:54.573",
"Id": "419615",
"Score": "0",
"body": "Feels like a beginner python program. Please edit if that is not the case here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T20:16:29.507",
"Id": "419616",
"Score": "0",
"body": "Also, please mention the python version you're using. python-3 or python-2?"
}
] | [
{
"body": "<p>First, your definition of <code>consonants</code> can be simplified a bit using set operations:</p>\n\n<pre><code>from string import ascii_lowercase\n\n# Storing vowels in a set instead of a list\nvowels = {'a', 'e', 'i', 'o', 'u'} \n\n# Read as \"Take the set of lowercase letters, and remove the vowels\"\nconsonants = set(ascii_lowercase) ^ vowels\n</code></pre>\n\n<hr>\n\n<p>The vowel counting code below that is repetitious. You have the same counting loop twice. This is a good place to make use of a function:</p>\n\n<pre><code>def count_vowels(name):\n count = 0\n for i in vowels:\n count += name.count(i)\n\n return count\n\ntotal_vowel1 = count_vowels(name1)\ntotal_vowel2 = count_vowels(name2)\n</code></pre>\n\n<hr>\n\n<p>Instead of importing <code>random</code> a few times throughout the script, just import it at the top once. Unless you have a good reason to hold off on importing something until you really need it, just import any modules right at the top for clarity.</p>\n\n<hr>\n\n<p>Your spacing is kind of a mess. At different points you have:</p>\n\n<ul>\n<li><code>total_vowel1 =0</code></li>\n<li><code>consonants1 = 0</code></li>\n<li><code>love +=random.randint(10,50)</code></li>\n<li><code>((love<49) or (love == 49))</code></li>\n<li><code>love +=random.randint(10,30)</code></li>\n<li><code>love+=random.randint(1,10)</code></li>\n</ul>\n\n<p>See the problem? You're either being wildly inconsistent in your spacing, or you aren't caring to make sure your code readable and nice looking. Pick a spacing style and stick to it. I'd recommend putting spaces around infix operators (<code>love < 49 or love == 49</code>).</p>\n\n<hr>\n\n<p>You're using two different counting and naming methods for vowels and consonants: a full loop, and a comprehension:</p>\n\n<pre><code>total_vowel1 =0\nfor i in ['a','e','i','o','u']:\n total_vowel1 += name1.count(i)\n\n. . .\n\nconsonants1 = len([letter for letter in name1 if letter.lower() in consonants])\n</code></pre>\n\n<p>Again, try to be consistent. You or someone else may need to read your code later, and consistency greatly helps readability.</p>\n\n<hr>\n\n<p><code>((love>90) or (love == 90))</code> is needlessly complicated. Just write <code>love >= 90</code>.</p>\n\n<hr>\n\n<p>In that same area, you have a bunch of <code>if</code>s. They're all exclusive of each other though, so really, all the <code>if</code>s after the first should be <code>elif</code>s.</p>\n\n<hr>\n\n<p><code>if love <= 89 and love >= 70</code> (which I fixed up) could be simply written as <code>70 <= love <= 89</code>. Python, unlike most languages, allows for comparison chaining.</p>\n\n<hr>\n\n<p>The last case can just be an <code>else</code>. By elimination, if the other cases weren't picked, the last one must be.</p>\n\n<hr>\n\n<hr>\n\n<p>After taking all that into consideration and fixing some more spacing, I ended up with:</p>\n\n<pre><code>from string import ascii_lowercase\nimport random\nimport time\n\nname1 = input(\"Please type Name 1.\\n\")\nname2 = input(\"Please type Name 2.\\n\")\n\nvowels = {'a', 'e', 'i', 'o', 'u'}\nconsonants = set(ascii_lowercase) ^ vowels\n\ndef count_vowels(name):\n count = 0\n for i in vowels:\n count += name2.count(i)\n\n return count\n\ntotal_vowel1 = count_vowels(name1)\ntotal_vowel2 = count_vowels(name2)\n\nlove = 0\nif(total_vowel1 == total_vowel2):\n love += random.randint(10, 30)\n\nconsonants1 = len([letter for letter in name1 if letter.lower() in consonants])\nconsonants2 = len([letter for letter in name2 if letter.lower() in consonants])\n\nif(consonants1 == consonants2):\n love += random.randint(20, 40)\n\nline1 = name1\nline2 = name2\nsplit1 = line1.split()\nsplit2 = line2.split()\nfl1 = [word[0] for word in split1]\nfl2 = [word[0] for word in split2]\n\nif (fl1 == fl2):\n love += random.randint(10,30)\n\nif (len(name1) == len(name2)):\n love += random.randint(1,10)\n\nlove += random.randint(10,50)\n\nif (love > 100):\n love = 100\n\nprint(\"Calculating...\")\n\nprint(name1, \"and\", name2, \"have a\", love, \"% relationship.\")\n\nif love >= 90:\n print(\"They have an unbreakable relationship that will last forever.\")\n\nelif 70 <= love <= 89:\n print(\"They have a strong relationship that will most likely lead to a marriage.\")\n\nelif 50 <= love <= 69:\n print(\"They have a good relationship that can lead to a honeymoon to Paris.\")\n\nelse:\n print(\"They have a weak relationship that could have been a 'match made in heaven'.\")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T21:21:15.350",
"Id": "419622",
"Score": "0",
"body": "Solid advice. I've been using python for quite some time and I didn't know you could comparison chaining. My life is changed for the better!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T21:28:45.550",
"Id": "419623",
"Score": "0",
"body": "@loganjones16 It's very handy. Unfortunately, the only languages that I know that support it are Python and Clojure (although Clojure's syntax is a little different because it's a lisp: `(<= 1 x 4)`)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T20:34:25.577",
"Id": "216949",
"ParentId": "216946",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T19:56:01.260",
"Id": "216946",
"Score": "1",
"Tags": [
"python",
"beginner",
"strings",
"random"
],
"Title": "Advanced love calculator that generates a result based on the similarities between the two names"
} | 216946 |
<p>I'm new to C language and want to explode a string like we do in PHP <code>explode()</code> function, I searched for a built-in function with the C standard library, and I found <code>strtok</code> , but It doesn't support empty tokens like <code>1,2,3,,5</code> . Inspired by the answers I found in this <a href="https://stackoverflow.com/a/3375776/5407848">SO question</a> I made this function, it is supposed to be thread safe and support empty tokens and doesn't change the original string</p>
<pre><code>char* strTok(char** newString, char* delimiter)
{
char* string = *newString;
char* delimiterFound = (char*) 0;
int tokLenght = 0;
char* tok = (char*) 0;
if(!string) return (char*) 0;
delimiterFound = strstr(string, delimiter);
if(delimiterFound){
tokLenght = delimiterFound-string;
}else{
tokLenght = strlen(string);
}
tok = malloc(tokLenght + 1);
memcpy(tok, string, tokLenght);
tok[tokLenght] = '\0';
*newString = delimiterFound ? delimiterFound + strlen(delimiter) : (char*)0;
return tok;
}
</code></pre>
<p>I designed it to be used like</p>
<pre><code>char* input = "1,2,3,4,5,6,7,,,10,";
char** inputP = &input;
char* tok;
while( (tok=strTok(inputP, ",")) ){
printf("%s\n", tok);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T01:59:22.893",
"Id": "419644",
"Score": "1",
"body": "Better user-interface then the original `strtok`. You may be interested in `strsep`, too. https://code.woboq.org/userspace/glibc/string/strsep.c.html"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T02:09:28.847",
"Id": "419649",
"Score": "0",
"body": "@NeilEdelman thanks I never saw this function before, I will check it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T02:17:49.587",
"Id": "419651",
"Score": "1",
"body": "It's not in the standard `C` libraries, but in `POSIX`, (any type of `gcc`.) However, like `strtok`, it obliterates the `char` to replace it with `\\0`, so it's not the same."
}
] | [
{
"body": "<p>From a readability viewpoint, you should use <code>NULL</code> instead of <code>(char*) 0</code> as it is easier to recognize what you're trying to do. Also, the <code>tokLenght</code> misspells \"length\", and should probably be <code>tokLength</code>.</p>\n\n<p>You leak memory, as the memory allocated to hold the returned string is never freed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T01:42:49.257",
"Id": "419642",
"Score": "0",
"body": "Thank you very much I will use NULL from now on, and I will remember to `free()` memory , *'I miss PHP garbage collector :('*, I didn't get the `tokLength` spelling note, aren't they the same ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T02:03:37.163",
"Id": "419646",
"Score": "1",
"body": "It's a matter of style, and including `.h` if you want to use `NULL`. However, you don't have to cast `(char *)0`, just use `0` (or `NULL`.) It knows from the return type."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T14:12:06.343",
"Id": "419673",
"Score": "1",
"body": "@Accountantم For the spelling, you used G-H-T when the correct spelling is G-T-H (the last two letters are swapped). I've made that typo before. I find having identifiers spelled correctly helps with reading and finding them, although the autocomplete in IDEs mitigates that a little but propagates the misspellings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T14:38:08.063",
"Id": "419674",
"Score": "0",
"body": "@1201ProgramAlarm ooh, how come I didn't notice this after revising it multiple times!, thanks."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T00:57:50.690",
"Id": "216957",
"ParentId": "216956",
"Score": "2"
}
},
{
"body": "<ul>\n<li><p><code>delimiterFound + strlen(delimiter)</code> sounds like a bug. If the delimiter is longer than one character, <code>*newString</code> will point too far into the original, maybe even beyond the end. Correct me if I am wrong, <code>delimiterFound + 1</code> is what you are actually after.</p></li>\n<li><p>Modern C allows, and strongly encourages, to declare variables as close to their use a possible. Consider</p>\n\n<pre><code>char * delimiterFound = strstr(string, delimiter);\n....\nchar * tok = malloc(tokLenght + 1);\n</code></pre>\n\n<p>etc.</p></li>\n<li><p>Always test that <code>malloc</code> didn't fail.</p></li>\n<li><p>More spaces - around keywords, braces, etc - definitely improve readability:</p>\n\n<pre><code> if (....) {\n ....\n } else {\n ....\n }\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T01:41:09.530",
"Id": "419641",
"Score": "1",
"body": "Thaaank you very much for these precious points, regarding the delimiter length bug, ummmm, I want to support long delimiters more than 1 characters like the boundary string in http requests that has content-type multi-part, and I don't think it's a bug because `delimiterFound + strlen(delimiter)` can never be after the 0 byte that terminates the original string!, right ? `\"fooDELIMITER\" 3 + 12`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T01:52:07.100",
"Id": "419643",
"Score": "0",
"body": "@Accountantم Long delimiters here refer to, say `\",;.\"`, in where any character delimits the string on its own right."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T02:03:11.213",
"Id": "419645",
"Score": "0",
"body": "I didn't get it, I'm sorry, can you please give me an example input that can break this code, exploiting this bug ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T02:09:11.793",
"Id": "419648",
"Score": "1",
"body": "@Accountantم Sorry for not being clear. I should realize that your intentions are different (and read `man strstr` more carefully). Consider it my blinder - since you mentioned `strtok`, I expected the `strtok` semantics."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T02:14:12.173",
"Id": "419650",
"Score": "0",
"body": "It's my fault because I said it's `strtok`, I wanted `strtok` that can support delimiters more than 1 characters, because I need this feature a lot. So do you mean it's not a bug ??"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T02:44:34.030",
"Id": "419654",
"Score": "0",
"body": "*\"Long delimiters here refer to, say \",;.\", in where any character delimits the string on its own right.\"*... aha, now I get it, no no, what I wanted is one delimiter with 1 or more characters e.g `\"fooDELIMITERbar\"`"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T01:24:13.380",
"Id": "216958",
"ParentId": "216956",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216958",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T00:03:33.513",
"Id": "216956",
"Score": "4",
"Tags": [
"beginner",
"c",
"strings"
],
"Title": "strTok function (thread safe, supports empty tokens, doesn't change string)"
} | 216956 |
<p>I'm currently working on <a href="https://open.kattis.com/problems/distinctivecharacter" rel="nofollow noreferrer">this</a> problem from Kattis. In short, we're supposed to find the string that has the least similarity to any other string given. Every element of a string is either 0 or 1. <strong>Similarity</strong> between two strings <strong>is measured</strong> by increasing the similarity by 1 if both strings have the <strong>same character in the same position</strong>. E.g: "01001" "11110" has similarity 1, because they both have 1 in their 2nd position, and for every other position they have different characters. <strong>An input starts with</strong> one line giving two numbers N and P, being first the number of strings in the list, and then the length of each string. The rest of the input is then N lines of single strings. The output should be a string that has the least possible similarity to any string in the input.</p>
<p>I'd like suggestions on how to reduce the number of calls I'm doing in my solution to this problem. Likely by some algorithmic magic.</p>
<h2>Example input:</h2>
<pre><code>3 5
01001
11100
10111
</code></pre>
<h2>Example output:</h2>
<pre><code>00010
</code></pre>
<h2>My code:</h2>
<pre><code>import sys
import itertools
def similarity(sx, sy):
'''Naively calculates similarity between two
strings.'''
result = 0
for i in range(n_feat):
if sx[i] == sy[i]:
result += 1
return result
line_1 = sys.stdin.readline()
line_1 = line_1.split()
N = int(line_1[0])
n_feat = int(line_1[1])
characters = set()
for i in range(N):
characters.add(str(sys.stdin.readline()))
# Generate all possible ways to write n_feat long string with alphabet {0,1}
all_pos_chars = ["".join(seq) for seq in itertools.product("01", repeat=n_feat)]
# Subset actually possible (removed ones have similarity == n_feat)
pos_chars = [pos_char for pos_char in all_pos_chars if pos_char not in characters]
# Impossibly high starting-point.
curr_min = n_feat+1
curr_small = ""
for pos_char in pos_chars:
curr = max(similarity(pos_char, character) for character in characters)
if curr == 0:
curr_small = pos_char
break;
if curr <= curr_min:
curr_min = curr
curr_small = pos_char
print(curr_small)
</code></pre>
<p>This solution works fine for smaller inputs. For example, I ran <code>python -m cProfile -s cumtime dischar.py < 1.in</code> where 1.in is the example input given above and received this:</p>
<pre><code> 300 function calls in 0.001 seconds
Ordered by: cumulative time
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.001 0.001 {built-in method builtins.exec}
1 0.000 0.000 0.001 0.001 dischar2.py:1(<module>)
1 0.000 0.000 0.000 0.000 {built-in method builtins.print}
31 0.000 0.000 0.000 0.000 {built-in method builtins.max}
124 0.000 0.000 0.000 0.000 dischar2.py:34(<genexpr>)
93 0.000 0.000 0.000 0.000 dischar2.py:5(similarity)
4 0.000 0.000 0.000 0.000 {method 'readline' of '_io.TextIOWrapper' objects}
1 0.000 0.000 0.000 0.000 dischar2.py:26(<listcomp>)
2 0.000 0.000 0.000 0.000 cp1252.py:22(decode)
32 0.000 0.000 0.000 0.000 {method 'join' of 'str' objects}
1 0.000 0.000 0.000 0.000 dischar2.py:28(<listcomp>)
2 0.000 0.000 0.000 0.000 {built-in method _codecs.charmap_decode}
2 0.000 0.000 0.000 0.000 codecs.py:281(getstate)
1 0.000 0.000 0.000 0.000 {method 'split' of 'str' objects}
3 0.000 0.000 0.000 0.000 {method 'add' of 'set' objects}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
</code></pre>
<p>But I was worried about the number of calls at line:34, which is this bit of code: <code>curr = max(similarity(pos_char, character) for character in characters)</code>, and then onwards to line:5 which is the similartiy-function. I made a 6.in, where the first line is <code>10000 20</code>, and the next 10000 lines are 20 zeros:</p>
<pre><code>python -m cProfile -s cumtime dischar2.py < 6.in
11111111111111111111
7360118 function calls in 9.280 seconds
Ordered by: cumulative time
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 9.280 9.280 {built-in method builtins.exec}
1 0.756 0.756 9.280 9.280 dischar2.py:1(<module>)
1048575 0.663 0.000 7.700 0.000 {built-in method builtins.max}
3145725 0.777 0.000 7.037 0.000 dischar2.py:34(<genexpr>)
2097150 6.260 0.000 6.260 0.000 dischar2.py:5(similarity)
1 0.325 0.325 0.656 0.656 dischar2.py:26(<listcomp>)
1048576 0.332 0.000 0.332 0.000 {method 'join' of 'str' objects}
1 0.161 0.161 0.161 0.161 dischar2.py:28(<listcomp>)
10001 0.004 0.000 0.005 0.000 {method 'readline' of '_io.TextIOWrapper' objects}
10000 0.001 0.000 0.001 0.000 {method 'add' of 'set' objects}
28 0.000 0.000 0.001 0.000 cp1252.py:22(decode)
28 0.001 0.000 0.001 0.000 {built-in method _codecs.charmap_decode}
1 0.000 0.000 0.000 0.000 {built-in method builtins.print}
28 0.000 0.000 0.000 0.000 codecs.py:281(getstate)
1 0.000 0.000 0.000 0.000 {method 'split' of 'str' objects}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
</code></pre>
<p>As you can see, this adds up quickly! I think my solution is sound, it provides the correct output for every case I can test for. But there has to be some trick that I'm not seeing, because Kattis expects the solution to run within 2 CPU-seconds. Any suggestions?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T12:03:56.957",
"Id": "419671",
"Score": "1",
"body": "You are supposed to use bit operators"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T19:24:04.997",
"Id": "419706",
"Score": "0",
"body": "Yes, I should. Thank you. But I believe using bit-operators would not help with the O(n^2)-nature of searching through every possible combination to find the string with the lowest maximum similarity. It would just make the n^2 operations a bit faster, or am I wrong? There's something conceptually wrong with what I'm doing, in terms of performance, I'm sure of it. The answer from @vnp is suggesting so also, but I haven't been able to decrypt the hint yet. But maybe this is more of a stackoverflow-question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T19:43:01.850",
"Id": "419707",
"Score": "0",
"body": "@E.Coms I think I might be getting it now. Thanks for your suggestion!"
}
] | [
{
"body": "<p>Line 34 is a wrong tree to bark on. The problem is in</p>\n\n<pre><code> all_pos_chars = [\"\".join(seq) for seq in itertools.product(\"01\", repeat=n_feat)]\n</code></pre>\n\n<p>which results in a list of <span class=\"math-container\">\\$2^{n\\_feat}\\$</span> characters. You have an exponential complexity right away.</p>\n\n<p>An opportunistic optimization (removal of impossible characters) doesn't buy you anything; at the end of the day you still comparing each - possible or impossible - character against each input character. Notice that in a 5 feature case there are <span class=\"math-container\">\\$31 = 2^5 - 1\\$</span> calls to <code>max</code>, and in a 20 feature case there are <span class=\"math-container\">\\$1048575 = 2^{20} - 1\\$</span> of them.</p>\n\n<p>Now, to get the problem right, you need to realize first that the features are independent. And second that a contribution of a particular feature only depends on how many characters have it. Hint: how would you solve the problem for just one feature?. I hope the hint is strong enough to reveal a linear time solution.</p>\n\n<hr>\n\n<p>An obligatory code review note. Using an <em>Impossibly high starting-point</em> is often wrong, and may not even exist. A natural starting point is safely derived from the first element:</p>\n\n<pre><code> curr = similarity(pos_char, character[0])\n</code></pre>\n\n<p>followed by iterating over <code>character[1:]</code>. Now the <code>if curr == 0:</code> special case disappear.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T06:35:24.397",
"Id": "419657",
"Score": "0",
"body": "Never mind, I have to rethink this a bit more. I judged too quickly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T07:00:34.903",
"Id": "419659",
"Score": "0",
"body": "Solving for one feature: If both 0 and 1 appear in the input-list, then 0 and 1 as output are equally valid. If only 1s appear in the list, then 0 has the smallest max-similarity, and vice versa for 0s. Maybe I could always select the one with the least appearances among the two – and just print either if they are equal? This is how I approached the problem in the beginning. I'm getting a \"wrong answer\" at test no.10, but I can't think of an example myself where it would be wrong. But the wrong answer convinced me that method must be wrong."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T07:04:12.760",
"Id": "419660",
"Score": "0",
"body": "Come to think of it, an example where that would fail is where the list has these characters already: `00` and `11`. By the reasoning in my last comment my program would print either `00` or `11` depending on what I decided to print where the number of 1s and 0s for a feature were equal. But that is the worst possible answer, because both have max similarity 2, whereas max similarity 1 is possible both for `01` and `10`. Could you bump me a bit further?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T05:03:13.853",
"Id": "216963",
"ParentId": "216960",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T01:28:04.693",
"Id": "216960",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"time-limit-exceeded",
"edit-distance"
],
"Title": "Programming Challenge from Kattis: Distinctive Characters"
} | 216960 |
<p>I understand that <code>C++</code> STL template <code>sort</code> runs faster than <code>qsort</code> in C because <code>qsort</code> needs to call the comparator multiple times and <code>C++</code> makes the code specific to that type. However, <code>C</code>'s pre-processor can hack that, too. So I build a test using <code>qsort</code>.</p>
<pre><code>#include <stdlib.h> /* EXIT */
#include <stdio.h> /* printf fputc stdout sprintf */
#include <string.h> /* strcmp */
#include <errno.h> /* errno */
#include <time.h> /* clock */
#include <ctype.h> /* toupper */
#include <math.h> /* pow */
/* Linked with a qsort called qsort_ that acts as a control to test qsort.
With C89, no inline, one has to optimise to get anything. */
/*#define QSORT_*/
static int int_cmp(const int *const a, const int *const b) {
return (*a > *b) - (*b > *a);
}
#define SORT_NAME Int
#define SORT_TYPE int
#define SORT_COMPARATOR &int_cmp
#include "Sort.h"
static int int_void_cmp(const void *a, const void *b) {
return int_cmp(a, b);
}
static void int_fill(int *const a) {
*a = rand();
}
struct Foo {
int no;
char name[64];
};
static const size_t foo_name_size = sizeof ((struct Foo *)0)->name;
static int foo_no_cmp(const struct Foo *const a, const struct Foo *const b) {
return (a->no > b->no) - (b->no > a->no);
}
#define SORT_NAME FooNo
#define SORT_TYPE struct Foo
#define SORT_COMPARATOR &foo_no_cmp
#include "Sort.h"
static int foo_name_cmp(const struct Foo *const a, const struct Foo *const b) {
return strcmp(a->name, b->name);
}
#define SORT_NAME FooName
#define SORT_TYPE struct Foo
#define SORT_COMPARATOR &foo_name_cmp
#include "Sort.h"
static int foo_void_no_cmp(const void *a, const void *b) {
return foo_no_cmp(a, b);
}
static int foo_void_name_cmp(const void *a, const void *b) {
return foo_name_cmp(a, b);
}
static void foo_fill(struct Foo *const a) {
const size_t num_chars = 4 + rand() / (RAND_MAX / (foo_name_size - 5) + 1);
size_t i;
int_fill(&a->no);
for(i = 0; i < num_chars; i++) {
a->name[i] = (i ? 'a' : 'A') + rand() / (RAND_MAX + 1.0) * 26;
}
a->name[i] = '\0';
}
/* The control -- not going to include this. C89 */
#ifdef QSORT_ /* <-- my */
void
qsort_(void *a, size_t n, size_t es, int (*cmp)(const void *, const void *));
#endif /* my --> */
typedef int (*TestFn)(const size_t, double *const);
/* This is messy. */
#define CAT_(x, y) x ## y
#define CAT(x, y) CAT_(x, y)
#define TEST_FN(NAME, TYPE, FILL, TEST) \
static int CAT(NAME, _test)(const size_t size, double *const p_ms_time) {\
TYPE *a = malloc(sizeof *a * size); \
size_t i; \
clock_t run; \
if(!a) return 0; \
for(i = 0; i < size; i++) (FILL)(a + i); \
run = -clock(); \
(TEST); \
run += clock(); \
*p_ms_time = (double)run / (CLOCKS_PER_SEC / 1000.0); \
free(a); \
return 1; \
}
TEST_FN(int_q, int, int_fill, qsort(a, size, sizeof *a, &int_void_cmp))
TEST_FN(int_s, int, int_fill, IntSort(a, size))
TEST_FN(foo_no_q, struct Foo, foo_fill, \
qsort(a, size, sizeof *a, &foo_void_no_cmp))
TEST_FN(foo_no_s, struct Foo, foo_fill, FooNoSort(a, size))
TEST_FN(foo_name_q, struct Foo, foo_fill, \
qsort(a, size, sizeof *a, &foo_void_name_cmp))
TEST_FN(foo_name_s, struct Foo, foo_fill, FooNameSort(a, size))
#ifdef QSORT_ /* <-- my */
TEST_FN(int_m, int, int_fill, qsort_(a, size, sizeof *a, &int_void_cmp))
TEST_FN(foo_no_m, struct Foo, foo_fill, \
qsort_(a, size, sizeof *a, &foo_void_no_cmp))
TEST_FN(foo_name_m, struct Foo, foo_fill, \
qsort_(a, size, sizeof *a, &foo_void_name_cmp))
#endif /* my --> */
static const char *const gnu_name = "sort.gnu";
static const char *const graph_name = "sort.eps";
static const unsigned replicas = 5;
static const size_t max_elements = 100000;
int main(void) {
struct TimeData { const char *const name; TestFn fn; } time_data[] = {
{ "qsort int", &int_q_test },
{ "IntSort", &int_s_test },
{ "qsort foo::no", &foo_no_q_test },
{ "FooNoSort", &foo_no_s_test },
{ "qsort foo::name", &foo_name_q_test },
{ "FooNameSort", &foo_name_s_test }
#ifdef QSORT_ /* <-- my */
,
{ "my qsort_ int", &int_m_test },
{ "my qsort_ foo::no", &foo_no_m_test },
{ "my qsort_ foo::name", &foo_name_m_test }
#endif /* my --> */
}, *td;
const size_t time_data_size = sizeof time_data / sizeof *time_data;
unsigned td_i;
FILE *fp = 0, *gnu = 0;
size_t elements, x, r;
char fn_name[32] = "not a file";
unsigned seed = (unsigned)clock();
const char *err = 0;
srand(seed), rand(), printf("Seed %u.\n", seed);
do { /* Try. */
if(!(gnu = fopen(gnu_name, "w"))) { err = gnu_name; break; }
fprintf(gnu, "set term postscript eps enhanced color\n"
"set output \"%s\"\n"
"set grid\n"
"set xlabel \"array elements\"\n"
"set ylabel \"processor time, t (ms)\"\n"
"set yrange [0:]\n"
"# seed %u\n"
"\n"
"plot", graph_name, seed);
for(td_i = 0; td = time_data + td_i, td_i < time_data_size; td_i++) {
/* Open <sort>.tsv for writing. */
if(sprintf(fn_name, "%s.tsv", td->name) < 0
|| !(fp = fopen(fn_name, "w"))) { err = fn_name; break; }
fprintf(stderr, "Created/overwrote, \"%s,\" to store data on %s "
"sort.\n", fn_name, td->name);
/* Do several experiments, increasing number of elements. */
fprintf(fp, "# %s: elements ms\n", td->name);
for(elements = 1, x = 2; elements <= max_elements;
elements = (unsigned)pow((double)x++, 3.5)) {
int n = 0;
double dt_ms = 0.0, mean_ms = 0.0, delta_ms, ssdm = 0.0;
fprintf(stderr, "%s: sorting %lu elements distributed uniformly"
" at random.\n", td->name, (unsigned long)elements);
/* \cite{Welford1962Note} */
for(r = 0; r < replicas; r++) {
fprintf(stderr, "#");
if(!td->fn(elements, &dt_ms)) { err = "experiment"; break; }
n++;
delta_ms = dt_ms - mean_ms;
mean_ms += delta_ms / n;
ssdm += delta_ms * (dt_ms - mean_ms);
}
fprintf(stderr, " done.\n");
if(r != replicas) break;
fprintf(fp, "%lu\t%f\t%f\n", (unsigned long)elements, mean_ms,
sqrt(ssdm / (n - 1)));
}
/* close the file */
if(fclose(fp)) { fp = 0; err = fn_name; break; }
fp = 0;
/* write the graph */
fprintf(gnu,
"%s\t\"%s\" using 1:2:3 with errorlines lw 3 title \"%s\"",
td_i ? ", \\\n" : " ", fn_name, td->name);
}
fprintf(gnu, "\n");
} while(0); if(err) perror(err); /* Catch. */
{ /* Finally. */
if(fp && fclose(fp)) perror(fn_name);
if(gnu && fclose(gnu)) perror(gnu_name);
}
return err ? EXIT_FAILURE : EXIT_SUCCESS;
}
</code></pre>
<p>This is code taken from <a href="https://onlinelibrary.wiley.com/doi/abs/10.1002/spe.4380231105" rel="noreferrer">Bentley McIlroy 1993</a> and Berkeley; I've modified it to take parameters in the form of pre-processor <code>#define</code>s. It must be run with optimisations on since I'm using <code>C89</code>: doesn't support <code>inline</code>. I've gotten rid of the warnings, but I'm not sure this compiles to the same code.</p>
<pre><code>/*
* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved
*
* Copyright (c) 1992, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)qsort.c 8.1 (Berkeley) 6/4/93
*/
/* Modified by Neil to make it parameterised.
The parameters are preprocessor macros and all are all undefined at the end of
the file for convenience.
@param SORT_NAME
A unique name associated with {<S>} that satisfies {C} naming conventions when
mangled.
@param SORT_TYPE
This type becomes {<S>}; required.
@param SORT_COMPARATOR
A function satisfying {<PS>SortComparator}.
@std C89
*/
/* Check defines. */
#ifndef SORT_NAME
#error Sort name SORT_NAME undefined.
#endif
#ifndef SORT_TYPE
#error Sort type SORT_TYPE undefined.
#endif
#ifndef SORT_COMPARATOR
#error Sort function SORT_COMPARATOR undefined.
#endif
/* Generics using the preprocessor;
\url{ http://stackoverflow.com/questions/16522341/pseudo-generics-in-c }. */
#ifdef CAT
#undef CAT
#endif
#ifdef CAT_
#undef CAT_
#endif
#ifdef PCAT
#undef PCAT
#endif
#ifdef PCAT_
#undef PCAT_
#endif
#ifdef S
#undef S
#endif
#ifdef S_
#undef S_
#endif
#ifdef PS_
#undef PS_
#endif
#define CAT_(x, y) x ## y
#define CAT(x, y) CAT_(x, y)
#define PCAT_(x, y) x ## _ ## y
#define PCAT(x, y) PCAT_(x, y)
#define S_(thing) CAT(SORT_NAME, thing)
#define PS_(thing) PCAT(sort, PCAT(SORT_NAME, thing)) /* Private. */
/* Troubles with this line? check to ensure that {SORT_TYPE} is a valid type,
whose definition is placed above {#include "Sort.h"}. */
typedef SORT_TYPE PS_(Type);
#define S PS_(Type)
/** Must establish a partial order amongst {<S>} by returning
{a < b, negative; a = b, 0; a > b, positive}. */
typedef int (*PS_(SortComparator))(const S *const a, const S *const b);
/* Check that {MAP_COMPARATOR} is a function implementing
{<PS>SortComparator}. */
static const PS_(SortComparator) PS_(cmp) = (SORT_COMPARATOR);
#include <sys/types.h>
#ifndef SORT_H /* <-- h Idempotent. */
#define SORT_H
#define sort_min(a, b) (a) < (b) ? a : b
enum SortSwapType { WORD, WORDS, BYTE };
#endif /* h --> */
/*
* Qsort routine from Bentley & McIlroy's "Engineering a Sort Function".
*
* (How does that work with the copyright?)
*/
static void
PS_(swapfunc)(S *a, S *b, const size_t n, const enum SortSwapType swaptype)
{
switch(swaptype) {
case WORDS:
case WORD:
{
long i = sizeof *a * n / sizeof(long);
long *pi = (long *)(void *)a;
long *pj = (long *)(void *)b;
do {
long t = *pi;
*pi++ = *pj;
*pj++ = t;
} while (--i > 0);
}
break;
case BYTE:
{
long i = sizeof *a * n;
char *pi = (char *)a;
char *pj = (char *)b;
do {
char t = *pi;
*pi++ = *pj;
*pj++ = t;
} while (--i > 0);
}
break;
}
}
static void
PS_(swap)(S *a, S *b, const enum SortSwapType swaptype)
{
if(swaptype == WORD) {
long t = *(long *)(void *)(a);
*(long *)(void *)(a) = *(long *)(void *)(b);
*(long *)(void *)(b) = t;
} else {
PS_(swapfunc)(a, b, (size_t)1, swaptype);
}
}
static S *
PS_(med3)(S *a, S *b, S *c)
{
return PS_(cmp)(a, b) < 0 ?
(PS_(cmp)(b, c) < 0 ? b : (PS_(cmp)(a, c) < 0 ? c : a ))
: (PS_(cmp)(b, c) > 0 ? b : (PS_(cmp)(a, c) < 0 ? a : c ));
}
static void
S_(Sort)(S *a, size_t n)
{
S *pa, *pb, *pc, *pd, *pl, *pm, *pn;
size_t vec;
long d;
enum SortSwapType swaptype;
int swap_cnt, r;
loop:
/* Re: (0*n) "warning: use of logical || with constant operand; switch to
bitwise | or remove constant [-Wconstant-logical-operand]" but sizeof are
not supported in pre-precessor. :S Wouldn't this be constant? */
swaptype = ((char *)a - (char *)0) % sizeof(long)
|| sizeof *a % sizeof(long) + (0*n) ? BYTE
: sizeof *a == sizeof(long) ? WORD : WORDS;
swap_cnt = 0;
if (n < 7) {
for (pm = a + 1; pm < a + n; pm++)
for (pl = pm; pl > a && PS_(cmp)(pl - 1, pl) > 0; pl--)
PS_(swap)(pl, pl - 1, swaptype);
return;
}
pm = a + (n / 2);
if (n > 7) {
pl = a;
pn = a + (n - 1);
if (n > 40) {
d = n / 8;
pl = PS_(med3)(pl, pl + d, pl + 2 * d);
pm = PS_(med3)(pm - d, pm, pm + d);
pn = PS_(med3)(pn - 2 * d, pn - d, pn);
}
pm = PS_(med3)(pl, pm, pn);
}
PS_(swap)(a, pm, swaptype);
pa = pb = a + 1;
pc = pd = a + (n - 1);
for (;;) {
while (pb <= pc && (r = PS_(cmp)(pb, a)) <= 0) {
if (r == 0) {
swap_cnt = 1;
PS_(swap)(pa, pb, swaptype);
pa++;
}
pb++;
}
while (pb <= pc && (r = PS_(cmp)(pc, a)) >= 0) {
if (r == 0) {
swap_cnt = 1;
PS_(swap)(pc, pd, swaptype);
pd--;
}
pc--;
}
if (pb > pc)
break;
PS_(swap)(pb, pc, swaptype);
swap_cnt = 1;
pb++;
pc--;
}
if (swap_cnt == 0) { /* Switch to insertion sort */
for (pm = a + 1; pm < a + n; pm++)
for (pl = pm; pl > a && PS_(cmp)(pl - 1, pl) > 0; pl--)
PS_(swap)(pl, pl - 1, swaptype);
return;
}
pn = a + n;
vec = sort_min(pa - a, pb - pa);
if(vec > 0) PS_(swapfunc)(a, pb - vec, vec, swaptype);
vec = sort_min((size_t)(pd - pc), (size_t)(pn - pd - 1));
if(vec > 0) PS_(swapfunc)(pb, pn - vec, vec, swaptype);
if ((size_t)(vec = pb - pa) > 1)
S_(Sort)(a, vec);
if ((vec = pd - pc) > 1) {
/* Iterate rather than recurse to save stack space */
a = pn - vec;
n = vec;
goto loop;
}
}
/* Un-define all macros. Undocumented; allows nestled inclusion so long as:
{CAT_}, {CAT}, {PCAT}, {PCAT_} conform, and {S}, is not used. */
#ifdef SORT_SUBTYPE /* <-- sub */
#undef SORT_SUBTYPE
#else /* sub --><-- !sub */
#undef CAT
#undef CAT_
#undef PCAT
#undef PCAT_
#endif /* !sub --> */
#undef S
#undef S_
#undef PS_
#undef SORT_NAME
#undef SORT_TYPE
#undef SORT_COMPARATOR
</code></pre>
<p>On my computer, it outputs, with optimisations on, <code>via</code> <code>gnuplot</code>. It is faster, but not by much.</p>
<p><a href="https://i.stack.imgur.com/zJ6av.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zJ6av.png" alt="As expected, parameterised sort is better then a general qsort."></a></p>
<p>I'm not sure about the changes I've made to <code>qsort.c</code>. Specifically, why <code>swaptype = (a-(char*)0 | es) % W ? 2 : es > W ? 1 : 0</code> (<a href="https://onlinelibrary.wiley.com/doi/abs/10.1002/spe.4380231105" rel="noreferrer">Bentley1993</a>,) where <code>es</code> is the size. Why is it called every time? Shouldn't it be <code>a | es</code> without the subtracting null? Isn't <code>a</code> aligned properly and it might be <code>es</code> and taken out of the loop?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T02:28:15.800",
"Id": "419652",
"Score": "1",
"body": "you might be interested in [Perl's qsort](https://github.com/Perl/perl5/blob/cc93400aa5a8d556c56c28a8de644bd178d050d4/pp_sort.c) which switches to insertion sort on small partitions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T02:42:20.360",
"Id": "419653",
"Score": "0",
"body": "I think that they were heavily influenced by the same paper."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T04:06:39.777",
"Id": "419655",
"Score": "2",
"body": "It would be interesting to see where std::sort places on that graph."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T01:38:57.687",
"Id": "216961",
"Score": "7",
"Tags": [
"c",
"sorting",
"quick-sort",
"c89"
],
"Title": "Engineering an even faster qsort"
} | 216961 |
<p>I am writing a Python script that will be used to generate <a href="https://docs.influxdata.com/influxdb/v1.7/write_protocols/line_protocol_tutorial/" rel="nofollow noreferrer">line protocol</a> for inserting metrics into an InfluxDB. I'm parsing the status page of my cable modem. That part works. I receive the data and can extract the table of information I need. </p>
<p>The HTML for the table looks like this (yes, it has the commented out lines)</p>
<p>The I have below works, but it feels inefficient. I feel like I have a lot of loops and these feel unnecessary. I'm not sure how to be more efficient though.</p>
<p>The only change between this and my real code is that I've moved the HTML to pastebin to cut down on the length of this post. That pastebin is <a href="https://pastebin.com/raw/bLZLFzy6" rel="nofollow noreferrer">here</a> and the HTML is not written or editable by me. It's generated on the cable modem. Since you aren't able to see the results of my cable modem by running the code I use to extract it from the modem, I hope this is good enough.</p>
<pre><code>from bs4 import BeautifulSoup
import requests
results_url = "https://pastebin.com/raw/bLZLFzy6"
content = requests.get(results_url).text
measurement = "modem"
hostname = "home-modem"
def strip_uom(data):
"""Strip Unit of Measurement
Some of our fields come with unit of measure. Rip that out and keep only
the value of the field.
"""
uom = ["dB", "Hz", "dBmV", "Ksym/sec"]
dataset = []
for d in data:
if d.split(" ")[-1] in uom:
dataset.append(d.split(" ")[0])
else:
dataset.append(d)
return dataset
soup = BeautifulSoup(content, 'html.parser')
dstable = soup.find('table', {'id': 'dsTable'})
# Pull the headers from the downstream table
# We want to make these tag friendly, so make them lowercase and remove spaces
dstable_tags = [td.get_text().lower().replace(" ", "_") for td in dstable.tr.find_all('td')]
# Pull out the rest of the data for each row in the table; associate it with the correct tag; Strip UoM
downstream_data = []
for row in dstable.find_all('tr')[1:]:
column_values = [col.get_text() for col in row.find_all('td')]
downstream_data.append(dict(zip(dstable_tags, strip_uom(column_values))))
# Print line protocol lines for telegraf's inputs.exec plugin to handle
for data in downstream_data:
line_protocol_line = f"{measurement},hostname={hostname}"
fields = []
for key, value in data.items():
# Check if our value is a number. If it's not, surround it in quotes.
# Don't actually use the float() value, as some numbers are returned as
# valid integers
try:
_ = float(value)
fields.append(f'{key}={value}')
except ValueError:
fields.append(f'{key}="{value}"')
fieldset = ",".join(fields)
line_protocol_line = line_protocol_line + f",channel={data['channel']} {fieldset}"
print(line_protocol_line)
</code></pre>
<p>Finally, the output this script generates is this:</p>
<pre class="lang-none prettyprint-override"><code>modem,hostname=netgear-cm400,channel=1 channel=1,lock_status="Locked",modulation="QAM 256",channel_id=121,frequency=585000000,power=5.6,snr=37.0,correctables=19443,uncorrectables=11263
modem,hostname=netgear-cm400,channel=2 channel=2,lock_status="Locked",modulation="QAM 256",channel_id=6,frequency=591000000,power=5.7,snr=37.0,correctables=19531,uncorrectables=9512
modem,hostname=netgear-cm400,channel=3 channel=3,lock_status="Locked",modulation="QAM 256",channel_id=7,frequency=597000000,power=5.7,snr=36.8,correctables=17457,uncorrectables=9736
modem,hostname=netgear-cm400,channel=4 channel=4,lock_status="Locked",modulation="QAM 256",channel_id=8,frequency=603000000,power=5.9,snr=37.0,correctables=12750,uncorrectables=11156
modem,hostname=netgear-cm400,channel=5 channel=5,lock_status="Locked",modulation="QAM 256",channel_id=122,frequency=609000000,power=2.6,snr=36.3,correctables=1855538,uncorrectables=18388
modem,hostname=netgear-cm400,channel=6 channel=6,lock_status="Locked",modulation="QAM 256",channel_id=10,frequency=615000000,power=2.6,snr=37.0,correctables=846194,uncorrectables=14615
modem,hostname=netgear-cm400,channel=7 channel=7,lock_status="Locked",modulation="QAM 256",channel_id=11,frequency=621000000,power=2.6,snr=37.6,correctables=281431,uncorrectables=13998
modem,hostname=netgear-cm400,channel=8 channel=8,lock_status="Locked",modulation="QAM 256",channel_id=12,frequency=627000000,power=2.4,snr=36.1,correctables=78059,uncorrectables=13695
</code></pre>
<p>I have loops and list comprehensions to get the tags, associate data with tags for each row, and to generate the line protocol lines. I have two additional comprehensions in <em>those</em> and a loop to see if I need to strip out an included unit of measure. Can I eliminate some of these to be more efficient?</p>
<p>I am running all of this code on Python 3.6.7. </p>
<p>Example Table to show field values (this is NOT the HTML table)</p>
<pre class="lang-none prettyprint-override"><code>Channel Lock Status Modulation Channel ID Frequency Power SNR Correctables UnCorrectables
1 Locked QAM 256 121 585000000 Hz 4.9 dBmV 37.0 dB 20513 11263
2 Locked QAM 256 6 591000000 Hz 5.0 dBmV 37.0 dB 20571 9512
3 Locked QAM 256 7 597000000 Hz 4.9 dBmV 36.8 dB 18347 9736
4 Locked QAM 256 8 603000000 Hz 5.1 dBmV 37.0 dB 13391 11156
5 Locked QAM 256 122 609000000 Hz 1.9 dBmV 36.3 dB 1936410 18388
6 Locked QAM 256 10 615000000 Hz 1.9 dBmV 37.0 dB 882543 14615
7 Locked QAM 256 11 621000000 Hz 1.8 dBmV 37.6 dB 293494 13998
8 Locked QAM 256 12 627000000 Hz 1.7 dBmV 35.9 dB 81559 13695
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T17:09:05.783",
"Id": "419696",
"Score": "0",
"body": "About your unit stripping. What does the stuff before it look like? Is it always a floating-point number? Regexes are good at this, and the regex can be simplified by targeting the number instead of the unit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T17:12:50.893",
"Id": "419698",
"Score": "0",
"body": "And what's consuming the output of this script? Because that output format is a strange mix of JSON-like key-value pairs and CSV. If you can change it, you should."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T17:14:49.257",
"Id": "419699",
"Score": "0",
"body": "Oh, I guess it's to feed this - https://github.com/influxdata/telegraf/tree/master/plugins/inputs/exec"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T20:22:03.437",
"Id": "419709",
"Score": "0",
"body": "@Reinderien Yes, the output is consumed by Telegraf's exec plugin. I've also attached the table in tabular format so that you can see the values I receive and how it looks with (and without) the UoM on the fields. The real table is in the HTML, this is just to give you an idea of what the lines looks like a little more easily."
}
] | [
{
"body": "<h2>Use regexes</h2>\n\n<p>...and a generator. This matches against an unknown prefix, and an optional unit suffix, and drops the suffix.</p>\n\n<pre><code>def strip_uom(data):\n rex = re.compile(r'^(.+?) *(dB|Hz|dBmV|Ksym/sec)?$')\n return (rex.match(d)[1] for d in data)\n</code></pre>\n\n<p>However, this is more easily done by matching on the number itself:</p>\n\n<pre><code>def strip_uom(data):\n rex = re.compile(r'^([0-9.]+)')\n return (rex.match(d)[1] for d in data)\n</code></pre>\n\n<p>I haven't tested this, so you should.</p>\n\n<h2>Make a main function</h2>\n\n<p>To house your global code.</p>\n\n<h2>Avoid a list for <code>fields</code></h2>\n\n<p>Instead, you can use a generator function here too:</p>\n\n<pre><code>def pairs_from_dict(data):\n for key, value in data.items():\n try:\n float(value)\n except ValueError:\n value = f'\"{value}\"'\n yield f'{key}={value}'\n</code></pre>\n\n<h2>Potential loop reduction</h2>\n\n<pre><code>downstream_data = []\nfor row in dstable.find_all('tr')[1:]:\n column_values = [col.get_text() for col in row.find_all('td')]\n downstream_data.append(dict(zip(dstable_tags, strip_uom(column_values))))\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>downstream_data = [\n dict(zip(dstable_tags, strip_uom(\n col.get_text() for col in row.find_all('td')\n )))\n for row in dstable.find_all('tr')[1:]\n]\n</code></pre>\n\n<p>though I don't particularly think that's an improvement.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T03:29:03.083",
"Id": "419719",
"Score": "0",
"body": "I tested the regular expression. It doesn't work against the text columns (`Lock Status` and `Modulation`). Since those don't start with a numeral, they return a NoneType (`TypeError: 'NoneType' object is not subscriptable`). Thank you for the idea in `pairs_from_dict`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T03:31:46.203",
"Id": "419720",
"Score": "0",
"body": "You can either choose to apply the regex only to columns you expect to have units; swallow the exception and take the whole column; or use the first regex shown that drops the suffixes listed explicitly."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T17:39:50.193",
"Id": "216984",
"ParentId": "216962",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "216984",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T04:24:09.273",
"Id": "216962",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"beautifulsoup"
],
"Title": "Eliminate unnecessary looping while parsing cable modem status table"
} | 216962 |
<p>I have some survey data that represents individual's responses to multiple survey questions. There are about 10,000 people in my actual dataset, and each person answered 35 questions. From these 35 survey questions, I create 1 composite score for each individual by taking the average of the values of all the questions that person answered. I am looking to see if I can find a subset of less than all 35 variables that produces a composite score that is highly correlated with the scores individuals receive if I use all of the questions.</p>
<p>Essentially, I want to be able identify which questions you should ask, if you can only ask <code>X</code> questions, and still end up with a composite score that is similar to if you asked all the questions.</p>
<hr>
<p>I have created an example dataset, but with only 1,000 individuals and 10 questions. I have then written the code below to identify every subset of variables and compare the correlation of individual's scores when using just that subset to individual's scores when using all of the variables.</p>
<p>While my method below works when there are 1,000 individuals and 10 questions, it does not scale to my reality of 10,000 individuals and 35 questions, because of all the possible combinations of variables (2^35 = 34,359,738,368).</p>
<p>(Note: I have simplified my question and the sample data below for the purpose of this question.)</p>
<hr>
<p>Code on GitHub: <a href="https://github.com/CurtLH/variable_subset/blob/master/powerset%20correlations.ipynb" rel="nofollow noreferrer">https://github.com/CurtLH/variable_subset/blob/master/powerset%20correlations.ipynb</a></p>
<hr>
<pre><code>import random
import numpy as np
import pandas as pd
from itertools import chain, combinations
# initial parameters
random.seed(1234)
num_ids = 1000
num_vars = 10
# create repeating IDs
ids = sorted(list(range(0, num_ids)) * num_vars)
# create repeating variables
variables = list(range(0, num_vars)) * num_ids
# create random integers
values = np.random.randint(1, 5, size = num_ids * num_vars)
# create a dataframe with these values
df = pd.DataFrame({"id": ids, "variable": variables, "values": values})
# sort the dataframe
df.sort_values(['id', 'variable'], inplace=True)
def powerset(iterable):
"""
Thanks to https://stackoverflow.com/questions/1482308
"""
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
# create every subset of variables
subsets = list(powerset(set(variables)))
# calculate the average value by ID when including all variables
actual = df.groupby('id')['values'].mean()
def calculate(df, subsets):
"""
1. Iterate over each permutation of variables
2. Subset the dataframe to only include those variables
3. Group by ID and recalculate the mean values per ID
4. Measure correlation with complete set of variables
"""
# create a dictionary to hold the results
results = {}
# iterate over each subset
for s in subsets:
# make sure there is at least 1 variable...
if len(s) > 0:
# filter the dataframe to only the variables in the subset
sub = df[df['variable'].isin(s)]
# group by ID and calculate average value
scores = sub.groupby('id')['values'].mean()
# calculate correlation compared to complete set of variables
corr = actual.corr(scores)
# add results to dictionary
results[s] = {'num_items': len(s),
'correlation': corr}
return results
# time how long it takes to run
%%timeit results = calculate(df, subsets)
</code></pre>
<hr>
<p>Timing results:</p>
<ul>
<li>2.23 s ± 3.91 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T17:01:06.513",
"Id": "419694",
"Score": "0",
"body": "This... smells. Like a few lines of R. Calculate your composite score, call `cor`, and chop out anything below a chosen threshold."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T17:06:25.403",
"Id": "419695",
"Score": "0",
"body": "I suppose the bigger question is - why try combinations at all? If a certain variable is uncorrelated to your composite, what's the harm in cutting it out wholesale instead of retrying it with other combinations of variables?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T01:05:54.740",
"Id": "419716",
"Score": "1",
"body": "Reduce dimensions with PCA etc."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T05:46:56.707",
"Id": "216966",
"Score": "3",
"Tags": [
"python",
"numpy",
"pandas"
],
"Title": "Compare every combination of variables within the powerset"
} | 216966 |
<p>I have written a code for a tic-tac-toe game and it works well. But, I don't know whether it is an efficient one. Any help on how to optimize it?</p>
<pre><code>def restart():
num=[0 for i in range(9)]
board=[" " for i in range(9)]
a=2
start(board,a,num)
def wincheck(t):
for i in range(8):
if t[win[i][0]]==t[win[i][1]] and t[win[i][0]]==t[win[i][2]] and
t[win[i][1]]==t[win[i][2]] and t[win[i][0]]!=" ":
if t[win[i][0]]=="X":
print("Player 1 wins")
else:
print("Player 2 wins")
playa = input("Do you want to play again? Y/N")
if playa.lower() == "y":
restart()
else:
exit(0)
def display_board(t,a,num):
print( " "*3+'|'+" "*3+'|'+" "*3)
print("{0:^3}|{1:^3}|{2:^3}".format(t[6],t[7],t[8]))
print( " "*3+'|'+" "*3+'|'+" "*3)
print("-"*11)
print( " "*3+'|'+" "*3+'|'+" "*3)
print("{0:^3}|{1:^3}|{2:^3}".format(t[3],t[4],t[5]))
print( " "*3+'|'+" "*3+'|'+" "*3)
print("-"*11)
print( " "*3+'|'+" "*3+'|'+" "*3)
print("{0:^3}|{1:^3}|{2:^3}".format(t[0],t[1],t[2]))
print( " "*3+'|'+" "*3+'|'+" "*3)
wincheck(t)
if 0 not in num:
print("Draw")
restart()
start(t,a,num)
def start(board,a,num):
if a%2==0:
p1n=int(input("Player 1, Enter a number from 1 to 9"))
if p1n not in num:
num[p1n-1]=p1n
print(num)
else:
print("Please enter in a free space")
start(board,a,num)
board[p1n-1]="X"
a=a+1
display_board(board,a,num)
else:
p2n=int(input("Player 2, Enter a number from 1 to 9"))
if p2n not in num:
num[p2n-1]=p2n
print(num)
else:
print("Please enter in a free space")
start(board,a,num)
board[p2n-1]="O"
a=a+1
display_board(board,a,num)
a=2
board=[" " for i in range(9)]
num=[0 for i in range(9)]
win = [[0,1,2],[3,4,5],[6,7,8],[0,4,8],[6,4,2],[6,3,0],[7,4,1],[8,5,2]]
start(board,a,num)
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p>Any help on how to optimize it?</p>\n</blockquote>\n\n<p>Optimise <em>readability</em>, starting with following the <a href=\"https://www.python.org/dev/peps/pep-0008/#comments\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a>.<br>\n(And yes, this is a useful step in <em>optimising efficiency</em>, too) </p>\n\n<p>(The below reads an ill-tempered diatribe more than a code review, the sole exculpation being the explicit question in the title. (I should look for a well-receives SE resource bound to exist.)) </p>\n\n<p><em>How to write efficient source code for …?</em><br>\nGiven a specification that looks ready for implementation,<br>\n- write tests shedding a light on correctness.<br>\n- fix(!) a limit for the effort to improve <em>efficiency</em><br>\n- <em>define</em> a measure for <em>efficient</em><br>\n(-if applicable, define <em>relevant input data</em>)<br>\n- automate measuring <em>efficiency</em> - memory usage is harder to assess than time used<br>\n (use available tools - <a href=\"https://docs.python.org/3/library/timeit.html\" rel=\"nofollow noreferrer\">timeit</a>, for starters)<br>\n (It saves a lot of trouble to include (basic) functional tests here)<br>\n (Don't believe sub-second measurements.<br>\n Measure work completed in a fixed amount of time, not time used for a fixed amount of work.)<br>\n- use your first working version to establish a <em>base line</em><br>\n- fix(!) what performance is <em>good enough</em><br>\n- pick alternative implementations, jot down your guesses re. <em>efficiency</em>, measure<br>\n- time allowing (see <em>limit</em> above), experiment with improvements</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T10:20:01.297",
"Id": "216972",
"ParentId": "216967",
"Score": "3"
}
},
{
"body": "<p>I think your code is outstanding. I don't think you should be concerned about optimizing it since it runs quickly anyway. It is clear and easy to understand (which Python claims to be), so no need to obscure it with attempts to make it more "Pythonic".</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-13T16:14:21.997",
"Id": "247865",
"ParentId": "216967",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T06:45:17.260",
"Id": "216967",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"tic-tac-toe"
],
"Title": "Tic-Tac-Toe game in Python 3"
} | 216967 |
<p>I would like to make the timer queue:
1. Each timer has id, time expired and callback to call
2. Queue stores timer and execute the callback of each timer whenever expired.</p>
<p>Here is my code and demo:</p>
<pre><code> #include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
#include <functional>
#include <list>
#include <condition_variable>
#include <ctime>
// Helper function to print time
void print_time()
{
std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();
std::chrono::system_clock::duration tp = now.time_since_epoch();
tp -= std::chrono::duration_cast<std::chrono::seconds>(tp);
std::time_t ttp = std::chrono::system_clock::to_time_t(now);
tm t = *gmtime(&ttp);
std::printf("[%04u-%02u-%02u %02u:%02u:%02u.%03u]: ", t.tm_year + 1900,
t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec,
static_cast<unsigned>(tp/std::chrono::milliseconds(1)));
}
typedef std::function<void(int)> TimerCallback;
struct TimerItem {
int id;
TimerCallback cb;
std::chrono::time_point<std::chrono::system_clock> until;
};
bool compareTimerItem(std::shared_ptr<TimerItem> lhs, std::shared_ptr<TimerItem> rhs)
{
return std::chrono::duration_cast<std::chrono::milliseconds>(lhs->until - rhs->until).count() < 0 ? true: false;
}
class TimerQueue {
public:
virtual ~TimerQueue() { m_thread.join(); }
TimerQueue(const TimerQueue&) = delete;
TimerQueue& operator=(TimerQueue&) = delete;
static std::shared_ptr<TimerQueue> getInstance() {
static std::shared_ptr<TimerQueue> instance(new TimerQueue);
return instance;
}
void setTimer(int id, long milliseconds, TimerCallback cb)
{
print_time();
std::cout << __FUNCTION__ << "id: " << id << "\ttimer: " << milliseconds << std::endl;
std::unique_lock<std::mutex> lk_cd(m_timerListMtx);
std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();
std::chrono::time_point<std::chrono::system_clock> until = now + std::chrono::milliseconds(milliseconds);
std::shared_ptr<TimerItem> item = std::make_shared<TimerItem>();
item->id = id;
item->cb = cb;
item->until = until;
{
if (isTimerExist(id) == false)
{
std::lock_guard<std::mutex> lk(m_queueMtx);
m_timerList.push_back(item);
m_timerList.sort(compareTimerItem);
TimerQueue::m_timer_ready = true;
}
}
lk_cd.unlock();
m_cvTimerList.notify_one();
}
void removeTimer(int id)
{
std::lock_guard<std::mutex> lk(m_queueMtx);
std::shared_ptr<TimerItem> item;
std::list<std::shared_ptr<TimerItem>>::iterator it = m_timerList.begin();
while (it != m_timerList.end())
{
item = *it;
if (item->id == id)
{
it = m_timerList.erase(it);
break;
}
else
{
++it;
}
}
}
bool isTimerExist(int id)
{
std::lock_guard<std::mutex> lk(m_queueMtx);
bool result = false;
std::shared_ptr<TimerItem> item;
std::list<std::shared_ptr<TimerItem>>::iterator it = m_timerList.begin();
while (it != m_timerList.end())
{
item = *it;
if (item->id == id)
{
result = true;
break;
}
else
{
++it;
}
}
return result;
}
static bool m_timer_ready;
private:
TimerQueue() {
std::cout << "Timer Queue constructor\n";
m_thread = std::thread(&TimerQueue::start, this);
}
void start()
{
std::cout << "Start thread\n";
std::shared_ptr<TimerItem> item;
while (true)
{
if (m_timerList.empty() == true)
{
// std::cout << "timer list is empty\n";
std::unique_lock<std::mutex> lk(m_timerListMtx);
m_cvTimerList.wait(lk, []{return TimerQueue::m_timer_ready;});
}
else
{
{
std::lock_guard<std::mutex> lk(m_queueMtx);
item = m_timerList.front();
}
{
std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();
auto count_down = std::chrono::duration_cast<std::chrono::milliseconds>(item->until - now);
// std::cout << "Count down: " << count_down.count() << std::endl;
if (count_down.count() <= 0)
{
item->cb(item->id);
{
std::lock_guard<std::mutex> lk(m_queueMtx);
m_timerList.pop_front();
}
}
}
}
}
}
std::list<std::shared_ptr<TimerItem>> m_timerList;
std::mutex m_timerListMtx;
std::mutex m_queueMtx;
std::condition_variable m_cvTimerList;
std::thread m_thread;
};
void foo(int num)
{
print_time();
std::cout << " Foo: " << num << std::endl;
}
bool TimerQueue::m_timer_ready = false;
int main(int argc, char *argv[])
{
long ms = 1000;
TimerCallback cb = foo;
for (int i = 0; i < 10; ++i)
{
TimerQueue::getInstance()->setTimer(i, ms * i, cb);
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
return 0;
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T10:55:35.100",
"Id": "216973",
"Score": "1",
"Tags": [
"c++",
"timer"
],
"Title": "Timer queue with chrono"
} | 216973 |
<p>The task:</p>
<blockquote>
<p>Given a list, sort it using this method: <code>reverse(lst, i, j)</code>, which
reverses <code>lst</code> from <code>i</code> to <code>j</code>.</p>
</blockquote>
<p>My functional solution:</p>
<pre><code>const reverse = (lst, i, j) => [...lst.slice(0, i), ...lst.slice(i, j + 1).reverse(), ...lst.slice(j + 1)];
console.log(reverse([0,1,2,3,4,5], 2, 4));
</code></pre>
<p>My imperative solution:</p>
<pre><code>function reverse(lst, i, j) {
const lstReversed = [];
let x = j;
for (let k = 0, len = lst.length; k < len; k++) {
lstReversed.push(lst[k < i || k > j ? k : x--]);
}
return lstReversed;
}
console.log(reverse([0,1,2,3,4,5], 2, 4));
</code></pre>
<p>The algorithm using the <code>reverse</code> function:</p>
<pre><code>let lst = [7,6,3,8,5,0,9,1,2,4];
const len = lst.length;
for (let x = 0; x < len; x++) {
for (let y = 1; y < len; y++) {
if (lst[y - 1] > lst[y]) { lst = reverse(lst, y - 1, y); }
}
}
console.log(lst);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T15:13:46.220",
"Id": "419682",
"Score": "2",
"body": "You are supposed to write an algorithm which sorts the list using a `reverse` function, you only created the `reverse` function.."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T11:11:58.057",
"Id": "216974",
"Score": "2",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"functional-programming"
],
"Title": "Sort a list using a reverse helper function"
} | 216974 |
<p>I am building some classes to serialize (in an <code>async</code> / <code>await</code> way) potentially pretty long <code>IEnumerable<T></code> over the network via the <code>Stream</code> class, I am wondering whether my code is easily readable et maintainable. </p>
<p>For example one purpose is that the serializer classes can be used in some ASP.NET controllers and write to the output stream a lot of data without wasting too many threads (hence the <code>async</code> / <code>await</code> approach). </p>
<p>In my example of implementation the item serialization leverages the <code>ServiceStack.Text</code> serializers.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.IO;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using ServiceStack;
namespace ConsoleApp
{
public static class Program
{
public static async Task Main(params string[] args)
{
var source = new[] {1, 2 ,3, 4};
var serializer = new JsonLineBasedEnumerableStreamSerializer();
using (var stream = new MemoryStream())
{
await serializer.SerializeToStreamAsync(source, stream, 1024, true);
stream.Position = 0;
using (var streamReader = new StreamReader(stream))
{
var serialization = streamReader.ReadToEnd();
Console.WriteLine(serialization);
}
}
}
}
public static class EnumerableExtensions
{
public static IEnumerable<Iteration<TSource>> Detailed<TSource>(this IEnumerable<TSource> source)
{
using (var enumerator = source.GetEnumerator())
{
var isFirst = true;
var hasNext = enumerator.MoveNext();
var index = BigInteger.Zero;
while (hasNext)
{
var current = enumerator.Current;
hasNext = enumerator.MoveNext();
yield return new Iteration<TSource>(index, current, isFirst, !hasNext);
isFirst = false;
index++;
}
}
}
}
public readonly struct Iteration<T>
{
public readonly BigInteger Index;
public readonly bool IsFirst;
public readonly bool IsLast;
public readonly T Value;
public Iteration(BigInteger index, T value, bool isFirst, bool isLast)
{
Index = index;
IsFirst = isFirst;
IsLast = isLast;
Value = value;
}
}
public interface IEnumerableStreamSerializer
{
Task SerializeToStreamAsync<T>(IEnumerable<T> source, Stream stream, ushort bufferSize = 1024, bool leaveOpen = false);
}
public abstract class EnumerableStreamSerializer : IEnumerableStreamSerializer
{
public abstract Task SerializeToStreamAsync<T>(IEnumerable<T> source, Stream stream, ushort bufferSize = 1024, bool leaveOpen = false);
}
public abstract class LineBasedEnumerableStreamSerializer : EnumerableStreamSerializer
{
public async Task SerializeToStreamAsync<T>(IEnumerable<T> source, Stream stream, Encoding encoding, ushort bufferSize = 1024, bool leaveOpen = false)
{
using (var streamWriter = new StreamWriter(stream, encoding, bufferSize, leaveOpen))
{
var firstLine = await GetFirstLineAsync();
await streamWriter.WriteLineAsync(firstLine);
foreach (var iteration in source.Detailed())
{
var itemLine = await GetItemLineAsync(iteration.Index, iteration.Value, iteration.IsFirst, iteration.IsLast);
await streamWriter.WriteLineAsync(itemLine);
}
var lastLine = await GetLastLineAsync();
await streamWriter.WriteLineAsync(lastLine);
}
}
public override async Task SerializeToStreamAsync<T>(IEnumerable<T> source, Stream stream, ushort bufferSize = 1024, bool leaveOpen = false)
{
await SerializeToStreamAsync(source, stream, Encoding.Default, bufferSize, leaveOpen);
}
protected abstract Task<string> GetFirstLineAsync();
protected abstract Task<string> GetItemLineAsync<T>(BigInteger index, T item, bool isFirst, bool isLast);
protected abstract Task<string> GetLastLineAsync();
}
public class JsonLineBasedEnumerableStreamSerializer : LineBasedEnumerableStreamSerializer
{
protected override async Task<string> GetFirstLineAsync() =>
"[";
protected override async Task<string> GetItemLineAsync<T>(BigInteger index, T item, bool isFirst, bool isLast)
{
var result = $" {item.ToJson()}";
return !isLast
? $"{result},"
: result;
}
protected override async Task<string> GetLastLineAsync() =>
"]";
}
public class XmlLineBasedEnumerableStreamSerializer : LineBasedEnumerableStreamSerializer
{
protected override async Task<string> GetFirstLineAsync() =>
"<Array>";
protected override async Task<string> GetItemLineAsync<T>(BigInteger index, T item, bool isFirst, bool isLast) =>
$" <Item>{item.ToXml()}</Item>";
protected override async Task<string> GetLastLineAsync() =>
"</Array>";
}
}
</code></pre>
<p>What do you think, is there anything I can improve in my implementation to make it better?</p>
| [] | [
{
"body": "<ol>\n<li>You have both <code>IEnumerableStreamSerializer</code> and <code>EnumerableStreamSerializer</code>, and in fact neither of them are used in the code you posted. I'd have just stuck with one or the other (probably the interface, and introduce the base class if you need to share common functionality; alternatively if you need to worry about backwards compatibility with other people implementing it, opt for the abstract base class).</li>\n<li>I'm not at all convinced that you need <code>BigInteger</code>. <code>long</code> goes up to <em>nine quintillion</em> - serializing something that large would mean transferring at least 36 exabytes of data (for json, more for xml). That's <a href=\"https://thenextweb.com/contributors/2017/04/11/current-global-state-internet/#.tnw_8pHvZxpk\" rel=\"noreferrer\">more than the entire world transfers over mobile data per month</a>.</li>\n<li>Avoid <code>Encoding.Default</code>. It's based on the computer's code page, and will therefore be different across different computers. That's a very bad thing for a serialization library! A sensible, standard choice is <code>Encoding.UTF8</code>.</li>\n<li>You've got default parameter values for <code>bufferSize</code> and <code>leaveOpen</code>, but use an overload for <code>encoding</code>. That's inconsistent. Just use <code>Encoding encoding = null</code>, then check for <code>null</code> in your method.</li>\n<li>To be honest, I wouldn't make the buffer size configurable personally.</li>\n<li>There's no point in having an <code>async</code> method which just does <code>await somethingElse;</code> Just make it non-async and <code>return somethingElse;</code> instead.</li>\n<li>Your <code>GetFirstLineAsync</code> implementations will be throwing warnings, as they're <code>async</code> but don't have <code>awaits</code>. You'd be best off making them <code>non-async</code>, and returning a <code>Task.FromResult(\"whatever\")</code>. You'll want to cache this <code>Task</code>, so you'll want a <code>private static readonly Task<string> firstLine = Task.FromResult(\"whatever\")</code> then <code>public Task<string> GetFirstLineAsync() => firstLine;</code></li>\n<li>Ditto <code>GetLastLineAsync()</code></li>\n<li>Ditto <code>GetItemLineAsync()</code>, although in this case you can't cache the resulting <code>Task</code>. </li>\n<li>That said, do those methods really need to be async? Serializing something is very unlikely to be IO-bound - it's either going to be so cheap it's almost free, or CPU-bound. If it's CPU-bound, you're not going to call <code>Task.Run</code> for <em>each line</em> - that's crazy expensive and of questionable benefit. I'd ditch it - if it becomes expensive and you need to farm it off to another thread for whatever reason, run the entire operation on another thread, not individual lines. With that gone, your entire serializer becomes synchronous which goes against your question, but then your code (being synchronous in reality) goes against your question.</li>\n<li>If you're worried about speed, <code>$\"{result},\"</code> is going to be a bit slower than <code>result + \",\"</code>, and I'm not sure it's any more readable (of course, with more complex interpolated strings, you might want to take the performance hit for readability). Ditto the other bits of string interpolation. </li>\n<li>Missing null-checks on parameters etc, generally, if you care. If you add null-checks to <code>EnumerableExtensions.Detailed</code>, don't forget to move the state machine to a separate private (possibly inner) method.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T20:43:06.793",
"Id": "419785",
"Score": "0",
"body": "thanks for your review! I started to think about this async all the way cause I am playing with the transformation of a remote resource content. Something like Remote File --> API (transforming each line of the remote file) --> Streaming of the transformation to the client.\nI kinda agree with you when it comes to my aggressive async policy but I still concern about the memory. The fact the remote file can be relatively big also means that the API may get stuck on one single thread while transforming the whole file at once. What do you think?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T21:42:22.373",
"Id": "419789",
"Score": "1",
"body": "I forgot you were asynchronously writing to the stream when I wrote that bit if the review: that is worth doing asynchronously. If you need to asynchronously fetch each item to be serialised, fine, but then your `source` should probably yield items asynchronously (a la `IAsyncEnumerable`) and you should probably write out the previous serialised item while fetching the next. In that case as well, actually serializing each item, once fetched, will probably still be sync. That's a good deal more complex than the case your code shows, so you might want a separate serializer implementation."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T20:13:22.333",
"Id": "217030",
"ParentId": "216975",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "217030",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T11:31:12.887",
"Id": "216975",
"Score": "2",
"Tags": [
"c#",
".net",
"serialization",
".net-core"
],
"Title": "IEnumerable<T> async serialization"
} | 216975 |
<p>I have been doing projects from the book <a href="https://rads.stackoverflow.com/amzn/click/com/0262640686" rel="noreferrer" rel="nofollow noreferrer">The Elements of Computing Systems</a>. Under the scope of project 10 and project 11, I had to implement a compiler for a (toy) programming language called Jack (its grammar can be found <a href="http://nand2tetris-questions-and-answers-forum.32033.n3.nabble.com/file/n4032358/JackSyntax-1.html" rel="noreferrer">here</a>). The compiler translates Jack code into Virtual Machine instructions (all Virtual Machine commands can be found <a href="http://nand2tetris-questions-and-answers-forum.32033.n3.nabble.com/VM-Language-and-Implementation-Summary-td4032326.html" rel="noreferrer">here</a>).</p>
<p>My code contains occasional free() statements, but my primary memory management strategy was not to release any memory, as the program works only for a couple of seconds.</p>
<p>I have added the most relevant parts of the compiler below. The full code can be found <a href="https://github.com/almaveln/jack-compiler" rel="noreferrer">here</a></p>
<h2>lexer.h</h2>
<pre><code>#ifndef COMPILER_TOKENIZER_H
#define COMPILER_TOKENIZER_H
#include <stdio.h>
#include <stdbool.h>
#include "util.h"
typedef enum {
KEYWORD,
SYMBOL,
IDENTIFIER,
INT_CONST,
STRING_CONST
} TokenType;
typedef enum {
CLASS,
METHOD,
FUNCTION,
CONSTRUCTOR,
INT,
BOOLEAN,
CHAR,
VOID,
VAR,
STATIC,
FIELD,
LET,
DO,
IF,
ELSE,
WHILE,
RETURN,
TRUE,
FALSE,
cNULL,
THIS
} KeyWord;
typedef enum KeywordConst {
KC_TRUE,
KC_FALSE,
KC_NULL,
KC_THIS
} KeywordConst;
typedef struct {
FILE *inStream;
bool hasMoreTokens;
Vector *tokens;
int current;
int end;
int lineNumber;
} Tokenizer;
typedef struct {
TokenType tokenType;
KeyWord keyword;
char *intValue;
char *identifier;
char symbol;
char *stringValue;
} Token;
Tokenizer *new_tokenizer(char *path);
TokenType advance(Tokenizer *tokenizer);
Token *lookahead(Tokenizer *tokenizer);
TokenType get_token_type(Tokenizer *tokenizer);
KeyWord get_keyword(Tokenizer *tokenizer);
char get_symbol(Tokenizer *tokenizer);
char *get_identifier(Tokenizer *tokenizer);
char *get_int(Tokenizer *tokenizer);
char *get_string(Tokenizer *tokenizer);
char *keyword_to_string(KeyWord keyWord);
KeywordConst keyword_to_keywordConst(KeyWord keyWord);
bool is_equal_to(int actual, int expected);
bool is_one_of(int actual, int nOfElements, ...);
bool is_int(Tokenizer *tokenizer);
bool is_str(Tokenizer *tokenizer);
bool is_identifier(Tokenizer *tokenizer);
bool is_class(Tokenizer *tokenizer);
bool is_class_var_dec(Tokenizer *tokenizer);
bool is_this_symbol(Tokenizer *tokenizer, char expected);
bool is_subroutine(Tokenizer *tokenizer);
bool is_type(Tokenizer *tokenizer);
bool is_var_dec(Tokenizer *tokenizer);
bool is_keyword_constant(Tokenizer *tokenizer);
bool is_op(Tokenizer *tokenizer);
bool is_unary_op(Tokenizer *tokenizer);
bool is_term(Tokenizer *tokenizer);
void raise_error(Tokenizer *tokenizer);
char *expect_identifier(Tokenizer *tokenizer);
char *expect_class(Tokenizer *tokenizer);
char expect_symbol(Tokenizer *tokenizer, char symbol);
KeyWord expect_keyword_n(Tokenizer *tokenizer, int n, ...);
char *expect_type(Tokenizer *tokenizer);
#endif //COMPILER_TOKENIZER_H
</code></pre>
<h2>lexer.c</h2>
<pre><code>#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <libgen.h>
#include <ctype.h>
#include <string.h>
#include <zconf.h>
#include "lexer.h"
static Map *keywords_table;
static Map *new_keyword_map();
static void add_next_token(Tokenizer *tokenizer);
Tokenizer *new_tokenizer(char *path) {
FILE *inStream = fopen(path, "r");
if (inStream == NULL) {
exit(EXIT_FAILURE);
}
Tokenizer *tokenizer = malloc(sizeof(Tokenizer));
tokenizer->inStream = inStream;
tokenizer->hasMoreTokens = true;
tokenizer->tokens = new_vec();
tokenizer->current = -1;
tokenizer->end = -1;
tokenizer->lineNumber = 1;
keywords_table = new_keyword_map();
return tokenizer;
}
// ------------------------------- New methods --------------------------
Token *peek(Tokenizer *tokenizer) {
return vec_get(tokenizer->tokens, tokenizer->end);
}
TokenType get_token_type(Tokenizer *tokenizer) {
return ((Token *) vec_get(tokenizer->tokens, tokenizer->current))->tokenType;
}
KeyWord get_keyword(Tokenizer *tokenizer) {
return ((Token *) vec_get(tokenizer->tokens, tokenizer->current))->keyword;
}
char get_symbol(Tokenizer *tokenizer) {
return ((Token *) vec_get(tokenizer->tokens, tokenizer->current))->symbol;
}
char *get_identifier(Tokenizer *tokenizer) {
return ((Token *) vec_get(tokenizer->tokens, tokenizer->current))->identifier;
}
char *get_int(Tokenizer *tokenizer) {
return ((Token *) vec_get(tokenizer->tokens, tokenizer->current))->intValue;
}
char *get_string(Tokenizer *tokenizer) {
return ((Token *) vec_get(tokenizer->tokens, tokenizer->current))->stringValue;
}
Token *lookahead(Tokenizer *tokenizer) {
add_next_token(tokenizer);
tokenizer->current--;
return peek(tokenizer);
}
void close_tokenizer(Tokenizer *tokenizer) {
if (tokenizer->inStream != NULL) {
fclose(tokenizer->inStream);
tokenizer->inStream = NULL;
}
free(tokenizer);
}
static Token *new_token(TokenType tokenType) {
Token *token = malloc(sizeof(Token));
token->tokenType = tokenType;
return token;
}
static void add_token(Tokenizer *tokenizer, Token *token) {
vec_push(tokenizer->tokens, token);
tokenizer->current++;
tokenizer->end++;
}
static bool had_to_catch_up_with_last_pos(Tokenizer *tokenizer) {
if (tokenizer->current < tokenizer->end) {
tokenizer->current = tokenizer->end;
return true;
}
return false;
}
TokenType advance(Tokenizer *tokenizer) {
add_next_token(tokenizer);
return get_token_type(tokenizer);
}
static void add_next_token(Tokenizer *tokenizer) {
if (!tokenizer->hasMoreTokens) {
return;
}
if (had_to_catch_up_with_last_pos(tokenizer)) return;
while (true) {
int chr = getc(tokenizer->inStream);
if (chr == EOF) {
tokenizer->hasMoreTokens = false;
break;
}
if (chr == '\n') {
tokenizer->lineNumber++;
continue;
}
// remove comments if they are present
if (chr == '/') {
int chrSecond = getc(tokenizer->inStream);
if (chrSecond == '/') {
while (getc(tokenizer->inStream) != '\n');
tokenizer->lineNumber++;
continue;
} else if (chrSecond == '*') {
int tmp1 = getc(tokenizer->inStream);
if (tmp1 == '\n') tokenizer->lineNumber++;
while (true) {
int tmp2 = getc(tokenizer->inStream);
if (tmp2 == '\n') tokenizer->lineNumber++;
if (tmp1 == '*' && tmp2 == '/') break;
tmp1 = tmp2;
};
continue;
} else {
ungetc(chrSecond, tokenizer->inStream);
}
}
if (chr == '"') {
StringBuilder *tmpSb = new_sb();
int tmp;
while ((tmp = getc(tokenizer->inStream)) != '"') {
sb_add(tmpSb, tmp);
};
Token *token = new_token(STRING_CONST);
token->stringValue = sb_get(tmpSb);
add_token(tokenizer, token);
free(tmpSb);
break;
}
if (strchr("{}()[].,;+-*/&|<>=~", chr) != NULL) {
Token *token = new_token(SYMBOL);
token->symbol = chr;
add_token(tokenizer, token);
break;
}
// identifier or keyword
if (isalpha(chr) || chr == '_') {
StringBuilder *tmpStr = new_sb();
int tmp = chr;
while (isalpha(tmp) || tmp == '_' || isdigit(tmp)) {
sb_add(tmpStr, tmp);
tmp = getc(tokenizer->inStream);
}
char *str = sb_get(tmpStr);
KeyWord curKeyWord = (KeyWord) map_geti(keywords_table, str, -1);
Token *token;
// is_equal_to if a keyword
if (curKeyWord != -1) {
token = new_token(KEYWORD);
token->keyword = curKeyWord;
} else {
token = new_token(IDENTIFIER);
token->identifier = str;
}
add_token(tokenizer, token);
free(tmpStr);
ungetc(tmp, tokenizer->inStream);
break;
}
if (isdigit(chr)) {
StringBuilder *tmpSb = new_sb();
int tmp = chr;
while (isdigit(tmp)) {
sb_add(tmpSb, tmp);
tmp = getc(tokenizer->inStream);
};
Token *token = new_token(INT_CONST);
token->intValue = sb_get(tmpSb);
add_token(tokenizer, token);
free(tmpSb);
ungetc(tmp, tokenizer->inStream);
break;
}
if (isspace(chr)) {
continue;
}
}
}
static Map *new_keyword_map() {
Map *map = new_map();
map_puti(map, "class", CLASS);
map_puti(map, "constructor", CONSTRUCTOR);
map_puti(map, "function", FUNCTION);
map_puti(map, "method", METHOD);
map_puti(map, "field", FIELD);
map_puti(map, "static", STATIC);
map_puti(map, "var", VAR);
map_puti(map, "int", INT);
map_puti(map, "char", CHAR);
map_puti(map, "boolean", BOOLEAN);
map_puti(map, "void", VOID);
map_puti(map, "true", TRUE);
map_puti(map, "false", FALSE);
map_puti(map, "null", cNULL);
map_puti(map, "this", THIS);
map_puti(map, "let", LET);
map_puti(map, "do", DO);
map_puti(map, "if", IF);
map_puti(map, "else", ELSE);
map_puti(map, "while", WHILE);
map_puti(map, "return", RETURN);
return map;
}
char *keyword_to_string(KeyWord keyWord) {
switch (keyWord) {
case CLASS:
return "class";
case STATIC:
return "static";
case FIELD:
return "field";
case INT:
return "int";
case CHAR:
return "char";
case BOOLEAN:
return "boolean";
case CONSTRUCTOR:
return "constructor";
case FUNCTION:
return "function";
case METHOD:
return "method";
case VOID:
return "void";
case VAR:
return "var";
case LET:
return "let";
case IF:
return "if";
case ELSE:
return "else";
case WHILE:
return "while";
case DO:
return "do";
case RETURN:
return "return";
case cNULL:
return "null";
case THIS:
return "this";
case TRUE:
return "true";
case FALSE:
return "false";
default:
xprintf("%i is not specified in keyword_to_string", keyWord);
exit(EXIT_FAILURE);
}
}
KeywordConst keyword_to_keywordConst(KeyWord keyWord) {
switch (keyWord) {
case cNULL:
return KC_NULL;
case THIS:
return KC_THIS;
case TRUE:
return KC_TRUE;
case FALSE:
return KC_FALSE;
default:
xprintf("%s is not specified in keyword_to_keywordConst", keyword_to_string(keyWord));
exit(EXIT_FAILURE);
}
}
bool is_equal_to(int actual, int expected) {
return expected == actual;
}
bool is_one_of(int actual, int nOfElements, ...) {
va_list argp;
va_start(argp, nOfElements);
while (nOfElements--) {
int expected = va_arg(argp, int);
if (actual == expected) {
va_end(argp);
return true;
}
}
va_end(argp);
return false;
}
bool is_int(Tokenizer *tokenizer) {
return is_equal_to(get_token_type(tokenizer), INT_CONST);
}
bool is_str(Tokenizer *tokenizer) {
return is_equal_to(get_token_type(tokenizer), STRING_CONST);
}
bool is_identifier(Tokenizer *tokenizer) {
return is_equal_to(get_token_type(tokenizer), IDENTIFIER);
}
bool is_class(Tokenizer *tokenizer) {
return is_equal_to(get_keyword(tokenizer), CLASS);
}
bool is_class_var_dec(Tokenizer *tokenizer) {
return is_one_of(get_keyword(tokenizer), 2, STATIC, FIELD);
}
bool is_this_symbol(Tokenizer *tokenizer, char expected) {
return is_equal_to(get_symbol(tokenizer), expected);
}
bool is_subroutine(Tokenizer *tokenizer) {
return is_one_of(get_keyword(tokenizer), 3, CONSTRUCTOR, FUNCTION, METHOD);
}
bool is_type(Tokenizer *tokenizer) {
return is_identifier(tokenizer) || is_one_of(get_keyword(tokenizer), 3, INT, CHAR, BOOLEAN);
}
bool is_var_dec(Tokenizer *tokenizer) {
return is_equal_to(get_keyword(tokenizer), VAR);
}
bool is_keyword_constant(Tokenizer *tokenizer) {
return is_one_of(get_keyword(tokenizer), 4, TRUE, FALSE, cNULL, THIS);
}
bool is_op(Tokenizer *tokenizer) {
return is_one_of(get_symbol(tokenizer), 9, '+', '-', '*', '/', '&', '|', '<', '>', '=');
}
bool is_unary_op(Tokenizer *tokenizer) {
return is_one_of(get_symbol(tokenizer), 2, '-', '~');
}
bool is_term(Tokenizer *tokenizer) {
return is_one_of(get_token_type(tokenizer), 2, INT_CONST, STRING_CONST)
|| is_keyword_constant(tokenizer)
|| is_identifier(tokenizer)
|| is_unary_op(tokenizer)
|| is_this_symbol(tokenizer, '(');
}
void raise_error(Tokenizer *tokenizer) {
xprintf("Wrong token at line %i\n", tokenizer->lineNumber);
xprintf("TokenType %i", get_token_type(tokenizer));
exit(EXIT_FAILURE);
}
char *expect_identifier(Tokenizer *tokenizer) {
if (is_identifier(tokenizer)) {
char *identifier = get_identifier(tokenizer);
advance(tokenizer);
return identifier;
}
raise_error(tokenizer);
}
char *expect_class(Tokenizer *tokenizer) {
if (is_class(tokenizer)) {
advance(tokenizer);
return "class";
}
raise_error(tokenizer);
}
char expect_symbol(Tokenizer *tokenizer, char symbol) {
if (is_this_symbol(tokenizer, symbol)) {
advance(tokenizer);
return symbol;
}
raise_error(tokenizer);
}
KeyWord expect_keyword_n(Tokenizer *tokenizer, int n, ...) {
va_list expectedArgs;
va_start(expectedArgs, n);;
KeyWord actualKeyWord = get_keyword(tokenizer);
while (n--) {
int expected = va_arg(expectedArgs, int);
if (actualKeyWord == expected) {
va_end(expectedArgs);
advance(tokenizer);
return actualKeyWord;
}
}
va_end(expectedArgs);
raise_error(tokenizer);
}
char *expect_type(Tokenizer *tokenizer) {
// 'int' | 'char' | 'boolean' | className
if (get_identifier(tokenizer)) {
char *identifier = get_identifier(tokenizer);
advance(tokenizer);
return identifier;
}
KeyWord keyWord = get_keyword(tokenizer);
switch (keyWord) {
case INT:
case CHAR:
case BOOLEAN:
advance(tokenizer);
return keyword_to_string(keyWord);
default:
raise_error(tokenizer);
}
</code></pre>
<p>}</p>
<h2>parser.h</h2>
<pre><code>#ifndef COMPILER_PARSER_H
#define COMPILER_PARSER_H
#include "lexer.h"
#include "symbol_table.h"
typedef struct Class {
char *name;
SymbolTable *gTable;
Vector *functions;
} Class;
typedef struct Function {
char *name;
KeyWord funcKind;
char *returnType;
SymbolTable *lTable;
Vector *statements;
} Function;
enum TermType {
TERM_INT,
TERM_STR,
TERM_KEYWORD,
TERM_VAR,
TERM_ARRAY,
TERM_SUB_CALL,
TERM_EXPR_PARENS,
TERM_TERM_PAIR
} TermType;
typedef struct Term {
enum TermType type;
union {
char *integer;
char *str;
KeywordConst kConst;
char *varName;
struct Array *array;
struct SubroutineCall *subCall;
struct Expression *expr;
struct TermPair *termPair;
};
} Term;
typedef struct TermPair {
char op;
struct Term *term;
} TermPair;
typedef struct Expression {
Term *firstTerm;
Vector *termPairs;
} Expression;
typedef struct SubroutineCall {
enum SubCallType {
PLAIN_SUB_CALL,
TARGET_SUB_CALL
} type;
char *target;
char *subroutineName;
struct ExpressionList *exprList;
} SubroutineCall;
typedef struct ExpressionList {
Vector *expressions;
} ExpressionList;
typedef struct Array {
char *varName;
struct Expression *expr;
} Array;
typedef struct WhileStatement {
Expression *expr;
Vector *stmts;
} WhileStmt;
typedef struct ReturnStatement {
Expression *expr;
} ReturnStmt;
typedef struct IfStatement {
Expression *expr;
Vector *ifStmts;
Vector *elseStmts;
} IfStmt;
typedef struct LetStatement {
enum LetType {
LET_TYPE_PLAIN,
LET_TYPE_ARRAY,
} type;
char *name;
Expression *firstExpr;
Expression *secondExpr;
} LetStmt;
typedef struct DoStatement {
SubroutineCall *call;
} DoStmt;
typedef struct Statement {
enum {
RETURN_STMT,
WHILE_STMT,
IF_STMT,
DO_STMT,
LET_STMT
} type;
union {
ReturnStmt *retStmt;
WhileStmt *whileStmt;
IfStmt *ifStmt;
LetStmt *letStmt;
DoStmt *doStmt;
};
} Statement;
Class *build_ast(Tokenizer *tokenizer);
#endif //COMPILER_PARSER_H
</code></pre>
<h2>parser.c</h2>
<pre><code>#include <stdlib.h>
#include <zconf.h>
#include "parser.h"
static Class *parse_class();
static void parse_class_var_dec(Tokenizer *tokenizer, SymbolTable *gTable);
static Function *parse_subroutine(Tokenizer *tokenizer, Class *class);
static void parse_var_dec(Tokenizer *tokenizer, Function *func);
static void parse_param_list(Tokenizer *tokenizer, Function *func, char *className);
static void parse_subroutine_body(Tokenizer *tokenizer, Function *func);
static Vector *parse_statements(Tokenizer *tokenizer);
static ReturnStmt * parse_return(Tokenizer *tokenizer);
static DoStmt *parse_do(Tokenizer *tokenizer);
static WhileStmt *parse_while(Tokenizer *tokenizer);
static IfStmt *parse_if(Tokenizer *tokenizer);
static LetStmt *parse_let(Tokenizer *tokenizer);
static Expression *parse_expression(Tokenizer *tokenizer);
static ExpressionList *parse_expression_list(Tokenizer *tokenizer);
static SubroutineCall *parse_subroutine_call(Tokenizer *tokenizer);
static Term *parse_term(Tokenizer *tokenizer);
static void print_funcs(Vector *funcs);
static void print_expr(Expression *expr);
static void print_exprs(Vector *exprs);
static void print_subcall(SubroutineCall *subCall);
static void print_stmts(Vector *stmts);
Class *build_ast(Tokenizer *tokenizer) {
Class *class = parse_class(tokenizer);
// for debugging purposes
// xprintf("class name: %s\n", class->name);
// print_symbol_table(class->gTable);
// print_funcs(class->functions);
return class;
}
static Class *new_class(char *className) {
Class *class = malloc(sizeof(Class));
class->gTable = init_table();
class->functions = new_vec();
class->name = className;
return class;
}
static Function *new_function(KeyWord funcKind, char *funcName, char *returnType) {
Function *func = malloc(sizeof(Function));
func->funcKind = funcKind;
func->name = funcName;
func->lTable = init_table();
func->returnType = returnType;
func->statements = NULL;
return func;
}
static void print_term(Term *term) {
switch (term->type) {
case TERM_INT:
xprintf("%s", term->integer);
break;
case TERM_STR:
xprintf("%s", term->str);
break;
case TERM_KEYWORD:
xprintf("%i", term->kConst);
break;
case TERM_VAR:
xprintf("%s", term->varName);
break;
case TERM_EXPR_PARENS: {
xprintf("(");
print_expr(term->expr);
xprintf(")");
break;
}
case TERM_TERM_PAIR: {
TermPair *pair = term->termPair;
xprintf("%c", pair->op);
print_term(pair->term);
break;
}
case TERM_SUB_CALL: {
print_subcall(term->subCall);
break;
}
case TERM_ARRAY: {
xprintf("%s[", term->array->varName);
print_expr(term->array-> expr);
xprintf("]");
break;
}
default:
break;
}
}
static void print_subcall(SubroutineCall *subCall) {
enum SubCallType type = subCall->type;
if (type == PLAIN_SUB_CALL) {
xprintf("%s(", subCall->subroutineName);
if (subCall->exprList != NULL) {
print_exprs(subCall->exprList->expressions);
}
xprintf(")");
} else {
xprintf("%s.%s(", subCall->target, subCall->subroutineName);
if (subCall->exprList != NULL) {
print_exprs(subCall->exprList->expressions);
}
xprintf(")");
}
}
static void print_expr(Expression *expr) {
print_term(expr->firstTerm);
if (expr->termPairs == NULL) return;
for (int i = 0; i < expr->termPairs->len; i++) {
TermPair *pair = vec_get(expr->termPairs, i);
xprintf(" %c ", pair->op);
print_term(pair->term);
}
}
static void print_exprs(Vector *exprs) {
for (int i = 0; i < exprs->len; i++) {
Expression *expr = vec_get(exprs, i);
print_expr(expr);
if (i != exprs->len - 1) {
xprintf(", ");
}
}
}
static void print_stmt(Statement *stmt) {
switch (stmt->type) {
case RETURN_STMT: {
xprintf("return ");
Expression *expr = stmt->retStmt->expr;
if (expr != NULL) {
print_expr(stmt->retStmt->expr);
}
xprintf("\n");
break;
}
case LET_STMT: {
xprintf("let %s", stmt->letStmt->name);
if (stmt->letStmt->type == LET_TYPE_ARRAY) {
xprintf("[");
print_expr(stmt->letStmt->firstExpr);
xprintf("]");
}
xprintf(" = ");
print_expr(stmt->letStmt->secondExpr);
xprintf("\n");
break;
}
case IF_STMT: {
xprintf("if ( ");
print_expr(stmt->ifStmt->expr);
xprintf(") {\n");
print_stmts(stmt->ifStmt->ifStmts);
xprintf("}\n");
if (stmt->ifStmt->elseStmts != NULL) {
xprintf("else {\n");
print_stmts(stmt->ifStmt->elseStmts);
xprintf("}\n");
}
break;
}
case WHILE_STMT: {
xprintf("while (");
print_expr(stmt->whileStmt->expr);
xprintf(") {\n");
print_stmts(stmt->whileStmt->stmts);
xprintf("}\n");
break;
}
case DO_STMT: {
xprintf("do ");
print_subcall(stmt->doStmt->call);
xprintf("\n");
break;
}
default:
break;
}
}
static void print_stmts(Vector *stmts) {
for (int i = 0; i < stmts->len; i++) {
Statement *stmt = vec_get(stmts, i);
print_stmt(stmt);
}
}
static void print_funcs(Vector *funcs) {
for (int i = 0; i < funcs->len; i++) {
Function *func = vec_get(funcs, i);
xprintf("--------------------------------\n");
xprintf("func name: %s; func kind: %s; return type: %s\n", func->name, keyword_to_string(func->funcKind), func->returnType);
print_symbol_table(func->lTable);
print_stmts(func->statements);
}
}
static Class *parse_class(Tokenizer *tokenizer) {
// 'class' className '{' classVarDec* subroutineDec* '}'
advance(tokenizer);
expect_class(tokenizer);
char *className = expect_identifier(tokenizer);
expect_symbol(tokenizer, '{');
Class *class = new_class(className);
while (is_class_var_dec(tokenizer)) {
parse_class_var_dec(tokenizer, class->gTable);
}
while (is_subroutine(tokenizer)) {
vec_push(class->functions, parse_subroutine(tokenizer, class));
}
expect_symbol(tokenizer, '}');
// check to see if there are tokens that have not been compiled
if (tokenizer->hasMoreTokens) raise_error(tokenizer);
return class;
}
static void parse_class_var_dec(Tokenizer *tokenizer, SymbolTable *gTable) {
// ( 'static' | 'field' ) type varName ( ',' varName)* ';'
KeyWord keyWord = expect_keyword_n(tokenizer, 2, STATIC, FIELD);
Kind curKind = transformToKind(keyWord);
char *type = expect_type(tokenizer);
char *varName = expect_identifier(tokenizer);
define(gTable, varName, type, curKind);
while (is_this_symbol(tokenizer, ',')) {
expect_symbol(tokenizer, ',');
varName = expect_identifier(tokenizer);
define(gTable, varName, type, curKind);
}
expect_symbol(tokenizer, ';');
}
static Function *parse_subroutine(Tokenizer *tokenizer, Class *class) {
// ('constructor' | 'function' | 'method') ('void' | type) subroutineName '(' parameterList ')' subroutineBody
KeyWord funcKind = expect_keyword_n(tokenizer, 3, CONSTRUCTOR, FUNCTION, METHOD);
char *returnType;
if (is_equal_to(get_keyword(tokenizer), VOID)) {
returnType = keyword_to_string(expect_keyword_n(tokenizer, 1, VOID));
} else {
returnType = expect_type(tokenizer);
}
char *funcName = expect_identifier(tokenizer);
Function *func = new_function(funcKind, funcName, returnType);
expect_symbol(tokenizer, '(');
parse_param_list(tokenizer, func, class->name);
expect_symbol(tokenizer, ')');
parse_subroutine_body(tokenizer, func);
return func;
}
static void parse_var_dec(Tokenizer *tokenizer, Function *func) {
// 'var' type varName ( ',' varName)* ';'
expect_keyword_n(tokenizer, 1, VAR);
char *varType = expect_type(tokenizer);
char *varName = expect_identifier(tokenizer);
define(func->lTable, varName, varType, KIND_VAR);
while(is_this_symbol(tokenizer, ',')) {
expect_symbol(tokenizer, ',');
varName = expect_identifier(tokenizer);
define(func->lTable, varName, varType, KIND_VAR);
}
expect_symbol(tokenizer, ';');
}
static void parse_param_list(Tokenizer *tokenizer, Function *func, char *className) {
// ((type varName) ( ',' type varName)*)?
if (is_one_of(func->funcKind, 1, METHOD)) {
define(func->lTable, "this", className, KIND_ARG);
}
if (!is_type(tokenizer)) return;
char *paramType = expect_type(tokenizer);
char *paramName = expect_identifier(tokenizer);
define(func->lTable, paramName, paramType, KIND_ARG);
while(is_this_symbol(tokenizer, ',')) {
expect_symbol(tokenizer, ',');
paramType = expect_type(tokenizer);
paramName = expect_identifier(tokenizer);
define(func->lTable, paramName, paramType, KIND_ARG);
}
}
static void parse_subroutine_body(Tokenizer *tokenizer, Function *func) {
// subroutineBody ('{' varDec* statements '}')
expect_symbol(tokenizer, '{');
while(is_var_dec(tokenizer)) {
parse_var_dec(tokenizer, func);
}
func->statements = parse_statements(tokenizer);
expect_symbol(tokenizer, '}');
}
//*============================ Statements ============================ */
static Vector *parse_statements(Tokenizer *tokenizer) {
Vector *statements = new_vec();
Statement *stmt;
KeyWord keyWord = get_keyword(tokenizer);
while(is_one_of(keyWord, 5, LET, IF, WHILE, DO, RETURN)) {
stmt = malloc(sizeof(Statement));
switch (keyWord) {
case LET: {
stmt->type = LET_STMT;
stmt->letStmt = parse_let(tokenizer);
break;
}
case IF: {
stmt->type = IF_STMT;
stmt->ifStmt = parse_if(tokenizer);
break;
}
case WHILE: {
stmt->type = WHILE_STMT;
stmt->whileStmt = parse_while(tokenizer);
break;
}
case DO:
stmt->type = DO_STMT;
stmt->doStmt = parse_do(tokenizer);
break;
case RETURN:
stmt->type = RETURN_STMT;
stmt->retStmt = parse_return(tokenizer);
break;
default:
raise_error(tokenizer);
break;
}
vec_push(statements, stmt);
keyWord = get_keyword(tokenizer);
}
return statements;
}
static LetStmt *parse_let(Tokenizer *tokenizer) {
// 'let' varName ( '[' expression ']' )? '=' expression ';'
expect_keyword_n(tokenizer, 1, LET);
LetStmt *letStmt = malloc(sizeof(LetStmt));
letStmt->name = expect_identifier(tokenizer);
if (is_this_symbol(tokenizer, '[')) {
expect_symbol(tokenizer, '[');
letStmt->firstExpr = parse_expression(tokenizer);
letStmt->type = LET_TYPE_ARRAY;
expect_symbol(tokenizer, ']');
} else {
letStmt->firstExpr = NULL;
letStmt->type = LET_TYPE_PLAIN;
}
expect_symbol(tokenizer, '=');
letStmt->secondExpr = parse_expression(tokenizer);
expect_symbol(tokenizer, ';');
return letStmt;
}
static IfStmt *parse_if(Tokenizer *tokenizer) {
// 'if' '(' expression ')' '{' statements '}' ( 'else' '{' statements '}' )?
expect_keyword_n(tokenizer, 1, IF);
IfStmt *ifStmt = malloc(sizeof(IfStmt));
expect_symbol(tokenizer, '(');
ifStmt->expr = parse_expression(tokenizer);
expect_symbol(tokenizer, ')');
expect_symbol(tokenizer, '{');
ifStmt->ifStmts = parse_statements(tokenizer);
expect_symbol(tokenizer, '}');
ifStmt->elseStmts = NULL;
if (is_equal_to(get_keyword(tokenizer), ELSE)) {
expect_keyword_n(tokenizer, 1, ELSE);
expect_symbol(tokenizer, '{');
ifStmt->elseStmts = parse_statements(tokenizer);
expect_symbol(tokenizer, '}');
}
return ifStmt;
}
static WhileStmt *parse_while(Tokenizer *tokenizer) {
// 'while' '(' expression ')' '{' statements '}'
expect_keyword_n(tokenizer, 1, WHILE);
WhileStmt *whileStmt = malloc(sizeof(WhileStmt));
expect_symbol(tokenizer, '(');
whileStmt->expr = parse_expression(tokenizer);
expect_symbol(tokenizer, ')');
expect_symbol(tokenizer, '{');
whileStmt->stmts = parse_statements(tokenizer);
expect_symbol(tokenizer, '}');
return whileStmt;
}
static DoStmt *parse_do(Tokenizer *tokenizer) {
// 'do' subroutineCall ';'
DoStmt *doStmt = malloc(sizeof(DoStmt));
expect_keyword_n(tokenizer, 1, DO);
doStmt->call = parse_subroutine_call(tokenizer);
expect_symbol(tokenizer, ';');
return doStmt;
}
static ReturnStmt *parse_return(Tokenizer *tokenizer) {
// 'return' expression? ';'
ReturnStmt *retStmt = malloc(sizeof(ReturnStmt));
retStmt->expr = NULL;
expect_keyword_n(tokenizer, 1, RETURN);
if (is_term(tokenizer)) {
retStmt->expr = parse_expression(tokenizer);
}
expect_symbol(tokenizer, ';');
return retStmt;
}
//*============================ Expressions ============================ */
static Expression *parse_expression(Tokenizer *tokenizer) {
// term (op term)*
Expression *expr = malloc(sizeof(Expression));
expr->firstTerm = parse_term(tokenizer);
expr->termPairs = NULL;
if (!is_op(tokenizer)) {
return expr;
}
expr->termPairs = new_vec();
while (is_op(tokenizer)) {
TermPair *pair = malloc(sizeof(TermPair));
pair->op = get_symbol(tokenizer);
advance(tokenizer);
pair->term = parse_term(tokenizer);
vec_push(expr->termPairs, pair);
}
return expr;
}
static ExpressionList *parse_expression_list(Tokenizer *tokenizer) {
// (expression ( ',' expression)* )?
if (!is_term(tokenizer)) {
return NULL;
}
ExpressionList *exprList = malloc(sizeof(ExpressionList));
exprList->expressions = new_vec();
vec_push(exprList->expressions, parse_expression(tokenizer));
while (is_this_symbol(tokenizer, ',')) {
expect_symbol(tokenizer, ',');
vec_push(exprList->expressions, parse_expression(tokenizer));
}
return exprList;
}
static SubroutineCall *parse_subroutine_call(Tokenizer *tokenizer) {
SubroutineCall *call = malloc(sizeof(SubroutineCall));
char *name = expect_identifier(tokenizer);
// subroutine call (name + expressionList)
if (is_this_symbol(tokenizer, '(')) {
call->type = PLAIN_SUB_CALL;
call->subroutineName = name;
expect_symbol(tokenizer, '(');
call->exprList = parse_expression_list(tokenizer);
expect_symbol(tokenizer, ')');
return call;
}
// subroutine call (name + name + expressionList)
if (is_this_symbol(tokenizer, '.')) {
expect_symbol(tokenizer, '.');
call->type = TARGET_SUB_CALL;
call->target = name;
call->subroutineName = expect_identifier(tokenizer);
expect_symbol(tokenizer, '(');
call->exprList = parse_expression_list(tokenizer);
expect_symbol(tokenizer, ')');
return call;
}
raise_error(tokenizer);
}
static Term *parse_term(Tokenizer *tokenizer) {
// integerConstant | stringConstant | keywordConstant |
// varName | varName '[' expression ']' | subroutineCall | '(' expression ')' | unaryOp term
Term *term = malloc(sizeof(Term));
if (is_int(tokenizer)) {
term->type = TERM_INT;
term->integer = get_int(tokenizer);
advance(tokenizer);
return term;
}
if (is_str(tokenizer)) {
term->type = TERM_STR;
term->str = get_string(tokenizer);
advance(tokenizer);
return term;
}
if (is_keyword_constant(tokenizer)) {
term->type = TERM_KEYWORD;
term->kConst = keyword_to_keywordConst(get_keyword(tokenizer));
advance(tokenizer);
return term;
}
if (is_this_symbol(tokenizer, '(')) {
expect_symbol(tokenizer, '(');
term->type = TERM_EXPR_PARENS;
term->expr = parse_expression(tokenizer);
expect_symbol(tokenizer, ')');
return term;
}
if (is_unary_op(tokenizer)) {
term->type = TERM_TERM_PAIR;
term->termPair = malloc(sizeof(TermPair));
term->termPair->op = get_symbol(tokenizer);
advance(tokenizer);
term->termPair->term = parse_term(tokenizer);
return term;
}
if (!is_identifier(tokenizer)) {
raise_error(tokenizer);
}
// means it is either subroutineCall or varName or varName + expressionList
Token *token = lookahead(tokenizer);
if (token->tokenType == SYMBOL) {
// varName + expression
if (token->symbol == '[') {
char *name = expect_identifier(tokenizer);
expect_symbol(tokenizer, '[');
Expression *expr = parse_expression(tokenizer);
expect_symbol(tokenizer, ']');
Array *array = malloc(sizeof(Array));
array->varName = name;
array->expr = expr;
term->type = TERM_ARRAY;
term->array = array;
return term;
}
// subroutineCall
if (token->symbol == '(' || token->symbol == '.') {
term->type = TERM_SUB_CALL;
term->subCall = parse_subroutine_call(tokenizer);
return term;
}
}
// varName
term->type = TERM_VAR;
term->varName = expect_identifier(tokenizer);
return term;
}
</code></pre>
<h2>compilation_engine.h</h2>
<pre><code>#ifndef COMPILER_COMPILATION_ENGINE_H
#define COMPILER_COMPILATION_ENGINE_H
#include <stdio.h>
#include "util.h"
#include "lexer.h"
#include "symbol_table.h"
#include "vm_writer.h"
#include "parser.h"
typedef struct {
VMwriter *writer;
Class *ast;
Function *curFunc;
int labelCounter;
} CompilationEngine;
CompilationEngine *new_engine(char *fileName, Class *class);
void compile_file(CompilationEngine *engine);
#endif //COMPILER_COMPILATION_ENGINE_H
</code></pre>
<h2>compilation_engine.c</h2>
<pre><code>#include <stdlib.h>
#include <zconf.h>
#include <ctype.h>
#include <string.h>
#include "compilation_engine.h"
#include "lexer.h"
CompilationEngine *new_engine(char *fileName, Class *class) {
CompilationEngine *engine = malloc(sizeof(CompilationEngine));
engine->writer = init_vmWriter(fileName);
engine->ast = class;
engine->curFunc = NULL;
engine->labelCounter = 0;
return engine;
}
/*============================ Compile routines ============================ */
static void compile_subroutine(CompilationEngine *engine, Function *func);
static void compile_expression(CompilationEngine *engine, Expression *expr);
static void compile_subroutineCall(CompilationEngine *engine, SubroutineCall *call);
static void compile_term(CompilationEngine *engine, Term *term);
static void compile_statement(CompilationEngine *engine, Statement *stmt);
static void compile_subroutineBody(CompilationEngine *engine, Vector *stmts);
static void compile_return(CompilationEngine *engine, ReturnStmt *stmt);
static void compile_do(CompilationEngine *engine, DoStmt *stmt);
static void compile_if(CompilationEngine *engine, IfStmt *stmt);
static void compile_let(CompilationEngine *engine, LetStmt *stmt);
static void compile_while(CompilationEngine *engine, WhileStmt *stmt);
static void compile_expression_list(CompilationEngine *engine, ExpressionList *list);
static void compile_operator(CompilationEngine *engine, char op);
static void compile_unary_operator(CompilationEngine *engine, char op);
static Segment kind_to_segment(Kind kind);
static int find_index(CompilationEngine *engine, char *identName);
static Kind find_kind(CompilationEngine *engine, char *identName);
static char *find_type(CompilationEngine *engine, char *identName);
static void alloc_mem(CompilationEngine *engine, int nwords);
void compile_file(CompilationEngine *engine) {
Class *class = engine->ast;
Vector *funcs = class->functions;
for (int i = 0; i < funcs->len; i++) {
Function *func = vec_get(funcs, i);
compile_subroutine(engine, func);
}
}
static void compile_subroutine(CompilationEngine *engine, Function *func) {
write_func(engine->writer, engine->ast->name, func->name, varCount(func->lTable, KIND_VAR));
Vector *stmts = func->statements;
engine->curFunc = func;
compile_subroutineBody(engine, stmts);
}
static void compile_subroutineBody(CompilationEngine *engine, Vector *stmts) {
if (engine->curFunc->funcKind == CONSTRUCTOR) {
alloc_mem(engine, varCount(engine->ast->gTable, KIND_FIELD));
write_pop_i(engine->writer, SEGMENT_POINTER, 0);
}
if (engine->curFunc->funcKind == METHOD) {
write_push_i(engine->writer, SEGMENT_ARG, 0);
write_pop_i(engine->writer, SEGMENT_POINTER, 0);
}
for (int i = 0; i < stmts->len; i++) {
Statement *stmt = vec_get(stmts, i);
compile_statement(engine, stmt);
}
}
static void compile_statement(CompilationEngine *engine, Statement *stmt) {
switch (stmt->type) {
case LET_STMT:
compile_let(engine, stmt->letStmt);
break;
case IF_STMT:
compile_if(engine, stmt->ifStmt);
break;
case WHILE_STMT:
compile_while(engine, stmt->whileStmt);
break;
case RETURN_STMT:
compile_return(engine, stmt->retStmt);
break;
case DO_STMT:
compile_do(engine, stmt->doStmt);
break;
default:
xprintf("%i, this statement is not implemented", stmt->type);
exit(EXIT_FAILURE);
}
}
char *new_label(char *label, int salt) {
StringBuilder *sb = new_sb();
sb_concat_strings(sb, 1, label);
sb_append_i(sb, salt);
return sb_get(sb);
}
static void compile_if(CompilationEngine *engine, IfStmt *stmt) {
char *elseLabel = new_label("IF_FALSE", engine->labelCounter);
char *endLabel = new_label("IF_END", engine->labelCounter);
engine->labelCounter++;
compile_expression(engine, stmt->expr);
write_arithmetic(engine->writer, NOT);
write_if(engine->writer, elseLabel);
compile_subroutineBody(engine, stmt->ifStmts);
write_goto(engine->writer, endLabel);
write_label(engine->writer, elseLabel);
if (stmt->elseStmts != NULL) {
compile_subroutineBody(engine, stmt->elseStmts);
}
write_label(engine->writer, endLabel);
}
static void compile_do(CompilationEngine *engine, DoStmt *stmt) {
compile_subroutineCall(engine, stmt->call);
// remove a value from the stack in order to avoid stackoverflow
write_pop_i(engine->writer, SEGMENT_TEMP, 0);
}
static void compile_let(CompilationEngine *engine, LetStmt *stmt) {
switch(stmt->type) {
case LET_TYPE_PLAIN: {
compile_expression(engine, stmt->secondExpr);
int index = find_index(engine, stmt->name);
Kind kind = find_kind(engine, stmt->name);
write_pop_i(engine->writer, kind_to_segment(kind), index);
break;
}
case LET_TYPE_ARRAY: {
int index = find_index(engine, stmt->name);
Kind kind = find_kind(engine, stmt->name);
if (kind == KIND_NONE) {
xprintf("%s is not defined", stmt->name);
exit(EXIT_FAILURE);
}
compile_expression(engine, stmt->secondExpr);
compile_expression(engine, stmt->firstExpr);
write_push_i(engine->writer, kind_to_segment(kind), index);
write_arithmetic(engine->writer, ADD);
write_pop_i(engine->writer, SEGMENT_POINTER, 1);
write_pop_i(engine->writer, SEGMENT_THAT, 0);
break;
}
default:
xprintf("unknown let statement type");
exit(EXIT_FAILURE);
}
}
static void compile_while(CompilationEngine *engine, WhileStmt *stmt) {
char *whileStart = new_label("WHILE_START", engine->labelCounter);
char *whileFalse = new_label("WHILE_FALSE", engine->labelCounter);
engine->labelCounter++;
write_label(engine->writer, whileStart);
compile_expression(engine, stmt->expr);
write_arithmetic(engine->writer, NOT);
write_if(engine->writer, whileFalse);
compile_subroutineBody(engine, stmt->stmts);
write_goto(engine->writer, whileStart);
write_label(engine->writer, whileFalse);
}
static void compile_return(CompilationEngine *engine, ReturnStmt *stmt) {
Expression *expr = stmt->expr;
if (expr != NULL) {
compile_expression(engine, stmt->expr);
} else {
write_push_i(engine->writer, SEGMENT_CONST, 0);
}
write_return(engine->writer);
}
static void compile_expression(CompilationEngine *engine, Expression *expr) {
compile_term(engine, expr->firstTerm);
if (expr->termPairs == NULL) return;
for (int i = 0; i < expr->termPairs->len; i++) {
TermPair *pair = vec_get(expr->termPairs, i);
compile_term(engine, pair->term);
compile_operator(engine, pair->op);
}
}
static void compile_subroutineCall(CompilationEngine *engine, SubroutineCall *call) {
enum SubCallType type = call->type;
int nArgs = 0;
// method call
if (type == PLAIN_SUB_CALL) {
// push "this" value onto the stack
write_push_i(engine->writer, SEGMENT_POINTER, 0);
if (call->exprList != NULL) {
nArgs = call->exprList->expressions->len;
compile_expression_list(engine, call->exprList);
}
write_call(engine->writer, engine->ast->name, call->subroutineName, nArgs + 1);
return;
}
if (call->exprList != NULL) {
nArgs = call->exprList->expressions->len;
}
char *targetType = find_type(engine, call->target);
// static function call
if (targetType == NULL) {
if (call->exprList != NULL) {
compile_expression_list(engine, call->exprList);
}
write_call(engine->writer, call->target, call->subroutineName, nArgs);
return;
}
int index = find_index(engine, call->target);
Kind kind = find_kind(engine, call->target);
// method call on a object instance
if (kind == KIND_FIELD || kind == KIND_VAR || kind == KIND_STATIC) {
// field Ball ball; ball.getVal();
// must be a field of another object; therefore, this should be set
// we take what we need from (this + index)
write_push_i(engine->writer, kind_to_segment(kind), index);
nArgs = nArgs + 1;
}
if (call->exprList != NULL) {
compile_expression_list(engine, call->exprList);
}
write_call(engine->writer, targetType, call->subroutineName, nArgs);
}
static void compile_term(CompilationEngine *engine, Term *term) {
switch (term->type) {
case TERM_INT:
write_push(engine->writer, SEGMENT_CONST, term->integer);
break;
case TERM_STR: {
size_t len = strlen(term->str);
write_push_i(engine->writer, SEGMENT_CONST, len);
write_call(engine->writer, "String", "new", 1);
for (int i = 0; i < len; i++) {
char chr = term->str[i];
write_push_i(engine->writer, SEGMENT_CONST, chr);
write_call(engine->writer, "String", "appendChar", 2);
}
break;
}
case TERM_KEYWORD: {
switch (term->kConst) {
case KC_TRUE:
write_push_i(engine->writer, SEGMENT_CONST, 1);
write_arithmetic(engine->writer, NEG);
break;
case KC_NULL: case KC_FALSE:
write_push_i(engine->writer, SEGMENT_CONST, 0);
break;
case KC_THIS:
// push the starting location of an object instance onto the stack
// only used in constructor for "return this"
write_push_i(engine->writer, SEGMENT_POINTER, 0);
break;
default:
xprintf("undefined TERM_KEYWORD");
exit(EXIT_FAILURE);
}
break;
}
case TERM_VAR: {
int index = find_index(engine, term->varName);
Kind kind = find_kind(engine, term->varName);
write_push_i(engine->writer, kind_to_segment(kind), index);
break;
}
case TERM_EXPR_PARENS: {
compile_expression(engine, term->expr);
break;
}
case TERM_TERM_PAIR: {
TermPair *pair = term->termPair;
compile_term(engine, pair->term);
compile_unary_operator(engine, pair->op);
break;
}
case TERM_SUB_CALL: {
compile_subroutineCall(engine, term->subCall);
break;
}
case TERM_ARRAY: {
int index = find_index(engine, term->array->varName);
Kind kind = find_kind(engine, term->array->varName);
if (kind == KIND_NONE) {
xprintf("%s is not defined", term->array->varName);
exit(EXIT_FAILURE);
}
compile_expression(engine, term->array->expr);
write_push_i(engine->writer, kind_to_segment(kind), index);
write_arithmetic(engine->writer, ADD);
write_pop_i(engine->writer, SEGMENT_POINTER, 1);
write_push_i(engine->writer, SEGMENT_THAT, 0);
break;
}
default:
break;
}
}
static void compile_expression_list(CompilationEngine *engine, ExpressionList *list) {
Vector *exprs = list->expressions;
for (int i = 0; i < exprs->len; i++) {
Expression *expr = vec_get(exprs, i);
compile_expression(engine, expr);
}
}
static void compile_operator(CompilationEngine *engine, char op) {
// Multiplication and division are handled using the OS functions
// Math.multiply() and Math.divide()
switch(op) {
case '+':
write_arithmetic(engine->writer, ADD);
break;
case '-':
write_arithmetic(engine->writer, SUB);
break;
case '*':
write_call(engine->writer, "Math", "multiply", 2);
break;
case '/':
write_call(engine->writer, "Math", "divide", 2);
break;
case '&':
write_arithmetic(engine->writer, AND);
break;
case '|':
write_arithmetic(engine->writer, OR);
break;
case '<':
write_arithmetic(engine->writer, LT);
break;
case '>':
write_arithmetic(engine->writer, GT);
break;
case '=':
write_arithmetic(engine->writer, EQ);
break;
default:
exit(EXIT_FAILURE);
}
}
static void compile_unary_operator(CompilationEngine *engine, char op) {
switch(op) {
case '~':
write_arithmetic(engine->writer, NOT);
break;
case '-':
write_arithmetic(engine->writer, NEG);
break;
default:
xprintf("%c is not implemented in compile_unary_operator", op);
exit(EXIT_FAILURE);
}
}
static Segment kind_to_segment(Kind kind) {
switch (kind) {
case KIND_VAR:
return SEGMENT_LOCAL;
case KIND_ARG:
return SEGMENT_ARG;
case KIND_FIELD:
return SEGMENT_THIS;
case KIND_STATIC:
return SEGMENT_STATIC;
default:
xprintf("%i not implemented in kind_to_segment", kind);
exit(EXIT_FAILURE);
}
}
static int find_index(CompilationEngine *engine, char *identName) {
int index = indexOf(engine->curFunc->lTable, identName);
if (index == NO_IDENTIFIER) {
index = indexOf(engine->ast->gTable, identName);
if (index == NO_IDENTIFIER) {
xprintf("%s is not defined in class %s", identName, engine->ast->name);
exit(EXIT_FAILURE);
}
}
return index;
}
static Kind find_kind(CompilationEngine *engine, char *identName) {
Kind kind = kindOf(engine->curFunc->lTable, identName);
if (kind == KIND_NONE) {
kind = kindOf(engine->ast->gTable, identName);
if (kind == KIND_NONE) {
xprintf("%s is not defined in class %s", identName, engine->ast->name);
exit(EXIT_FAILURE);
}
}
return kind;
}
static char *find_type(CompilationEngine *engine, char *identName) {
char *type = typeOf(engine->curFunc->lTable, identName);
if (type == NULL) {
type = typeOf(engine->ast->gTable, identName);
return type;
}
return type;
}
static void alloc_mem(CompilationEngine *engine, int nwords) {
// Memory.alloc(size), where size is the number of words
write_push_i(engine->writer, SEGMENT_CONST, nwords);
write_call(engine->writer, "Memory", "alloc", 1);
}
</code></pre>
<h2>Questions</h2>
<ul>
<li>How could I improve the code organization of the compiler? Should I have used other data and procedural abstractions? </li>
<li>Are there any C language features (or libraries) that I should have used, but did not?</li>
</ul>
<p>If there any other comments or suggestions, please let me know! </p>
| [] | [
{
"body": "<p>First, you tackled a tough problem and you obviously put a lot of effort into it. The code is well structured. The organization of the code seems fine.</p>\n\n<blockquote>\n <p>My code contains occasional free() statements, but my primary memory\n management strategy was not to release any memory, as the program\n works only for a couple of seconds.</p>\n</blockquote>\n\n<p>Two seconds is a lot of time, you could fill up a lot of memory.</p>\n\n<p>You may want to look into compiler development tools such as <a href=\"https://en.wikipedia.org/wiki/Lex_(software)\" rel=\"noreferrer\">lex</a>, <a href=\"https://en.wikipedia.org/wiki/Flex_(lexical_analyser_generator)\" rel=\"noreferrer\">flex</a>, <a href=\"https://en.wikipedia.org/wiki/Yacc\" rel=\"noreferrer\">yacc</a> and <a href=\"https://en.wikipedia.org/wiki/GNU_Bison\" rel=\"noreferrer\">bison</a> that can be used to generate the lexical analyzer and the parser.</p>\n\n<p>A minor nit about indentation, 2 spaces may be too small to see the logic.</p>\n\n<p><strong>Reserved Words as Variable Names</strong> </p>\n\n<p>Some users might be using C++ to compile C, the user of a variable name that is keyword in C++ such as <code>class</code> in main.c might therefore be a problem.</p>\n\n<p><strong>Portability</strong> </p>\n\n<p>Not all C compilers provide the function <code>xprintf()</code>. To write to stdout by default it might be better to use <code>printf()</code>. To print error messages it might be better to use <code>fprintf(stderr, FMT, Args);</code> The header files <code>libgen.h</code> and <code>dirent.h</code> are not common header files and may not be available on all systems, for example <code>windows</code>.</p>\n\n<p>It might be better to make use of common function such as <code>fopen()</code> and to write code to navigate the file system and directory.</p>\n\n<p><strong>Avoid calling <code>exit()</code> From Lower Level Functions</strong> </p>\n\n<p>There are a number of places where <code>exit(EXIT_FAILURE)</code> is called, this is not a good programming practice in C. It prevents the program from cleaning up after itself and can have side effects. If this was an operating system instead of a compiler it would bring the system down. A better way would be to call <a href=\"https://en.wikipedia.org/wiki/Setjmp.h\" rel=\"noreferrer\">setjmp()</a> <a href=\"https://stackoverflow.com/questions/14685406/practical-usage-of-setjmp-and-longjmp-in-c\">in main.c and longjmp()</a> where the error occurs.</p>\n\n<p><strong>Use Tables and Arrays</strong> </p>\n\n<p>The extended switch/case statement in the function <code>char *keyword_to_string(KeyWord keyWord)</code> might be better implemented as indexing into an array. This would be just as easy to maintain and would improve performance of the program.</p>\n\n<p>There are 2 ways this could be implemented, the first and prefered one would be an array of strings where the integer value of the KeyWord enum is used as an index into the array.</p>\n\n<pre><code>typedef enum {\n CLASS = 0,\n STATIC = 1,\n ...\n LASTKEYWORD\n}\n\nchar *KeyWordToStringValues[] = {\n \"class\",\n \"static\",\n ...\n}\n\nchar *keyword_to_string(KeyWord keyWord) {\n if (keyWord < LASTKEYWORD) {\n return KeyWordToStringValues[(int) keyWord];\n }\n else {\n xprintf(\"%i is not specified in keyword_to_string\", keyWord);\n longjmp();\n }\n}\n</code></pre>\n\n<p>The second method would be</p>\n\n<pre><code>typedef struct {\n KeyWord keyword;\n char *stringKeyWord;\n} KeyWordToken;\n\nKeyWordToken keyWordTokens[] = {\n {CLASS, \"class\"},\n {STATIC, \"static\"},\n ...\n {FALSE, \"false\"}\n}\n\nchar *keyword_to_string(KeyWord keyWord) {\n int keyWordCount = sizeof(keyWordTokens) / sizeof(*keyWordTokens);\n if (keyWord < keyWordCount {\n int i;\n for (i = 0; i < keyWordCount; i++) {\n if (keyWordTokens[i].keyword == keyWord) {\n return KeyWordToStringValues[(int) keyWord];\n }\n }\n }\n else {\n xprintf(\"%i is not specified in keyword_to_string\", keyWord);\n longjmp();\n }\n}\n</code></pre>\n\n<p>Another place where arrays might be beneficial would be to replace the varargs implementation of the function <code>bool is_one_of(int actual, int nOfElements, ...)</code>.</p>\n\n<pre><code>KeyWord VarDeclKeywords[] = {STATIC, FIELD};\nKeyWord SubroutineKeywords[] = {CONSTRUCTOR, FUNCTION, METHOD};\nKeyWord TypeKeywords[] = {INT, CHAR, BOOLEAN};\n\nbool is_one_of(KeyWord keyword, Keyword members) {\n int membersCount = sizeof(members) / sizeof(*members);\n int i;\n for (i = 0; i < membersCount; i++) {\n if (keyword = members[i]) {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n\n<p>This improves performance because there is overhead involved in using va_list argp, va_start(argp, nOfElements), va_arg(argp, int). It also simplifies the implementation in 2 ways, because varargs isn't necessary and the count of items doesn't need to be included in the function call. The count of arguments is error prone as it is implemented.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T20:35:24.467",
"Id": "419921",
"Score": "0",
"body": "Thanks for your answer! I have a followup question. I considered using arrays for holding strings more extensively (and I use this approach in some places). What put me off is that I could not find a way to keep enums and arrays in one place, but still being able to export enums to other files. Is there any way to do that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T22:02:52.210",
"Id": "419924",
"Score": "0",
"body": "@almaveln Create a header file for just the enum and a refrence to the array and include it where ever you need it. The reference for the array should be extern. Create the array in one C file. Remember in C all global variables are available throughout the executable. keyword.h and termtype.h would be examples."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T00:12:59.590",
"Id": "216994",
"ParentId": "216977",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "216994",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T12:16:54.563",
"Id": "216977",
"Score": "12",
"Tags": [
"beginner",
"c",
"compiler"
],
"Title": "Jack compiler in C"
} | 216977 |
<p>Is doing something like this utilizing currying in a practical sense?</p>
<pre><code>function processOneClickPurchase(item) {
let context = { step: 0 }
let addItemToCart = item => {
let cart = getSession().cart
cart.items.push(item)
log('Cart items', cart.items)
return cart
}
...
let purchase = generate([
addItemToCart,
makePurchase,
processBilling,
setupShipping,
sendPurchaseAndShippingNotification,
], null, cleanup)
return purchase(item)
function generate(steps, before, after) {
const takeStep = (incoming, outgoing) => {
let message = {
step: ++context.step,
incoming: incoming,
outgoing: outgoing
};
log('step #'+(context.step), message)
return outgoing
}
const walk = value => {
return steps.reduce((from, to) => {
return takeStep(from, to(from))
}, value)
}
(before && steps.push(before)) + (after && steps.push(after))
return function invoke(state) {
const hasItems = Array.isArray(state) || !(state = [state])
const processed = state.map(walk)
return hasItems ? processed : processed[0]
}
}
}
</code></pre>
<p><a href="https://jsfiddle.net/f7mdak6z/25/" rel="nofollow noreferrer">https://jsfiddle.net/f7mdak6z/25/</a></p>
<p>I realize there's algebra going on with currying and maybe this is nonsensical, so we're not talking rigid math concepts. However, it seems to me this pattern is rudimentary and it feels like an application of currying over an input to achieve an output. <code>takeStep()</code> almost seems like a monad, etc.</p>
<p>I think it would definitely start to sound like a fit if the methods passed to <code>generate()</code> simply modified the stream, and perhaps the <code>takeStep()</code> function handled side-effects.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T17:47:51.140",
"Id": "419701",
"Score": "0",
"body": "Currying is converting a function taking `n` arguments into series of `n-1` functions each taking 1 argument. For example, currying `foo = (a, b, c) => ...` would be `foo = a => b => c => ...`. Maybe you could clarify to which function do you refer to."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T21:31:52.183",
"Id": "419710",
"Score": "1",
"body": "What does this code accomplish? Please tell us, and also make that the title of the question, as per the [ask] guidelines. Note that there is a `return purchase(item)` that doesn't make sense since it's not within a function — please ensure that you have included enough code for the question to make sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T01:40:20.440",
"Id": "419718",
"Score": "0",
"body": "@morbusg I use `steps` instead of `arguments` for the `n` series of functions, and `invoke()` is being called over the series of functions."
}
] | [
{
"body": "<p>I take it here that you mean “algebra” to mean <a href=\"https://en.wikipedia.org/wiki/Lambda_calculus\" rel=\"nofollow noreferrer\">lambda calculus</a> and by extension, <a href=\"https://en.wikipedia.org/wiki/Combinatory_logic\" rel=\"nofollow noreferrer\">combinatory logic</a>.</p>\n\n<p>The <code>takeStep</code> function is essentially (disregarding side-effects): <span class=\"math-container\">$$\n\\lambda ab.b\n$$</span> in lambda calculus, or in JS in terms of identity (using Haskell Curry’s combinator naming):</p>\n\n<pre><code>I = a => a\nK = a => b => a\nKI = K(I)\n</code></pre>\n\n<p>So as the <code>takeStep</code> function is simply disregarding the first argument, and the <code>walk</code> function calling the second argument with the previous (/initial) value there and then, I’m wondering if you would really be after the <code>B</code>-combinator <span class=\"math-container\">$$\n \\lambda fga.f(ga)\n$$</span> (or, as JS: <code>B = f => g => a => f(g(a))</code>, often named <code>compose</code>) with possibly the <code>C</code>-combinator <span class=\"math-container\">$$\n \\lambda fab.fba\n$$</span> (<code>C = f => a => b => f(b)(a)</code>) for reversing the arguments (often named <code>pipe</code> or <code>sequence</code> for <code>f => g => a => g(f(a))</code>).</p>\n\n<p>(I’m not sure if the commutativity of the functions or JS evaluation strategy plays a role here.)</p>\n\n<p>Regarding currying, I wonder if you were thinking of <a href=\"https://en.wikipedia.org/wiki/Partial_application\" rel=\"nofollow noreferrer\">partial application</a> instead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T16:24:56.200",
"Id": "420038",
"Score": "0",
"body": "That's interesting, the compose part; my initial desire was to create a piped procedural that allowed an array of functional modifiers to be applied. The `takeStep()` is essentially a bridge observing both, mainly to keep the functions pure (saving to a store would be in the `takeStep()` method). I'll have to read through this a few times to get it, thank you for the response."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T20:17:04.643",
"Id": "420065",
"Score": "0",
"body": "A cleaner, updated version: https://jsfiddle.net/f7mdak6z/42/ `generate()` is now `coalesce()` at the bottom."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T15:32:20.937",
"Id": "217141",
"ParentId": "216979",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T15:40:23.873",
"Id": "216979",
"Score": "2",
"Tags": [
"javascript",
"functional-programming",
"e-commerce"
],
"Title": "Executing multiple steps to handle a purchase using currying"
} | 216979 |
<p>Recently, I've been experimenting with an <strong>array searching algorithm</strong> that I'm not sure I've seen anywhere <em>(minor references <a href="https://www.geeksforgeeks.org/searching-algorithms/" rel="nofollow noreferrer">here</a>)</em>.</p>
<p>I'm still not fully-learned on how to state the efficiency of what I've done (as per writing it's speed in mathematical notation (e.g.: <span class="math-container">\$O(\log n)\$</span>) either but I'd like to pass on that this <strong>method</strong> is most efficient when searching through <strong>large non-sorted arrays</strong>.</p>
<p>With the tests I've done in JavaScript (which I mainly use to program), it is faster than:</p>
<ul>
<li>Linear searching when the element is at the end of the array.</li>
<li>Reversed linear searching when the element is at the start of the array.</li>
</ul>
<hr>
<p>This was the original code (but ported to C++):</p>
<pre><code>/* Assert if an element is within an (int) array */
bool includes(int array[], int element, int length) {
if (length == 1)
return array[0] == element;
else if (length) {
int iterator = length,
halfLength = (length / 2) >> 0, // Convert to integer.
quarterLength = (halfLength / 2) >> 0,
thirdQuarterLength = halfLength + quarterLength;
// Do not iterate completely through the array
while (iterator != thirdQuarterLength) {
iterator -= 1;
// Check four indexes at once.
if (
array[length - iterator - 1] == element ||
(iterator - halfLength > -1 && array[iterator - halfLength] == element) ||
(halfLength + (length - iterator - 1) < length) && (array[halfLength + (length - iterator - 1)] == element) ||
array[iterator] == element
) return true;
}
return false;
}
else
return false;
}
</code></pre>
<p>With this code:</p>
<ul>
<li>The iteration count of the loop is reduced four-fold.</li>
<li>Four indexes of the array are queried each iteration of the loop (instead of 1 at a time).</li>
<li>The algorithm's speed is not dependent on the element's location in the array (e.g.: Linear searching is slow if the element is at the end of the array).</li>
</ul>
<p>Syntax-wise I would say this method tends toward writing <code>"Hello, World!"</code> four (or <code>x</code> depending on how it's scaled) times instead of using a repetition structure (e.g.: <code>for...</code> loop).</p>
<hr>
<p>Now, this was all well and good, but I decided to go even further.</p>
<p>I asked what if could search more than (or less than) four indexes at once? The number of indexes queried each iteration specified by the user.</p>
<p>So I came up with this (again ported to C++):</p>
<pre><code>#include <stdlib.h>
// Format each element of an (int) array.
void build(int array[], int length, int (&handler)(int element)) {
int iterator = length;
while (iterator) { iterator -= 1; array[iterator] = handler(array[iterator]); }
}
// Return a set of the multiples of Number ÷ Count lower than or equal to the Number.
int* step(int number, int count) {
float difference = number / count;
int* steps = (int*) malloc(20) /* This was an array literal in JavaScript but I think this counts... :P */;
bool hasStepped = false;
while (count) {
steps[count -= 1] = (hasStepped ? steps[count + 1] : 0) + difference;
hasStepped = true;
}
return steps;
}
/* Assert if an element is within an (int) array */
bool includes(int array[], int element, int length, int iterationStopCount = 4) {
if (length == 1)
return array[0] == element;
else if (length) {
int iterator = length;
// Perform a Reversed Linear Search
if (iterationStopCount == 1)
while (iterator) if (array[iterator -= 1] == element) return true;
// Perform what I call a "Gradient Search"
else {
/*
This condition is here because I do not know
the algorithm behaves otherwise.
*/
if (iterationStopCount > length) iterationStopCount = length;
bool hasRedundantIterations = length % iterationStopCount;
int* iterationStops = step(length, iterationStopCount),
iterationStopsLength = iterationStopCount;
build(iterationStops, [](int step) { return step >> 0; });
iterator -= iterationStops[1];
iterationStops[0] = 0;
if (iterator != -1)
while (iterator) {
int iterationStopsIterator = iterationStopsLength;
iterator -= 1;
while (iterationStopsIterator)
if (array[iterator + iterationStops[iterationStopsIterator -= 1]] == element)
return true;
}
}
}
return false;
}
</code></pre>
<p>This method is exactly like the first code earlier, but indexes <code>iterationStopCount</code> elements at a time every iteration (From prior testing I found <code>iterationStopCount = 4</code> to be the most performant).</p>
<p>Now, to address the elephant in this code. </p>
<p>Yes, the <code>hasRedundantIndexes</code> variable states that this algorithm can perform redundant checks (query an array index multiple times (twice at maximum)), but this only happens if the <code>iterationStopCount</code> is not a factor of the <code>length</code> of the array.</p>
<hr>
<p>I call this method of searching arrays a <strong>Gradient Search</strong> because it:</p>
<ul>
<li>Splits the array at various stops (indexes) and</li>
<li>Linear searches every stop's range each iteration (which has been
reduced to avoid inaccuracy/ redundancy).</li>
</ul>
<p><strong>What I've done here could be (or is, I don't know) slower than Linear Searching or Binary Searching for ordered lists</strong> but I see it has merit because:</p>
<ul>
<li>It does not need the list to be ordered.</li>
<li>It spends less time than the slowest speed of a Linear Search (e.g.: <span class="math-container">\$O(n)\$</span>) since each iteration covers a broad scope of the array.</li>
</ul>
<p>I would say it falls short for basic searches through minimal-sized arrays.</p>
<hr>
<p>I want to now hand this to you: Does this <strong>method</strong> (what I called an algorithm) really have any advantage or utility?</p>
<p>If the <strong>method</strong> is efficient in its field, then I will use it further on for my personal projects; else I'll debunk it myself and forget about it.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T16:31:56.563",
"Id": "419690",
"Score": "4",
"body": "Without trying to understand what your method does, let me just state that theoretically, you cannot beat a linear scan. Indeed, there is a linear lower bound for the problem and a matching upper bound is exhibited by a linear scan. Moreover, even in practice, scanning an array in a linear fashion is natural for modern hardware and thus very fast."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T17:09:51.427",
"Id": "419697",
"Score": "2",
"body": "this is tagged as both [tag:c] and [tag:c++]. Please pick one. They are different languages with different features and different idioms."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T16:22:44.377",
"Id": "216981",
"Score": "4",
"Tags": [
"c++",
"algorithm",
"search",
"binary-search"
],
"Title": "Array Search Algorithm"
} | 216981 |
<p>I have a macro where I open several text files to copy and transpose several columns into my worksheet. As it is now this actually works. I am right now opening the text file, copying a column, going back to my original worksheet pasting and transposing the data, then switching back and forward between the two sheets until all relevant columns have been copied, then I close down the text file and open a new one... </p>
<p>I figured it could probably be optimized if I understood VBA a little better.</p>
<p>My question is: can I save the column data as ranges instead and then copy it all at once and pasting and transposing it all at once as well? Or is there any other ways to improve my macro?</p>
<p>I have shown an example of my code below hope you can make sense of it (I have only shown the import of one column, the rest follow the same code):</p>
<pre><code>Sub Hent_og_Transponer()
Dim f As String
f = ActiveWorkbook.Name
'Select files for import
Dim K As Integer
FILOPEN = Application.GetOpenFilename("Files (*.txt; *.jpg; *.bmp; *.tif),*.chr; *_chr.txt; *chr.txt; *.tif", _
, "Select Picture to Import", MultiSelect:=True)
If IsArray(FILOPEN) Then
For K = LBound(FILOPEN) To UBound(FILOPEN)
Application.ScreenUpdating = False
Workbooks.OpenText FileName:=FILOPEN(K), _
Origin:=xlWindows, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=True, _
Comma:=False, Space:=False, Other:=False, FieldInfo:=Array(1, 2), _
TrailingMinusNumbers:=True
'Save name of file opened
Dim z As String
z = ActiveWorkbook.Name
Windows(Left(z, Len(z))).Activate
'Copy Temperature Data from opened file
Range("A1").Select
'Find row with temp data
Dim RowTemp1 As Range
Dim RowTemp As Integer
Set RowTemp1 = Range("B:B").Find("f in Hz", SearchOrder:=xlRows, MatchCase:=False)
If Not RowTemp1 Is Nothing Then ' if findrow is something (Prevents Errors)
RowTemp = RowTemp1.Row ' set FirstRow to the first time a match is found
End If
ActiveSheet.Cells(RowTemp + 1, 1).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
'Go back to DMA sheet
Windows(Left(f, Len(f))).Activate
'Paste and Transpose Temp Data
If IsEmpty(ActiveSheet.Cells(4, 2).Value) = True Then
ActiveSheet.Cells(4, 1).Select
ActiveCell.Offset(0, 1).Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=True
ActiveSheet.Cells(4 + 5 + Range("A2").Value, 1).Select
ActiveCell.Offset(0, 1).Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues,
Operation:=xlNone, SkipBlanks _
:=False, Transpose:=True
End If
'Here I continue to do the same with different columns...
Next K
End If
End Sub
</code></pre>
<p>Textfile:</p>
<blockquote>
<p>Date / Time / Version: 29.03.2019 / 7:21:01 / HAAKE RheoWin 4.82.0001
Substance / Sample no: pasta mix vége run1 / pasta mix vége run1</p>
<p>;f in Hz;|G*| in Pa;tan(delta) in -;Fn in N;h in mm;
1|1;10,0;1736000;0,650;0,505;1,05; 1|2;5,62;1431000;0,603;0,486;1,05;
1|3;3,16;1203000;0,575;0,510;1,05; 1|4;1,78;1016000;0,561;0,481;1,05;
1|5;1,00;857000;0,565;0,471;1,05; 1|6;0,562;722300;0,585;0,447;1,05;
1|7;0,316;608300;0,619;0,437;1,05; 1|8;0,178;505200;0,664;0,422;1,05;
1|9;0,100;413900;0,715;0,383;1,05; 2|1;0,0562;328400;0,771;0,338;1,05;
2|2;0,0316;264700;0,827;0,297;1,05;
2|3;0,0178;208000;0,871;0,252;1,05;
2|4;0,0100;159600;0,907;0,203;1,05;
2|5;0,00562;129800;0,916;0,158;1,05;
2|6;0,00316;98510;0,913;0,114;1,05;</p>
</blockquote>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T19:59:18.663",
"Id": "419708",
"Score": "0",
"body": "The process can be improved. Do you have an example text file? Why do you have image filters in your file dialog?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T00:12:28.973",
"Id": "419713",
"Score": "0",
"body": "Bad formatting/indenting, using `GoTo`s, incomplete routine (where is the sub/function signature?), really crazy code that shows very little thought when copying someone else's code (`Left(z, Len(z))`), missing labels (`Data2:`) which in themselves is real code stink, activating windows for what purpose?. I am not going to review this, because my basic first comment is to scrap the code and then rewrite the logic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T06:26:38.450",
"Id": "419724",
"Score": "0",
"body": "@TinMan , the image part is a mistake. I got this bit of code of somewhere and as it worked I did not consider that the text was wrong. But that should be an easy fix. I have added the textfile below the code - did not know how to attach it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T06:28:25.683",
"Id": "419726",
"Score": "0",
"body": "@ADJ The GoTo code is something I was trying to implement as the first two columns I import from each textfile will be the same, so figured I would skip this part when I imported the second text file etc... I have removed the code as this part actually did not run yet."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T10:12:02.270",
"Id": "419732",
"Score": "0",
"body": "Your code does not work with this data \"as is\". You need to upload the file to a service like Google Drive or Dropbox and then share the link."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T16:52:54.083",
"Id": "216982",
"Score": "1",
"Tags": [
"vba",
"excel"
],
"Title": "Copy and Transpose Macro VBA"
} | 216982 |
<p>I tried to solve the simple problem of generating all permutations of length n with m distinct elements where repetition is allowed. Doing this recursively took me like 10 minutes:</p>
<pre><code>void genAllPermsRec(vector<int>& perm, vector<vector<int>>& perms, int n, int m) {
if (perm.size() == n) {
perms.push_back(perm);
return;
}
for (int i = 0; i < m + 1; ++i) {
perm.push_back(i);
genAllPermsRec(perm, perms, n, m);
perm.pop_back();
}
}
</code></pre>
<p>I tried to do it iteratively then and it took me a lot longer. I ended up looking exactly at what happens in the recursive version and came up with the following solution:</p>
<pre><code>vector<vector<int>> genAllPerms(int n, int m) {
vector<vector<int>> perms;
vector<int> perm(1, 0);
int i = 0;
while (!perm.empty()) {
if (perm.size() == n) {
perms.push_back(perm);
if (perm.back() < m) {
perm.pop_back();
++i;
continue; // That is why Python has the while: .. else: construct.
}
while (perm.back() == m) { perm.pop_back(); }
if (!perm.empty()) {
perm.back() += 1;
i = 0;
}
} else { perm.push_back(i); }
}
return perms;
}
</code></pre>
<p>It seems to work but I am not satisfied with the result. I suspect that there is a more intuitive way to approach the problem that would lead to shorter code. Please enlighten me :)</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T05:03:11.127",
"Id": "419722",
"Score": "0",
"body": "Please update your posted code to make it a complete program that one can build and test your functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T06:06:57.550",
"Id": "423127",
"Score": "0",
"body": "The recursive version seems to generate permutations of \\$m+1\\$ values: the loop `for (int i = 0; i < m + 1; ...` iterates from `i==0` up to `i==m`. Either start with `i=1` or proceed while `i < m`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T09:34:24.537",
"Id": "423159",
"Score": "0",
"body": "Apparently same applies to the iterative version: it starts with zeros and increments values up to `m`, so it finds permutations of \\$m+1\\$ values, not \\$m\\$."
}
] | [
{
"body": "<p>I think a first problem is that m should be changed to m-1. Or maybe better you should change it so that the lines \"i=0;\" are changed to \"i=1;\" instead, and also initializing the vector with 1 instead of 0.</p>\n\n<p>By what I understand a permutation does not necessarily contain each number at least once. So we just need to generate all possible vectors of length <span class=\"math-container\">\\$n\\$</span> with elements in the set <span class=\"math-container\">\\$ \\{1,2,\\dots, m\\}\\$</span>.</p>\n\n<p>Your method is the same thing I would do, except I would not use pop_back and instead I would just modify the elements in place (although this is really a small change):</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>vector <vector <int> > genperms(int n,int m) {\n vector <vector<int>> perms;\n vector <int> curr(n,1);\n perms.push_back(curr);\n while(true){\n int change = 0;\n for(int i=n-1;i>=0;i--){\n if(curr[i] < m){\n curr[i]++;\n for(int j=i+1;j<n;j++){\n curr[j] = 1;\n }\n change = 1;\n perms.push_back(curr);\n break; //try to change again\n }\n }\n if(change == 0) break; //if we couldnt make a change we are done\n }\n return perms;\n}\n</code></pre>\n\n<p>This modification seems to give like an 8% boost in speed in my computer (using the n=8,m=8 case) . Although probably one can get better improvements if a vector is changed for something else.</p>\n\n<p>If you want to speed this up you can also reserve the outer \"perms\" vector to a large enough size.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T13:01:18.933",
"Id": "423185",
"Score": "0",
"body": "Also looking at this 18 days later this seems to be easier to understand."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T05:45:00.173",
"Id": "219073",
"ParentId": "216985",
"Score": "1"
}
},
{
"body": "<p>Your use of the <code>i</code> variable isn't clear to me.</p>\n\n<p>The algorithm might look like this (starting with an empty permutation):</p>\n\n<ol>\n<li>Repeat 'forever' (precisely: until a break):</li>\n<li>if the permutation isn't full yet (length less than <code>n</code>), append zeros (or whatever the minimum allowed value is);</li>\n<li>otherwise:</li>\n<li><ol>\n<li>add the permutation to results,</li>\n<li>remove the tail of maximum values (<code>m</code> in your code, although I suppose it should be <code>m-1</code>),</li>\n<li>if the permutation is empty, it was <code>mm...m</code> hence we're done - exit;</li>\n<li>otherwise increment the last element, and continue the loop to fill the tail with zeros.</li>\n</ol></li>\n</ol>\n\n<p>The implementation below has the condition in the main <code>if</code> negated and if/else clauses swapped when compared to algo above, so the program structure is more similar to yours:</p>\n\n<pre><code>vector<vector<int>> genAllPerms(int n, int m) {\n vector<vector<int>> perms;\n vector<int> perm;\n const int MinVal = 0;\n const int MaxVal = m; // (m+1) different values allowed\n\n while (true) {\n if (perm.size() == n) {\n perms.push_back(perm);\n while (!perm.empty() && perm.back() == MaxVal) {\n perm.pop_back();\n }\n if (perm.empty())\n break;\n perm.back() += 1;\n }\n else { perm.push_back(MinVal); }\n }\n return perms;\n}\n</code></pre>\n\n<p><strong>Note:</strong> <code>back()</code> has nothing to return from an empty vector - test it with <code>empty()</code> before calling <code>back()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T13:05:33.073",
"Id": "423186",
"Score": "0",
"body": "You mean here: while (perm.back() == m) { perm.pop_back(); } Yep that is a bug I should have called empty() first!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T07:01:28.980",
"Id": "219080",
"ParentId": "216985",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "219073",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T18:57:25.783",
"Id": "216985",
"Score": "2",
"Tags": [
"c++",
"combinatorics",
"c++17"
],
"Title": "Iteratively generating permutations with repetitions"
} | 216985 |
<p>I needed to use some c++ code on both standard Linux and the Android variant, and the code will use filesystem library but it isn't yet in the ndk.<br>
So I'm making a one to use on Android<br>
It will be also usable on Linux because working with files and dirs go through the linux api which is the same on android</p>
<p>So, this is my implementation of the <code>remove_all()</code> function.<br>
It reports errors in <code>int</code> variable and may be wrapped later with a function that will translate expected <code>errno</code> to proper c++ <code>err_code</code>.<br>
It can't delete a dir that contains subdir with files exceeding the file descriptors limit for current process.<br>
Also it can take the whole stack if called recursively too many times.<br>
My filesystem implementation uses a thread local variable (<code>int filesystem_errno</code>) to store errors if needed.</p>
<pre><code>size_t remove_all(const filesystem::path& p, int& err = filesystem_errno)
{
int dir_fd = open(p.c_str(),O_RDONLY|O_DIRECTORY);
if (dir_fd < 0)
{
err = errno;
return 0;
}
if (p.native().length() > PATH_MAX)
{
close(dir_fd);
err = ENAMETOOLONG;
return 0;
}
const int BUFF_SIZE = 1024;
char buffer[BUFF_SIZE];
char subdir[PATH_MAX];
int base_dir_len = strlen(p.c_str());
memcpy(subdir,p.c_str(),base_dir_len);
if (subdir[base_dir_len - 1] != '/')
{
subdir[base_dir_len] = '/';
++base_dir_len;
}
char *subdir_ptr = subdir;
subdir_ptr += base_dir_len;
struct linux_dirent
{
unsigned long inod;
off64_t off;
unsigned short len;
unsigned char type;
char name[];
};
struct linux_dirent32
{
unsigned long inod;
off_t off;
unsigned short len;
char name[];
};
linux_dirent *ldir_ptr;
linux_dirent32 *ldir_ptr32;
size_t fd_count = 0;
while(true)
{
int nread = syscall(SYS_getdents64,dir_fd,buffer,BUFF_SIZE);
if (!nread)
break;
if (nread == -1)
{
err = errno;
close(dir_fd);
return fd_count;
}
for (int pos = 0; pos < nread; pos += ldir_ptr->len)
{
ldir_ptr = (linux_dirent*)(buffer + pos);
// skip . and ..
if (ldir_ptr->name[0] == '.')
{
if (ldir_ptr->name[1] == 0)
continue;
else if (ldir_ptr->name[1] == '.')
if (ldir_ptr->name[2] == 0)
continue;
}
int subdir_len = strlen(ldir_ptr->name);
if ((subdir_len + base_dir_len) > PATH_MAX)
{
close(dir_fd);
err = ENAMETOOLONG;
return fd_count;
} memcpy(subdir_ptr,ldir_ptr->name,subdir_len);
subdir_ptr[subdir_len] = 0;
if (ldir_ptr->type == DT_DIR)
{
size_t deleted_dirs = 0;
if (!rmdir(subdir)) // empty dir
++deleted_dirs;
else if (!(deleted_dirs = filesystem::remove_all(subdir,err)))
{
close(dir_fd);
return fd_count;
}
fd_count += deleted_dirs;
}
else if (ldir_ptr->type != DT_UNKNOWN)
{
if(unlink(subdir))
{
err = errno;
close(dir_fd);
return fd_count;
}
++fd_count;
}
else
{
struct stat st;
if (stat(subdir,&st))
{
err = errno;
close(dir_fd);
return fd_count;
}
if (filesystem::is_directory(st))
{
size_t deleted_dirs = 0;
if (!rmdir(subdir))
++deleted_dirs;
else if (!(deleted_dirs = filesystem::remove_all(subdir,err)))
{
close(dir_fd);
return fd_count;
}
fd_count += deleted_dirs;
}
else
{
if (unlink(subdir))
{
err = errno;
close(dir_fd);
return fd_count;
}
++fd_count;
}
}
}
}
close(dir_fd);
if (rmdir(p.c_str()))
{
err = errno;
return fd_count;
}
err = 0;
++fd_count;
return fd_count;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T19:26:18.193",
"Id": "419778",
"Score": "0",
"body": "Is there a reason to not use `opendir/readdir` API?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T19:35:10.153",
"Id": "419779",
"Score": "0",
"body": "This is much faster for dirs with too many files ."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T19:01:44.580",
"Id": "216986",
"Score": "1",
"Tags": [
"c++",
"android",
"file-system",
"linux",
"c++17"
],
"Title": "Implementing std::filesystem::remove_all() for Android"
} | 216986 |
<p>The purpose of the pricingTest object is to grab pricing information from the dataLayer on the page and render content blocks accordingly. My goal in posting this is to hopefully receive some feedback in regards to the design pattern used and performance of the code, or anything else you see as worth pointing out. For example:</p>
<ol>
<li>Is my use of a constructor implemented in a standard and acceptable way?</li>
<li>Is there anything that can be done to optimize the performance of this code?</li>
</ol>
<p>I've been learning JavaScript for about a year and it is my first language.</p>
<pre><code>// source of the data and details to the best of my understanding
// this is loaded in the <head> of each different page
// each page can have a different combination of 'levelsofcare'
// the 'care_type_id' of 'AL' can have a different 'name' depending on geographic location
// 'AllCareIncluded' is set for individual 'care' levels, excluding 'IL'
// 'Medicaid' and 'SemiPrivateAvailable' are each set at a global level
// 'care_type_category' and 'sort_order' are being ignored for this task
<script type="text/javascript">
var digitalData = {
page: {
pageInfo: {}
}
};
</script>
<script type="text/javascript">
digitalData.page.pageInfo['levelsOfCare'] = [{"care_type_id":"MC","name":"Memory Care","care_type_category":"resident","sort_order":3},{"care_type_id":"AL","name":"Personal Care Home","care_type_category":"resident","sort_order":4},{"care_type_id":"IL","name":"Independent Living","care_type_category":"resident","sort_order":5}];
digitalData.page.pageInfo['pricingIL'] = '2600';
digitalData.page.pageInfo['pricingAL'] = '5817';
digitalData.page.pageInfo['pricingMC'] = '8558';
digitalData.page.pageInfo['pricingAllCareIncludedAL'] = '0';
digitalData.page.pageInfo['pricingAllCareIncludedMC'] = '1';
digitalData.page.pageInfo['pricingMedicaid'] = '0';
digitalData.page.pageInfo['pricingSemiPrivateAvailable'] = '1';
</script>
// end source of the data
var pricingTest = {
careLevels: digitalData.page.pageInfo.levelsOfCare,
ilPrice: digitalData.page.pageInfo.pricingIL,
alPrice: digitalData.page.pageInfo.pricingAL,
mcPrice: digitalData.page.pageInfo.pricingMC,
ilCareIncluded: '0',
alCareIncluded: digitalData.page.pageInfo.pricingAllCareIncludedAL || '0',
mcCareIncluded: digitalData.page.pageInfo.pricingAllCareIncludedMC || '0',
medicaid: digitalData.page.pageInfo.pricingMedicaid,
semiPrivate: digitalData.page.pageInfo.pricingSemiPrivateAvailable,
iconLinkTails: {
MC: 'mc-path-ending',
AL: 'al-path-ending',
IL: 'il-path-ending'
},
descriptions: {
MC: [
'MC Description A',
'MC Description B'
],
AL: [
'AL Description A',
'AL Description B'
],
IL: [
'IL Description A',
'IL Description B'
]
},
svgLogo: '<svg class="pricing-info__item--leaf" height="82px" version="1.1" viewbox="0 0 50 82" width="50px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">...</svg>',
checkLargeAlMcPriceGap: function () {
if (pricingTest.mcPrice - pricingTest.alPrice > 1500) {
console.log("MC Price: " + pricingTest.mcPrice + " AL Price: " + pricingTest.alPrice + " Difference is greater than 1500");
return true;
}
},
checkIfMedicaid: function () {
if (pricingTest.medicaid === '1') {
return '<p class="pricing-info__footer-medicaid"><span class="fa fa-dollar"></span>Medicaid accepted at this community</p>';
} else {
return '';
}
},
checkIfSemiPrivate: function () {
if (pricingTest.semiPrivate === '1') {
return '<p class="pricing-info__footer-semiprivate"><span class="fa fa-arrow-down"></span>Semiprivate rooms available at a lower cost</p>';
} else {
return '';
}
},
init: function () {
// polyfill Array.prototype.map
if(!Array.prototype.map){Array.prototype.map=function(callback){var T,A,k;if(this==null){throw new TypeError("this is null or not defined");}var O=Object(this);var len=O.length>>>0;if(typeof callback!=="function"){throw new TypeError(callback+" is not a function");}if(arguments.length>1){T=arguments[1];}A=new Array(len);k=0;while(k<len){var kValue,mappedValue;if(k in O){kValue=O[k];mappedValue=callback.call(T,kValue,k,O);A[k]=mappedValue;}k++;}return A;};}
// end polyfill
function getYesterdaysDate() {
var today = new Date();
var yesterday = new Date(today);
yesterday.setDate(today.getDate() - 1);
var dd = yesterday.getDate();
var mm = yesterday.getMonth() + 1;
var yyyy = yesterday.getFullYear();
if (dd < 10) { dd = '0' + dd; } if (mm < 10) { mm = '0' + mm; }
yesterday = mm + '/' + dd + '/' + yyyy;
return '<span class="pricing-info__date">As of ' + yesterday + '</span>';
}
var outerAnchor = document.querySelector('.communityTwoColumn');
var communityName = document.querySelector('h1[itemprop="name"]').textContent;
outerAnchor.insertAdjacentHTML("afterEnd", '<div id="pricingInfo"><div class="pricing-info retain retain--padded"><div class="headline3 text-center">Pricing for ' +
communityName +
getYesterdaysDate() +
'</div><div class="flex-row row" id="pricing-info-row"></div><div class="pricing-info__footer text-center"><div class="pricing-info__footer-community-specials">' +
pricingTest.checkIfMedicaid() +
pricingTest.checkIfSemiPrivate() + '</div><p class="pricing-info__footer--heading">For more details on pricing and availability</p><div class="pricing-info__footer--ctas"><div>Call <a class="pricing-info__footer--phone" href="tel:800-350-3800">800-350-3800</a></div><div><span>or</span></div><div><a class="pricing-info__footer--form-link hidden-md hidden-lg" onclick="app.communityCTAContactForm.openMobileScrollandShowLogin(event, this)" href="#">Complete the form above</a><a class="pricing-info__footer--form-link hidden-xs hidden-sm" onclick="functionName(event)" href="#">Complete the form above</a></div></div><p class="pricing-info__footer--disclaimer"><span class="pricing-info__footer--disclaimer-asterisk">*</span>Lorem ipsum dolor sit amet.</p></div></div></div>'
);
function getCareName(item) {
var careProfile = [item.care_type_id, item.name];
if (item.care_type_id === "IL") {
careProfile.push(
pricingTest.iconLinkTails.IL,
pricingTest.descriptions.IL[0],
parseInt(pricingTest.ilPrice, 10).toLocaleString("en"),
pricingTest.ilCareIncluded,
pricingTest.descriptions.IL[1]
);
} else if (item.care_type_id === "AL") {
careProfile.push(
pricingTest.iconLinkTails.AL,
pricingTest.descriptions.AL[0],
parseInt(pricingTest.alPrice, 10).toLocaleString("en"),
pricingTest.alCareIncluded,
pricingTest.descriptions.AL[1]
);
} else if (item.care_type_id === "MC") {
careProfile.push(
pricingTest.iconLinkTails.MC,
pricingTest.descriptions.MC[0],
parseInt(pricingTest.mcPrice, 10).toLocaleString("en"),
pricingTest.mcCareIncluded,
pricingTest.descriptions.MC[1]
);
}
return careProfile;
}
var careProfiles = pricingTest.careLevels.map(getCareName);
var innerAnchor = document.getElementById('pricing-info-row');
// Constructor
function Block(careId, careName, iconLinkTail, descriptionA, price, careIncluded, descriptionB) {
this.careId = careId;
this.careName = careName;
this.iconLinkTail = iconLinkTail;
this.descriptionA = descriptionA;
this.price = price;
this.careIncluded = careIncluded;
this.descriptionB = descriptionB;
this.renderPrice = function () {
if (this.price === "NaN" || (this.careId === "MC" && pricingTest.checkLargeAlMcPriceGap() === true)) {
return 'Call for Pricing';
} else {
return '<p class="pricing-info__item--price-label">– Base Rental Rate –</p><p>Starting at <span id="itemPrice">$' + this.price + '</span><span class="pricing-info__item--price-asterisk">*</span>per month</p>';
}
};
this.renderCareIncludedPill = function () {
if (this.careIncluded === '1') {
return '<div class="pricing-info__item--care-included"><span class="fa fa-heart"></span>Care Included*</div>';
} else {
return '';
}
};
innerAnchor.insertAdjacentHTML(
"beforeEnd",
'<div class="col-md-4 text-center pricing-info__care-included-' +
this.careIncluded +
'" id="pricingBlock' +
this.careId +
'"><div class="pricing-info__item"><img src="https://www.domain.com/content/path/path/en/icons/' +
this.iconLinkTail +
'-icon.svg" alt="' +
this.careName +
' Icon" height="84px" width="84px" /><p class="pricing-info__item--heading">' +
this.careName +
'</p><p class="pricing-info__item--description">' +
this.descriptionA +
'</p><div class="pricing-info__item--price-footer"><div class="pricing-info__item--price">' +
this.renderPrice() +
'</div><div class="pricing-info__item--footer"><p>' +
this.descriptionB +
'</p>' +
pricingTest.svgLogo +
'</div></div></div>' +
this.renderCareIncludedPill() + '</div>'
);
}
// pass each careProfile array as a parameter to the constructor
for (var i = 0; i < careProfiles.length; i++) { Block.apply({}, careProfiles[i]); }
}
};
$(document).ready(function(){ pricingTest.init(); });
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T21:37:46.193",
"Id": "419711",
"Score": "5",
"body": "Welcome to Code Review! It would be a good idea to explain the source of the data and provide a sample of what that data looks like."
}
] | [
{
"body": "<h2>Old school</h2>\n<blockquote>\n<p><em>"I've been learning JavaScript for about a year and it is my first language."</em></p>\n</blockquote>\n<p>Welcome to the world of programming where learning and the eagerness to learn is a primary skill all good programmers must have stay relevant in the ever changing IT industry.</p>\n<p>That segues me to the issue with your code. It is near <strong>9 years</strong> out of date, wherever you are getting your study material from it is time to look for something current.</p>\n<p>The current draft version is ECMAScript2019 which is what you should be learning. Your code is haphazardly pre ES5 which was released in 2011.</p>\n<p>The first line inside the init function (the Array.map polyfill) pre-dates even ES5.</p>\n<h2>Questions</h2>\n<blockquote>\n<p><em>"Is my use of a constructor implemented in a standard and acceptable way?"</em></p>\n</blockquote>\n<p>No the standard is <a href=\"http://www.ecma-international.org/publications/standards/Ecma-262.htm\" rel=\"nofollow noreferrer\">ES2018</a>/19</p>\n<blockquote>\n<p><em>"Is there anything that can be done to optimize the performance of this code?"</em></p>\n</blockquote>\n<p>Yes, update to <a href=\"http://www.ecma-international.org/publications/standards/Ecma-262.htm\" rel=\"nofollow noreferrer\">ES2018</a>/19</p>\n<p>For a reasonably up to date reference <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript\" rel=\"nofollow noreferrer\">MDN Javascript</a> is not as dry as the official <a href=\"http://www.ecma-international.org/publications/standards/Ecma-262.htm\" rel=\"nofollow noreferrer\">ECMA-262</a> site.</p>\n<h2>Good points</h2>\n<ul>\n<li><p>Your code has a consistent style and good layout (indentation, naming format, spaces, etc), however some line lengths are a little too long.</p>\n</li>\n<li><p>Correct use of equality operators, and statement block layout.</p>\n</li>\n<li><p>Good naming, room for improvement but nothing to leave me guessing.</p>\n</li>\n</ul>\n<p><sup><sub><strong>Note</strong> I qualified the good points so to avoid CR commenting backlash</sub></sup></p>\n<h2>Bad points</h2>\n<ul>\n<li>Bad data structuring</li>\n</ul>\n<p>eg if you have a set of named items that share the same category/association move the cat name out of the names and create an object to hold the items.</p>\n<pre><code>ilPrice: digitalData.page.pageInfo.pricingIL,\nalPrice: digitalData.page.pageInfo.pricingAL,\nmcPrice: digitalData.page.pageInfo.pricingMC,\n</code></pre>\n<p>should be</p>\n<pre><code>price: {\n il: digitalData.page.pageInfo.pricingIL,\n al: digitalData.page.pageInfo.pricingAL,\n mc: digitalData.page.pageInfo.pricingMC, \n}\n \n</code></pre>\n<ul>\n<li><p>Repetitive</p>\n<ul>\n<li>Repeated long accessors. If you repeatably access values via a long object paths, create a reference to the object needed, don't use the full path each time. See <strong>Ex A</strong></li>\n<li>Repeated code. There are is a section where you have the same 7 lines repeated 3 times with the only difference between 3 is 2 characters.</li>\n</ul>\n</li>\n</ul>\n<p><strong>Ex A</strong> (As your code needs a rewrite from the ground up, the example does the above using a IIFE and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters\" rel=\"nofollow noreferrer\">default parameter</a> as example only)</p>\n<pre><code>price: {\n il: digitalData.page.pageInfo.pricingIL,\n al: digitalData.page.pageInfo.pricingAL,\n mc: digitalData.page.pageInfo.pricingMC, \n},\n\n\nprice: ((info = digitalData.page.pageInfo) => ({\n il: info.pricingIL,\n al: info.pricingAL,\n mc: info.pricingMC, \n}))(),\n</code></pre>\n<ul>\n<li><p>Magic constants. There are many repeated constants as strings, parts of strings, numbers, distributed throughout your code. Move these out of the code and define them as named constants in one place. You should not have to navigate the body of the code to change a simple number, or string.</p>\n</li>\n<li><p>Don't add HTML to the page via strings, use the DOM API to create and modify elements, its significantly quicker, and lets you structure your code to better fit its role.</p>\n</li>\n</ul>\n<h2>Summary</h2>\n<p>All in all not bad for one year, I have seen worse code from CS post-grads with 5 years under their belts.</p>\n<p>Just don't fall behind. If you are worried about legacy browser support use a transpiler like <a href=\"https://babeljs.io/\" rel=\"nofollow noreferrer\">Babel.js</a>, don't let a tiny, <sub><sup>tiny </sup><sub><sup><sup>tiny </sup></sup></sub></sub> minority hold your skill development back.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T04:11:46.183",
"Id": "419721",
"Score": "0",
"body": "Thank you for your feedback Blindman67! I'll take these notes and improve my my code and approach."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T00:54:10.397",
"Id": "216995",
"ParentId": "216989",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216995",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T20:51:17.163",
"Id": "216989",
"Score": "1",
"Tags": [
"javascript",
"performance",
"beginner",
"jquery"
],
"Title": "Loop through data layer and display dynamic content"
} | 216989 |
<p>I have a list which has 25000 data and I am iterating in all data and in each iteration, I am searching data in another data table. my whole routine is taking a long time to finish.</p>
<p>Loading data from XML file into a dataset.</p>
<p>If the <code>ignoredata</code> field is there in <code>QCCommentstmp</code> dataset table <code>QCCommentstmp.Tables[0].Columns.Contains("IgnoreData")</code> then deserialize QCCommentstmp table data to list <code>List<clsCommentPopup> QCCommentlist</code>.</p>
<p>Iterate in <code>QCCommentlist</code>'s data using a <code>for</code> loop and finding data in <code>QCViewAlltmp.Tables[0]</code> data table for each iteration.</p>
<p>When <strong><code>QCCommentlist</code> has 25000 data</strong> then I am iterating in all 25000 data and finding data in another data table. If data is found then I am updating data in the list. This process is getting very slow and the code is taking a long time to finish all the iteration and searching data in the data table.</p>
<p>Please review my code and tell me how to restructure my code, as a result, there will be the improvement in code execution speed.</p>
<p>If my approach is wrong then guide me with the right approach and also give me the relevant code which I can use in my above code, as a result, my routine will take minimum time to finish if I iterate in more than 25000 data. I'm looking for suggestions and better code to achieve the same task.</p>
<h1>Code</h1>
<pre><code>private void UpdateCommentFirst(string strCommentPath, string TickerName)
{
int counter = 0;
bool QcViewAllFileExist = false;
bool QcCommentFileExist = false;
bool AllowUpdate = false;
string savepath = Convert.ToString(ConfigurationManager.AppSettings["OutputPath"]).Trim() + TickerName + "\\" + TickerName + "_QC-ViewwAll.xml";
DataSet QCCommentstmp = new DataSet();
DataSet QCViewAlltmp = new DataSet();
if (File.Exists(strCommentPath))
{
QCCommentstmp.ReadXml(strCommentPath);
QcCommentFileExist = true;
}
if (File.Exists(savepath))
{
QCViewAlltmp.ReadXml(savepath);
QcViewAllFileExist = true;
}
if (QcCommentFileExist && QcViewAllFileExist)
{
if (QCCommentstmp.Tables.Count > 0)
{
if (!QCCommentstmp.Tables[0].Columns.Contains("IgnoreData"))
{
AllowUpdate = true;
}
}
if (AllowUpdate)
{
List<clsCommentPopup> QCCommentlist = QCCommentstmp.Tables[0].AsEnumerable()
.Select(row => new clsCommentPopup
{
//BrokerFor,Formula,LineItem,Section,PeriodCollection
bolFollowUP = (row.Field<string>("FollowUP")) == null ? false : Convert.ToBoolean((row.Field<string>("FollowUP"))),
bolThisPeriod = (row.Field<string>("ThisPeriod")) == null ? false : Convert.ToBoolean((row.Field<string>("ThisPeriod"))),
Formula = (row.Field<string>("Formula")) == null ? string.Empty : (row.Field<string>("Formula")),
ModelValue = (row.Field<string>("ModelValue")) == null ? string.Empty : (row.Field<string>("ModelValue")),
ExternalComment = (row.Field<string>("ExternalComment")) == null ? string.Empty : (row.Field<string>("ExternalComment")),
InternalComment = (row.Field<string>("InternalComment")) == null ? string.Empty : (row.Field<string>("InternalComment")),
strEndPeriod = (row.Field<string>("EndPeriod")) == null ? string.Empty : (row.Field<string>("EndPeriod")),
strStartPeriod = (row.Field<string>("StartPeriod")) == null ? string.Empty : (row.Field<string>("StartPeriod")),
PeriodType = (row.Field<string>("PeriodType")) == null ? string.Empty : (row.Field<string>("PeriodType")),
SectionFor = (row.Field<string>("Section")) == null ? string.Empty : (row.Field<string>("Section")),
LiFor = (row.Field<string>("LineItem")) == null ? string.Empty : (row.Field<string>("LineItem")),
QcPeriodFor = (row.Field<string>("QcPeriod")) == null ? string.Empty : (row.Field<string>("QcPeriod")),
BrokerFor = (row.Field<string>("BrokerFor")) == null ? string.Empty : (row.Field<string>("BrokerFor")),
PeriodCollection = (row.Field<string>("PeriodCollection")) == null ? string.Empty : (row.Field<string>("PeriodCollection")),
boolIgnoreValue = (row.Field<string>("IgnoreValue")) == null ? false : Convert.ToBoolean((row.Field<string>("IgnoreValue"))),
IgnoreData = (!QCCommentstmp.Tables[0].Columns.Contains("IgnoreData") ? string.Empty : (row.Field<string>("IgnoreData") == null ? string.Empty : row.Field<string>("IgnoreData")))
}).ToList();
if (QCCommentlist != null)
{
foreach (var comment in QCCommentlist)
{
string section = comment.SectionFor;
string li = comment.LiFor;
string broker = comment.BrokerFor;
string period = comment.PeriodCollection;
string strQCPeriodValue = "";
if (comment.boolIgnoreValue && period.Trim() != "")
{
var QcViewColumnName = QCViewAlltmp.Tables[0].Columns.Cast<DataColumn>().AsParallel()
.Where(x => x.ColumnName.Contains(period))
.Select(x => new { x.ColumnName }).FirstOrDefault();
if (QcViewColumnName != null)
{
period = QcViewColumnName.ColumnName;
if (period.Trim() != "")
{
var datarow = QCViewAlltmp.Tables[0].AsEnumerable().AsParallel()
.Where(row => row.Field<string>("GroupKey").Split('~')[0].ToUpper() == section.ToUpper()
&& row.Field<string>("GroupKey").Split('~')[1].ToUpper() == li.ToUpper()
&& row.Field<string>("Section ").ToUpper() == broker.ToUpper());
if (datarow != null && datarow.Count() > 0)
{
strQCPeriodValue = (datarow.FirstOrDefault()[period] != null ? datarow.FirstOrDefault()[period].ToString() : string.Empty);
if (strQCPeriodValue.Trim() != string.Empty)
{
comment.IgnoreData = strQCPeriodValue;
counter++;
}
}
}
}
}
}
}
SerializeQcComment(QCCommentlist);
toolTip1.Hide(this);
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T00:26:18.717",
"Id": "419715",
"Score": "2",
"body": "Break this up into smaller functions and find where you are spending the most time. This function is too complex."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T18:16:10.993",
"Id": "419772",
"Score": "0",
"body": "should i use parallel foreach instead of normal foreach to get better performance?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T11:56:05.233",
"Id": "448662",
"Score": "1",
"body": "The only way you'll know which is faster is if you time it: we don't have the data, so we can't really answer that question. We might be able to suggest how it might be faster, but in the end you have to do the measurements and make a call."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T21:08:37.237",
"Id": "216990",
"Score": "2",
"Tags": [
"c#",
"performance",
"collections"
],
"Title": "Iterating in a list of data and search data in another datatable"
} | 216990 |
<p>I want to convert strings to their hex representations as strings too (like hex dump programs), for example <code>"abz"</code> to <code>"61627A"</code>. </p>
<pre><code>char * strToHex( char * str )
{
int length = strlen ( str );
char * newStr = malloc( length * 2 );
if ( !newStr ) shutDown ( "can't alloc memory" ) ;
for ( int x = 0; x < length; x++){
char y = str[ x ];
sprintf ( newStr + x * 2, "%02X", y );
}
return newStr;
}
</code></pre>
<p><code>ShutDown</code> definition is omitted here, it is a function that calls <code>perror</code> and <code>exit()</code></p>
<p>I designed <code>strToHex</code> to be used like</p>
<pre><code>char * str = "abcdefghijklmnopqrstuvwxyz";
char * hex = strToHex(str);
printf("%s\n",hex);
//outputs : 6162636465666768696A6B6C6D6E6F707172737475767778797A
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T00:21:23.083",
"Id": "419714",
"Score": "3",
"body": "I'd be really interested to see what shutdown(char* msg) does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T01:23:31.350",
"Id": "419717",
"Score": "0",
"body": "In the use case that was provided, since you can effectively predict the size, I would think it would be more natural to have a string buffer and the size passed in instead of creating it dynamically."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T07:43:20.070",
"Id": "419729",
"Score": "2",
"body": "Won't `printf()` require `hex` to have a trailing `\\0` byte?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T15:22:05.917",
"Id": "419748",
"Score": "0",
"body": "@pacmaninbw The argument name is actually \"msg\" as you guessed . `void shutDown(char * msg)\n{\n perror(msg);\n exit(EXIT_FAILURE);\n}`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T15:23:00.043",
"Id": "419749",
"Score": "0",
"body": "@jochen Yes, thank you, I forgot to terminate `newStr`, and I was unlucky the couple of tests that I run didn't fail."
}
] | [
{
"body": "<h2>Bug</h2>\n\n<p>As Carsten points out, you need to allocate <span class=\"math-container\">\\$(\\text{length}\\cdot 2)+1\\$</span> bytes, rather than <span class=\"math-container\">\\$(\\text{length}\\cdot2)\\$</span> to account for the null terminator <code>sprintf()</code> adds.</p>\n\n<h2>Formatting</h2>\n\n<p>Most C formatting guides do not include spaces around the arguments to function calls, nor the expressions within an if-statement. For an example of a C style most C programmers would find acceptable, see OpenBSD's <a href=\"https://man.openbsd.org/style\" rel=\"noreferrer\"><code>style(9)</code></a> manual.</p>\n\n<p>I choose to associate <code>*</code> with the variable name, rather than floating between the type and name. This disambiguates the following example:</p>\n\n<pre><code>int *a, b;\n</code></pre>\n\n<p>Here, <code>a</code> is a pointer to an integer, but <code>b</code> is only an integer. By moving the asterisk next to the name, it makes this clearer.</p>\n\n<pre><code>int length = strlen ( str );\nchar * newStr = malloc (length * 2 );\nif ( !newStr) shutDown ( \"can't allocate memory\" ) ;\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>int const len = strlen(str);\nchar *const new_str = malloc(1 + len * 2);\n\nif (new_str == NULL) {\n shutDown(\"can't allocate memory\");\n}\n</code></pre>\n\n<h2>Error checking</h2>\n\n<p>Rather than calling <code>shutDown()</code> and <code>exit()</code>ing the program, you should instead return an error value which can be checked by the caller of <code>str_to_hex()</code>. Because you return a pointer, you can return <code>NULL</code> to indicate an error occurred and the caller should check <code>errno</code>.</p>\n\n<p>Likewise, on some systems your program can incorrectly exit when <code>length == 0</code>. If we look at the manual page for <a href=\"https://linux.die.net/man/3/malloc\" rel=\"noreferrer\"><code>malloc(3)</code></a>:</p>\n\n<blockquote>\n <h3>Return Value</h3>\n \n <p>The malloc() and calloc() functions return a pointer to the allocated memory that is suitably aligned for any kind of variable. On error, these functions return NULL. <strong>NULL may also be returned by a successful call to malloc() with a size of zero</strong>, or by a successful call to calloc() with nmemb or size equal to zero.</p>\n</blockquote>\n\n<p>So by returning <code>NULL</code> we account for the case where <code>malloc(3)</code> returns NULL on <em>success</em>.</p>\n\n<pre><code>if (new_str == NULL) {\n shutDown(\"can't alloc memory\");\n}\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>if (new_str == NULL) {\n return NULL;\n}\n</code></pre>\n\n<p>If you choose, you can also check if <code>str</code> is NULL before calling <code>strlen()</code>. This is up to you, and it's not uncommon in C to ignore this case and leave it as user error.</p>\n\n<h2>Looping</h2>\n\n<p>Use the <code>size_t</code> type in your loop rather than <code>int</code>. <code>size_t</code> is guaranteed be wide enough to hold any array index, while <code>int</code> is not.</p>\n\n<p>Using <code>i</code> rather than <code>x</code> is more common for looping variables.</p>\n\n<p>The <code>y</code> variable isn't needed. You can simply use <code>str[i]</code> in its place.</p>\n\n<p>In terms of performance there's likely a faster option than using <code>sprintf()</code>. You should look into <a href=\"https://linux.die.net/man/3/strtol\" rel=\"noreferrer\"><code>strtol(3)</code></a>.</p>\n\n<h2>Conclusion</h2>\n\n<p>Here is the code I ended up with:</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nchar *\nstr_to_hex(char const *const str)\n{\n size_t const len = strlen(str);\n\n char *const new_str = malloc(1 + len * 2);\n\n if (new_str == NULL) {\n return NULL;\n }\n\n for (size_t i = 0; i < len; ++i) {\n sprintf(new_str + i * 2, \"%02X\", str[i]);\n }\n\n return new_str;\n}\n\nint\nmain(void)\n{\n char *str = \"abz\";\n char *hex = str_to_hex(str);\n\n if (hex == NULL && strlen(str) != 0) {\n /* error ... */\n }\n\n printf(\"%s\\n\",hex);\n\n free(hex);\n}\n</code></pre>\n\n<p>Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T07:43:32.833",
"Id": "419730",
"Score": "2",
"body": "Won't `printf()` require `hex` to have a trailing `\\0` byte?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T09:01:59.687",
"Id": "419731",
"Score": "4",
"body": "You should allocate 2*len+1 bytes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T13:58:59.387",
"Id": "419740",
"Score": "0",
"body": "sprintf [adds a null terminator](https://stackoverflow.com/questions/357068/sprintf-without-trailing-null-space-in-c#357081). @Carsten thanks, I forgot to include that, I'll update my answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T15:23:48.930",
"Id": "419750",
"Score": "0",
"body": "Thank you very much I'll consider every point seriously. regarding the functions definition, you wrote the return type on a separate line then on the next line you continue the function like `char * \\nstr_to_hex(char const *const str)\\n` is this convention has a name or reference that I can refer to ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T17:28:35.670",
"Id": "419767",
"Score": "1",
"body": "@Accountantم It is from the OpenBSD [manual](https://man.openbsd.org/style), the style is called BSD kernel normal form (KNF). Around the middle of manual: \"The function type should be on a line by itself preceding the function.\""
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T01:17:02.780",
"Id": "216996",
"ParentId": "216992",
"Score": "10"
}
},
{
"body": "<p>Just one addition: like <code>asprintf</code> <em>vs</em> <code>snprintf</code>. One can effectively predict the size, so I would think it natural to have a string buffer and the size passed in instead of creating it dynamically.</p>\n\n<pre><code>#include <stdlib.h> /* strtol */\n#include <string.h> /* strlen */\n#include <stdio.h> /* printf */\n#include <assert.h> /* assert */\n\n/** Converts {str} to the underlying bit representation in hex, stored in\n {hex}. It may fail to compute the entire string due to {hex_size}, in which\n case the return will be less then the {str} length.\n str: A valid null-terminated string.\n hex: The output string.\n hex_size: The output string's size.\n return: The number of characters from the original that it processed. */\nstatic size_t strToHex(const char *str, char *hex, size_t hex_size)\n{\n static const char digits[0x0F] = { '0', '1', '2', '3', '4', '5',\n '6', '7', '8', '9', 'A', 'B', 'C', 'E', 'F' };\n const size_t str_len = strlen(str), hex_len = hex_size - 1;\n const size_t length = str_len < hex_len / 2 ? str_len : hex_len / 2;\n const char *s = str;\n char *h = hex;\n size_t x;\n assert(str && hex);\n if(!hex_size) return 0;\n for(x = 0; x < length; x++)\n *h++ = digits[(*s & 0xF0) >> 4], *h++ = digits[*s++ & 0x0F];\n *h = '\\0';\n return s - str;\n}\n\nint main(void)\n{\n const char *str = \"abcdefghijklmnopqrstuvwxyz\", *str2 = \"æôƌԹظⓐa\";\n char hex[80];\n size_t ret;\n ret = strToHex(str, hex, sizeof hex);\n printf(\"\\\"%s\\\" -> \\\"%s\\\" (%lu.)\\n\", str, hex, (unsigned long)ret);\n ret = strToHex(str, hex, sizeof hex / 2);\n printf(\"\\\"%s\\\" -> \\\"%s\\\" (%lu.)\\n\", str, hex, (unsigned long)ret);\n ret = strToHex(str, hex, 0);\n printf(\"\\\"%s\\\" -> \\\"%s\\\" (%lu.)\\n\", str, hex, (unsigned long)ret);\n ret = strToHex(str2, hex, sizeof hex);\n printf(\"\\\"%s\\\" -> \\\"%s\\\" (%lu.)\\n\", str2, hex, (unsigned long)ret);\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>It cannot really fail if given the proper input, so this simplifies error checking a lot, especially in <code>C</code>. <code>malloc</code> and <code>sprintf</code> are pretty slow functions, comparatively, so I expect this to be faster and more robust.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T15:25:42.157",
"Id": "419752",
"Score": "0",
"body": "Thank you very much, I like the way you documented the function, is this a known convention for documenting C code ? I also like the performance consideration that this function has over the function I posted, but I generally give easier user interfaces more priority over performance, unless I get bottlenecks. I will study your code today again with a deeper look."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T20:33:53.433",
"Id": "419920",
"Score": "1",
"body": "The key thing here is the absence of `malloc`, which makes it much easier to use. Not that `malloc` is bad, eg, `asprintf`, but I find it makes it more complex to use properly. I like to try to code so that it's easy to put into https://en.wikipedia.org/wiki/Doxygen, with some modifications for SO."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T03:09:37.573",
"Id": "216997",
"ParentId": "216992",
"Score": "1"
}
},
{
"body": "<p>In my opinion, the most severe problem is \"Insufficient target memory\".</p>\n\n<pre><code>int length = strlen ( str );\nchar * newStr = malloc( length * 2 );\n</code></pre>\n\n<p>You are allocating twice the length of <code>str</code>, which is enough for all the hex characters (two hex chars per input byte).</p>\n\n<p>But <code>sprintf</code> works different: \"<em>A terminating null character is automatically appended after the content</em>\" (see <a href=\"http://www.cplusplus.com/reference/cstdio/sprintf/\" rel=\"nofollow noreferrer\">here</a>).</p>\n\n<p>So the last call to <code>sprintf</code> will write a terminating zero byte right <em>after</em> <code>newStr</code>, into unallocated memory. This might provoke all kinds of unintended behaviour, including (but not limited to) crashes. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T15:26:17.857",
"Id": "419753",
"Score": "0",
"body": "Yes thank you, it's a bug. I forgot to terminate `newStr`, thanks for highlighting this as it's the biggest problem in my code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T14:03:00.923",
"Id": "217013",
"ParentId": "216992",
"Score": "3"
}
},
{
"body": "<p>I did more tests on the function today and found another Bug (shame on me), and <a href=\"https://codereview.stackexchange.com/help/what-to-do-instead-of-deleting-question\">AFAIK on code review I can't change the original code</a> in the question since it got reviews.</p>\n\n<p>if there are bytes have values more than 127 it will be all displayed as <code>FF</code> by the function. To reproduce</p>\n\n<pre><code>char str[] = {127,0};\nchar * hex = strToHex(str);\nprintf(\"%s\\n\",hex); //pritnts 7F (NORMAL)\n\n//now try with this\nchar str[] = {128,0};\nchar * hex = strToHex(str);\nprintf(\"%s\\n\",hex); //pritnts FF (BUG)\n</code></pre>\n\n<p>It appears if the function is used with non English characters because they are stored with the most significant bit is set <code>1</code> in UTF-8</p>\n\n<h2>The Fix</h2>\n\n<p>To Fix it, replace this line</p>\n\n<pre><code>sprintf ( newStr + x * 2, \"%02X\", y );\n</code></pre>\n\n<p>with this</p>\n\n<pre><code>sprintf ( newStr + x * 2, \"%02hhX\", y ); // added hh\n</code></pre>\n\n<p>This is because <code>y</code> is of type <code>char</code> or <code>signed char</code> and the <code>X</code> specifier expects the argument to be <code>unsigned int</code> if no length is provided, so we provided length <code>hh</code> to tell the function that <code>X</code> is <code>unsigned char</code> . Check the <a href=\"http://www.cplusplus.com/reference/cstdio/printf/\" rel=\"nofollow noreferrer\">length table of printf</a>.</p>\n\n<p>If we didn't provided <code>hh</code>, the <code>sprintf</code> function is going to promote <code>Y</code> from <code>signed char</code> to <code>unsigned int</code> and this promotion will go like this</p>\n\n<p>when we defined the <code>str</code> as char and assigned the value 128 to it, it's represented as</p>\n\n<pre><code>1000 0000\n</code></pre>\n\n<p>The compiler thought it is -128 because it's type is <em>signed</em> char, now function <code>sprintf</code> wants to promote it to unsigned int, so to represent -128 in size of int, it will be like</p>\n\n<pre><code>1111 1111 1111 1111 1111 1111 1000 0000\n^^^^ ^^^^ ^^^^ ^^^^\n</code></pre>\n\n<p>and because we chose to show only 2 digits then we see the last 2 bytes <code>FF</code>.</p>\n\n<p>more info are <a href=\"https://stackoverflow.com/a/30464068/5407848\">here</a> , and <a href=\"https://github.com/LambdaSchool/CS-Wiki/wiki/Casting-Signed-to-Unsigned-in-C\" rel=\"nofollow noreferrer\">here</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T01:06:58.283",
"Id": "419798",
"Score": "1",
"body": "This is only an issue on implementations that treat `char` as signed. If a `char` is unsigned it isn't a problem. Other possible fixes include declaring `y` as an `unsigned char`, casting `y` to an `unsigned char` in the `sprintf` call, or masking it (`y & 0xFF`)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T00:36:51.380",
"Id": "217045",
"ParentId": "216992",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "216996",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T23:02:04.277",
"Id": "216992",
"Score": "8",
"Tags": [
"beginner",
"c",
"strings"
],
"Title": "strToHex ( string to its hex representation as string)"
} | 216992 |
<p>Is the following code easy to understand? If not how should it be changed to be more understandable. The purpose of this is reducing similar code in unit tests. This avoids repeating lines for calling getters, setters, and checking for equality.</p>
<pre><code>/**
* Example string for testing.
*/
private static final String STRING_EXAMPLE="stringExample";
/**
* Test that a getter and setter are consistent.
*/
@Test
public void testGetterSettersForA() {
A a = new A();
assertGetterSetterConsistent(STRING_EXAMPLE,a::setC,a::getC);
}
/**
* Assert that a getter and setter are consistent.
* @param input the object to be set.
* @param setter the setter.
* @param getter the getter.
*/
private static <T> void assertGetterSetterConsistent(T input, Consumer<T> setter, Supplier<T> getter) {
boolean consistent =isSetConsistentToGet(input,setter,getter);
assertTrue("Getter and Setter should be consistent.",consistent);
}
/**
* Check if the object being set is the same as the object being gotten.
* @param input the object to be set.
* @param setter the setter.
* @param getter the getter.
* @return whether the object being set is the same as the object being gotten.
*/
private static <T> boolean isSetConsistentToGet(T input, Consumer<T> setter, Supplier<T> getter) {
setter.accept(input);
T getValue = getter.get();
return areEqual(input,getValue);
}
/**
* Null safe check if two objects are equal.
* @param first the first object.
* @param second the second object.
* @return whether the two objects are equal.
*/
private static <T> boolean areEqual(Object first, Object second) {
if(first==null) {
return second==null;
}
return first.equals(second);
}
/**
* Class for testing a getter and setter.
*/
private static final class A{
/**
* Variable named c.
*/
private String c;
/**
* Get c.
* @return c.
*/
public String getC() {
return c;
}
/**
* Set c.
* @param c the value to be set.
*/
public void setC(String c) {
this.c = c;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T06:48:30.233",
"Id": "419832",
"Score": "0",
"body": "Welcome to codereview.se - In my view it would be better to implement `equals` (and `hashcode`) in your DTOs rather than using \"external\" code for that. Almost every IDE generates them for you (as a starting point) so its almost no effort."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T11:46:23.577",
"Id": "419859",
"Score": "0",
"body": "I believe you should only compare object reference equality (e.g. assertSame) when verifying that the value returned by getter is the same as what was passed to the setter."
}
] | [
{
"body": "<p>I had no issues, but I'm not sure if \"easy to understand\" is actually answerable.</p>\n\n<p>There's still room for improvement, though: Your <code>areEqual</code> method can be replaced by <a href=\"https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/Objects.html#equals(java.lang.Object,java.lang.Object)\" rel=\"nofollow noreferrer\"><code>Objects.equals</code></a>.</p>\n\n<pre><code>private static <T> boolean isSetConsistentToGet(T input, Consumer<T> setter, Supplier<T> getter) {\n setter.accept(input);\n T getValue = getter.get();\n return Objects.equals(input, getValue);\n}\n</code></pre>\n\n<p>Let me also throw in two frameworks that might make your life easier:</p>\n\n<ol>\n<li><a href=\"https://projectlombok.org/\" rel=\"nofollow noreferrer\">Project Lombok</a>. Lombok can generate getters and setters for your fields, (IMHO) removing the necessity for writing any explicit tests completely.</li>\n<li><a href=\"https://github.com/OpenPojo/openpojo\" rel=\"nofollow noreferrer\">OpenPojo</a>. I haven't used that one yet, but it claims to do getter/setter validation automagically and has been <a href=\"https://stackoverflow.com/questions/6197370/should-unit-tests-be-written-for-getter-and-setters/6206564#6206564\">suggested on Stack Overflow</a>.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T16:18:49.863",
"Id": "217020",
"ParentId": "216993",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "217020",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T23:17:21.333",
"Id": "216993",
"Score": "1",
"Tags": [
"java",
"unit-testing"
],
"Title": "Abstracting getter and setter method references for testing"
} | 216993 |
<p>My solution to Leetcode <a href="https://leetcode.com/problems/next-permutation/" rel="nofollow noreferrer">Next Permutation</a> in Python. </p>
<blockquote>
<p>Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.</p>
<p>If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).</p>
<p>The replacement must be in-place and use only constant extra memory.</p>
<p>Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.</p>
<p>1,2,3 → 1,3,2<br>
3,2,1 → 1,2,3<br>
1,1,5 → 1,5,1</p>
</blockquote>
<p>Q:if the following code is Big <span class="math-container">\$O(N)\$</span>.</p>
<pre><code>def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
def swap(i, j):
while i < j:
nums[i], nums[j] = nums[j], nums[i]
i += 1
j -= 1
n = len(nums)
index = n - 2
while index > -1 and nums[index] >= nums[index + 1]:
index -= 1
if index == -1:
swap(0, n - 1)
return
i = n - 1
while i > index and nums[i] <= nums[index]:
i -= 1
nums[i], nums[index] = nums[index], nums[i]
swap(index + 1, n - 1)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T05:36:04.630",
"Id": "419723",
"Score": "0",
"body": "Please include the problem description in the question. Off site links can go away."
}
] | [
{
"body": "<p>Maybe it is a personal taste, but I don't like introducing a nested function because some code is repeated in a particular case. Maybe a refactoring \ncould avoid this. </p>\n\n<ol>\n<li><p>first you notice that index is naturally offset by one... refactor it:</p>\n\n<pre><code>index = n - 1\nwhile index > 0 and nums[index-1] >= nums[index]:\n index -= 1\nif index == 0:\n swap(0, n - 1)\n return\ni = n - 1\nwhile i > index-1 and nums[i] <= nums[index-1]:\n i -= 1\nnums[i], nums[index-1] = nums[index-1], nums[i]\nswap(index, n - 1)\n</code></pre></li>\n<li><p>now you can remove the duplicated call to swap:</p>\n\n<pre><code>if index > 0:\n i = n - 1\n while i > index-1 and nums[i] <= nums[index-1]:\n i -= 1\n nums[i], nums[index-1] = nums[index-1], nums[i]\nswap(index, n - 1)\n</code></pre></li>\n<li><p>and you can remove the nested function:</p>\n\n<pre><code>n -= 1\nwhile index < n:\n nums[index], nums[n] = nums[n], nums[index]\n index += 1\n n -= 1\n</code></pre></li>\n</ol>\n\n<p>This is the resulting code. It is clear that this code is O(n) since there are no nested loops.</p>\n\n<pre><code>def nextPermutation(nums):\n \"\"\"\n :type nums: List[int]\n :rtype: void Do not return anything, modify nums in-place instead.\n \"\"\"\n n = len(nums)\n index = n - 1\n while index > 0 and nums[index-1] >= nums[index]:\n index -= 1\n if index > 0:\n i = n - 1\n while i > index-1 and nums[i] <= nums[index-1]:\n i -= 1\n nums[i], nums[index-1] = nums[index-1], nums[i]\n n -= 1\n while index < n:\n nums[index], nums[n] = nums[n], nums[index]\n index += 1\n n -= 1\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T10:00:36.140",
"Id": "217004",
"ParentId": "216998",
"Score": "1"
}
},
{
"body": "<blockquote>\n<pre><code>def nextPermutation(self, nums):\n</code></pre>\n</blockquote>\n\n<p><code>self</code> doesn't appear to be used at all: is it necessary?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> def swap(i, j):\n while i < j:\n nums[i], nums[j] = nums[j], nums[i]\n i += 1\n j -= 1\n</code></pre>\n</blockquote>\n\n<p>I find this name misleading. A swap is a single exchange. What this method does is reverse a sublist.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> n = len(nums)\n index = n - 2\n</code></pre>\n</blockquote>\n\n<p><code>n</code> is standard enough as the length of a list that I find it expressive enough as a name, but what is <code>index</code> the index <em>of</em>?</p>\n\n<blockquote>\n<pre><code> i = n - 1\n</code></pre>\n</blockquote>\n\n<p>Similarly, what is <code>i</code> the index of?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T11:14:44.847",
"Id": "217068",
"ParentId": "216998",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T04:31:21.073",
"Id": "216998",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"combinatorics"
],
"Title": "Leetcode Next Permutation in Python"
} | 216998 |
<p>The following code is making two asynchronous requests to obtain the desired data. The second request needs to access the data from the first request, hence I need to nest it. I know that it is better to chain promises, but this is a case where nesting seems necessary.</p>
<p>However the <code>lint</code> raises a warning: avoid nesting promises. Should I ignore the warning or there is a better way to rewrite the code?</p>
<pre><code>function get_note_full(note_id) {
return db.collection('notes').doc(note_id).get()
.then(doc => {
const data = doc.data();
return get_author_data(data.author_uid)
.then(author => {
return ({
id: note_id,
title: data.title,
text: data.text,
author: author
});
});
});
}
</code></pre>
| [] | [
{
"body": "<p>You should be able to convert that code to using async / await from ES2017. Notice that I changed the function names to suit general JavaScript naming standards (camelCase for functions and variables, etc.)</p>\n\n<pre><code>async function getFullNote(noteId) {\n const note = await db.collection('notes').doc(note_id).get();\n const author = await getAuthorData(note.author_uid);\n return {\n id: note_id,\n title: data.title,\n ext: data.text,\n author: author\n }\n}\n</code></pre>\n\n<p>This is how MDN defines an async function:</p>\n\n<pre><code>An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result. But the syntax and structure of your code using async functions is much more like using standard synchronous functions.\n</code></pre>\n\n<p>Link: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T11:11:22.173",
"Id": "217007",
"ParentId": "217001",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T06:57:39.697",
"Id": "217001",
"Score": "0",
"Tags": [
"javascript",
"node.js",
"promise"
],
"Title": "Making two sequential asynchronous requests using promises"
} | 217001 |
<p>I am working on a basic <strong>blog application</strong> in Codeigniter 3.1.8 and Bootstrap 4.</p>
<p>Several entities are present in <em>all controllers</em> (except Login.php and Register.php): static data, categories and pages.</p>
<pre><code>$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['categories'] = $this->Categories_model->get_categories();
</code></pre>
<p>Further more, in most controller, the code above appears more then one time.</p>
<p>I am afraid this is mot the only case of repetitive code in the application. (See the entire application, at its current state, <strong><a href="https://github.com/Ajax30/lightblog" rel="nofollow noreferrer">on my Github account</a></strong>).</p>
<p>I am looking for specific and/or general advice from experienced PHP developers that would help me reduce code redundancy and make it more efficient. </p>
<p>What is the best way to avoid the repeating of the code above in my controllers?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T17:07:52.843",
"Id": "419896",
"Score": "0",
"body": "Instead of this `$this->Static_model` why not make a new config for this data, it seems like a better way. Because you can then create a development copy etc. https://www.codeigniter.com/user_guide/general/environments.html#configuration-files"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T11:04:39.313",
"Id": "420114",
"Score": "0",
"body": "I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. The exerpted code that you have posted is not reviewable in this form because the overall code you want reviewed is still behind a link. Please include all the code that you want reviewed in your question to make it available to reviewers. Thanks!"
}
] | [
{
"body": "<p>I had a very short look at <code>lightblog/application/controllers/Pages.php</code> and I noticed that these two values were not used in the <code>page()</code> method:</p>\n\n<pre><code>$data['pages']\n$data['posts']\n</code></pre>\n\n<p>Then I realized that you hand over <code>data</code> to other objects and they might be using these two values. Who knows? This makes your code very hard to understand and to debug. </p>\n\n<p>Basically you're treating the <code>$data</code> array as a sort of object you hand over to other classes.</p>\n\n<p>But wait, did I say 'object'? But what if it was? Clearly you have a need to keep data accessible, but why use an array that you need to recreate every time? Why not use a class?</p>\n\n<p>Now I don't have any idea how your code is structure, and which class would be the best to use for this. But it would make sense to extend the basic CodeIgniter controller class to hold this data, like so:</p>\n\n<pre><code>class Data_Controller extends CI_Controller \n{\n private $data;\n\n public function __construct()\n {\n parent::__construct();\n $this->data = $this->Static_model->get_static_data();\n $this->data['pages'] = $this->Pages_model->get_pages();\n $this->data['categories'] = $this->Categories_model->get_categories();\n $this->data['posts'] = $this->Posts_model->sidebar_posts($limit=5, $offset=0);\n $this->data['page'] = $this->Pages_model->get_page($page_id);\n }\n\n\n public function getData()\n {\n return $this->data;\n }\n\n}\n</code></pre>\n\n<p>or something to the same effect and then extend this for your pages class:</p>\n\n<pre><code>class Pages extends Data_Controller {\n\n public function __construct()\n {\n // currently this whole method doesn't do anything, it can be removed\n parent::__construct();\n }\n\n public function page($page_id) {\n $data = $this->getData();\n ..........................\n\n }\n\n}\n</code></pre>\n\n<p>And, of course, those controller classes that don't need all that data can just extend <code>CI_Controller</code>.</p>\n\n<p>I'm sure there are other ways of doing this. I don't like the fact that now you still collect all that information without actually knowning if it is needed. I would make the retrieval of the data dependent on the fact that it is actually used. In other words use getter methods, not a data array. I'll give an example for 'pages' and 'posts', but you have to create the other ones yourself:</p>\n\n<pre><code>class Data_Controller extends CI_Controller \n{\n\n public function getPages()\n {\n return $this->Pages_model->get_pages();\n }\n\n public function getCatagories()\n {\n return $this->Categories_model->get_categories();\n\n }\n\n}\n</code></pre>\n\n<p>If you need to buffer the data you can do:</p>\n\n<pre><code>class Data_Controller extends CI_Controller \n{\n\n public function getCatagories()\n {\n static $buffer = NULL;\n if (is_null($buffer)) $buffer = $this->Categories_model->get_categories();\n return $buffer;\n }\n\n}\n</code></pre>\n\n<p>Keep in mind that this buffer will work for all instances of <code>Data_Controller</code>. That can be an advantage, or a disadvantage.</p>\n\n<p>OK, that was a bit long. I hope you got some new ideas from my ramblings.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-12T07:33:09.447",
"Id": "429816",
"Score": "0",
"body": "Where is it best to place Data_Controller, in the controller directory or someware else?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T16:12:09.980",
"Id": "217084",
"ParentId": "217002",
"Score": "4"
}
},
{
"body": "<p>In this case I would probably convert this <code>$this->Static_model</code> into a Config file that I can use through CI (that is what they are there for). You can even make CI load this file automatically, with hook. And you can even load different version based on your <code>ENVIORMENT</code> setting (for testing and what not).</p>\n\n<p>For the dynamic data, now depending how dynamic this is:</p>\n\n<pre><code> $data['pages'] = $this->Pages_model->get_pages();\n</code></pre>\n\n<p>I would probably use the <a href=\"https://www.codeigniter.com/userguide3/libraries/caching.html\" rel=\"nofollow noreferrer\">Caching Driver</a>. Chances are this doesn't update that much, and even when it does you can reset the cache. For example how often will you really add a new category. Certainly not every couple minutes, or even hours.</p>\n\n<p>One other thing not mentioned</p>\n\n<p>Avoid changing data types when returning from a method. You may not even realize you are doing it. In some cases its perfectly fine to return mixed data types, but as a general rule you should avoid it as it complicates your downstream code by having to check the return data all the time for it's type.</p>\n\n<p>I found this quick example (in your code):</p>\n\n<pre><code>class Categories_model extends CI_Model {\n\n public function get_category($category_id){\n $query = $this->db->get_where('categories', array('id' => $category_id));\n if ($query->num_rows() > 0) {\n return $query->row();\n }\n\n } //<-- returns null || array\n\n}\n\nclass Pages extends CI_Controller {\n public function page($page_id) {\n\n //...\n $data['categories'] = $this->Categories_model->get_categories(); //returns an array || null\n //...\n //requires a check (null is false, so is [])\n if ($data['categories']) {\n foreach ($data['categories'] as &$category) {\n $category->posts_count = $this->Posts_model->count_posts_in_category($category->id);\n }\n }\n //...\n }\n}\n</code></pre>\n\n<p>Instead consider this:</p>\n\n<pre><code>class Categories_model extends CI_Model {\n\n public function get_category($category_id){\n $query = $this->db->get_where('categories', array('id' => $category_id));\n if ($query->num_rows() > 0) {\n return $query->row();\n }\n return [];\n } \n\n}\n\nclass Pages extends CI_Controller {\n public function page($page_id) {\n //...\n $data['categories'] = $this->Categories_model->get_categories(); //always returns an array\n //...\n //requires no type check, as an empty array simply skips the loop\n foreach ($data['categories'] as &$category) {\n $category->posts_count = $this->Posts_model->count_posts_in_category($category->id);\n }\n //...\n }\n}\n</code></pre>\n\n<p>This may seem trivial, but it can add up to a lot of code. In PHP7 you can even set return type hints eg. <code>public function get_category($category_id) : array</code>. To insure the return type is consistent etc.</p>\n\n<p>Really when it comes to programing one of the most important things is consistency.</p>\n\n<p>Hope it helps!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T18:24:34.470",
"Id": "217092",
"ParentId": "217002",
"Score": "3"
}
},
{
"body": "<p>Personally I recommend you to create a Controller in core folder like MY_Controller\nAnd each controller will extend this controller.</p>\n\n<p>Sample here : <a href=\"https://avenir.ro/codeigniter-tutorials/creating-working-with-my_controller-codeigniter/\" rel=\"nofollow noreferrer\">https://avenir.ro/codeigniter-tutorials/creating-working-with-my_controller-codeigniter/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T04:55:32.070",
"Id": "217112",
"ParentId": "217002",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "217084",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T08:19:53.230",
"Id": "217002",
"Score": "1",
"Tags": [
"php",
"codeigniter"
],
"Title": "Codeigniter 3: how can I avoid repeating this chunk of code in my controllers?"
} | 217002 |
<p>I'm trying to create a node based scripting/computation system.
I've come up with 2 solution that seems to work. One involves template, the other one inheritance. Basically what I want to achieve is: when a node is connected to another node, data computed from the previous node are transferred to the second one. Connection happens through a socket.
The template solution uses a Socket Object to store the data, so it must be a template in order to store every type a user wants to store (Socket). Sockets are stored in every node in a map>
So in order to initialize the Node, I have to use templates to initialize the variant. In the end, what it will happen is every time a new socket type is created, the user must add this type to every template instance.</p>
<p>The inheritance way, don't use socket at all. Instead, use a sequence of "if" to get the correct type based on socket name.</p>
<p>There is a third "ugly way". It's similar to the second. But there is a socket. A Socket interface without interface... Basically, The user inherits from the socket and use it to store the type it needs. The in the Node, in order to retrieve the data, it downcast to the Socket it should be, always based on its name. Since the node user designer should know what each Socket is.</p>
<p>So, in the end, I've come up with this list of pros and cons:</p>
<p><strong>For Template</strong></p>
<p><strong>Pros:</strong></p>
<ul>
<li>Nice API</li>
<li>Simple design</li>
<li>It respects how my mind structured the library</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li>As soon the Socket types increase, it increases also the length of the template name. Plus you should remember every place where the template is instantiated and update each instance.</li>
</ul>
<p><strong>Inheritance</strong></p>
<p><strong>Pros:</strong></p>
<ul>
<li>Naive design</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li>I don't like it much, it's not how I thought it</li>
<li>A lot of Sockets mean a lot of "if" conditions</li>
<li>Node connection seems unnatural (but it's hidden to the user)</li>
</ul>
<p><strong>Template Version:</strong></p>
<pre><code>#include <map>
#include <string>
#include <variant>
template <typename T>
class Socket
{
std::string m_name;
T mValue;
public:
Socket(const std::string &name){m_name = name;}
void setValue(const T &t){mValue = t;}
T getValue(const T &t);
const std::string &getName(){return m_name;}
};
template <typename ...SocketTypes>
class Node
{
using TSocket = std::variant<SocketTypes...>;
public:
template <typename T>
void addSocket(Socket<T> socket){
mSockets.insert(std::pair<std::string, TSocket>(socket.getName(), socket));
}
template < typename Visitor>
auto getSocket(const std::string &name, Visitor visitor){
return std::visit(visitor, mSockets.find(name)->second);
}
private:
std::map<std::string, TSocket> mSockets;
};
using IntSocket = Socket<int>;
using FloatSocket = Socket<float>;
struct DefaultVisitor {
template <typename T>
void operator ()(T &t) {;}
};
// Skip this... it was just to test if it works.
// connection basically gets the value from one socket and pass it to the other
int main() {
Node<IntSocket, FloatSocket> data;
IntSocket i(std::string("value"));
i.setValue(10);
data.addSocket(i);
DefaultVisitor v;
data.getSocket(std::string("value"), v);
}
</code></pre>
<p><strong>Inheritance</strong></p>
<pre><code>#include <vector>
#include <string>
struct Node {
int number;
float fNumber;
template <typename T>
void inputConnect(std::string &socket, T value){
if(socket == "r")
number = value;
}
template <typename Object>
void outputConnect(std::string socketIn,
Object &obj, std::string socketOut)
{
if(socketIn == "r")
obj.inputConnect(socketOut, number);
}
};
void connect(Node &n1, std::string socket1,
Node &n2, std::string socket2){
n1.outputConnect(socket1, n2, socket2);
}
int main() {
Node n;
Node n2;
n.number = 10;
connect(n, std::string("r"), n2, std::string("r"));
return n2.number;
}
</code></pre>
<p>Help me decide wich is a better solution for my problem.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T10:56:55.783",
"Id": "419733",
"Score": "0",
"body": "Welcome to code review. It is unclear what you are asking for, are you asking for a code review or are you asking for opinion on which is better? Please take a look at how to ask a good question https://codereview.stackexchange.com/help/how-to-ask."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T13:44:10.843",
"Id": "419737",
"Score": "0",
"body": "done, I just need to know which is better, the code I've posted is some test code I've done on godbolt.org. Thanks for the tip"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T07:58:10.940",
"Id": "419838",
"Score": "1",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T12:58:05.600",
"Id": "419864",
"Score": "0",
"body": "My code is so specific that's impossible to use a more \"useful title\" that can be useful for other people. It's not an algorithm that you can decide it's purpose, but this are two classes abstracting an idea: A Node and a Socket and how to build a framework around them after someone help me decide the best solution for my code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T14:39:58.067",
"Id": "420273",
"Score": "0",
"body": "@rebellion: In that case, \"A Node and a Socket, template or inheritance?\" would be a better title than your current one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T12:46:20.593",
"Id": "420413",
"Score": "1",
"body": "@Graipher, Ok, I'll try to use it, even if I'm not sure if it really fit. Thanks for the tip!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-20T03:34:15.320",
"Id": "421345",
"Score": "0",
"body": "I think this question might be on-topic for programmers.stackexchange.com but check to be sure."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T08:44:00.360",
"Id": "217003",
"Score": "3",
"Tags": [
"c++",
"comparative-review",
"inheritance",
"template-meta-programming"
],
"Title": "A Node and a Socket, template or inheritance?"
} | 217003 |
<p>My intention is to <a href="https://en.wikipedia.org/wiki/POSIX" rel="nofollow noreferrer">POSIX</a>-ly write one generalized function for running various text editors I use for different purposes through <code>sudoedit</code>, i.e. editing files as root safely. Safely = for instance, if a power loss occurs during the file edit; another example could be lost SSH connection, etc.</p>
<hr>
<p><strong>Originally</strong>, I had these Bash functions defined for this purpose in my <code>.bash_aliases</code> file:</p>
<pre><code>function sucode
{
export SUDO_EDITOR='/usr/bin/code --wait'
sudoedit "$@"
}
function susubl
{
export SUDO_EDITOR='/opt/sublime_text/sublime_text --wait'
sudoedit "$@"
}
function suxed
{
export SUDO_EDITOR='/usr/bin/xed --wait'
sudoedit "$@"
}
</code></pre>
<hr>
<p><strong>Since yesterday</strong>, I'm trying to generalize that solution for other Linux users to be able to take advantage of it. Momentary peek:</p>
<pre><code># Text editing as root; The proper way through `sudoedit`.
sudoedit_internal()
{
[ "${#}" -lt 3 ] && { printf '%s\n' 'sudoedit_internal(): Invalid number of arguments.' 1>&2; return; }
editor_path=$( command -v "${1}" )
[ -x "${editor_path}" ] || { printf '%s\n' "sudoedit_internal(): The editor path ${editor_path} does not exist on this system." 1>&2; return; }
editor_wait_option=${2}
shift 2
env SUDO_EDITOR="${editor_path} ${editor_wait_option}" sudoedit "${@}"
}
# CLI
suvi() { sudoedit_internal vi '' "${@}"; }
sunano() { sudoedit_internal nano '' "${@}"; }
# GUI
sucode() { sudoedit_internal code -w "${@}"; }
susubl() { sudoedit_internal subl -w "${@}"; }
suxed() { sudoedit_internal xed -w "${@}"; }
</code></pre>
<p>These 5 editors <em>I use</em>. Please take that as an example only.</p>
<p>As I should not update this question any further, you can find the up-to-date version of this script snippet in my <a href="https://unix.stackexchange.com/a/473774/126755">Unix & Linux Answer</a>.</p>
| [] | [
{
"body": "<p>It's good form to return non-zero on error. The not-optional option is a little ugly and an environment variable may work better.</p>\n\n<p>Some extraneous syntax can go:</p>\n\n<ul>\n<li><code>1</code> before <code>>&2</code> is implied</li>\n<li><code>{}</code> around unsubstituted dereferences doesn't add anything</li>\n<li><code>echo</code> is an alias for <code>printf \"%s\\n\"</code></li>\n<li>testing for error instead of success allows <code>test && echo && return</code> without braces</li>\n<li><code>command -v</code> tests validity for you; no need to test again</li>\n<li>you've moved the complexity into a function already; reward yourself by using aliases to invoke it</li>\n</ul>\n\n<pre class=\"lang-none prettyprint-override\"><code>sudoedit_internal()\n{\n [ $# -lt 2 ] && echo \"sudoedit_internal(): Invalid number of arguments.\" >&2 && return 1\n ! command -v \"$1\" >/dev/null && echo \"sudoedit_internal(): The editor $1 does not exist on this system.\" >&2 && return 1\n editor=\"$1\"; shift \n SUDO_EDITOR=\"$editor $opt\" sudoedit \"$@\"\n}\n\nfor ed in vi nano ; do alias su$ed=\"opt= sudoedit_internal $ed\"; done\nfor ed in code subl xed ; do alias su$ed=\"opt=-w sudoedit_internal $ed\"; done\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T06:27:49.500",
"Id": "217054",
"ParentId": "217005",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217054",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T10:39:35.103",
"Id": "217005",
"Score": "2",
"Tags": [
"linux",
"posix",
"sh",
"text-editor"
],
"Title": "Editing system files in Linux (as root) with GUI and CLI text editors"
} | 217005 |
<p>The task is to write a JavaScript-function which translates a given blank-separated sentence to title-case.</p>
<p>Means that all words shall start with a capital and then the rest of the word in lower-case. <strong>But:</strong> A certain, specified set of conjunctions, preposition as well as article shall be <strong>all</strong> lower-case.</p>
<p>Example: "The second of the four items." becomes "The Second of the Four Items.".</p>
<p>Here's my implementation of such a function: </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function translateToTitleCase(str) {
const translateWord = (sWord) => {
return sWord.slice(0, 1).toUpperCase() + sWord.slice(1).toLowerCase();
}
const words = str.split(" ");
words[0] = translateWord(words[0]);
for (let i = 1; i < words.length; i++) {
if (!["of", "and", "the", "to"].includes(words[i].toLowerCase())) {
words[i] = translateWord(words[i]);
} else {
words[i] = words[i].toLowerCase(); // Make sure is's the correct case, when the sentence (or parts of it) is given in uppercase.
}
}
return words.join(" ");
}
// -- Examples -------------------------------------------------------------------------------
console.log(translateToTitleCase("Into unmerciful the entreating stronger to of word guessing."));
console.log(translateToTitleCase("the OLD MAN aND THE sEa"));</code></pre>
</div>
</div>
</p>
<p>I think my coding is still a bit "noisy" with the usage of all those brackets, chained methods and concatenation.</p>
<p><strong>Any ideas about how to improve my implementation?</strong></p>
<p>Perhaps some cool new ES6-feature I wasn't aware of.</p>
<p><strong>What would you have done differently and why?</strong></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T16:53:03.480",
"Id": "419759",
"Score": "0",
"body": "I'd argue that the functionality should be changed slightly – this'll trip over words like xkcd and eBay – but I suppose that's not really in-scope for Code Review."
}
] | [
{
"body": "<p>I find this code quite reasonable on the whole, but you might consider the following suggestions relating to consistency, succinctness and semantics.</p>\n\n<hr>\n\n<h3>Move and rename the inner helper function</h3>\n\n<p><code>translateWord</code> is reusable as a general utility function and seems better-placed in the global scope and renamed to <code>titleCase</code>. This meshes with similarly-named Ruby, Python and PHP builtins (<code>titlecase</code>, <code>title</code>, <code>ucfirst</code>, respectively). When I see \"translate\", I think of linguistics or mathematics before I think of strings or casing.</p>\n\n<h3>Avoid excessive calls to toLowerCase</h3>\n\n<p><code>.toLowerCase()</code> is more efficient called once on the entire sentence before splitting rather than incurring the overhead of calling it multiple times per word. With this in mind, you can skip calling the <code>titleCase</code> function described above if you wish.</p>\n\n<h3>Improve \"ignore\" list</h3>\n\n<pre><code>if (![\"of\", \"and\", \"the\", \"to\"].includes(words[i].toLowerCase())) {\n</code></pre>\n\n<p>is problematic for a few reasons:</p>\n\n<ul>\n<li>It creates a new array object for every word. Move initialization to the top of the function and create it once.</li>\n<li><a href=\"https://en.wikipedia.org/wiki/Hard_coding\" rel=\"noreferrer\">Hardcoding</a> restricts your function's reusability. Making this ignore list a default parameter allows the client to adjust the list as needed.</li>\n<li>Giving this array a variable name makes its purpose more obvious.</li>\n<li>Although the array is small, it needs to be traversed linearly to perform a lookup; using a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"noreferrer\">set</a> improves semantics, readability and time complexity all at once and is the ideal structure for testing membership.</li>\n</ul>\n\n<h3>Avoid the loop</h3>\n\n<p>This task is a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"noreferrer\">map</a> operation: each word has a function applied to it. You can roll <code>split</code>, <code>map</code> (your <code>for</code> loop) and <code>join</code> into one call to <code>replace</code>, which takes a regular expression that splits on non-word characters and applies the <code>titleCase</code> function to each one that passes the <code>ignore</code> test.</p>\n\n<h3>Minor points</h3>\n\n<ul>\n<li><code>sWord.slice(0, 1)</code> can be <code>sWord[0]</code>. </li>\n<li><code>sWord</code> is an okay variable name, but <code>str</code> (matching your outer function) or <code>word</code> seems more consistent.</li>\n<li>Unless there is a good hoisting or context reason, I'd make the outer function also use an arrow function for consistency with your inner function.</li>\n</ul>\n\n<h3>A rewrite</h3>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const titleCaseWords = (words, ignore=[\"of\", \"and\", \"the\", \"to\"]) => {\n ignore = new Set(ignore);\n \n return words.replace(/\\w+/g, (word, i) => {\n word = word.toLowerCase();\n \n if (i && ignore.has(word)) {\n return word;\n }\n \n return word[0].toUpperCase() + word.slice(1);\n });\n};\n\n[\n \"Into unmerciful the entreating stronger to of word guessing.\",\n \"the OLD MAN aND THE sEa\"\n].forEach(test => console.log(titleCaseWords(test)));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T15:08:13.877",
"Id": "217015",
"ParentId": "217006",
"Score": "11"
}
},
{
"body": "<blockquote>\n<pre><code> if (![\"of\", \"and\", \"the\", \"to\"].includes(words[i].toLowerCase())) {\n</code></pre>\n</blockquote>\n\n<p>Not a coding issue exactly, but this is missing a lot of words that should not be capitalized. In particular, you only have one of the seven <a href=\"http://www.chompchomp.com/terms/coordinatingconjunction.htm\" rel=\"nofollow noreferrer\">coordinating conjunctions</a>, one of three articles, and two prepositions. <a href=\"https://www.quickanddirtytips.com/education/grammar/capitalizing-titles?page=1\" rel=\"nofollow noreferrer\">Grammar Girl</a> suggests </p>\n\n<blockquote>\n <p>“a,” “an,” “and,” “at,” “but,” “by,” “for,” “in,” “nor,” “of,” “on,” “or,” \"out,\" “so,” “the,” “to,” “up,” and “yet.”</p>\n</blockquote>\n\n<p>She says this is from <em>AP</em> style (which the Associated Press apparently no longer uses). </p>\n\n<p>Incidentally, you should also be capitalizing the last word of the title (as well as the first). Your two examples have nouns as the last word, so this gets capitalized correctly. You may want to add an example where the word is in the lower case list. E.g. \"If it's the last word of the title, should I capitalize 'the'?\" </p>\n\n<p>If you were trying to implement the <em>Chicago</em> style, this would be much more complicated, as there are some words that can be prepositions, adjectives, or adverbs depending on usage. In <em>Chicago</em> style, you have to parse the sentence grammar to determine what gets capitalized. Also, <em>Chicago</em> style uses lower case for prepositions with four letters or more. So there are far more of them. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T20:04:15.847",
"Id": "217028",
"ParentId": "217006",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217015",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T10:59:43.240",
"Id": "217006",
"Score": "9",
"Tags": [
"javascript",
"strings"
],
"Title": "A function which translates a sentence to title-case"
} | 217006 |
<p>Upon solving the problem 'contain duplicates` in leetcode:</p>
<blockquote>
<p>Given an array of integers and an integer <em>k</em> , find out whether there are two distinct indices <em>i</em> and <em>j</em> in the array such that <strong>nums[i] = nums[j]</strong> and the <strong>absolute</strong> difference between <em>i</em> and <em>j</em> is at most <em>k</em> .</p>
<p><strong>Example 1:</strong></p>
<pre><code>
Input: nums = [1,2,3,1] , k = 3
Output: true
</code></pre>
<p><strong>Example 2:</strong></p>
<pre><code>
Input: nums = [1,0,1,1] , k = 1
Output: true
</code></pre>
<p><strong>Example 3:</strong></p>
<pre><code>
Input: nums = [1,2,3,1,2,3] , k = 2
Output: false
</code></pre>
</blockquote>
<p>I tried best to write a Pythonic style solution and improve the performance.</p>
<pre><code>class Solution2:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
lookup = dict() #{value:index}
for cur, val in enumerate(nums):
prev = lookup.get(val)
if prev != None and cur - prev <= k:
#logging.debug(f"{cur - prev}")
return True
lookup[val] = cur #add it to lookup
return False
</code></pre>
<blockquote>
<p>Runtime: 68 ms, faster than 12.21% of Python3 online submissions for Contains Duplicate II.
Memory Usage: 20.4 MB, less than 13.64% of Python3 online submissions for Contains Duplicate II.</p>
</blockquote>
<p>I am confused about the score. I was 100% assure that it was the best possible solution.</p>
<p>What's the problem with my solution? </p>
| [] | [
{
"body": "<p>The <code>lookup</code> dictionary might grow as large as the size of array (all array elements are distinct). It immediately gives an <span class=\"math-container\">\\$(O(n))\\$</span> space complexity, and has detrimental effect on the time complexity as well. It is possible to get away with <span class=\"math-container\">\\$O(k))\\$</span>.</p>\n\n<p>It makes no difference if <span class=\"math-container\">\\$k \\approx n\\$</span>, but boosts the performance for <span class=\"math-container\">\\$k \\ll n\\$</span> (which I presume is so for the bulk of test cases).</p>\n\n<p>To keep the dictionary \"small\", observe that if its size reaches <code>k</code>, it is safe to remove the oldest element. As a side benefit, you wouldn't need to test for <code>cur - prev <= k</code> anymore.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T16:47:30.753",
"Id": "217023",
"ParentId": "217008",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T11:20:18.503",
"Id": "217008",
"Score": "2",
"Tags": [
"python",
"performance",
"programming-challenge"
],
"Title": "Leetcode: Detecting duplicate elements in an array within a k-element window"
} | 217008 |
<p>I am trying to implement AES CTR encryption mode with HMAC authentication for messages. </p>
<p>It's encrypting and decrypting fine as long as the key length is 64 bytes, since AES key and HMAC key are being derived from this key.</p>
<h2>Questions</h2>
<ul>
<li>Is it safe to append IV or nonce to the encrypted messages? </li>
<li>Is it safe to append HMAC digest to append to the messages?</li>
<li>Can you review it for best security coding practices?
I am using Pycryptodome</li>
</ul>
<h2>Code</h2>
<pre><code>import os
import zlib
from Crypto.Hash import HMAC
from Crypto.Hash import SHA256
from Crypto.Cipher import AES
from Crypto.Util import Counter
import zlib
def encrypt(full_key, plaintext):
if len(full_key) != 64:
raise Exception("FULL key length shall be equal to 64")
key = full_key[:len(full_key) //2]
# Use the last half as the HMAC key
hmac_key = full_key[len(full_key) // 2:]
if isinstance(plaintext, str):
plaintext = plaintext.encode()
compressed = zlib.compress(plaintext, 5)
print (f"compressed plaintext {compressed}")
# Choose a random, 16-byte IV.
iv = os.urandom(16)
# Convert the IV to a Python integer.
iv_int = int(binascii.hexlify(iv), 16)
# Create a new Counter object with IV = iv_int.
ctr = Counter.new(128, initial_value=iv_int)
# Create AES-CTR cipher.
aes = AES.new(key, AES.MODE_CTR, counter=ctr)
# Encrypt and return IV and ciphertext.
ciphertext = aes.encrypt(compressed)
hmac_obj = HMAC.new(hmac_key, compressed, SHA256)
mac = hmac_obj.digest()
return iv+ciphertext+mac
def decrypt(key, ciphertext):
# Initialize counter for decryption. iv should be the same as the output of
# encrypt().
if len(full_key) != 64:
raise Exception("FULL key length shall be equal to 64")
key = full_key[:len(full_key) //2]
# Use the last half as the HMAC key
hmac_key = full_key[len(full_key) // 2:]
mac_length = 32
iv_length = 16
iv = ciphertext[:16]
mac = ciphertext[-mac_length:]
_ciphertext = ciphertext[iv_length:-mac_length]
iv_int = int(iv.hex(), 16)
ctr = Counter.new(128, initial_value=iv_int)
# Create AES-CTR cipher.
aes = AES.new(key, AES.MODE_CTR, counter=ctr)
ciphertext = aes.decrypt(_ciphertext)
# Extract the MAC from the end of the file
hmac_obj = HMAC.new(hmac_key, ciphertext, SHA256)
computed_mac = hmac_obj.digest()
if computed_mac != mac:
raise Exception("Messege integrity violated")
plaintext= zlib.decompress(ciphertext)
# Decrypt and return the plaintext.
return plaintext
</code></pre>
| [] | [
{
"body": "<p>I'm not a security expert, so my review will focus on general best practices first.</p>\n\n<h2>Code structure and style</h2>\n\n<p><strong>1. Imports</strong><br/>\nYou can group import that belong together, e.g</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from Crypto.Hash import HMAC\nfrom Crypto.Hash import SHA256\n</code></pre>\n\n<p>can be written as</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from Crypto.Hash import HMAC, SHA256\n</code></pre>\n\n<p>The <a href=\"https://www.python.org/dev/peps/pep-0008/#imports\" rel=\"nofollow noreferrer\">Official Style Guide for Python</a> also recommends to place import from the standard library before any third party libraries. Apart from the double import of <code>zlib</code> you're already following this.</p>\n\n<p><strong>2. Documentation</strong><br/>\nYou started to add some kind of documentation on <code>decrypt</code>, so <code>encrypt</code> should be treated the same. The officially <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">recommended</a> way is to provide function documentation surrounded by <code>\"\"\"...\"\"\"</code> like so</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def decrypt(key, ciphertext):\n \"\"\"Initialize counter for decryption.\n\n iv should be the same as the output of encrypt().\n \"\"\"\n #^--- you probably also mean ciphertext here\n</code></pre>\n\n<p>This will also allow Python's built-in <code>help(...)</code> function to pick up your documentation.</p>\n\n<p><strong>3. Whitespace</strong><br/>\nYou should tidy up the newlines in your code. There are often two (sometimes more) newlines within a function's body, while there are none between the imports and functions. This might be an issue from posting the code here on Code Review, but you should definitely check that. A reasonable convention many people agree on is to use two newlines to seperate functions (or imports from the following functions) and only use a single newline in function bodys to visually create logical groups of code.</p>\n\n<h2>The code itself</h2>\n\n<p><strong>1. Exceptions</strong><br/>\n\"You're not doing the right thing!\" What thing you might ask? Well, ... \"Read it! Find it out yourself!\"<br/>\nSounds frustrating, doesn't it? Python offers a wide variety of built-in exceptions so you can easily convey the type of error that has happened, without the need to parse/read the actual error message. In your case <a href=\"https://docs.python.org/3/library/exceptions.html#ValueError\" rel=\"nofollow noreferrer\"><code>ValueError</code></a> seems to be appropriate. From the documentation:</p>\n\n<blockquote>\n <p><em>exception</em> <code>ValueError</code>\n Raised when an operation or function receives an argument that has the right type but an inappropriate value, [...]</p>\n</blockquote>\n\n<p>In case of an error on checking the HMAC, you might add your <a href=\"https://stackoverflow.com/a/1319675/5682996\">own exception</a> derived from <code>Exception</code> (maybe <code>HMACValidationError</code>?). I will leave this as an exercise to you.</p>\n\n<p><strong>2. encrypt/decrypt</strong><br/>\nThese functions look quite reasonable from what I can jugde and work the way I would expect them to work. A minor \"issue\" I found, is that they are not handling string encoding/decoding symmetrically. While <code>encrypt</code> does handle unicode strings by converting them to bytes representation before encryption, <code>decrypt</code> has no way of knowing that this step has taken place and will always return the raw bytes.<br/>\nAt the moment, I would favor an approach where the application using those functions has to take care that the input is already encoded into bytes and also decode the bytes back into a unicode string if desired. This would also be in line with not handling string values for the key, which strongly hints that there is an earlier step where those are created and possibly encoded. </p>\n\n<p><strong>3. Security</strong><br/>\nFrom what I've seen on my journey through cryptoland, it is a <a href=\"https://crypto.stackexchange.com/a/7922\">quite common practice</a> to simply prepend the ciphertext with the initialiation vector (IV). Password hashing functions do something similar and tend to store the salt prepended to the actual hash to have it available for validation later. Remember: the IV does not protect your ciphertext in the same way the key does, and therefore must not be handled with the same care. It instead prevents an attacker to see the same plaintext mapped the same ciphertext repeatedly, which is maybe more than you can afford to reveal.<br/>\nSomething similar applys to the HMAC. The security of the HMAC authentication should only rely on the secrecy of the key, and nothing else. So as long as you use a <a href=\"https://crypto.stackexchange.com/a/1073\">suitable HMAC implementation</a> and a reasonably secure key, you should be good to go. Just bear in mind that an HMAC alone does not and cannot prevent <a href=\"https://security.stackexchange.com/a/20301\">all kind of attacks</a>, e.g. HMAC alone cannot prevent replay. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T23:26:31.313",
"Id": "217104",
"ParentId": "217014",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T14:54:23.510",
"Id": "217014",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"security",
"authentication",
"aes"
],
"Title": "AES CTR mode encryption with HMAC"
} | 217014 |
<p>I'm trying to figure out what to call this sorting algorithm:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function sort(array) {
array = array.slice();
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length - 1; j++) {
if (array[j] > array[i]) {
//swap
[array[i], array[j]] = [array[j], array[i]]
}
}
}
return array;
}
console.log(sort([8, 4, 5, 2, 3, 7]));</code></pre>
</div>
</div>
</p>
<p>I wrote it while trying to figure out bubble sort which is a lot different. Tho will have slightly the same running time as the actual bubble sort. I might be wrong :(</p>
| [] | [
{
"body": "<p><strike>To me, that's exactly <a href=\"https://en.wikipedia.org/wiki/Bubble_sort\" rel=\"nofollow noreferrer\">Bubblesort</a>: it takes care the largest element moves to the end of the array, and then operates on <code>length-1</code> elements.</strike></p>\n\n<p>Edit: this does look quite similar to Bubblesort, but - as a diligent reader noticed - is <strong>not</strong> <em>quite</em> Bubblesort, as the algorithm does <em>not</em> compare (and swap) <em>adjacent</em> elements (which indeed is the main characteristic of Bubblesort). If you replace <code>array[j] > array[i]</code> with <code>array[j] > array[j+1]</code>, you will get Bubblesort.</p>\n\n<p>This implementation will fail if less than two input elements are given (0 or 1) - hint: the array is already sorted in these cases (just add an <code>if</code>).</p>\n\n<p>A small improvement would be to add a flag in the <code>i</code> loop which records if any swapping happened at all - the outer <code>for</code> loop may terminate if the inner loop didn't perform any swaps. (Time) performance of Bubblesort is considered to be awful in comparison to other algorithms, but it must be noted it's the fastest algorithm on an already sorted array - if you add that flag ;) </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T16:36:06.647",
"Id": "419757",
"Score": "1",
"body": "So, I visualized the execution on pythontutor.com. One should \"never\" use this. It's worse than the unoptimized version of bubble sort. I goes forth and back, which takes more time.\n\nThanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T16:53:54.960",
"Id": "419760",
"Score": "1",
"body": "No. One of the defining characteristics of [Bubble sort](https://en.wikipedia.org/wiki/Bubble_sort) is that it swaps _adjacent_ elements — which is not the case with this code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T17:58:01.630",
"Id": "419769",
"Score": "0",
"body": "@200_success you are absolutely right - about to edit my answer :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T23:32:11.357",
"Id": "419794",
"Score": "0",
"body": "@200_success: The OP's code is actually a (rather inefficient) variant of [insertion sort](https://en.wikipedia.org/wiki/Insertion_sort), with some mostly useless extra shuffling of the tail end of the array thrown in."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T16:11:30.997",
"Id": "217018",
"ParentId": "217017",
"Score": "4"
}
},
{
"body": "<p>It's not even obvious at a glance that your algorithm really sorts all inputs correctly. In fact, it does, but proving that takes a bit of thought.</p>\n\n<p>The key insight is that, at the end of each iteration of the outer loop, the elements at positions from 0 to <code>i</code> will be sorted correctly:</p>\n\n<pre><code>for (let i = 0; i < array.length; i++) {\n for (let j = 0; j < array.length - 1; j++) {\n if (array[j] > array[i]) {\n [array[i], array[j]] = [array[j], array[i]]\n }\n }\n // Invariant: here array[0] to array[i] will be correctly sorted!\n}\n</code></pre>\n\n<p>In particular, this invariant will obviously be true at the end of the <em>first</em> iteration, when <code>i == 0</code>. It is then not hard to inductively show that, if this was true at the end of the previous iteration, then it will remain true (with <code>i</code> now one greater than before) after the next one as well. Thus, at the end of the last iteration, with <code>i == array.length - 1</code>, the whole array will be correctly sorted.</p>\n\n<hr>\n\n<p>Actually, to achieve this, we only need to iterate the inner loop up to <code>j == i - 1</code>; the iteration with <code>i == j</code> obviously does nothing useful, and any later iterations of the inner loop have no effect on the invariant. (Those iterations can only swap the element currently at index <code>i</code> with a larger one from the tail end of the array, which will still leave <code>array[i]</code> greater than or equal to all its predecessors.) So we can speed up your algorithm by only iterating the inner loop until <code>j == i</code>:</p>\n\n<pre><code>for (let i = 0; i < array.length; i++) {\n for (let j = 0; j < i; j++) {\n if (array[j] > array[i]) {\n [array[i], array[j]] = [array[j], array[i]]\n }\n }\n // Invariant: here array[0] to array[i] will be correctly sorted!\n}\n</code></pre>\n\n<p>With this optimization, your algorithm can be recognized as a form of <a href=\"https://en.wikipedia.org/wiki/Insertion_sort\" rel=\"nofollow noreferrer\">insertion sort</a>.</p>\n\n<hr>\n\n<p>It's generally not the most efficient form of that algorithm, though, since the inner loop does the insertion of <code>array[i]</code> into its correct position somewhat inefficiently. A somewhat more efficient implementation would be something like this:</p>\n\n<pre><code>for (let i = 1; i < array.length; i++) {\n let j = i, temp = array[i];\n while (j > 0 && array[j - 1] > temp) {\n array[j] = array[j - 1];\n j--;\n }\n if (j < i) array[j] = temp;\n // Invariant: here array[0] to array[i] will be correctly sorted!\n}\n</code></pre>\n\n<p>By running the inner loop \"backwards\" we can stop it as soon as we find an element that's ranked lower than the one we're inserting (thus avoiding lots of needless comparisons, especially if the input array is already mostly sorted), and by saving the element to be inserted in a temporary variable, we can replace the swaps with simple assignments.</p>\n\n<p>The <code>if (j < i)</code> part of the code above is not really necessary, since if <code>j == i</code>, assigning <code>temp</code> back to <code>array[i]</code> would have no effect. That said, it's generally a useful optimization if integer comparisons are cheaper than array assignments, which is usually the case. The same goes for starting the outer loop from <code>let i = 1</code> instead of <code>let i = 0</code>; the iteration with <code>i == 0</code> does nothing anyway, so we can safely skip it!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T23:28:53.787",
"Id": "217042",
"ParentId": "217017",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217018",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T15:46:18.617",
"Id": "217017",
"Score": "4",
"Tags": [
"javascript",
"algorithm",
"sorting"
],
"Title": "Possibly bubble sort algorithm"
} | 217017 |
<p><code>device_raw_ptr</code> is a simple fancy pointer. It essentially wrap pointers to GPU memory. It's sole purpose is to separate out host pointers from device pointers, i.e. they should not be inter-convertible and must not be dereferenced. At the same time, they should be zero-cost (with respect to raw host pointers) and be maximally compatible with regular pointers.</p>
<p><strong>Helper class:</strong></p>
<pre><code>template <class T>
struct equality_operators {
/*
** The deriving class must implement the following:
** friend bool operator==(const T&, const T&);
*/
friend bool operator!=(const T& lhs, const T& rhs) { return !static_cast<bool>(lhs == rhs); }
};
template <class T>
struct less_than_operators {
/*
** The deriving class must implement the following:
** friend bool operator<(const T&, const T&);
*/
friend bool operator>(const T& lhs, const T& rhs) { return rhs < lhs; }
friend bool operator<=(const T& lhs, const T& rhs) { return !static_cast<bool>(lhs > rhs); }
friend bool operator>=(const T& lhs, const T& rhs) { return !static_cast<bool>(lhs < rhs); }
};
template <class T>
struct relational_operators : equality_operators<T>, less_than_operators<T> { };
</code></pre>
<p><strong><code>device_raw_ptr</code> implementation:</strong></p>
<pre><code>template <class T>
class device_raw_ptr : public relational_operators<T> {
static_assert(std::is_standard_layout<T>::value, "T must satisfy StandardLayoutType");
public:
using element_type = std::remove_extent_t<T>;
constexpr device_raw_ptr() noexcept = default;
constexpr device_raw_ptr(std::nullptr_t) noexcept : ptr { nullptr } { }
constexpr device_raw_ptr(const device_raw_ptr& other) noexcept = default;
explicit device_raw_ptr(element_type* ptr_) noexcept : ptr{ ptr_ } { }
device_raw_ptr(device_raw_ptr&& other) noexcept : ptr{ other.ptr } { other.reset(); }
device_raw_ptr& operator=(const device_raw_ptr& other) noexcept {
swap(device_raw_ptr(other), *this);
return *this;
}
device_raw_ptr& operator=(device_raw_ptr&& other) noexcept {
swap(device_raw_ptr(other), *this);
return *this;
}
void reset() noexcept { ptr = nullptr; }
void reset(T* ptr_) noexcept { ptr = ptr_; }
element_type* get() noexcept { return ptr; };
const element_type* get() const noexcept { return ptr; }
friend void swap(device_raw_ptr& lhs, device_raw_ptr& rhs) noexcept {
using std::swap;
std::swap(lhs.ptr, rhs.ptr);
}
explicit operator bool() const noexcept { return static_cast<bool>(ptr); }
device_raw_ptr& operator++() noexcept {
++ptr;
return *this;
}
device_raw_ptr operator++(int) noexcept {
device_raw_ptr tmp(*this);
ptr++;
return tmp;
}
device_raw_ptr& operator+=(std::ptrdiff_t offset) noexcept {
ptr += offset;
return *this;
}
device_raw_ptr& operator-=(std::ptrdiff_t offset) noexcept {
ptr -= offset;
return *this;
}
friend device_raw_ptr& operator+(device_raw_ptr lhs, std::ptrdiff_t offset) noexcept {
lhs += offset;
return lhs;
}
friend device_raw_ptr& operator-(device_raw_ptr lhs, std::ptrdiff_t offset) noexcept {
lhs -= offset;
return lhs;
}
/* required by relational_operators base class */
friend bool operator==(const device_raw_ptr& lhs, const device_raw_ptr& rhs) noexcept { return lhs.ptr == rhs.ptr; }
friend bool operator<(const device_raw_ptr& lhs, const device_raw_ptr& rhs) noexcept { return lhs.ptr < rhs.ptr; }
protected:
T *ptr;
};
template <class T, class U, class V>
std::basic_ostream<U, V>& operator<<(std::basic_ostream<U, V>& os, const device_raw_ptr<T>& other) {
os << other.get() << " (device)";
return os;
}
</code></pre>
<p>I am also looking for suggestions on how to order different things inside a class.</p>
<p>Might it be better to initialize with <code>nullptr</code> instead of the default constructor. This breaks compatibility but I think it might be worth considering the compiler would mostly optimize the assignment if it's immediately overwritten.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T16:56:52.850",
"Id": "419761",
"Score": "0",
"body": "I just noticed that I am passing rvalues to `swap` which accepts non-const lvalue as arguments. You can find it in the copy & move constructor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T05:14:07.147",
"Id": "419822",
"Score": "0",
"body": "If anyone did not notice, I messed up the `relational_operator` inheritance."
}
] | [
{
"body": "<p><strong>Helper classes</strong></p>\n\n<p>There is no need to use <code>static_cast<bool></code> for your comparisons. The relational operators are already <code>bool</code> values. (If they are not, that is a problem with the definition of the operator for the type <code>T</code>.)</p>\n\n<p>The standard <code><utility></code> header provides definitions for <code>operator!=</code> (from <code>operator==</code>) and <code>operator></code>, <code>operator<=</code>, and <code>operator>=</code> (from <code>operator<</code>). There is no need for you to define those four operators if you have the other two (equality and less-than).</p>\n\n<p>Why do you have the <code>relational_operators</code> struct at all? It shouldn't be necessary.</p>\n\n<p><strong>Implementation</strong></p>\n\n<p>The default constructor for <code>device_raw_ptr</code> leaves the <code>ptr</code> member uninitialized. Typically a class like this would initialize <code>ptr</code> to <code>nullptr</code>, and you wouldn't need the constructor that takes a <code>std::nullptr_t</code> object.</p>\n\n<p>The copy assignment operator should just be <code>ptr = other.ptr</code>, since that is the only thing in your class. The way you have it is nonstandard behavior. You construct a temporary, then pass it as a non-const reference to <code>swap</code>. This is not supported as part of the language, although some compilers (MSVC) support it as an extension. You're constructing a temporary, doing a swap, then destroying the temporary (a noop in this case). Similarly, the move assignment operator can be simplified to not use the temporary (<code>ptr = other.ptr; other.reset();</code>, or use three statements with an assignment to a local to avoid problems if you move assign an object to itself).</p>\n\n<p><code>operator bool</code> does not need a <code>static_cast</code>. Perhaps an explicit <code>ptr != nullptr</code> check, although a pointer will implicitly convert to a <code>bool</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T17:07:44.417",
"Id": "419762",
"Score": "0",
"body": "I thought using `std::rel_ops` is generally frowned upon. https://stackoverflow.com/questions/6225375/idiomatic-use-of-stdrel-ops suggests using `boost:operators`. I wrote my own version instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T17:09:16.487",
"Id": "419763",
"Score": "0",
"body": "The default constructor leaves `ptr` unitialized because that's how raw pointers behave (initialized with garbage?). But I am considering the option of initializing it to `nullptr`. The `std::nullptr_t` is a consequence of the aforementioned statement. I intended to have a `constexpr` constructor which sets `ptr` to `nullptr`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T17:12:27.913",
"Id": "419764",
"Score": "0",
"body": "For the abuse of swap, I made started (https://codereview.stackexchange.com/questions/217019/simple-device-fancy-pointer-implementation/217024#comment419761_217019) using temporaries right after I posted the question. It was an attempt to reuse the constructors to perform move/copy but I think it was overkill for such a simple class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T17:14:05.877",
"Id": "419765",
"Score": "0",
"body": "@Yashas `std::rel_ops` is there to avoid having duplicate definitions of those relational operators. If a class does not want some of them (as mentioned in your linked question), then it should define _all_ of them, and `= delete` the ones it doesn't want to support. But its up to you to decide how to implement them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T17:16:16.557",
"Id": "419766",
"Score": "0",
"body": "@Yashas leaving raw pointer uninitialized is, generally, a bad idea. The cost of assigning a `nullptr` someplace where it isn't strictly necessary is outweighed by the predictability and consistent (mis)behavior the NULL value will give you."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T17:00:56.397",
"Id": "217024",
"ParentId": "217019",
"Score": "2"
}
},
{
"body": "<ol>\n<li><p><code>device_raw_ptr</code> is extremely cheap to copy, so remove all hints of move-semantics and use of <code>swap()</code>.</p></li>\n<li><p>Now you can remove the copy-constructor and copy-assignment, as there is no need to explicitly declare them. Especially making them user-defined must be avoided to keep them trivial.</p></li>\n<li><p>Kudos on trying to use the approved two-step for <code>swap()</code>. Though you get a failing grade anyway because you bungled it by using a qualified call in the second part. Hopefully, C++20 will abolish that nonsense by introducing <a href=\"https://stackoverflow.com/questions/53495848/what-are-customization-point-objects-and-how-to-use-them\">customization point objects</a>.</p></li>\n<li><p>Yes, you should pass your <code>device_raw_ptr</code> by value if you have the choice, as it is a tiny trivial type. Still, refrain from returning a reference to such a temporary.</p></li>\n<li><p>There is no reason <code>operator-(device_raw_ptr, std::ptrdiff_t)</code> should not be <code>constexpr</code>. Aside from your implementation for some reason delegating to <code>operator-=</code>, which is not. Same for <code>operator+</code> which uses <code>operator+=</code>.</p></li>\n<li><p>Is there any reason you don't support subtracting a <code>device_raw_ptr</code> from another?</p></li>\n<li><p>I'm really puzzled why you make the only data-member <code>protected</code> instead of <code>private</code>.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T05:05:23.463",
"Id": "419820",
"Score": "0",
"body": "Wouldn't the implicitly defined copy-assignment operator return a reference?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T07:43:58.560",
"Id": "419837",
"Score": "0",
"body": "I have incorporated the changes you suggested. Please check [latest code](https://gist.github.com/YashasSamaga/a57fba277c310cdede32c9618b124e4b)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T20:16:18.770",
"Id": "217031",
"ParentId": "217019",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T16:15:19.267",
"Id": "217019",
"Score": "4",
"Tags": [
"c++",
"c++11",
"pointers"
],
"Title": "Simple device (fancy) pointer implementation"
} | 217019 |
<p>I have this grouping thing, which is would be a switch case if it weren't for the ranges or a Counter of some sorts, but as there are those ranges I don't know how to implement this any more efficiently.</p>
<pre><code>def getGroups(user_array):
# group1 is group 1-10 x
group1 = 0
# group2 is group 10-50 x
group2 = 0
# group3 is group 50-100 x
group3 = 0
# group4 is group 100-200 x
group4 = 0
# group5 is group 200-500 x
group5 = 0
# group6 is group 500 - 1000 x
group6 = 0
# group7 is group 1000+ x
group7 = 0
for user in user_array:
if user.x_count == 0:
pass
elif user.x_count <= 10:
group1 += 1
elif user.x_count <= 50:
group2 += 1
elif user.x_count <= 100:
group3 += 1
elif user.x_count <= 200:
group4 += 1
elif user.x_count <= 500:
group5 += 1
elif user.x_count <= 1000:
group6 += 1
else:
group7 += 1
return [group1, group2, group3, group4, group5, group6, group7]
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T20:39:54.710",
"Id": "419783",
"Score": "0",
"body": "For what type of application are you using/planning to use this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T21:55:56.283",
"Id": "419790",
"Score": "0",
"body": "@Alex Does it matter? I'm trying to group some users for a small project for visualisation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T22:13:26.980",
"Id": "419791",
"Score": "0",
"body": "Indeed, it does. Your application can greatly influence what aspects matter most about your code. Random examples: hyper-critical, real-time, background application, code it and never touch again? Aim for fast execution. You/others should be able to \"play\" with it? Ease of use and clarity are prime considerations here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T01:57:36.313",
"Id": "419800",
"Score": "0",
"body": "Also, does `user_array` only contain `int` values, or can it contain floating point numbers?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T08:28:30.337",
"Id": "419842",
"Score": "0",
"body": "@Alex Ah ok, the focus is mainly performance as we use it to group the results of some mined data... And yes it only contains int values."
}
] | [
{
"body": "<p>If your data is strictly integer values, you can use <code>user.x_count in range(...)</code> to test whether or not the <code>user.x_count</code> value is a member of the <code>range(...)</code> set. Ie)</p>\n\n<pre><code>def getUsers(user_array):\n group1 = sum(1 for user in user_array if user.x_count in range(1, 11))\n group2 = sum(1 for user in user_array if user.x_count in range(11, 51))\n # ... etc ...\n</code></pre>\n\n<p>This unfortunately will require several passes through your <code>user_array</code> data, so will not work if that data is ephemeral, such as iterator or generator based.</p>\n\n<p>A more complex method will categorize the <code>user.x_count</code> value into a group value, and then increment the appropriate group counter. <code>bisect</code> will find an insertion index in a sorted array, so we can leverage this to turn a <code>user.x_count</code> into a group based on its corresponding insertion index. This will function properly if floating point values are encountered.</p>\n\n<pre><code>import bisect\n\ndef getUsers(user_array):\n thresholds = (0, 10, 50, 100, 200, 500, 1000)\n groups = [0] * (len(thresholds) + 1)\n\n for user in user_array:\n groups[bisect.bisect_left(thresholds, user.x_count)] += 1\n\n return groups[1:]\n</code></pre>\n\n<p>Notice there are no more group-specific variables, like <code>group1</code>. Instead, all counters are created based on data, allowing you to add additional groups without modifying lines of code; you just modify <em>data</em>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T08:33:11.563",
"Id": "419845",
"Score": "0",
"body": "That second solution looks really good. We don't need the temporary variables anyways and as the result is the same array, that is very good. The first option however is probably to slow, as it is a very large array. Even tho the code would be more readable. Thank you for your answer!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T11:02:24.630",
"Id": "419851",
"Score": "1",
"body": "I also like the second solution. If you're not bound to the standard library, maybe also have a look at Python packages like [pandas](https://pandas.pydata.org/) which are widely used in data analytics."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T02:33:24.600",
"Id": "217048",
"ParentId": "217021",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217048",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T16:24:55.303",
"Id": "217021",
"Score": "3",
"Tags": [
"python"
],
"Title": "Group counter for ranges of values"
} | 217021 |
<p>I've recently started looking into encryption in python and I came across with pycryptodome library. I made this simple program that encrypt/decrypt a file using AES-GCM. Could someone take a look if I implemented the encryption and authentication correctly? For sake of simplicity, I'm posting only the encryption and makeKey functions. </p>
<pre><code>import os
import struct
import secrets
import hahslib
from Cryptodome.Cipher import AES
def makeKey(password, salt):
key = hashlib.pbkdf2_hmac('sha512',password.encode('ascii'), salt, 1000000)
return key[:32]
def encrypt(password, inputFileName):
#creates the needed variables for encryption
salt = secrets.token_bytes(16)
key = makeKey(password, salt)
nonce = secrets.token_bytes(AES.block_size)
cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
#put the file size, salt and nonce in outputfile
fileSize = os.path.getsize(inputFileName)
with open("output", "wb") as outputFile:
outputFile.write(struct.pack('<Q', fileSize))
outputFile.write(salt)
outputFile.write(nonce)
#beginning of encryption itself
chunkSize = 64 * 1024
with open(inputFileName, "rb") as inputFile:
while True:
chunk = inputFile.read(chunkSize)
if len(chunk) == 0:
outputFile.write(cipher.digest())
break
outputFile.write(cipher.encrypt(chunk))
</code></pre>
| [] | [
{
"body": "<h2>Handling files - the Python way</h2>\n\n<p>Without being able to test run your code at the momemt, there is one thing I can already recommend to you, which is to make use of Python's powerful <a href=\"https://effbot.org/zone/python-with-statement.htm\" rel=\"nofollow noreferrer\"><code>with</code> statement</a>. Using <code>with</code> will make sure that files will be closed no matter what happens (e.g. unexpected exceptions). <code>with</code> also works with more than one file as described in this <a href=\"https://stackoverflow.com/a/4617069/5682996\">SO post</a>.</p>\n\n<p>Also consider adding the output filename as parameter to your function. You can even give your momentary value of <code>\"output\"</code> as default value.</p>\n\n<hr>\n\n<h2>Minor notes on style</h2>\n\n<p>I'm not sure if you're aware of the official <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide for Python</a>, often just called PEP8. The official recommendation is to use <code>snake_case</code> for variable and function names. This would create a more unified code appearance when working with other Python libraries which often stick to that convention. As always, <a href=\"https://www.qt.io/qt-for-python\" rel=\"nofollow noreferrer\">exceptions</a> apply.</p>\n\n<hr>\n\n<p>Below is your code including these changes.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def make_key(password, salt):\n ...\n\ndef encrypt(password, input_filename, output_filename=\"output\"):\n #creates the needed variables for encryption\n salt = secrets.token_bytes(16)\n key = make_key(password, salt)\n nonce = secrets.token_bytes(AES.block_size)\n cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)\n # put the file size, salt and nonce in outputfile\n filesize = os.path.getsize(input_filename)\n with open(output_filename, \"wb\") as output_file,\\\n open(input_filename, \"rb\") as input_file:\n output_file.write(struct.pack('<Q', filesize))\n output_file.write(salt)\n output_file.write(nonce)\n #beginning of encryption itself\n chunkSize = 64 * 1024\n while True:\n chunk = input_file.read(chunkSize)\n if len(chunk) == 0:\n output_file.write(cipher.digest())\n break\n output_file.write(cipher.encrypt(chunk))\n print(\"File encrypted successfully!\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T20:11:19.163",
"Id": "217029",
"ParentId": "217025",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T17:06:12.570",
"Id": "217025",
"Score": "3",
"Tags": [
"python",
"aes"
],
"Title": "AES GCM Python implementation"
} | 217025 |
<p>What can be done better? My future plans is to implement algorithms such as: DFS, BFS, Prims, Dijkstra, Kruskal, ...</p>
<p><br>
<strong>Faults I know of:</strong></p>
<ul>
<li>Not implementing rule of five</li>
</ul>
<hr>
<p><strong>Vertex.h:</strong></p>
<pre><code>#pragma once
#include <iostream>
#include <unordered_map>
template<typename T>
class Vertex
{
public:
Vertex(const T& value);
~Vertex();
const T& value() const;
void add_edge_in(Vertex<T>* dest, int weight);
void add_edge_out(Vertex<T>* dest, int weight);
void remove_edge_in(Vertex<T>* dest);
void remove_edge_out(Vertex<T>* dest);
private:
template<typename T> friend std::ostream& operator<<(std::ostream& out, const Vertex<T>& rhs);
const T value_;
std::unordered_map<Vertex<T>*, int> edges_in_;
std::unordered_map<Vertex<T>*, int> edges_out_;
};
template<typename T>
Vertex<T>::Vertex(const T& value)
: value_(value)
{
}
/*
Removes all edges associated with this vertex
*/
template<typename T>
Vertex<T>::~Vertex<T>()
{
for (auto edge : edges_in_)
{
Vertex<T>* dest = edge.first;
dest->remove_edge_in(this);
}
for (auto edge : edges_out_)
{
Vertex<T>* dest = edge.first;
dest->remove_edge_out(this);
}
}
template<typename T>
const T& Vertex<T>::value() const
{
return value_;
}
template<typename T>
void Vertex<T>::add_edge_in(Vertex<T>* dest, int weight)
{
edges_in_.insert({ dest, weight });
}
template<typename T>
void Vertex<T>::add_edge_out(Vertex<T>* dest, int weight)
{
edges_out_.insert({ dest, weight });
}
template<typename T>
void Vertex<T>::remove_edge_in(Vertex<T>* dest)
{
edges_in_.erase(dest);
}
template<typename T>
void Vertex<T>::remove_edge_out(Vertex<T>* dest)
{
edges_out_.erase(dest);
}
template<typename T>
std::ostream& operator<<(std::ostream& out, const Vertex<T>& rhs)
{
out << "[" << rhs.value_ << "]:";
out << "\r\n{";
out << "\r\n\t EDGES_IN = {";
for (auto edge : rhs.edges_in_)
{
out << " (" << edge.first->value_ << ", " << edge.second << ")";
}
out << " },";
out << "\r\n\t EDGES_OUT = {";
for (auto edge : rhs.edges_out_)
{
out << " (" << edge.first->value_ << ", " << edge.second << ")";
}
out << " }";
out << "\r\n};";
return out;
}
</code></pre>
<p><br></p>
<p><strong>Graph.h:</strong></p>
<pre><code>#pragma once
#include "Vertex.h"
#include <iostream>
#include <vector>
template<typename T>
class Graph
{
public:
Graph(const bool directed);
~Graph();
void print() const;
bool is_directed() const;
void add_vertex(const T&);
void remove_vertex(const T&);
void add_edge(const T&, const T&, int weight);
void remove_edge(const T&, const T&);
private:
Vertex<T>* get_vertex(const T&);
std::vector<Vertex<T>*> graph_;
const bool directed_;
};
template<typename T>
Graph<T>::Graph(const bool directed)
: directed_(directed)
{
}
template<typename T>
Graph<T>::~Graph()
{
for (Vertex<T>* v : graph_)
{
delete v;
}
}
template<typename T>
void Graph<T>::print() const
{
for (Vertex<T>* v : graph_)
{
std::cout << *v << std::endl;
}
}
template<typename T>
bool Graph<T>::is_directed() const
{
return directed_;
}
template<typename T>
void Graph<T>::add_vertex(const T& value)
{
graph_.push_back(new Vertex<T>(value));
return;
}
template<typename T>
void Graph<T>::remove_vertex(const T& value)
{
for (auto it = graph_.begin(); it != graph_.end(); ++it)
{
if ((*it)->value() == value)
{
delete *it;
graph_.erase(it);
return;
}
}
}
template<typename T>
void Graph<T>::add_edge(const T& src_value, const T& dest_value, int weight)
{
Vertex<T>* src = get_vertex(src_value);
Vertex<T>* dest = get_vertex(dest_value);
src->add_edge_out(dest, weight);
dest->add_edge_in(src, weight);
if (!directed_)
{
src->add_edge_in(dest, weight);
dest->add_edge_out(src, weight);
}
}
template<typename T>
void Graph<T>::remove_edge(const T& src_value, const T& dest_value)
{
Vertex<T>* src = get_vertex(src_value);
Vertex<T>* dest = get_vertex(dest_value);
src->remove_edge_out(dest);
dest->remove_edge_in(src);
if (!directed_)
{
src->remove_edge_in(dest);
dest->remove_edge_out(src);
}
}
template<typename T>
Vertex<T>* Graph<T>::get_vertex(const T& value)
{
for (Vertex<T>* v : graph_)
{
if (v->value() == value)
{
return v;
}
}
return nullptr;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T01:07:43.603",
"Id": "419799",
"Score": "1",
"body": "The rule of five would become the rule of zero if it weren't for your decision to use dynamically-allocated `T` objects in your vertices. I can understand an implementation of a graph where it holds pointers to resources it does not own, but that's not what's happening here. Using `new` and `delete` in your case offers no advantages and only makes things more complicated. If you store plain-old `Vertex<T>`'s in your `std::vector`, then your rule of five functions can all be `default`ed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T15:25:31.437",
"Id": "419886",
"Score": "0",
"body": "Too many pointers being passed around."
}
] | [
{
"body": "<h2>Design</h2>\n<p>The problem is that there can only be one vertext with a particular value. Well actually you can add the same value multiple times <strong>BUT</strong> any operation will be applied to the first vertex with that value, so its like there is only one visible value in the vertex list.</p>\n<p>Either you should allow multiple values (in which case use the value is not a valid way to find a vertex). Or you should prevent the same value being added to the vertex list more than once.</p>\n<p>You have issues with memory management. Caused by using new/delete and not considering the rule of 5.</p>\n<p>You play with pointers all over the place with no attempt to check that they are <code>nullptr</code>.</p>\n<h2>Code Review</h2>\n<p>Yes you need to store them as pointers (non owning).</p>\n<pre><code>std::unordered_map<Vertex<T>*, int> edges_in_;\nstd::unordered_map<Vertex<T>*, int> edges_out_;\n</code></pre>\n<p>But that does not mean the interface needs to be pointers.</p>\n<pre><code>void add_edge_in(Vertex<T>* dest, int weight);\nvoid add_edge_out(Vertex<T>* dest, int weight);\nvoid remove_edge_in(Vertex<T>* dest);\nvoid remove_edge_out(Vertex<T>* dest);\n</code></pre>\n<p>Here I would pass in references. That way you know that a <code>dest</code> can never be null.</p>\n<hr />\n<p>I don't see why you are storing pointer here:</p>\n<pre><code>std::vector<Vertex<T>*> graph_;\n</code></pre>\n<p>Here the graph has ownership (and <code>Vertex<T></code> is not polymorphic). So by using pointers you are adding the whole issue of memory management to your class without needing to.</p>\n<p>By making this <code>std::vector<Vertex<T>></code> you get around the whole problem of memory management. By making this <code>std::vector<std::unique_ptr<Vertex<T>>></code> you make the graph non copyable (an alternative solution). I would go with the first.</p>\n<hr />\n<p>Because you store owned RAW pointers you need to implement the rule of 3/5. Or you need to fix it like I suggest above.</p>\n<pre><code> {\n Graph<int> x;\n x. add_vertex(1);\n Graph<int> y(x);\n }\n // This currently is broken and will result in a double delete.\n</code></pre>\n<hr />\n<p>Sure. I don't mind a <code>void Graph<T>::print() const</code>. But I also expect to see <code>friend std::ostream& operator<<(std::ostream&, Graph<T> const&)</code> for printing.</p>\n<p>Also why does <code>print()</code> only print to <code>std::cout</code> you should allow it to print to any stream!</p>\n<pre><code>class Graph\n{\n void print(std::ostream& str = std::cout) const;\n friend std::ostream& operator<<(std::ostream& s, Graph const& d) {\n d.print(s);\n return s;\n }\n};\n</code></pre>\n<hr />\n<pre><code>Vertex<T>* Graph<T>::get_vertex(const T& value)\n{\n // STUFF\n return nullptr;\n}\n</code></pre>\n<p>No caller of <code>get_vertex()</code> ever checks for <code>nullptr</code> being returned. This is going to blow up so easily.</p>\n<hr />\n<pre><code>for (auto it = graph_.begin(); it != graph_.end(); ++it)\n{\n if ((*it)->value() == value)\n {\n delete *it;\n graph_.erase(it);\n return;\n }\n}\n</code></pre>\n<p>There is a pattern for this: <strong>Erase Remove Idiom</strong>.</p>\n<pre><code>auto end = std::remove_if(std::begin(graph_), std::end(graph_), [&value](Vertex* it){return it->value == value;});\nfor(auto loop = end; loop != std::end(graph_); ++loop) {\n delete *loop;\n}\ngraph_.erase(end, std::end(graph_));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T15:42:38.190",
"Id": "217083",
"ParentId": "217032",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217083",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T20:20:13.297",
"Id": "217032",
"Score": "5",
"Tags": [
"c++",
"beginner",
"graph"
],
"Title": "C++ graph class"
} | 217032 |
<p>I have a list of unsorted numbers. Each time, I need to remove 2 smallest numbers and insert back its sum into the list. Repeatedly do this till the 1 final element is remaining in the list.</p>
<p><strong>Return the total sum of newly inserted elements</strong></p>
<p>My logic was to use heap sort, remove 2 elems, insert elems sum back - repeat.</p>
<p>This program of input of 10 elements has called heapify function 310 times!</p>
<p>Link: <a href="http://cpp.sh/8vkjd" rel="nofollow noreferrer">http://cpp.sh/8vkjd</a></p>
<p>How do I optimize this scenario?</p>
<ol>
<li>Use Binary Search Tree?</li>
<li>Use Heap Sort on LinkedList?</li>
<li>Is this possible with graphs?</li>
<li>Since there are several insertions, I'm trying to only restrict to O(N) or <span class="math-container">\$O(\log N)\$</span> or <span class="math-container">\$O(n \log N)\$</span> insertion.</li>
<li>Can this be done with 2 lists?</li>
<li>Since the elements will be sorted after the 1st iteration, is there a good insertion algorithm that does faster insertion?</li>
</ol>
<p></p>
<pre><code>#include <iostream>
#include <sstream>
#include <vector>
int count = 0; // A global variable to keep track of number of time heapify function is called
void heapify(std::vector<int> &arr, int n, int i)
{
count++;
int largest = i;
int l = 2*i + 1;
int r = 2*i + 2;
if(l<n && arr[l] >arr[largest])
largest = l;
if(r<n && arr[r] > arr[largest])
largest = r;
if(largest != i)
{
std::swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}
void heapSort(std::vector<int> &arr, int n)
{
for(int i=n/2 -1 ; i>=0 ; i--)
{
heapify(arr,n,i);
}
for(int i=n-1 ; i>=0 ; i--)
{
std::swap(arr[0],arr[i]);
heapify(arr,i,0);
}
}
void printArray(std::vector<int> &arr, int n)
{
for(int i=0 ; i<n ; i++)
{
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}
int main()
{
std::vector<int> arr{1,2,3,4,5,6,7,8,9,10};
int n = arr.size();
printArray(arr,n);
heapSort(arr,n);
int ans=0;
int tempEle=0;
while(arr.size()>1)
{
heapSort(arr,n);
tempEle = arr[0]+arr[1];
arr.erase(arr.begin(),arr.begin()+2);
ans+=tempEle;
arr.push_back(tempEle);
printArray(arr,arr.size());
}
ans+=arr[0];
std::cout << "Repeatedly adding all elements, 2 small elements at a time and reducing it to a single number : " << ans << std::endl;
std::cout << "Heapify was called " << count << " times" << std::endl;
return 0;
}
</code></pre>
<p><a href="https://i.stack.imgur.com/1wMe5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1wMe5.png" alt="sample test case for 10 elements showing expected output"></a></p>
<p>And for an input of 5000 numbers, the <code>heapify()</code> func is being called 246 million times.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T21:36:52.130",
"Id": "419788",
"Score": "1",
"body": "Seems like busy work; you could simply add all the integers together in unsorted order, O(N) time and O(1) space, and the result would be the same. If the unsorted array contained _floating point numbers_, the approach of adding together the smallest numbers first can improve the accuracy of the resulting sum; with fixed point numbers (including integers), this is pointless."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T22:39:16.960",
"Id": "419793",
"Score": "0",
"body": "@AJNeufeld: condition is to remove the minimum 2 elements in a list every single time and add it to the sum."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T00:15:05.947",
"Id": "419797",
"Score": "1",
"body": "If you have 10 numbers, how many additions will be performed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T02:22:27.110",
"Id": "419801",
"Score": "0",
"body": "@E.Coms: For 10 elements, there are 10 add operations will be performed and 10 insertion operations will be performed and 10*2=20 remove operations will be performed on that list"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T08:35:27.373",
"Id": "419846",
"Score": "1",
"body": "Use a heap to keep the list sorted."
}
] | [
{
"body": "<pre><code>#include <sstream>\n</code></pre>\n\n<p>Only include what is necessary.</p>\n\n<hr>\n\n<pre><code> for(int i=0 ; i<n ; i++) { ... }\n</code></pre>\n\n<p>Use range-based <code>for</code>.</p>\n\n<pre><code> std::cout << ... << std::endl;\n</code></pre>\n\n<p>Avoid <code>std::endl</code>.</p>\n\n<hr>\n\n<pre><code>void printArray(std::vector<int> &arr, int n) { ... }\n ^^^^^\nint main() {\n int n = arr.size();\n ^^^^^^^^^^^^\n printArray(arr,n);\n ^\n</code></pre>\n\n<p>You have an implicit conversions from <code>std::vector::size_type</code> to <code>int</code> when you initialize <code>n</code> and pass an <code>int</code> argument to parameter <code>n</code>.</p>\n\n<hr>\n\n<pre><code> printArray(arr, n);\n heapSort(arr, n);\n</code></pre>\n\n<p><code>std::vector</code> carries its size. You do not have to capture it in a variable and pass it.</p>\n\n<pre><code> int n = arr.size();\n while (arr.size() > 1) {\n heapSort(arr, n);\n arr.erase(...);\n arr.push_back(...);\n }\n</code></pre>\n\n<p>With each iteration of the loop, you pop 2 elements and push 1 element reducing the size of <code>arr</code> by 1. <code>n</code> is a local copy of <code>arr.size()</code> and is never updated. This results in out-of-bounds index access in your sort functions after the first iteration of this loop.</p>\n\n<p>As for your issues with excessive calls to <code>heapify()</code>, you are calling <code>heapSort()</code> on every iteration. <code>heapSort()</code> takes a sequence in any order, sorts all of the values into heap order, then sorts all of the values again into sequential sorted order. This is done so you can operate on the two minimum values at the same time. Instead of fully sorting the sequence on every iteration, you can take a partial sort approach. Maintain the sequence in heap order by sifting values around as you mutate the sequence. Finding each minimum values is simply a swap and a sift down. Repairing the heap order on insertion is simply a sift up. Which brings me to know your <a href=\"https://en.cppreference.com/w/cpp/header/algorithm\" rel=\"nofollow noreferrer\"><code><algorithm></code></a>s. The C++ standard library provides heap operations (<a href=\"https://en.cppreference.com/w/cpp/algorithm/is_heap\" rel=\"nofollow noreferrer\"><code>is</code></a>, <a href=\"https://en.cppreference.com/w/cpp/algorithm/make_heap\" rel=\"nofollow noreferrer\"><code>make</code></a>, <a href=\"https://en.cppreference.com/w/cpp/algorithm/push_heap\" rel=\"nofollow noreferrer\"><code>push</code></a>, <a href=\"https://en.cppreference.com/w/cpp/algorithm/pop_heap\" rel=\"nofollow noreferrer\"><code>pop</code></a>, <a href=\"https://en.cppreference.com/w/cpp/algorithm/sort_heap\" rel=\"nofollow noreferrer\"><code>sort</code></a>).</p>\n\n<pre><code> // Sort into min-heap order\n std::make_heap(arr.begin(), arr.end(), std::greater()) \n\n while (arr.size() > 1) {\n // rotate out the 1st min keeping heap order intact\n std::pop_heap(arr.begin(), arr.end(), std::greater());\n const auto first = arr.back();\n arr.pop_back();\n\n // rotate out the 2nd min keeping heap order intact\n std::pop_heap(arr.begin(), arr.end(), std::greater());\n const auto second = arr.back();\n arr.pop_back();\n\n const auto sum = first + second;\n ans += sum;\n\n // Move the inserted value into its heap order position\n arr.push_back(sum);\n std::push_heap(arr.begin(), arr.end(), std::greater());\n }\n</code></pre>\n\n<p><a href=\"https://en.cppreference.com/w/cpp/container/priority_queue\" rel=\"nofollow noreferrer\"><code>std::priority_queue</code></a> helps clean up some of the duplication.</p>\n\n<pre><code> std::priority_queue min_heap{std::greater(), std::move(arr)};\n while (min_heap.size() > 1) {\n const auto first = min_heap.top();\n min_heap.pop();\n const auto second = min_heap.top();\n min_heap.pop();\n\n const auto sum = first + second;\n ans += sum;\n min_heap.push(sum);\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T04:01:02.867",
"Id": "217050",
"ParentId": "217034",
"Score": "2"
}
},
{
"body": "<p>The numbers you insert must be monotonic increasing (either strictly larger than the last or equal to it).</p>\n\n<p>So: sort the original list smallest to largest.</p>\n\n<p>Create a second, empty queue.</p>\n\n<p>Peek at four values: the head and next of the sorted list, and the head and next of the queue. Remove the lowest two, and push their sum onto the queue.</p>\n\n<p>Of course, you could also just sum the list in O(n) time, but exploiting the fact that the sums are monotonic increasing allows you to avoid a bunch of heapifys.\nRepeat until both the list and queue are empty.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T05:25:27.540",
"Id": "217051",
"ParentId": "217034",
"Score": "1"
}
},
{
"body": "<p>There is a cleaner way to write your algorithm, relying on iterators and <code><algorithm></code>. Cleaner is almost always better, because you can more easily reason about your code and spot the bugs' origin. Let me ask you a few questions:</p>\n\n<ul>\n<li><p>what are those <code>i</code> and <code>n</code> variables? (there's a good chance you'll have to look back at your code, and maybe match your code and what you know / remember about the algorithm you used; whereas <code>first</code>, <code>last</code> are always iterators to the first and past the last elements, no need to check). By the way <code>n</code> isn't even used.</p></li>\n<li><p>how will your functions react if given an empty vector? If <code>i</code> isn't coherent with the vector's size? (idem, you'll need to check, think about the division result, etc).</p></li>\n<li><p>what will your function return if given an empty vector? <code>0</code> seems a good choice, but in some contexts, the absence of elements should be discriminated from the presence of null values. With iterators, <code>last</code> is the default \"void\" or \"failure\" value.</p></li>\n<li><p>the requirements are also clearly stated in the <code><algorithm></code> implementation: for instance, <code>std::nth_element</code> could be used here but requires iterators to be random access iterators. You won't use it on a linked list. On the other hand, <code>std::min_element</code> only requires forward iterators, so is compatible with a linked list. Having the least two elements at the beginning would look like </p></li>\n</ul>\n\n<p>this:</p>\n\n<pre><code>std::iter_swap(first, std::min_element(first, last));\nstd::iter_swap(std::next(first), std::min_element(std::next(first), last));\n</code></pre>\n\n<p>So here's for instance what I'd consider a cleaner code:</p>\n\n<pre><code>template <typename Iterator>\nauto bottom_progressive_sum(Iterator first, Iterator last) {\n if (first == last) return last;\n if (std::next(first) == last) return first;\n while (std::next(first) != last) {\n std::iter_swap(first, std::min_element(first, last));\n std::iter_swap(std::next(first), std::min_element(std::next(first), last));\n *std::next(first) += *first;\n ++first;\n }\n *std::next(first) += *first;\n return ++first;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T17:17:32.747",
"Id": "419897",
"Score": "0",
"body": "this code is so good. thank you.\nLooks like this will perform better than a Balanced BST too."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T08:23:39.533",
"Id": "217058",
"ParentId": "217034",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T20:29:52.227",
"Id": "217034",
"Score": "5",
"Tags": [
"c++",
"algorithm",
"sorting",
"tree",
"heap"
],
"Title": "Repeatedly keep removing 2 smallest elements and add its sum back to the list and return newly inserted elements' total"
} | 217034 |
<p>I am trying to write a NDK program for quicksorting an array. However, in my benchmarks C is doing consistently worse than Java, as indicated by my results:</p>
<p>Java 1190625
C 1809218</p>
<p>Java 895104
C 1372656</p>
<p>Java 1104792
C 1491198</p>
<p>Java 10766875
C 14929115</p>
<p>Java 9200104
C 9770833</p>
<p>Java 5740782
C 9177135</p>
<p>Could someone help me?</p>
<pre><code>package com.example.bill.androidredblacktree;
import android.content.Intent;
import android.net.Uri;
import android.os.Debug;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import java.util.Arrays;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
public class QuicksortBenchmarks extends AppCompatActivity {
public native void QuicksortCPassArray(int a[]);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quicksort_benchmarks);
int n1[] = {2000,20000};
int j1 = 0;
for (j1 = 0; j1 < n1.length; j1++) {
int counts=0;
for (int k1=0;k1<3;k1++) {
int i, n = n1[j1];
long startTime, estimatedTime, estimatedTime1;
int a[];
a = new int[n];
for (i = 0; i < n; i++) {
a[i] = i;
}
int z, j;
Random rnd = ThreadLocalRandom.current();
for (j = n - 1; j > 0; j--) {
z = rnd.nextInt(j + 1);
swap(a, z, j);
}
int b[]= Arrays.copyOf(a,a.length);
startTime = System.nanoTime();
quicksort(a, 0, n - 1);
estimatedTime = System.nanoTime() - startTime;
System.out.print("Java " + estimatedTime + '\n');
startTime = System.nanoTime();
QuicksortCPassArray(b);
estimatedTime1 = System.nanoTime() - startTime;
System.out.print("C " + estimatedTime1 + '\n');
}
}
}
private static void quicksort(int a[], int x, int y) {
int q;
if (x < y) {
q = partition(a, x, y);
quicksort(a, x, q - 1);
quicksort(a, q + 1, y);
}
}
private static int partition(int a[], int x, int y) {
int temp = a[y];
int i = x - 1;
int j;
for (j = x; j <= y - 1; j++) {
if (a[j] <= temp) {
i++;
swap(a, i, j);
}
}
swap(a, i + 1, y);
return (i + 1);
}
private static void swap(int a[], int i, int j) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
private int[] shuffleArray(int a[]){
int i;
for (i = 0; i < a.length; i++) {
a[i] = i;
}
int z;
Random rnd = ThreadLocalRandom.current();
for (int j = a.length - 1; j > 0; j--) {
z = rnd.nextInt(j + 1);
swap(a, z, j);
}
return a;
}
}
</code></pre>
<pre><code>#include <jni.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void quicksort(jint *a, jint x, jint y);
jint partition(jint *a, jint x, jint y);
void swap(jint *a, jint *b);
JNIEXPORT void JNICALL
Java_com_example_bill_androidredblacktree_QuicksortBenchmarks_QuicksortCPassArray(
JNIEnv *env,
jobject this,
jintArray arr) {
jint *c_array = (*env)->GetIntArrayElements(env, arr, 0);
jint n = (*env)->GetArrayLength(env, arr);
quicksort(c_array, 0, n - 1);
(*env)->ReleaseIntArrayElements(env, arr, c_array, 0);
}
void quicksort(jint *a, jint x, jint y) {
jint q;
if (x < y) {
q = partition(a, x, y);
quicksort(a, x, q - 1);
quicksort(a, q + 1, y);
}
}
jint partition(jint *a, jint x, jint y) {
jint temp = *(a + y);
jint i = x - 1;
jint j;
for (j = x; j <= y - 1; j++) {
if (*(a + j) <= temp) {
i++;
jint temp1 = *(a + i);
*(a + i) = *(a + j);
*(a + j) = temp1;
//swap(&a[i], &a[j]);
}
}
jint temp2 = *(a + i + 1);
*(a + i + 1) = *(a + y);
*(a + y) = temp2;
//swap(&a[i + 1], &a[y]);
return (i + 1);
}
void swap(jint *a, jint *b) {
jint temp = *a;
*a = *b;
*b = temp;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T05:06:56.223",
"Id": "419821",
"Score": "0",
"body": "Can you include the definition of `jint`? Also, how are you calculating the times in the C portion? Are you including the calls to get the array in the timing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T05:59:56.180",
"Id": "419825",
"Score": "0",
"body": "@user1118321 jint is the int type of the JNI function. I am including the calls to the C function as I'm measuring the time in the Java program."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T02:01:16.953",
"Id": "419937",
"Score": "0",
"body": "\"jint is the int type of the JNI function.\" - well yeah, I get that's what it is, but how is it defined? Is it just a `typedef` that makes an alias of `int` or is it some other sort of thing? Aren't all types in Java objects?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T09:04:58.670",
"Id": "419963",
"Score": "0",
"body": "@user1118321 To be honest, I do not know. I suppose it's an alias of int."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T02:53:15.263",
"Id": "420081",
"Score": "0",
"body": "According to [the documentation](https://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/types.html) `jint` is a 32-bit signed integer native type. I just wanted to make sure because Java handles native types a little differently than C or C-based OOP languages."
}
] | [
{
"body": "<h1>Performance</h1>\n<p>What are you trying to determine with this test? I ask because if you're simply trying to compare the speed of sorting in Java vs. sorting in C, you haven't constructed the test correctly. As it stands, the calls to <code>GetIntArrayElements()</code>, <code>GetArrayLength()</code>, and <code>ReleaseIntArrayElements()</code> are doing work that's not counted in the Java case.</p>\n<p>If, on the other hand, you're trying to determine if converting your data from Java format to C format and then sorting it in C is faster than just sorting it in Java, then you've got a reasonable test. But the results should be fairly unsurprising. (Though it's always good to test your assumptions!)</p>\n<p>If I'm understanding <a href=\"https://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/design.html#wp16696\" rel=\"nofollow noreferrer\">the documentation</a> correctly, the calls to <code>GetIntArrayElements()</code> and <code>ReleaseIntArrayElements()</code> may be allocating, copying, and freeing memory. Those operations can be time consuming and may explain the differences you're seeing. You should run your code under a profiler to see for sure.</p>\n<p>That said, your implementation is about twice as fast as the built-in <code>qsort()</code> function, which needs to make a function call for each comparison. That's pretty decent.</p>\n<h1>Naming</h1>\n<p>I realize this is just simple sorting but you really should name your function arguments better. For <code>quicksort()</code>, the arguments are the array, the start index of the range to sort and the end index of the range to sort. Honestly, <code>a</code> is fine for a general-purpose sort function. (If you are writing something more specific and you know the array will represent something specific, you should name the array argument based on that.) But there's no reason you can name <code>x</code> and <code>y</code> something like <code>startIndex</code> and <code>endIndex</code>, or at least <code>start</code> and <code>end</code>.</p>\n<p>Likewise, when you have a bunch of temporary variables, naming them <code>temp</code>, <code>temp1</code>, and <code>temp2</code> is useless. In <code>partition()</code> the variable <code>temp</code> is the value in the last element of the range, so just call it <code>lastElement</code>. <code>temp1</code> and <code>temp2</code> are used for swapping, so you could name them <code>swap</code>. Although, personally, calling the <code>swap()</code> function you wrote would be clearer and it would likely be inlined anyway, giving you the same speed when compiled with optimizations on.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T05:14:16.253",
"Id": "217180",
"ParentId": "217035",
"Score": "2"
}
},
{
"body": "<h3>Tested on Windows</h3>\n\n<p>I tried your program natively on Windows to see what would happen. First, I modified the Java and C files to remove all of the Android related code/naming. Second, I increased the array sizes to 200000 and 2000000. Then I used Visual Studio C++ to compile the C file, using this command:</p>\n\n<pre><code>cl /LD csort.c /I<$JAVA_HOME>\\include /I<$JAVA_HOME>\\include\\win32\n</code></pre>\n\n<p>(where <code><$JAVA_HOME></code> was the name of my Java home directory).</p>\n\n<p>Then I compiled and ran the Java portion:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>% javac qsort.java\n% java -Djava.library.path=. qsort\n\nJava 23927588 C 29405966\nJava 17247793 C 29613407\nJava 16999298 C 28819718\nJava 192228697 C 371417828\nJava 193105113 C 344951184\nJava 193282387 C 344107735\n</code></pre>\n\n<p>As you can see, the C sort was slower than the Java sort, just like what you encountered.</p>\n\n<h3>Turn optimizations on</h3>\n\n<p>I instrumented the C code to print out timestamps after each line of C code and found that the <code>GetIntArrayElements()</code> and <code>ReleaseIntArrayElements()</code> were not using any time. \n All of the time was spent in <code>quicksort()</code> itself. So I was puzzled by why the C code would be slower than the Java code.</p>\n\n<p>Then I thought about turning optimizations on. I recompiled the C code with an additional <code>/O2</code> flag:</p>\n\n<pre><code>cl /LD csort.c /I<$JAVA_HOME>\\include /I<$JAVA_HOME>\\include\\win32 /O2\n</code></pre>\n\n<p>I reran the test:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>java -Djava.library.path=. qsort \n\nJava 21830161 C 12143244\nJava 16070011 C 11936736\nJava 16373243 C 13104565\nJava 186278523 C 143997203\nJava 189248011 C 144834744\nJava 193083653 C 141156471\n</code></pre>\n\n<p>Now you can see that the C code is actually about 30% faster than the Java code.</p>\n\n<h3>Modified code</h3>\n\n<p>Here is the modified code in case you want to try it yourself:</p>\n\n<h3>qsort.java</h3>\n\n<pre><code>import java.util.Arrays;\nimport java.util.Map;\nimport java.util.Random;\nimport java.util.concurrent.ThreadLocalRandom;\n\npublic class qsort {\n public native void QuicksortCPassArray(int a[]);\n\n static {\n System.loadLibrary(\"csort\");\n }\n\n public static void main(String [] args)\n {\n int n1[] = {200000, 2000000};\n int j1 = 0;\n for (j1 = 0; j1 < n1.length; j1++) {\n int counts=0;\n for (int k1=0;k1<3;k1++) {\n int i, n = n1[j1];\n long startTime, estimatedTime, estimatedTime1;\n\n int a[];\n a = new int[n];\n for (i = 0; i < n; i++) {\n a[i] = i;\n }\n\n int z, j;\n Random rnd = new Random(System.currentTimeMillis());\n for (j = n - 1; j > 0; j--) {\n z = rnd.nextInt(j + 1);\n swap(a, z, j);\n }\n\n int b[]= Arrays.copyOf(a,a.length);\n\n startTime = System.nanoTime();\n quicksort(a, 0, n - 1);\n estimatedTime = System.nanoTime() - startTime;\n System.out.print(\"Java \" + estimatedTime + ' ');\n\n startTime = System.nanoTime();\n new qsort().QuicksortCPassArray(b);\n estimatedTime1 = System.nanoTime() - startTime;\n System.out.print(\"C \" + estimatedTime1 + '\\n');\n\n }\n\n }\n }\n\n private static void quicksort(int a[], int x, int y) {\n\n int q;\n if (x < y) {\n q = partition(a, x, y);\n quicksort(a, x, q - 1);\n quicksort(a, q + 1, y);\n }\n }\n\n private static int partition(int a[], int x, int y) {\n int temp = a[y];\n int i = x - 1;\n int j;\n for (j = x; j <= y - 1; j++) {\n if (a[j] <= temp) {\n i++;\n swap(a, i, j);\n }\n }\n swap(a, i + 1, y);\n return (i + 1);\n }\n\n private static void swap(int a[], int i, int j) {\n int t = a[i];\n a[i] = a[j];\n a[j] = t;\n }\n\n private int[] shuffleArray(int a[]){\n int i;\n for (i = 0; i < a.length; i++) {\n a[i] = i;\n }\n\n int z;\n Random rnd = ThreadLocalRandom.current();\n for (int j = a.length - 1; j > 0; j--) {\n z = rnd.nextInt(j + 1);\n swap(a, z, j);\n }\n return a;\n\n }\n}\n</code></pre>\n\n<h3>csort.c</h3>\n\n<p>(only changed the name of the function)</p>\n\n<pre><code>#include <jni.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nvoid quicksort(jint *a, jint x, jint y);\n\njint partition(jint *a, jint x, jint y);\n\nvoid swap(jint *a, jint *b);\n\nJNIEXPORT void JNICALL\nJava_qsort_QuicksortCPassArray(\n JNIEnv *env,\n jobject this,\n jintArray arr) {\n\n jint *c_array = (*env)->GetIntArrayElements(env, arr, 0);\n\n jint n = (*env)->GetArrayLength(env, arr);\n\n quicksort(c_array, 0, n - 1);\n\n (*env)->ReleaseIntArrayElements(env, arr, c_array, 0);\n}\n\n\nvoid quicksort(jint *a, jint x, jint y) {\n jint q;\n if (x < y) {\n q = partition(a, x, y);\n quicksort(a, x, q - 1);\n quicksort(a, q + 1, y);\n }\n}\n\n\njint partition(jint *a, jint x, jint y) {\n jint temp = *(a + y);\n jint i = x - 1;\n jint j;\n for (j = x; j <= y - 1; j++) {\n if (*(a + j) <= temp) {\n i++;\n jint temp1 = *(a + i);\n *(a + i) = *(a + j);\n *(a + j) = temp1;\n //swap(&a[i], &a[j]);\n }\n }\n jint temp2 = *(a + i + 1);\n *(a + i + 1) = *(a + y);\n *(a + y) = temp2;\n //swap(&a[i + 1], &a[y]);\n return (i + 1);\n}\n\n\nvoid swap(jint *a, jint *b) {\n jint temp = *a;\n *a = *b;\n *b = temp;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T09:57:24.383",
"Id": "420104",
"Score": "0",
"body": "You are the real MVP! Thank you for taking the time to try to figure out the solution to my stupid problem, I appreciate it. Do you have any idea what -O2 does and it takes so little time while using O2?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T18:47:07.783",
"Id": "420151",
"Score": "1",
"body": "@Bill For the Visual C++ compiler that I used, the `/O2` flag means \"optimize for speed\". If you are building for Android, you are probably using the clang compiler, which has similar optimization options such as `-O2` and `-O3` (the higher the number the more aggressive the optimizations allowed)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T18:53:26.790",
"Id": "420152",
"Score": "1",
"body": "@Bill As for what exactly `/O2` does to make the code faster, some possibilities are: inlining functions, unrolling loops, common subexpression elimination, etc. You can [look at this article](https://en.wikipedia.org/wiki/Optimizing_compiler) if you want to learn about optimizing compilers."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T07:51:40.087",
"Id": "217185",
"ParentId": "217035",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "217185",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T20:39:44.887",
"Id": "217035",
"Score": "4",
"Tags": [
"java",
"c",
"android",
"jni"
],
"Title": "Android NDK Low performance"
} | 217035 |
<p>I have implemented mathematical functions using a C# library. I basically need to output data by the <code>RiskMatrixByFunds</code> in the following format.</p>
<p>Key will contain Id and value will contain collection of string, double, double </p>
<p>For example:</p>
<p>Id 1</p>
<p>value </p>
<pre><code>{'ArithmeticMean', 12.34, 3.44},
{'AverageGain', 12.35, 3.45},
{'AverageLoss', 12.36, 3.46},
</code></pre>
<p>I have used a Dictionary structure that will contain the int and list of tuple collection.</p>
<p>Let me know if it can be enhanced, any ideas on magic strings used, a better way to implement it.</p>
<pre><code>public class RiskMatrix : IRiskMatrix
{
public (double Monthly, double Annual) ArithmeticMean(IEnumerable<double> ReturnsList)
{
double returnList = ReturnsList.Mean();
return (Monthly: returnList, Annual: returnList * Math.Pow(12, 0.5));
}
public (double Monthly, double Annual) AverageGain(IEnumerable<double> ReturnsList)
{
double returnList = ReturnsList.GainMean();
return (Monthly: returnList, Annual: returnList * Math.Pow(12, 0.5));
}
public (double Monthly, double Annual) AverageLoss(IEnumerable<double> ReturnsList)
{
double returnList = ReturnsList.LossMean();
return (Monthly: returnList, Annual: returnList * Math.Pow(12, 0.5));
}
public Dictionary<int, List<Tuple<string,double, double>>> RiskMatrixByFunds(Dictionary<int, IEnumerable<double>> ReturnsList)
{
Dictionary<int, List<Tuple<string ,double, double>>> returnsList = new Dictionary<int, List<Tuple<string,double, double>>>();
List <Tuple<string, double, double>> list = null;
foreach (KeyValuePair<int, IEnumerable<double>> entry in ReturnsList)
{
list = new List<Tuple<string, double, double>>();
(double Monthly, double Annual) arithmeticMeanResult = ArithmeticMean(entry.Value);
list.Add(new Tuple<string, double, double>("ArithmeticMean", arithmeticMeanResult.Monthly, arithmeticMeanResult.Annual));
(double Monthly, double Annual) averageGainResult = AverageGain(entry.Value);
list.Add(new Tuple<string, double, double>("AverageGain", averageGainResult.Monthly, averageGainResult.Annual));
(double Monthly, double Annual) averageLossResult = AverageLoss(entry.Value);
list.Add(new Tuple<string, double, double>("AverageLoss", averageLossResult.Monthly, averageLossResult.Annual));
(double Monthly, double Annual) betaCorrelationresult = BetaCorrelation(entry.Value);
returnsList.Add(entry.Key, list);
}
return returnsList;
}
}
</code></pre>
| [] | [
{
"body": "<p>There might be a reason why you used a <code>List<Tuple<string ,double, double>></code>. E.g. if you need to pass the data to an existing library or your UI needs to bind to a list. Otherwise I would recommend to create a dedicated class</p>\n\n<pre><code>public class RiskStatistics\n{\n public double ArithmeticMeanMonthly { get; set; }\n public double ArithmeticMeanAnnual { get; set; }\n\n public double AverageGainMonthly { get; set; }\n public double AverageGainAnnual { get; set; }\n\n public double AverageLossMonthly { get; set; }\n public double AverageLossAnnual { get; set; }\n}\n</code></pre>\n\n<p>Since the properties are named, there's no need for magic strings. This makes the creation and usage of the risk matrix less convoluted:</p>\n\n<pre><code>public Dictionary<int, RiskStatistics> RiskMatrixByFunds(\n Dictionary<int, IEnumerable<double>> returnsLists)\n{\n var riskMatrixDict = new Dictionary<int, RiskStatistics>();\n\n foreach (KeyValuePair<int, IEnumerable<double>> entry in returnsLists) {\n var risk = new RiskStatistics();\n (risk.ArithmeticMeanMonthly, risk.ArithmeticMeanAnnual) = ArithmeticMean(entry.Value);\n (risk.AverageGainMonthly, risk.AverageGainAnnual) = AverageGain(entry.Value);\n (risk.AverageLossMonthly, risk.AverageLossAnnual) = AverageLoss(entry.Value);\n riskMatrixDict.Add(entry.Key, risk);\n }\n return riskMatrixDict;\n}\n</code></pre>\n\n<hr>\n\n<p>You could also calculate the annual values on the fly. This would make the creation even easier. Here the adapted average gain properties as an example:</p>\n\n<pre><code>private static readonly double Sqrt12 = Math.Pow(12, 0.5);\n\npublic double ArithmeticMeanMonthly { get; set; }\npublic double ArithmeticMeanAnnual => ArithmeticMeanMonthly * Sqrt12;\n</code></pre>\n\n<p>With this adapted <code>RiskStatistics</code> class, you could directly assign from the extension methods and skip the methods returning tuples.</p>\n\n<pre><code>var risk = new RiskStatistics {\n ArithmeticMeanMonthly = entry.Value.Mean(),\n AverageGainMonthly = entry.Value.GainMean(),\n AverageLossMonthly = entry.Value.LossMean()\n};\nriskMatrixDict.Add(entry.Key, risk);\n</code></pre>\n\n<p>The annual values are read-only and need not to be assigned.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T12:04:44.743",
"Id": "419860",
"Score": "0",
"body": "Good idea. Integrated it in my answer. Multiplication is fast and should have no noticeable impact on speed."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T22:00:32.407",
"Id": "217038",
"ParentId": "217036",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T21:25:53.857",
"Id": "217036",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Using Dictionary of int and list of tuple in C#"
} | 217036 |
<p>I wrote my own implementation of the linux cat command in C for my computer laboratory class. We were asked to replicate its functionality with no options passed as arguments or with just the -b, -n and -s options. </p>
<p>I'm posting the code here because, although it works fine, i feel a little bit insecure about. Firstly because i think i "over-coded" it a bit, specially on the option handling part, and also, because i'm still not very confortable working with pointers and so i am not very sure if my approach does not generate memory leaks or malfunctions. </p>
<p>Here it is: </p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#define BUF_SIZE 1024
int readStdin(int index, int bflag, int nflag){
char buffer[BUF_SIZE];
while(fgets(buffer, BUF_SIZE, stdin)){ //reads from the standard input and prints the input
if (nflag){
printf(" %d %s", index, buffer);
index++;
}
if (bflag){
if (*buffer == '\n'){
printf ("%s", buffer);
}
else{
printf (" %d %s", index, buffer);
index++;
}
}
else {
printf("%s", buffer);
}
}
return index; //returns the incremented index to perpetuate its use
}
int readFile(char* filename, FILE* fp, int index, int bflag, int nflag){
char ch;
char s[BUF_SIZE];
if (fp==NULL){ //in case the file doesn't exist
printf("%s: No such file or directory\n", filename);
exit(1);
}
if (bflag){
while ((fgets(s,BUF_SIZE,fp))){
if (strcmp(s,"\n") == 0){
printf (" %s", s);
}
else {
printf (" %d %s", index, s);
index++;
}
}
fclose(fp);
}
if (nflag){
while ((fgets(s,BUF_SIZE,fp))){
printf (" %d %s", index, s);
index++;
}
fclose(fp);
}
else{
while ((ch=fgetc(fp)) != EOF){ //printing loop
putchar(ch);
}
fclose(fp);
}
return index;
}
void readArgs(int argc, char* argv[]){
FILE* fp;
int index = 1; //line index. to be used in case -b or -n is passed as an argument
int option; //option passed as argument
int bflag = 0; //-b option deactivated by default
int nflag = 0; //-n option deactivated by default
opterr = 0; //deactivates getopt's default error messages
//checks if there are options passed as argument and updates their flags
while ((option = getopt(argc, argv, "bn")) != -1){
switch (option){
case 'b':
bflag = 1;
break;
case 'n':
nflag = 1;
break;
case '?': //in case there was some problem
exit(1);
}
}
if (bflag == 1 && nflag == 1){ //if -b and -n are passed as argument, b overrides n
nflag = 0;
}
for (int i=optind; i<argc; i++){
if (*argv[i] == '-'){ //in case of '-' in argv[i], reads from stdin and prints
index = readStdin(index, bflag, nflag);
clearerr(stdin);
}
else { //prints the contents of the file in *argv[i]
fp = fopen(argv[i], "r");
index = readFile(argv[i], fp, index, bflag, nflag);
}
}
}
int main(int argc, char* argv[]){
if (argc<2){ //if there are no arguments
readStdin(1,0,0);
return 0;
}
readArgs(argc, argv); //otherwise
return 0;
}
</code></pre>
<p>I didn't implement the -s option because i cant think of a way to handle it at the same time as the other options. That's why i think that the way i am handling the options part is a bit inefficient. </p>
<p>Any suggestions?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T23:41:30.337",
"Id": "419795",
"Score": "0",
"body": "Are you allowed to use Linux system calls like `read(2)` and `write(2)`, or are you forced to use the C standard functions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T00:01:05.677",
"Id": "419796",
"Score": "1",
"body": "@esote there are no objections to that. I might take a look into it"
}
] | [
{
"body": "<p><strong>Use Standard Constants When You Can</strong> </p>\n\n<p>The stdio.h header file contains a definition of <a href=\"https://stackoverflow.com/questions/28364085/how-to-use-read-and-write-past-bufsiz-in-c\">BUFSIZ</a>. This is a good constant to use for input and output buffers.</p>\n\n<p>In the stdlib.h header file are 2 constants that are useful when calling exit or returning from main, these are <a href=\"https://en.cppreference.com/w/c/program/EXIT_status\" rel=\"nofollow noreferrer\">EXIT_FAILURE and EXIT_SUCCESS</a>. These constants are universal, even if the underlying operating system expects different numbers for success or failure this constants will provide the correct value.</p>\n\n<p><strong>DRY Code</strong><br>\nThere is a programming principle called the <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't Repeat Yourself principle</a>. The principle is this, if you find yourself repeating code, it might be better to create a function or sub-program and call that function where the code is repeated. This reduces the amount of code in a module and makes it easier to read. What is more beneficial than the readability is the fact that you only have to write and debug that code once. Another benefit of puting repeating code into a function is that if the code needs to be changed, there is only one place to change it.\n.</p>\n\n<p>Code that repeats a lot in this program:</p>\n\n<pre><code> printf(\" %d %s\", index, buffer);\n index++;\n</code></pre>\n\n<p>While this is only one line of code, making a function out of it reduces the possibility of errors such as missing spaces or too many spaces.</p>\n\n<p>All of the output could be in their own functions:</p>\n\n<pre><code>void formattedLineOut(int *index, char buffer[])\n{\n printf(\" %d %s\", *index, buffer);\n *index++;\n}\n</code></pre>\n\n<p>The function formattedLineOut is receiving a reference to index rather than\nthe value. This way the function doesn't have to have a return value for\nindex.</p>\n\n<pre><code>void bprint(int *index, char buffer[])\n{\n if (strcmp(s, \"\\n\") == 0) {\n printf(\" %s\", s);\n }\n else {\n formattedLineOut(index, s);\n }\n}\n\nvoid outputLine(int *index, char buffer[], int nflag, int bflag)\n{\n if (nflag)\n {\n formattedLineOut(index, buffer);\n }\n else if (bflag)\n {\n bprint(index, buffer);\n }\n else\n {\n printf(\"%s\", buffer);\n }\n}\n\nint readFile(char* filename, FILE* fp, int index, int bflag, int nflag) {\n char ch;\n char s[BUF_SIZE];\n if (fp == NULL) { //in case the file doesn't exist\n printf(\"%s: No such file or directory\\n\", filename);\n exit(1);\n }\n\n while ((fgets(s, BUF_SIZE, fp))) {\n outputLine(&index, s, bflag, nflag)\n }\n\n return index;\n}\n</code></pre>\n\n<p><strong>Match fclose() With fopen()</strong> </p>\n\n<p>The function readFile has multiple calls to fclose(). This can lead to bugs,\nit might be better to call fclose() after readFile returns in the calling\nfunction. This will also allow readFile to handle stdin, since stdin is a file pointer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T14:51:52.840",
"Id": "419879",
"Score": "0",
"body": "i'm having a problem with the index pointer. it is not updating its value. how can i approach this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T15:16:50.653",
"Id": "419883",
"Score": "1",
"body": "@GuilhermeLima try (*index)++;"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T15:18:59.517",
"Id": "419885",
"Score": "0",
"body": "oh right, i forgot the parentheses. another thing, it is no longer reading from stdin if i pass just an option (or more) and nothing else after that. (for example, ./my_cat -n). how can i approach this? i'm really scratching my head"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T15:33:22.147",
"Id": "419887",
"Score": "0",
"body": "If you still need to hand in your homework I can't help you, it is beyond the scope of this website. Hand in what you had working. I also can't answer without seeing the code. Since it is broken you might want to post it on stackoverflow.com."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T00:29:53.313",
"Id": "217044",
"ParentId": "217037",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217044",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T21:49:54.540",
"Id": "217037",
"Score": "6",
"Tags": [
"c",
"file",
"homework",
"io"
],
"Title": "Linux cat command in C"
} | 217037 |
<p>For an Information System Security course I've applied to, I need to learn C and decided to start learning it yesterday.</p>
<p><a href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" rel="nofollow noreferrer">Conway's Game of Life</a> has historically been a good project to start with, so I picked it. Here's a GIF of the end result (sorry about the wobble; it's just simple console printing so the result isn't perfect. I might try using Curses next):</p>
<p><a href="https://i.stack.imgur.com/8U2hN.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8U2hN.gif" alt="Conway's GoL Sample"></a></p>
<p>I'd like comments on <strong>anything</strong>. I've never worked this low down before, so I'm likely doing some things incorrectly. I have a few main concerns though:</p>
<ul>
<li><p>Am I allocating and handling memory correctly? Do I have any undefined behavior?</p></li>
<li><p>Is there a better way of writing <code>formatWorld</code>? In Clojure, that would be like 5 lines. It ended up getting a little messy on me here though. String operations seem incredibly difficult to pull off.</p></li>
<li><p>Is my use of <code>size_t</code> appropriate here? It seems to be the type to use when dealing with data that shouldn't be allowed to be negative, but as soon as I started looking for places to use it, I realized that it seems it should be used everywhere.</p></li>
<li><p>Am I using headers properly? It seems like I should declare functions in the header that I expect the end user to use, and don't declare internal "private" functions.</p></li>
<li><p>Any stylistic/convention concerns.</p></li>
</ul>
<hr>
<h1>world.h</h1>
<pre><code>#pragma once
#include <stdbool.h>
#include <stdlib.h>
typedef struct {
bool* readCells;
bool* writeCells;
size_t width;
size_t height;
} World;
// All write operations are done to writeArray, and all read operations are read from
// read array.
// Returns a pointer to a newly allocated World with the given dimensions
World* newWorld(size_t width, size_t height);
// Gets/Sets the Cell at the given position
void setCell(World* world, size_t x, size_t y, bool isAlive);
bool getCell(World*, size_t x, size_t y);
// Returns a char array representing the World
char* formatWorld(World*);
// Helper that prints the array returned from the function
void printWorld(World*);
// Advances the world by one "tick"
void advanceWorld(World*);
</code></pre>
<h1>world.c</h1>
<pre><code>#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <windows.h> // For sleep
#include "world.h"
#define MOORE_SEARCH_DEPTH 1
#define WORLD_WIDTH 50
#define WORLD_HEIGHT 50
#define LOOP_ADVANCE_DELAY 100
// Returns a representation of a non-ragged 2D array with the given dimensions
// where all the cells are dead
bool* newDeadCells(size_t width, size_t height) {
bool* cells = malloc(sizeof(bool) * width * height);
for (size_t i = 0; i < (width * height); i++) {
cells[i] = false;
}
return cells;
}
World* newWorld(size_t width, size_t height) {
World* w = malloc(sizeof(World));
w->width = width;
w->height = height;
w->readCells = newDeadCells(width, height);
w->writeCells = newDeadCells(width, height);
return w;
}
// Randomizes the cells so that each cell has an aliveChance chance of being alive
void randomizeCells(World* world, float aliveChance) {
size_t width = world->width;
size_t height = world->height;
for (size_t i = 0; i < (width * height); i++) {
world->readCells[i] = (rand() % 100) < aliveChance * 100;
}
}
// Overwrites the readable cells with the writable cells
void copyWritableToReadable(World* world) {
memcpy(world->readCells, world->writeCells,
sizeof(bool) * world->width * world->height);
}
// Frees the given World and any memory associated with it
void freeWorld(World* world) {
free(world->readCells);
free(world->writeCells);
free(world);
}
size_t indexOf(size_t width, size_t x, size_t y) {
return width * y + x;
}
void setCell(World* world, size_t x, size_t y, bool isAlive) {
size_t index = indexOf(world->width, x, y);
world->writeCells[index] = isAlive;
}
bool getCell(World* world, size_t x, size_t y) {
int index = indexOf(world->width, x, y);
return world->readCells[index];
}
// Returns the number of live neighbors surrounding the given position.
// depth returns how many squares to look in each direction. 1 = Standard Moore Neighborhood.
size_t nAliveNeighborsSurrounding(World* world, size_t x, size_t y, size_t depth) {
size_t xBound = min(x + depth + 1, world->width);
size_t yBound = min(y + depth + 1, world->height);
size_t aliveCount = 0;
for (size_t ny = max(0, y - depth); ny < yBound; ny++) {
for (size_t nx = max(0, x - depth); nx < xBound; nx++) {
if (getCell(world, nx, ny) && !(nx == x && ny == y)) {
aliveCount++;
}
}
}
return aliveCount;
}
bool cellShouldLive(bool isAlive, size_t nNeighbors) {
return (isAlive && nNeighbors >= 2 && nNeighbors <= 3)
|| (!isAlive && nNeighbors == 3);
}
// Decides if a cell should live or die, and sets it accordingly
void advanceCellAt(World* world, size_t x, size_t y) {
size_t nNeighbors = nAliveNeighborsSurrounding(world, x, y, MOORE_SEARCH_DEPTH);
bool isAlive = getCell(world, x, y);
setCell(world, x, y, cellShouldLive(isAlive, nNeighbors));
}
void advanceWorld(World* world) {
size_t width = world->width;
size_t height = world->height;
for (size_t y = 0; y < height; y++) {
for (size_t x = 0; x < width; x++) {
advanceCellAt(world, x, y);
}
}
copyWritableToReadable(world);
}
char* formatWorld(World* world) {
size_t width = world->width;
size_t height = world->height;
size_t nCells = width * height;
// total cells needed + extra for newlines + NL term
size_t buffSize = sizeof(char) * nCells + height + 1;
char* buffer = malloc(buffSize);
buffer[buffSize - 1] = '\0';
size_t i = 0;
for (size_t y = 0; y < height; y++) {
for (size_t x = 0; x < width; x++) {
bool isAlive = getCell(world, x, y);
char rep = isAlive ? '#' : ' ';
buffer[i] = rep;
i++;
}
buffer[i] = '\n';
i++;
}
return buffer;
}
void printWorld(World* world) {
char* formatted = formatWorld(world);
printf("%s", formatted);
free(formatted);
}
void simpleConsoleRoutine() {
srand(NULL);
World* world = newWorld(WORLD_WIDTH, WORLD_HEIGHT);
randomizeCells(world, 0.3);
// Leaving it with a counter so I can limit it easily later
for (size_t i = 0; ; i++) {
printWorld(world);
printf("----------\n");
advanceWorld(world);
Sleep(LOOP_ADVANCE_DELAY);
}
// No need to free world?
}
int main() {
simpleConsoleRoutine();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T23:49:50.177",
"Id": "419930",
"Score": "0",
"body": "`windows.h` is very limiting for just `sleep`: https://en.wikipedia.org/wiki/Sleep_(system_call). I'd go with the more general POSIX, but then Windows will probably have trouble. Perhaps an `#ifdef`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T23:58:50.490",
"Id": "419931",
"Score": "0",
"body": "@Neil Ya, I wasn't able to find out a good general solution other than to do conditional `#includes`. I'm using it here purely for demo purposes, so I didn't think it would be a big deal. Ideally I wouldn't be using `Sleep` at all in a \"real program\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T02:27:10.457",
"Id": "419938",
"Score": "0",
"body": "One solution which is kind of a hack is to `#ifdef DEMO`/`#endif` around the `#include <windows.h>` and `Sleep()`; then one can define `DEMO` in your compiler settings (Windows version with the `Sleep`) or not, and it will change the code."
}
] | [
{
"body": "<p>If this is your first C program then all I can say is \"Nice\".</p>\n\n<p>I modified the structure of your program slightly to make it more conventional, I created main.c which contains int main() and simpleConsoleRoutine() and world.c which has all the other functions.</p>\n\n<p>Generally main() is going to process any command line arguments and do any setup, everything else will be in C program modules defined by a header files.</p>\n\n<p>Suggestion, all the functions that are NOT public interfaces might be better defined as <a href=\"https://stackoverflow.com/questions/558122/what-is-a-static-function\">static</a>. This reduces the name of functions in the global namespace and allows a function name to be reused in different modules as necessary.</p>\n\n<p><em>Example:</em></p>\n\n<pre><code>// Overwrites the readable cells with the writable cells\nstatic void copyWritableToReadable(World* world) {\n memcpy(world->readCells, world->writeCells,\n sizeof(bool) * world->width * world->height);\n}\n</code></pre>\n\n<p><strong>Header File Missing Function Declaration</strong> </p>\n\n<p>It would be best to add void randomizeCells(World* world, float aliveChance); to the header file, since this function is required by simpleConsoleRoutine().</p>\n\n<p><strong>Portability</strong> </p>\n\n<pre><code>#pragma once may not be in the C standard and may not be portable, use guards instead\n\n#ifndef WORLD_H\n#define WORLD_H\n\n...\n\n#endif\n</code></pre>\n\n<p><strong>Memory Allocation and De-allocation</strong> </p>\n\n<pre><code>// No need to free world?\n</code></pre>\n\n<p>In this particular instance there is no need to free world, however, if simpleConsoleRoutine() was ever called in a loop there would be a memory leak, which is generally considered a bad thing when programming in C. You might want to put <code>void freeWorld(World* world)</code> into the header file and replace this comment with a call to <code>freeWorld()</code>. In this simple case it would allow you to test and debug the code.</p>\n\n<p><strong>size_t</strong> </p>\n\n<p>The use of this type is correct in this application. For memory allocation or indexing through arrays this may be the best type to use.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T12:44:27.770",
"Id": "217069",
"ParentId": "217040",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217069",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T22:55:09.567",
"Id": "217040",
"Score": "4",
"Tags": [
"beginner",
"c",
"game-of-life",
"c99"
],
"Title": "Beginner Console Conway's Game of Life in C"
} | 217040 |
<p>I've been learning PHP and I've just gotten into using OOP. Classes/objects/methods etc. My end goal is to take an old Mad libs program I did with PHP, and convert it to OOP. The gist of the project was allowing the user to enter a verb, adverb, adjective, and noun and storing it in the DB, then displaying it on the page as a Mad lib (along with the rest of the DB). </p>
<p>I was hoping someone could review my source and let me know how to properly use the setters and getters, right now I think my code is just using POST to pass the user entered data to the method?? But if I take it out, it doesn't work anymore.</p>
<p>Basically I'm pretty lost right now and would appreciate any and all advice on how I can improve/fix this code. Right now it does work (including insertion and query of DB), but i'm not sure if I did It properly. </p>
<p>General guidelines Im following to covert to OOP (Inside Madlibs Class):</p>
<ul>
<li><p>Create instance vars for holding a noun, verb, adjective, adverb, and story</p></li>
<li><p>Create getters and setters for all instance vars</p></li>
<li><p>Create method for inserting the new instance vars into DB</p></li>
<li><p>Create method for querying the stories that returns a results set newest to oldest</p></li>
<li><p>Create a method that takes the results set (from the query) as an argument, and returns the results onto page</p></li>
</ul>
<p>Madlibs Class Code:</p>
<pre><code><?php
class MadLibs {
private $noun; // String
private $verb; // String
private $adjective; // String
private $adverb; // String
private $story; // String - entire madlib story
// Getters
public function getNoun() {
return $this->noun;
}
public function getVerb() {
return $this->verb;
}
public function getAdjective() {
return $this->adjective;
}
public function getAdverb() {
return $this->adverb;
}
public function getStory() {
return $this->story;
}
// Setters
public function setNoun($noun) {
$this->noun = $noun;
}
public function setVerb($verb) {
$this->verb = $verb;
}
public function setAdjective($adjective) {
$this->adjective = $adjective;
}
public function setAdverb($adverb) {
$this->adverb = $adverb;
}
public function setStory($story) {
$this->story = $story;
}
// method for inserting the new properties into mad libs database table
public function insertMadLibs($noun, $verb, $adjective, $adverb, $story) {
$story = "Have you seen the $adjective $noun? They got up and started to $verb $adverb!";
$dbc = mysqli_connect('localhost', 'root', '', 'project1')
or die('Error connecting to DB');
$query = "INSERT INTO Madlibs (id, noun, verb, adjective, adverb, story, dateAdded)" .
"VALUES (0, '$noun', '$verb', '$adjective', '$adverb', '$story', NOW())";
$result = mysqli_query($dbc, $query)
or die('Error querying DB');
mysqli_close($dbc);
echo '<span id="success">Success!</span>';
}
// method for querying the stories that return results set newest to oldest
public function fetchStory() {
$dbc = mysqli_connect('localhost', 'root', '', 'project1')
or die('Error connecting to DB.');
$query = "SELECT * FROM Madlibs ORDER BY dateAdded DESC";
$result = mysqli_query($dbc, $query)
or die('Error querying DB.');
mysqli_close($dbc);
return $result;
}
// method that takes the results set (from the query) as an argument, and returns the results in a formatted HTML table
public function displayStory($result) {
$dbc = mysqli_connect('localhost', 'root', '', 'project1')
or die('Error connecting to DB.');
while ($row = mysqli_fetch_array($result)) {
echo '<div id="comments"><p>Have you seen the <b>' . $row['adjective'] . ' ' . $row['noun'] . '</b>? <br />';
echo 'They got up and started to <b>' . $row['verb'] . ' ' . $row['adverb'] . '</b>! </p>';
echo '<span id="footer">Date: ' . $row['dateAdded'] . '</span></div>';
}
mysqli_close($dbc);
}
}
?>
</code></pre>
<p>index file where calls are made:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Mad libs</title>
<link rel="stylesheet" href="styles.css" type="text/css" />
</head>
<body>
<?php
require_once('MadLibs.php');
$mad_libs = new MadLibs();
$mad_libs->setNoun($_POST['noun']);
$mad_libs->setVerb($_POST['verb']);
$mad_libs->setAdjective($_POST['adjective']);
$mad_libs->setAdverb($_POST['adverb']);
// How do I remove these and still have the program function??
// Get entered info form form
$noun = $_POST['noun'];
$verb = $_POST['verb'];
$adjective = $_POST['adjective'];
$adverb = $_POST['adverb'];
if (isset($_POST['submit'])) {
if ( (!empty($noun)) && (!empty($verb)) && (!empty($adjective)) && (!empty($adverb)) ) {
$mad_libs->insertMadLibs($noun, $verb, $adjective, $adverb, $story);
} else {
echo '<span id="error">Please fill out all fields!</span>';
}
}
?>
<div id="wrapper">
<h1>Mad Libs</h1>
<hr>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="noun">Enter a <b>Noun</b>: </label>
<input type="text" name="noun" id="noun" class="input" value="<?php echo $noun; ?>"/>
<br />
<label for="verb">Enter a <b>Verb</b> (Present Tense): </label>
<input type="text" name="verb" id="verb" class="input" value="<?php echo $verb; ?>"/>
<br />
<label for="adjective">Enter an <b>Adjective</b>: </label>
<input type="text" name="adjective" id="adjective" class="input" value="<?php echo $adjective; ?>"/>
<br />
<label for="adverb">Enter an <b>Adverb</b>: </label>
<input type="text" name="adverb" id="adverb" class="input" value="<?php echo $adverb; ?>"/>
<br />
<input name="submit" id="submit" type="submit" value="Submit"/>
</form>
</div>
<?php
$result = $mad_libs->fetchStory();
$mad_libs->displayStory($result);
?>
</body>
</html>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T08:44:57.693",
"Id": "419847",
"Score": "0",
"body": "This is a good problem to start with; It is not too complicated. However, this is not how Object Oriented Programming was intended. You have not defined any objects (stories, substitutes, etc). The code cannot be used, without modification, for another story. This needs a complete rewrite. Start by imagining what the objects could be, and then add code to that. How do these objects interact? Instead of concentrating on syntax, have a look at [SOLID Principles](https://scotch.io/bar-talk/s-o-l-i-d-the-first-five-principles-of-object-oriented-design)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T10:31:47.297",
"Id": "419849",
"Score": "0",
"body": "First of all fix the SQLInjection issues.... `$query = \"INSERT INTO Madlibs (id, noun, verb, adjective, adverb, story, dateAdded)\" .\n \"VALUES (0, '$noun', '$verb', '$adjective', '$adverb', '$story', NOW())\";\n`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T14:30:49.643",
"Id": "419874",
"Score": "1",
"body": "@Alex I posted a real answer, it's imperfect, but better than just pointing to abstract principles which can be difficult to understand."
}
] | [
{
"body": "<p>You've used a single class to encapsulate virtual all the behavior of Mad Libs. Although this code is syntactically correct, it is clear you started with existing code and just poured most of it into a class. That's not the best approach.</p>\n\n<p>Your code is also extremely inflexible. It cannot be reused for any other Mad Lib story, and that would be the whole point, I think.</p>\n\n<p>So, what to do?</p>\n\n<p>First you need to analyze the domain for which you're going to write OOP code. What are the obvious elements here? There's a story with blanks which need to be substituted by user input. That gives you, right away, three object: The <code>MadLibStory</code>, the <code>MadLibBlank</code>, and <code>MadLibUserInput</code>. Let's not think any futher, that can really hurt, and just create these classes:</p>\n\n<pre><code>class MadLibStory {\n}\n\nclass MadLibBlank {\n}\n\nclass MadLibUserInput {\n}\n</code></pre>\n\n<p>Before we go on we need to think about the relations between these classes. To me the story is at the center. First a story needs to be chosen. That story requires certain substitutions. The user will supply the substitutions and the result is a funny story.</p>\n\n<p>We want to be flexible, so there will be different types of substitutions. Therefore we need a way to identify which type we are dealing with. For greatest flexibility I will use simple strings, which can also be used in the story, like this:</p>\n\n<pre><code>'Have you seen the [adjective] [noun]? They got up and started to [verb] [adverb]!'\n</code></pre>\n\n<p>This means that in a story, anything between '[' and ']' needs to be substituted with the type indicated.</p>\n\n<p>Let's now write the constructors of the classes. The constructor will, in this case, have all the needed parameters to set up the class.</p>\n\n<pre><code>class MadLibStory {\n\n private $storyText;\n private $blanks = [];\n\n public function __construct($storyText)\n {\n $this->storyText = $storyText;\n // match all blanks and remember them\n if (preg_match_all('/\\[([^\\]]*)\\]/', $this->storyText, $matches, PREG_OFFSET_CAPTURE)) {\n foreach ($matches[1] as $match) {\n $this->blanks[] = new MadLibBlank($this, $match[0], $match[1]);\n }\n }\n }\n\n public function getStoryText()\n {\n return $this->storyText;\n }\n\n}\n\nclass MadLibBlank {\n\n private $story;\n private $type;\n private $offset;\n\n public function __construct($story, $type, $offset)\n {\n $this->story = $story;\n $this->type = $type;\n $this->offset = $offset;\n }\n\n public function getStory()\n {\n return $this->story;\n }\n\n public function getType()\n {\n return $this->type;\n }\n\n public function getOffset()\n {\n return $this->offset;\n }\n\n}\n</code></pre>\n\n<p>At this point I am going to forget about user input. This is going to be simple, and I am putting user input and HTML output at the global level, just like you did. Mind you, for larger programs this is not optimal, but for now it will do. See <a href=\"https://medium.com/@noufel.gouirhate/create-your-own-mvc-framework-in-php-af7bd1f0ca19\" rel=\"nofollow noreferrer\">MVC design pattern</a>.</p>\n\n<p>We have only two classes, one which deals with the overall story, and one that deals with the blanks. These two classes are intimately linked. Inside the story class constructor we use blank objects, and the blank class constructor has a story object as a parameter. These classes know about each other.</p>\n\n<p>I did not use <a href=\"https://www.php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration\" rel=\"nofollow noreferrer\">type hinting</a>.</p>\n\n<p>I also defined the getters for the constructor parameters, they can be useful. Alternatively I could have made the fields 'public'. I prefer it this way, because it gives the class more control over the field. This is a personal choice.</p>\n\n<p>The <code>preg_match_all()</code> function, in the <code>MadLibStory</code> constructor, uses a regular expression. Personally I don't like these, because they are difficult to understand and debug. I used it here because it results in the least amount of code. For an explanation of the regular expression see: <a href=\"https://regex101.com/r/jXeChC/1\" rel=\"nofollow noreferrer\">regex101.com</a> All I can say is: It works. Sorry.</p>\n\n<p>I would now like to change what is stored in the database, to be more flexible. I will make two database tables, one for the stories and one for the user input. Like this:</p>\n\n<pre><code>CREATE TABLE `madlib_story` (\n `id` INT NOT NULL AUTO_INCREMENT,\n `story` TEXT NOT NULL,\n PRIMARY KEY (`id`)\n);\n\nCREATE TABLE `madlib_input` (\n `id` INT NOT NULL AUTO_INCREMENT,\n `story_id` INT NOT NULL,\n `type` VARCHAR(50) NOT NULL,\n `offset` INT NOT NULL,\n `substitute` TEXT NOT NULL,\n PRIMARY KEY (`id`),\n INDEX (`story_id`,`type`)\n);\n</code></pre>\n\n<p>I have chosen, in this case, not to put any prepared stories in a database table. The story table here will be used, each time the user submits substitutions for a story, to store that story and give it an unique identifier which can be used to store the substitutions. It is, of course, quite easy to store prepared stories in another database table. Note that there's a reference to the unique story identifier in the input table.</p>\n\n<p>The only thing left now is that we need to make use of these database tables. I will use mysqli, as you did, but with parameter binding. I will also complete these classes.</p>\n\n<p>The code below is placed in a file called 'madlib.inc':</p>\n\n<pre><code><?php\n\nclass MadLibStory {\n\n private $storyText;\n private $blanks = [];\n private $storyId = 0; // zero mean it is not known\n\n public function __construct($storyText)\n {\n $this->storyText = $storyText;\n // match all blanks and remember them\n if (preg_match_all('/\\[([^\\]]*)\\]/', $this->storyText, $matches, PREG_OFFSET_CAPTURE)) {\n foreach ($matches[1] as $match) {\n $this->blanks[] = new MadLibBlank($this, $match[0], $match[1]);\n }\n }\n }\n\n public function getStoryText()\n {\n return $this->storyText;\n }\n\n public function storeStory($mysqli)\n {\n $text = $this->getStoryText();\n // store story in database (no error handling!)\n $stmt = $mysqli->prepare(\"INSERT INTO madlib_story(text) VALUES (?)\");\n $stmt->bind_param('s', $text);\n $stmt->execute();\n $stmt->close();\n // and set the story id\n $this->storyId = $mysqli->insert_id;\n // return object for chaining\n return $this;\n }\n\n public function getStoryId()\n {\n return $this->storyId;\n }\n\n public function getBlanks()\n {\n return $this->blanks;\n }\n\n public function getMadness()\n {\n // put substitutions into blanks, correct for length differences\n $storyText = $this->getStoryText();\n $correction = 0;\n foreach ($this->getBlanks() as $blank) {\n $offset = $blank->getOffset() + $correction;\n $substitute = $blank->getSubstitute();\n $typeLength = strlen($blank->getType());\n $storyText = substr_replace($storyText, $substitute, $offset, $typeLength);\n $correction += strlen($substitute) - $typeLength;\n }\n return $storyText;\n }\n\n}\n\nclass MadLibBlank {\n\n private $story;\n private $type;\n private $offset;\n private $substitute = '????';\n\n public function __construct($story, $type, $offset)\n {\n $this->story = $story;\n $this->type = $type;\n $this->offset = $offset;\n }\n\n public function getStory()\n {\n return $this->story;\n }\n\n public function getType()\n {\n return $this->type;\n }\n\n public function getOffset()\n {\n return $this->offset;\n }\n\n public function setSubstitute($substitute)\n {\n $this->substitute = $substitute;\n // return object for chaining\n return $this;\n }\n\n public function storeSubstitute($mysqli)\n {\n $storyId = $this->getStory()->getStoryId();\n $type = $this->getType();\n $offset = $this->getOffset();\n $substitute = $this->getSubstitute();\n // store substitute in database (no error handling!)\n $stmt = $mysqli->prepare(\"INSERT INTO madlib_input(story_id, type, offset, text) VALUES (?,?,?,?)\");\n $stmt->bind_param('isis', $storyId, $type, $offset, $substitute);\n $stmt->execute();\n $stmt->close();\n // return object for chaining\n return $this;\n }\n\n public function getSubstitute()\n {\n return $this->substitute;\n }\n\n}\n</code></pre>\n\n<p>The only thing, apart form the database storage methods, that's new, is the <code>getMadness()</code> method. It uses an existing story, fills in the substitutions, and returns it. This returned story still has the '[' and ']' brackets in it. That's because I want to replace them with HTML tags, and it is bad practice to do that inside this class. The class should be about the Mad Lib story, not about generating HTML.</p>\n\n<p>Normally you would probably place both classes in a seperate file and use autoloading, but there's only so much we can do in this answer.</p>\n\n<p>Finally we have our main script:</p>\n\n<pre><code><?php\n\n// show errors during development (disable in production)\nini_set('display_errors', 1);\nini_set('display_startup_errors', 1);\nerror_reporting(E_ALL);\n\n// get classes \nrequire('madlib.inc');\n\n// compressed page start\necho '<!DOCTYPE html><html><body><h1>Mad Libs</h1><hr><br>';\n\n// this is the story in this example code\n$text = 'Have you seen the [adjective] [noun]? They got up and started to [verb] [adverb]!';\n$story = new MadLibStory($text);\n\nif (count($_POST) > 0) {\n // open connection to database\n $mysqli = new mysqli('127.0.0.1', 'user', 'password', 'database');\n if (mysqli_connect_errno()) die('Connect failed: '.mysqli_connect_error().PHP_EOL);\n\n // store the story\n $story->storeStory($mysqli);\n\n // get information from story object\n $storyId = $story->getStoryId();\n $blanks = $story->getBlanks();\n\n // fill in the substitutions\n foreach ($blanks as $key => $blank) {\n $substitute = filter_input(INPUT_POST, 'blank'.$key, FILTER_SANITIZE_STRING);\n $blank->setSubstitute($substitute)\n ->storeSubstitute($mysqli);\n }\n\n // show the result\n $madness = $story->getMadness();\n echo str_replace(['[', ']'], ['<b>', '</b>'], $madness);\n\n // close connection to database\n $mysqli->close();\n}\nelse {\n // use a form to get user input\n echo '<form method=\"post\">';\n $blanks = $story->getBlanks();\n foreach ($blanks as $key => $blank) {\n $id = 'blank'.$key;\n echo '<label>Enter a <b>'.ucfirst($blank->getType()).'</b>: </label>'.\n '<input name=\"'.$id.'\"><br><br>';\n }\n echo '<input type=\"submit\" value=\"Submit\">'.\n '</form>';\n}\n\n// compressed page end\necho '</body></html>';\n</code></pre>\n\n<p>And that's it, for now. I hope you can see that these two classes can easily be expanded. You might want to restructure everything a bit when you store original stories in a database table, and you want to retrieve any previously created Mad Lib stories. This code is only meant as an example, it is far from perfect. It tries to illustrate two points:</p>\n\n<ul>\n<li><p>Each class should represent one thing in your program (a story, a blank, etc) and all the methods should relate to that.</p></li>\n<li><p>Classes should be extendible, like when I added database storage. But I didn't put the story text into the story class, so I can reuse that class for another story.</p></li>\n</ul>\n\n<p>Those are the first two principle of <a href=\"https://scotch.io/bar-talk/s-o-l-i-d-the-first-five-principles-of-object-oriented-design\" rel=\"nofollow noreferrer\">SOLID</a>. The other principles are not really applicable yet to these two simple classes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T16:48:49.907",
"Id": "419894",
"Score": "1",
"body": "`This returned story still has the '[' and ']' brackets in it. That's because I want to replace them with HTML tags, and it is bad practice to do that inside this class.` - Personally I would pass them as part of the user input that replaces it in this class. That way some properties of the HTML can be exposed (Color, class, id, etc.) - That said what you have is fine as you only touched on the User Input part. Cant really rewrite the whole thing for them. (I has upvoted _(o.0)/)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T14:29:56.937",
"Id": "217078",
"ParentId": "217043",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T23:44:29.253",
"Id": "217043",
"Score": "2",
"Tags": [
"beginner",
"php",
"object-oriented",
"mysql"
],
"Title": "PHP Mad Libs with OOP and SQL"
} | 217043 |
<p>I'm trying to find <a href="https://en.wikipedia.org/wiki/Pangram" rel="nofollow noreferrer">pangrams</a> ie sentences that contain all the letters of the alphabet, for instance <em>"The quick brown fox jumps over the lazy dog"</em>.</p>
<p>I'm an absolute beginner in elisp, and it ended up being a really difficult exercice for me. My idea what to put all the letters in a <em>set</em> check if all the letters of the alphabet are in this set.</p>
<p>I don't think it was a very good idea because elisp doesn't seem to really have sets, so I ended up using a hashmap, which seems very clunky.</p>
<p>Another things that really bothers me is the two <code>if</code> in <code>is-pangram</code>. I feel that they make the function really difficult to reason about, although it's doing something very basic.</p>
<pre class="lang-lisp prettyprint-override"><code>(defun add-to-hashmap (hashmap item)
"Insert ITEM into HASHMAP and return HASHMAP."
(puthash item t hashmap)
hashmap)
(defun iter-hashmap-keys (hashmap)
"Return a sequence of the keys in HASHMAP"
(let ((keys '()))
(maphash
(lambda (key _) (setq keys (cons key keys)))
hashmap)
keys))
(defun get-letters (s)
"Return the set of letters in S.
The set is a hashmap where keys are ascii characters and values are `t`."
(setq letters (make-hash-table :test 'equal))
(seq-reduce
(lambda (hashmap letter) (add-to-hashmap hashmap (downcase letter)))
(split-string s "")
letters))
(defvar ALPHABET
(let* ((letters (get-letters "abcdefghijklmnopqrstuvwxyz"))
(_ (remhash "" letters)))
letters))
(defun is-pangram (s)
"Return `t` is S is a pangram, `nil` otherwise."
(setq letters (get-letters s))
(if (seq-some
;; this function returns returns `nil` if the given letter is
;; *present* in the set, and `t` otherwise. That way, seq-some
;; returns a non-nil value when there's a letter that is *not* in
;; the set.
(lambda (letter) (if (gethash letter letters) nil t))
(iter-hashmap-keys ALPHABET))
nil
t))
(provide 'pangram)
<span class="math-container">```</span>
</code></pre>
| [] | [
{
"body": "<pre><code>(setq letters (get-letters s))\n</code></pre>\n\n<p>You are setting the same <code>letters</code> variable from different functions; in Emacs Lisp, that sets a global variable which is bad style: (1) that pollutes the global namespace, (2) that could overwrite an existing variable, and (3) the functions are not reentrant and could lead to bad suprises with side-effects. Better introduce variables with <code>let</code>.</p>\n\n<p>Instead of doing <code>(remhash \"\" letters)</code>, you can pass T for OMIT-NULLS in <code>split-string</code>.</p>\n\n<p>Another approach is to transform the input text so as to downcase all letters, remove spaces, remove duplicate letters and check if it corresponds to the expected alphabet. For example:</p>\n\n<pre><code>(equalp (delete-duplicates\n (sort (coerce\n (downcase\n (remove ?\\s \"The quick brown fox jumps over the lazy dog\"))\n 'list)\n '<))\n (coerce \"abcdefghijklmnopqrstuvwxyz\" 'list))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T19:25:52.283",
"Id": "439137",
"Score": "0",
"body": "Generic implementations of `sort` have a running time of O(n log n). It is possible to determine if a string is a panagram in O(n) time. This is not a case where sorting is cheaper than the big-O of the core problem."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T13:01:43.807",
"Id": "220230",
"ParentId": "217046",
"Score": "4"
}
},
{
"body": "<p>At the high level bit, there's not much to complain about and a lot to like. Not so much because the code works (a necessary but non-trivial requirement for this site). But because the logic is sound (sets/hashmaps) <em>and</em> can be described and understood easily without a lot of details in the code. But I might be biased because I've written similar code to so solve somewhat similar problems in the past.</p>\n\n<h3>Code reveiew trope: performance</h3>\n\n<p>I want to be clear that I don't think performance matters much in this context. Firstly because the context is Emacs and second because it's in eLisp and third because this particular problem probably isn't all that important (even though the larger class of problems is important). If raw performance really mattered the code wouldn't be running in Emacs and even if it were we'd write it in C rather than eLisp.</p>\n\n<p>But I find there is something unsettling about the solution.</p>\n\n<h3>Aesthetics/idioms</h3>\n\n<p><a href=\"https://www.gnu.org/software/emacs/manual/html_node/elisp/Sets-And-Lists.html#Sets-And-Lists\" rel=\"nofollow noreferrer\">The eLisp way to implement sets is with lists</a>. Using lists to represent sets is idiomatic. Using hashmaps is unidiomatic. And it feels unidiomatic.</p>\n\n<p>The other issue is that hashmaps aren't idiomatic math. Sets are. Whether we use lists or hashmaps to implement the set <em>abstraction</em>, wrapping the implementation in the language of sets makes it clearer what we are doing. </p>\n\n<pre><code>;; add-to-hashmap (hashmap item) ...\n;; becomes\n\n(defun add-element-to-set (set element)\n \"Insert ELEMENT into SET and return SET.\"\n (puthash element t set)\n set)\n</code></pre>\n\n<p>layering abstractions is even more idiomatic:</p>\n\n<pre><code> (setf 'set-insert (function puthash))\n</code></pre>\n\n<p>helps the set abstraction permeate deeper into code</p>\n\n<pre><code>(defun add-element-to-set (set element)\n \"Insert ELEMENT into SET and return SET.\"\n (set-insert element t set) ;;; CHANGED\n set)\n</code></pre>\n\n<p>On the other hand, some people see this idiom as a bug not a feature.</p>\n\n<h3>About performance</h3>\n\n<p>The reason lists are idiomatic for sets (and many other things in Lisp) is because a lot of the time, lists are good enough. Checking if a string is a panagram inside of Emacs is probably one of those times. Suppose we use the procedure.</p>\n\n<pre><code>;;; PROGRAM ONE\n(defun panagram? (sentence)\n (let (s (upcase sentence))\n (and\n (string-match \"A\" s)\n (string-match \"B\" s)\n ...\n (string-match \"Z\" s))))\n</code></pre>\n\n<p>Implementation details aside, this blunt force form is O(n) time and space. Because each letter in the input matters (at least in theory) we can't get better than O(n). </p>\n\n<h3>About hashmaps</h3>\n\n<p>O(1) time for lookups and insertions makes hashmaps attractive for many implementations. But the O(1) is amortized. Inserting <code>n</code> elements into a hashmap takes O(n) time. Reading each of those <code>n</code> elements also takes O(n) time. Hashmaps are only more efficient when we make many more reads than insertions. But here we have <code>n</code> insertions into and <code>n</code> reads from the hashmap before it gets garbage collected. There's no amortization. Using hashmaps is not a performance optimization.</p>\n\n<p>But hashing is more than hashmaps. So is mapping.</p>\n\n<h2>Mapping and Hashing</h2>\n\n<p>If we had a wishing well, after we wished for more wishing wells, we might wish for a hash function that hashes our string into the boolean <code>panogram?</code>. Wait a minute, at the high level, that's what the problem is. It's just at the high level, the hash of the input string is a hashmap of characters rather than a simpler data structure that's easier to unpack. Let's be fearless and try writing our own hash function.</p>\n\n<h3>Hashing with primes</h3>\n\n<p>The first 26 primes are <code>2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101</code>. Their product is <code>1267259750580658434</code>. Pseudo-code for <code>panagram?</code></p>\n\n<pre><code>### PROGRAM TWO ###\nproduct = 1\nprimes = array[2 3 5 ...101]\nforeach character in string\n product = product * primes[downcase(character) - 97]\nreturn product modulo 1267259750580658434 == 0\n</code></pre>\n\n<p>avoids allocating the hash map, writing to it, and reading from it. Hashing at the level of the string rather than the character is generally simpler. The use of prime factors makes it a little more clever than is ideal. It requires more mental effort to understand than the blunt approach using <code>(and ...)</code> or the use of hashmaps. It might not be worth it. But it might be a step in the right direction</p>\n\n<p>PROGRAM TWO has some useful attributes: </p>\n\n<ul>\n<li>The reduction is simple. It compresses the string into an easily interpreted value.</li>\n<li>It utilizes the lexographic order inherent in the alphabet to map characters to values in an array.</li>\n<li>It reflects the boundaries of the input domain (26 characters). This is also true for PROGRAM ONE.</li>\n<li>Thinking about the characteristics of the input is a good thing. For example strings of less than 26 characters cannot be panagrams.</li>\n</ul>\n\n<h3>Simpler hashing</h3>\n\n<p>Using prime factorization is a generic approach that scales all the way out to things like Git source control and https. But like hashmaps, it feels like overkill here. There are simpler ways to record whether or not a character occurs in a string. All we need is one bit...</p>\n\n<p>...but bitwise operations are a bit low level for elisp and emacs, so maybe we simulate them.</p>\n\n<pre><code>### PROGRAM THREE ###\nbitmap = [0]\ndo 25 times\n append 0 to bitmap # array length 26 all zeros\nforeach character in string\n bitmap[downcase(character) - 97] = 1\nreturn reduce(bitmap 0 '#+) == 26\n</code></pre>\n\n<h2>Remarks</h2>\n\n<p>What makes this problem potentially interesting is that we have to start thinking about properties of the data. For example, no string less than 26 characters can possibly be a pangram. And not only do we know that most strings are not pangrams we know the most likely ways in which they are not pangrams...such as missing <code>q</code> or <code>z</code> or <code>x</code>. </p>\n\n<p>That means we might come back to PROGRAM ONE and refactor the <code>(and ...)</code> to</p>\n\n<pre><code>;;; PROGRAM FOUR ;;;\n(defun panagram? (sentence)\n (let (s (upcase sentence))\n (and\n (string-match \"Q\" s)\n (string-match \"Z\" s)\n ...\n (string-match \"E\" s)))) \n</code></pre>\n\n<p>Most ordinary sentences will be rejected by the first <code>string-match</code> and nearly all sentences would be rejected if the first regex was <code>[QZXJ]</code>. </p>\n\n<p>To put it another way, if we represent each character as one bit in a bitmap, there are 2<sup>26</sup>-1 bitmaps that are not pangrams and only one that is. Finding pangrams efficiently correlates with rejecting strings quickly.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T20:08:32.473",
"Id": "226065",
"ParentId": "217046",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "220230",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T01:13:03.357",
"Id": "217046",
"Score": "3",
"Tags": [
"beginner",
"strings",
"lisp",
"elisp"
],
"Title": "Check for pangrams in elisp"
} | 217046 |
<p><a href="https://github.com/reinderien/factorio/tree/462370a728defc4427d437be82adca3ac0e1f6c0" rel="nofollow noreferrer">This project</a> is... a little ridiculous. It's working, but it's a complete mess.</p>
<p>Data about Factorio's game economy are pulled from the wiki via the MediaWiki API, scrubbed, preprocessed, and thrown into Scipy for linear programming analysis using the MOSEK interior point method.</p>
<p>The pull script only depends on <code>requests</code>:</p>
<pre><code>#!/usr/bin/env python3
import json, lzma, re
from os.path import getsize
from requests import Session
from sys import stdout
session = Session()
def get_mediawiki(content=False, progress=None, **kwargs):
"""
https://stable.wiki.factorio.com is an instance of MediaWiki.
The API endpoint is
https://stable.wiki.factorio.com/api.php
"""
params = {'action': 'query',
'format': 'json',
**kwargs}
if content:
params.update({'prop': 'revisions',
'rvprop': 'content'})
so_far = 0
while True:
resp = session.get('https://stable.wiki.factorio.com/api.php',
params=params)
resp.raise_for_status()
doc = resp.json()
pages = doc['query']['pages'].values()
if content:
full_pages = tuple(p for p in pages if 'revisions' in p)
if progress:
so_far += len(full_pages)
progress(so_far, len(pages))
yield from full_pages
else:
yield from pages
if 'batchcomplete' in doc:
break
params.update(doc['continue'])
def get_category(name, content=False, progress=None, **kwargs):
return get_mediawiki(content=content, progress=progress,
generator='categorymembers',
gcmtitle=f'Category:{name}',
gcmtype='page',
gcmlimit=500,
**kwargs)
def get_archived_titles():
return get_category('Archived')
def get_infoboxes(progress):
return get_category('Infobox_page', content=True, progress=progress)
def get_inter_tables(titles, progress):
return get_mediawiki(content=True, progress=progress,
titles='|'.join(titles))
line_re = re.compile(r'\n\s*\|')
var_re = re.compile(
r'^\s*'
r'(\S+)'
r'\s*=\s*'
r'(.+?)'
r'\s*$')
def parse_infobox(page):
"""
Example:
{{Infobox
|map-color = 006090
|prototype-type = mining-drill
|internal-name = burner-mining-drill
|expensive-total-raw = Time, 8 + Iron plate, 30 + Stone, 10
|expensive-recipe = Time, 4 + Iron gear wheel, 6 + Iron plate, 6 + Stone furnace, 2
|category = Production
|image=Burner-Mining-Drill-Example
|health = 150
|stack-size=50
|dimensions=2×2
|energy=300 {{Translation|kW}} burner
|mining-power=2.5
|mining-speed=0.35
|mining-area=2×2
|pollution=10
|valid-fuel = Wood + Raw wood + Wooden chest + Coal + Solid fuel + Small electric pole + Rocket fuel + Nuclear fuel
|recipe = Time, 2 + Iron gear wheel, 3 + Iron plate, 3 + Stone furnace, 1
|total-raw = Time, 4 + Iron plate, 9 + Stone, 5
|producers=Manual + Assembling machine 2 + Assembling machine 3
}}<noinclude>
[[Category:Infobox page]]
</noinclude>
Splitting on newline isn't a great idea, because
https://www.mediawiki.org/wiki/Help:Templates#Named_parameters
shows that only the pipe is mandatory as a separator. However, only
splitting on pipe is worse, because there are pipes on the inside of links.
"""
content = page['revisions'][0]['*']
entries = (
var_re.match(e)
for e in line_re.split(
content.split('{{', maxsplit=1)[1]
.rsplit('}}', maxsplit=1)[0]
)
)
title = page['title'].split(':', maxsplit=1)[1]
d = {'pageid': page['pageid'],
'title': title}
d.update(dict(e.groups() for e in entries if e))
return d
part_tok = r'\s*([^|{}]*?)'
border_tok = r'\s*\|'
row_image_re = re.compile(
r'\{\{\s*'
r'(?P<type>\w+)'
f'{border_tok}'
f'{part_tok}'
r'(?:'
f'{border_tok}'
f'{part_tok}'
r')?'
r'(?:'
f'{border_tok}'
r'[^{}]*'
r')?'
r'\}\}\s*'
r'(?P<sep>'
r'(?:'
r'\|\||\+|→'
r')?'
r')',
)
def iter_cells(row):
"""
e.g.
| {{Icon|Solid fuel from light oil||}}
|| {{icon|Light oil|10}} + {{icon|time|3}}
|| {{icon|Solid fuel|1}}
or
| {{Imagelink|Oil refinery}}
|| {{Imagelink|Basic oil processing}}
|| {{Icon|Crude oil|100}} + {{icon|Time|5}}
→ {{Icon|Heavy oil|30}} + ({{Icon|Light oil|30}} {{Icon|Petroleum gas|40}})
"""
cell = []
for m in row_image_re.finditer(row):
if m.group('sep') == '||':
cell.append(m.groups()[:-1])
yield cell
cell = []
else:
cell.append(m.groups())
if cell:
yield cell
def parse_inter_table(page):
"""
Example:
{| class="wikitable"
! Building !! Process !! Results
|-
| {{Imagelink|Oil refinery}} || {{Imagelink|Basic oil processing}} || {{Icon|Crude oil|100}} + {{icon|Time|5}} → {{Icon|Heavy oil|30}} + ({{Icon|Light oil|30}} {{Icon|Petroleum gas|40}})
|-
| {{Imagelink|Oil refinery}} || {{Imagelink|Advanced oil processing}} || {{Icon|Crude oil|100}} + {{icon|Water|50}} + {{icon|Time|5}} → {{Icon|Heavy oil|10}} + ({{Icon|Light oil|45}} {{Icon|Petroleum gas|55}})
|-
| {{Imagelink|Oil refinery}} || {{imagelink|Coal liquefaction}} || {{icon|Coal|10}} + {{Icon|Heavy oil|25}} + {{icon|Steam|50}} + {{icon|Time|5}} → {{Icon|Heavy oil|35}} + ({{Icon|Light oil|15}} + {{Icon|Petroleum gas|20}})
|}
or
{| class="wikitable"
! Process !! Input !! Output
|-
| {{Icon|Solid fuel from heavy oil||}} || {{icon|Heavy oil|20}} + {{icon|time|3}} || {{icon|Solid fuel|1}}
|-
| {{Icon|Solid fuel from light oil||}} || {{icon|Light oil|10}} + {{icon|time|3}} || {{icon|Solid fuel|1}}
|-
| {{Icon|Solid fuel from petroleum gas||}} || {{icon|Petroleum gas|20}} + {{icon|time|3}} || {{icon|Solid fuel|1}}
|-
|}
"""
title = page['title']
content = page['revisions'][0]['*']
if '{|' not in content:
return title, {}
rows = []
body = (content
.replace('\n', '')
.split('{|', maxsplit=1)[1]
.rsplit('|}', maxsplit=1)[0])
row_strings = body.split('|-')
heads = tuple(h.strip().lower() for h in row_strings[0]
.split('!', maxsplit=1)[1]
.split('!!'))
for line in row_strings[1:]:
inputs = {}
outputs = {}
row = {'inputs': inputs, 'outputs': outputs}
for head, parts in zip(heads, iter_cells(line)):
if head in ('process', 'building'):
row[head.lower()] = parts[0][1]
continue
elif head not in ('input', 'output', 'results'):
if head == '':
return title, {} # Space science pack edge case
raise ValueError(f'Unrecognized head {head}')
if 'input' in head:
side = inputs
elif 'output' in head:
side = outputs
else:
side = inputs
if 'results' not in head:
raise ValueError(f'Unexpected heading {head}')
for part in parts:
res_type = part[0].lower()
if res_type != 'icon':
raise ValueError(f'Unexpected resource type {res_type}')
side[part[1]] = int(part[2])
if 'results' in head and len(part) == 4 and part[-1] == '→':
side = outputs
if inputs or outputs:
rows.append(row)
return title, {'recipes': rows}
def inter_needed(items):
return (i['title'] for i in items if
not i['archived']
and i.get('category') == 'Intermediate products'
and not ('cost' in i or 'recipe' in i))
def save(fn, recipes):
with lzma.open(fn, 'wt') as f:
json.dump(recipes, f, indent=4)
def main():
def progress(so_far, total):
print(f'{so_far}/{total} {so_far/total:.0%}', end='\r')
stdout.flush()
print('Getting archived items... ', end='')
archived_titles = {p['title'] for p in get_archived_titles()}
print(len(archived_titles))
print('Getting item content...')
items = tuple(parse_infobox(p) for p in get_infoboxes(progress))
items_by_name = {i['title']: i for i in items}
for item in items:
item['archived'] = item['title'] in archived_titles
print('\nFilling in intermediate products...')
inter_tables = get_inter_tables(inter_needed(items), progress)
used = 0
for table_page in inter_tables:
try:
title, recipes = parse_inter_table(table_page)
if recipes:
used += 1
items_by_name[title].update(recipes)
except Exception as e:
print(f'\nWarning: {table_page["title"]} failed to parse - {e}')
print(f'\n{used} intermediate tables used.')
fn = 'items.json.xz'
print(f'Saving to {fn}... ', end='')
save(fn, items_by_name)
print(f'{getsize(fn)//1024} kiB')
if __name__ == '__main__':
main()
</code></pre>
<p>You need to run it before any of the next steps. After the data are pulled, run the preprocessing script:</p>
<pre><code>#!/usr/bin/env python3
import json, lzma, re
import numpy as np
from collections import defaultdict
from os.path import getsize
from scipy.sparse import lil_matrix, save_npz
from sys import stdout
from typing import Dict, Iterable, Set, Sequence
power_re = re.compile(r'([0-9.]+) .*([kMG])[WJ]')
si_facs = {
c: 10**(3*i) for i, c in enumerate(('', 'k', 'M', 'G'))
}
class Item:
def __init__(self, data: dict):
self.data = data
(
self.archived,
self.cost,
self.cost_multiplier,
self.crafting_speed,
self.dimensions,
self.energy,
self.fluid_consumption,
self.fuel_value,
self.mining_hardness,
self.mining_power,
self.mining_speed,
self.mining_time,
self.pollution,
self.power_output,
self.producers,
self.prototype_type,
self.recipe,
self.recipes,
self.title,
self.valid_fuel
) = (None,)*20
self.__dict__.update({k.replace('-', '_'): v
for k, v in data.items()})
self.fill_gaps()
def fill_gaps(self):
if self.prototype_type == 'technology':
self.producers = 'Lab'
elif self.title in ('Flamethrower turret', 'Gun turret',
'Laser turret'):
self.producers = 'Assembling machine + manual'
elif self.title == 'Space science pack':
self.recipe = 'Time, 41.25 + Rocket part, 100 = ' \
'Space science pack, 1000'
elif self.title == 'Steam':
ex_rate = 10e6 * 60 / 5.82e6
self.recipes = (
{
'process': 'Steam165 (Boiler)',
'building': 'Boiler',
'inputs': {
'Water': 60,
'Time': 1
},
'outputs': {
'Steam165': 60
}
},
{
'process': 'Steam500 (Heat exchanger)',
'building': 'Heat exchanger',
'inputs': {
'Water': ex_rate,
'Time': 1
},
'outputs': {
'Steam500': ex_rate
}
}
)
def __str__(self) -> str:
return self.title
@property
def keep(self) -> bool:
return (
(not self.archived) and
(self.title not in {'Rock', 'Tree'}) and
(
any(self.data.get(k) for k in ('cost', 'recipe', 'recipes'))
or 'mining-hardness' in self.data
or self.title in {'Crude oil',
'Water',
'Space science pack',
'Steam'}
)
)
def get_recipes(self) -> Iterable:
if self.recipes:
for rates in self.recipes:
fac = RecipeFactory(self, rates=rates)
yield from fac.make()
else:
fac = RecipeFactory(self)
yield from fac.make()
def mine_rate(self, mining_hardness: float, mining_time: float) -> float:
return (
(float(self.mining_power) - mining_hardness)
* float(self.mining_speed) / mining_time
)
all_items: Dict[str, Item] = None
class ManualMiner:
def __init__(self, tool: Item):
self.tool = tool
self.title = f'Manual with {tool}'
self.pollution = 0
self.dimensions = '0×0'
def __str__(self) -> str:
return self.title
def mine_rate(self, mining_hardness: float, mining_time: float) -> float:
return (
0.6 * (float(self.tool.mining_power) - mining_hardness)
/ mining_time
)
class Recipe:
def __init__(self, resource: str, producer: Item, rates: dict,
title: str = None):
self.resource = resource
if title:
self.title = title
else:
self.title = f'{resource} ({producer})'
self.rates = dict(rates)
self.producer = producer
self.multiply_producer(producer)
def __str__(self) -> str:
return self.title
def multiply_producer(self, prod: Item):
if prod.title in {'Boiler', 'Heat exchanger', 'Solar panel',
'Steam engine', 'Steam turbine'}:
pass # no crafting rate modifier
elif prod.title == 'Nuclear reactor':
self.rates['Heat'] = parse_power(prod.energy)
else:
rate = float(prod.crafting_speed)
for k in self.rates:
self.rates[k] *= rate
class MiningRecipe(Recipe):
def __init__(self, resource: str, producer: Item, rates: dict,
mining_hardness: float, mining_time: float, title: str = ''):
self.mining_hardness, self.mining_time = mining_hardness, mining_time
super().__init__(resource, producer, rates, title)
def multiply_producer(self, miner: Item):
self.rates[self.resource] = self.producer.mine_rate(
self.mining_hardness, self.mining_time
)
if self.resource == 'Uranium ore':
self.rates['Sulphuric acid'] = -self.rates[self.resource]
class TechRecipe(Recipe):
def __init__(self, resource: str, producer: Item, rates: dict,
cost_multiplier: float, title: str = ''):
self.cost_multiplier = cost_multiplier
super().__init__(resource, producer, rates, title)
def multiply_producer(self, lab: Item):
self.rates[self.resource] /= self.cost_multiplier
class FluidRecipe(Recipe):
# Pumpjacks, offshore pumps
def multiply_producer(self, producer: Item):
if producer.title == 'Pumpjack':
yield_factor = 1.00 # Assumed
rate = 10*yield_factor
elif producer.title == 'Offshore pump':
rate = 1200
else:
raise NotImplementedError()
self.rates[self.resource] = rate
class RecipeFactory:
def __init__(self, resource: Item, rates: dict = None):
self.resource = resource
self.producers = ()
if rates:
self.producers, self.title, self.rates = self.intermediate(rates)
else:
self.title = None
needs_producers = False
recipe = resource.recipe or resource.cost
if recipe:
self.rates = self.parse_recipe(recipe)
if resource.prototype_type == 'technology':
self.producers = (all_items['lab'],)
else:
needs_producers = True
else:
if resource.mining_time or \
resource.title in {'Crude oil', 'Water'}:
self.rates = {}
if resource.title != 'Raw wood':
needs_producers = True
else:
raise NotImplementedError()
if needs_producers:
self.producers = tuple(parse_producers(resource.producers))
def __str__(self) -> str:
return self.title
def intermediate(self, rates) -> (Iterable[Item], str, dict):
building = rates.get('building')
if building:
producers = (all_items[building.lower()],)
else:
producers = parse_producers(self.resource.producers)
title = rates['process']
sane_rates = self.calc_recipe(rates['inputs'], rates['outputs'])
return producers, title, sane_rates
@staticmethod
def parse_side(s: str) -> Dict[str, float]:
out = {}
for pair in s.split('+'):
k, v = pair.split(',')
out[k.strip()] = float(v.strip())
return out
@staticmethod
def calc_recipe(inputs: Dict[str, float],
outputs: Dict[str, float]) -> Dict[str, float]:
rates = defaultdict(float, outputs)
if 'time' in inputs:
k = 'time'
else:
k = 'Time'
t = inputs.pop(k)
for k in rates:
rates[k] /= t
for k, v in inputs.items():
rates[k] -= v / t
return rates
def parse_recipe(self, recipe: str) -> Dict[str, float]:
if '=' in recipe:
inputs, outputs = recipe.split('=')
outputs = self.parse_side(outputs)
else:
inputs = recipe
outputs = {self.resource.title: 1}
return self.calc_recipe(self.parse_side(inputs), outputs)
def produce(self, cls, producer, **kwargs):
kwargs.setdefault('title', self.title)
recipe = cls(self.resource.title, producer, self.rates, **kwargs)
if producer.pollution:
recipe.rates['Pollution'] = float(producer.pollution)
dims = tuple(float(x) for x in producer.dimensions.split('×'))
recipe.rates['Area'] = dims[0] * dims[1]
return recipe
def for_energy(self, cls, **kwargs) -> Iterable[Recipe]:
for producer in self.producers:
energy = -parse_power(producer.energy)
if 'electric' in producer.energy:
recipe = self.produce(cls, producer, **kwargs)
recipe.rates['Energy'] = energy
yield recipe
elif 'heat' in producer.energy:
recipe = self.produce(cls, producer, **kwargs)
recipe.rates['Heat'] = energy
yield recipe
elif 'burner' in producer.energy:
for fuel_name in producer.valid_fuel.split('+'):
fuel_name = fuel_name.strip().lower()
fuel = all_items[fuel_name]
fuel_value = parse_power(fuel.fuel_value)
new_kwargs = dict(kwargs)
if self.title:
title = self.title
else:
title = f'{self.resource} ({producer})'
new_kwargs['title'] = f'{title} fueled by {fuel_name}'
recipe = self.produce(cls, producer, **new_kwargs)
recipe.rates[fuel.title] = energy / fuel_value
yield recipe
else:
raise NotImplementedError()
tree_re = re.compile(r'(\d+) .*?\|([^}|]+)\}')
def wood_mining(self) -> Iterable[MiningRecipe]:
miners = tuple(
ManualMiner(tool)
for tool in all_items.values()
if tool.prototype_type == 'mining-tool'
)
for m in self.tree_re.finditer(self.resource.mining_time):
mining_time, source = int(m[1]), m[2]
for miner in miners:
yield self.produce(
MiningRecipe, miner,
mining_hardness=float(self.resource.mining_hardness),
mining_time=mining_time,
title=f'{self.resource} ({miner} from {source})')
def make(self) -> Iterable[Recipe]:
if self.rates:
if self.resource.prototype_type == 'technology':
yield self.produce(
TechRecipe, self.producers[0],
cost_multiplier=float(self.resource.cost_multiplier))
elif self.resource.title == 'Energy':
yield self.produce(Recipe, self.producers[0])
else:
yield from self.for_energy(Recipe)
elif self.resource.title == 'Raw wood':
yield from self.wood_mining()
elif self.resource.mining_time:
yield from self.for_energy(
MiningRecipe,
mining_hardness=float(self.resource.mining_hardness),
mining_time=float(self.resource.mining_time))
elif self.resource.title == 'Crude oil':
yield from self.for_energy(FluidRecipe)
elif self.resource.title == 'Water':
yield self.produce(FluidRecipe, self.producers[0])
else:
raise NotImplementedError()
def parse_power(s: str) -> float:
m = power_re.search(s)
return float(m[1]) * si_facs[m[2]]
def items_of_type(t: str) -> Iterable[Item]:
return (i for i in all_items.values()
if i.prototype_type == t)
barrel_re = re.compile(r'empty .+ barrel')
def parse_producers(s: str) -> Iterable[Item]:
for p in s.split('+'):
p = p.strip().lower()
if p == 'furnace':
yield from items_of_type('furnace')
elif p == 'assembling machine':
yield from (all_items[f'assembling machine {i}']
for i in range(1, 4))
elif p == 'mining drill':
yield from (all_items[f'{t} mining drill']
for t in ('burner', 'electric'))
elif p == 'manual' or barrel_re.match(p):
continue
else:
yield all_items[p]
def trim(items: dict):
to_delete = tuple(k for k, v in items.items() if not v.keep)
print(f'Dropping {len(to_delete)} items...')
for k in to_delete:
del items[k]
def energy_data() -> dict:
solar_ave = parse_power(next(
s for s in all_items['solar panel'].power_output.split('<br/>')
if 'average' in s))
eng = all_items['steam engine']
eng_rate = float(eng.fluid_consumption
.split('/')[0])
eng_power = parse_power(eng.power_output)
turbine = all_items['steam turbine']
turbine_rate = float(turbine.fluid_consumption
.split('/')[0])
turbine_power_500 = 5.82e6 # ignore non-precise data and use this instead
turbine_power_165 = 1.8e6 # from wiki page body
return {
'title': 'Energy',
'recipes': (
{
'building': 'Solar panel',
'process': 'Energy (Solar panel)',
'inputs': {
'Time': 1
},
'outputs': {
'Energy': solar_ave
}
},
{
'building': 'Steam engine',
'process': 'Energy (Steam engine)',
'inputs': {
'Time': 1,
'Steam165': eng_rate
},
'outputs': {
'Energy': eng_power
}
},
{
'building': 'Steam turbine',
'process': 'Energy (Steam turbine @ 165C)',
'inputs': {
'Time': 1,
'Steam165': turbine_rate
},
'outputs': {
'Energy': turbine_power_165
}
},
{
'building': 'Steam turbine',
'process': 'Energy (Steam turbine @ 500C)',
'inputs': {
'Time': 1,
'Steam500': turbine_rate
},
'outputs': {
'Energy': turbine_power_500
}
}
)
}
def load(fn: str):
with lzma.open(fn) as f:
global all_items
all_items = {k.lower(): Item(d) for k, d in json.load(f).items()}
all_items['energy'] = Item(energy_data())
def get_recipes() -> (Dict[str, Recipe], Set[str]):
recipes = {}
resources = set()
for item in all_items.values():
item_recipes = tuple(item.get_recipes())
recipes.update({i.title: i for i in item_recipes})
for recipe in item_recipes:
resources.update(recipe.rates.keys())
return recipes, resources
def field_size(names: Iterable) -> int:
return max(len(str(o)) for o in names)
def write_csv_for_r(recipes: Sequence[Recipe], resources: Sequence[str],
fn: str):
# Recipes going down, resources going right
rec_width = field_size(recipes)
float_width = 15
col_format = f'{{:{float_width+8}}}'
rec_format = '\n{:' + str(rec_width+1) + '}'
with lzma.open(fn, 'wt') as f:
f.write(' '*(rec_width+1))
for res in resources:
f.write(col_format.format(f'{res},'))
for rec in recipes:
f.write(rec_format.format(f'{rec},'))
for res in resources:
x = rec.rates.get(res, 0)
col_format = f'{{:+{len(res)}.{float_width}e}},'
f.write(col_format.format(x))
def write_for_numpy(recipes: Sequence[Recipe], resources: Sequence[str],
meta_fn: str, npz_fn: str):
rec_names = [r.title for r in recipes]
w_rec = max(len(r) for r in rec_names)
recipe_names = np.array(rec_names, copy=False, dtype=f'U{w_rec}')
w_res = max(len(r) for r in resources)
resource_names = np.array(resources, copy=False, dtype=f'U{w_res}')
np.savez_compressed(meta_fn, recipe_names=recipe_names, resource_names=resource_names)
rec_mat = lil_matrix((len(resources), len(recipes)))
for j, rec in enumerate(recipes):
for res, q in rec.rates.items():
i = resources.index(res)
rec_mat[i, j] = q
save_npz(npz_fn, rec_mat.tocsr())
def file_banner(fn):
print(f'{fn} {getsize(fn)//1024} kiB')
def main():
fn = 'items.json.xz'
print(f'Loading {fn}... ', end='')
load(fn)
print(f'{len(all_items)} items')
trim(all_items)
print('Calculating recipes... ', end='')
recipes, resources = get_recipes()
print(f'{len(recipes)} recipes, {len(resources)} resources')
resources = sorted(resources)
recipes = sorted(recipes.values(), key=lambda i: i.title)
print('Saving files for numpy...')
meta_fn, npz_fn = 'recipe-names.npz', 'recipes.npz'
write_for_numpy(recipes, resources, meta_fn, npz_fn)
file_banner(meta_fn)
file_banner(npz_fn)
fn = 'recipes.csv.xz'
print(f'Saving recipes for use by R...')
stdout.flush()
write_csv_for_r(recipes, resources, fn)
file_banner(fn)
if __name__ == '__main__':
main()
</code></pre>
<p>That's followed by an analysis script that I won't post here, to constrain the scope of this first review.</p>
<p><code>items.json.xz</code> is somewhat large; an excerpt is:</p>
<pre class="lang-none prettyprint-override"><code>{
"Advanced circuit": {
"pageid": 38306,
"title": "Advanced circuit",
"prototype-type": "item",
"internal-name": "advanced-circuit",
"expensive-total-raw": "Time, 14 + Copper plate, 14 + Iron plate, 4 + Plastic bar, 4",
"expensive-recipe": "Time, 6 + Copper cable, 8 + Electronic circuit, 2 + Plastic bar, 4",
"category": "Intermediate products",
"stack-size": "200",
"recipe": "Time, 6 + Copper cable, 4 + Electronic circuit, 2 + Plastic bar, 2",
"total-raw": "Time, 9.5 + Copper plate, 5 + Iron plate, 2 + Plastic bar, 2",
"required-technologies": "Advanced electronics",
"producers": "Manual + Assembling machine 2+Assembling machine 3",
"consumers": "Artillery turret + Artillery wagon + Beacon + Centrifuge + Distractor capsule + Efficiency module + Efficiency module 2 + Efficiency module 3 + Electric furnace + Energy shield + Express splitter + Active provider chest + Buffer chest + Passive provider chest + Requester chest + Storage chest + Logistic robot + Modular armor + Nightvision + Nuclear reactor + Personal roboport + Processing unit + Productivity module + Productivity module 2 + Productivity module 3 + Roboport + Science pack 3 + Portable solar panel + Speed module + Speed module 2 + Speed module 3 + Stack inserter + Substation + Tank",
"archived": false
},
"Advanced oil processing (research)": {
"pageid": 38335,
"title": "Advanced oil processing (research)",
"prototype-type": "technology",
"internal-name": "advanced-oil-processing",
"allows": "Coal liquefaction",
"expensive-cost-multiplier": "300",
"category": "Technology",
"cost": "Time, 30 + Science pack 1, 1 + Science pack 2, 1 + Science pack 3, 1",
"cost-multiplier": "75",
"required-technologies": "Oil processing",
"effects": "Advanced oil processing + Heavy oil cracking + Light oil cracking",
"archived": false
},
</code></pre>
<p>It's just as easy for you to generate it yourself. Similarly, here is an excerpt of <code>recipes.csv.xz</code>:</p>
<pre class="lang-none prettyprint-override"><code> Accumulator, Active provider chest, Advanced circuit, Advanced electronics (research),Advanced electronics 2 (research),Advanced material processing (research),Advanced material processing 2 (research),Advanced oil processing (research),Area, Arithmetic combinator, Artillery (research), Artillery shell, Artillery shell range (research),Artillery shell shooting speed (research),Artillery targeting remote,Artillery turret, Artillery wagon, Assembling machine 1, Assembling machine 2, Assembling machine 3, Atomic bomb, Atomic bomb (research),Auto character logistic trash slots (research),Automated rail transportation (research),Automation (research), Automation 2 (research),Automation 3 (research),Automobilism (research),Battery, Battery (research), Battery MK1, Battery MK2 equipment (research),Battery equipment (research),Beacon, Big electric pole, Boiler, Braking force (research),Buffer chest, Bullet damage (research),Bullet shooting speed (research),Burner inserter, Burner mining drill, Cannon shell, Cannon shell damage (research),Cannon shell shooting speed (research),Car, Cargo wagon, Centrifuge, Character logistic slots (research),Character logistic trash slots (research),Chemical plant, Circuit network (research),Cliff explosives, Cliff explosives (research),Cluster grenade, Coal, Coal liquefaction (research),Combat robot damage (research),Combat robotics (research),Combat robotics 2 (research),Combat robotics 3 (research),Combat shotgun, Concrete, Concrete (research), Constant combinator, Construction robot, Construction robotics (research),Copper cable, Copper ore, Copper plate, Crude oil, Decider combinator, Defender capsule, Destroyer capsule, Discharge defense, Discharge defense (research),Discharge defense remote,Distractor capsule, Effect transmission (research),Efficiency module, Efficiency module (research),Efficiency module 2, Efficiency module 2 (research),Efficiency module 3, Efficiency module 3 (research),Electric energy accumulators (research),Electric energy distribution 1 (research),Electric energy distribution 2 (research),Electric engine (research),Electric engine unit, Electric furnace, Electric mining drill, Electronic circuit, Electronics (research),Empty barrel, Energy, Energy shield, Energy shield MK2, Energy shield MK2 equipment (research),Energy shield equipment (research),Engine (research), Engine unit, Exoskeleton, Exoskeleton equipment (research),Explosive cannon shell,Explosive rocket, Explosive rocketry (research),Explosive uranium cannon shell,Explosives, Explosives (research), Express splitter, Express transport belt,Express underground belt,Fast inserter, Fast splitter, Fast transport belt, Fast underground belt, Filter inserter, Firearm magazine, Flamethrower, Flamethrower (research),Flamethrower ammo, Flamethrower damage (research),Flamethrower turret, Flammables (research), Flight (research), Fluid handling (research),Fluid wagon, Fluid wagon (research),Flying robot frame, Follower robot count (research),Gate, Gates (research), Green wire, Grenade, Grenade damage (research),Gun turret, Gun turret damage (research),Hazard concrete, Heat, Heat exchanger, Heat pipe, Heavy armor, Heavy armor (research),Heavy oil, High tech science pack,Inserter, Inserter capacity bonus (research),Iron axe, Iron chest, Iron gear wheel, Iron ore, Iron plate, Iron stick, Kovarex enrichment process (research),Lab, Lab research speed (research),Lamp, Land mine, Landfill, Landfill (research), Landmines (research), Laser (research), Laser turret, Laser turret damage (research),Laser turret shooting speed (research),Laser turrets (research),Light armor, Light oil, Locomotive, Logistic robot, Logistic robotics (research),Logistic system (research),Logistics (research), Logistics 2 (research),Logistics 3 (research),Long handed inserter, Low density structure, Lubricant, Medium electric pole, Military (research), Military 2 (research), Military 3 (research), Military 4 (research), Military science pack, Mining productivity (research),Modular armor, Modular armor (research),Modules (research), Nightvision, Nightvision equipment (research),Nuclear fuel, Nuclear fuel reprocessing (research),Nuclear power (research),Nuclear reactor, Offshore pump, Oil processing (research),Oil refinery, Optics (research), Passive provider chest,Personal battery, Personal battery MK2, Personal laser defense,Personal laser defense (research),Personal roboport, Personal roboport (research),Personal roboport 2 (research),Personal roboport MK2, Petroleum gas, Piercing rounds magazine,Piercing shotgun shells,Pipe, Pipe to ground, Pistol, Plastic bar, Plastics (research), Poison capsule, Pollution, Portable fusion reactor,Portable fusion reactor (research),Portable solar panel, Portable solar panel (research),Power armor, Power armor (research),Power armor 2 (research),Power armor MK2, Power switch, Processing unit, Production science pack,Productivity module, Productivity module (research),Productivity module 2, Productivity module 2 (research),Productivity module 3, Productivity module 3 (research),Programmable speaker, Pump, Pumpjack, Radar, Rail, Rail chain signal, Rail signal, Rail signals (research),Railway (research), Raw wood, Red wire, Refined concrete, Refined hazard concrete,Repair pack, Requester chest, Roboport, Robotics (research), Rocket, Rocket control unit, Rocket damage (research),Rocket fuel, Rocket launcher, Rocket part, Rocket shooting speed (research),Rocket silo, Rocket silo (research),Rocketry (research), Satellite, Science pack 1, Science pack 2, Science pack 3, Shotgun, Shotgun shell damage (research),Shotgun shell shooting speed (research),Shotgun shells, Slowdown capsule, Small electric pole, Solar energy (research),Solar panel, Solid fuel, Space science pack, Speed module, Speed module (research),Speed module 2, Speed module 2 (research),Speed module 3, Speed module 3 (research),Splitter, Stack filter inserter, Stack inserter, Stack inserter (research),Steam, Steam engine, Steam turbine, Steam165, Steam500, Steel axe, Steel chest, Steel furnace, Steel plate, Steel processing (research),Stone, Stone brick, Stone furnace, Stone wall, Stone walls (research),Storage chest, Storage tank, Submachine gun, Substation, Sulfur, Sulfur processing (research),Sulfuric acid, Sulphuric acid, Tank, Tanks (research), Toolbelt (research), Train stop, Transport belt, Turrets (research), Underground belt, Uranium ammo (research),Uranium cannon shell, Uranium fuel cell, Uranium ore, Uranium rounds magazine,Uranium-235, Uranium-238, Used up uranium fuel cell,Water, Wood, Wooden chest, Worker robot cargo size (research),Worker robot speed (research),
Accumulator (Assembling machine 1), +5.000000000000000e-02,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+9.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,-2.500000000000000e-01,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,-9.000000000000000e+04,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,-1.000000000000000e-01,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+3.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,
Accumulator (Assembling machine 2), +7.500000000000001e-02,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+9.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,-3.750000000000000e-01,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,-1.500000000000000e+05,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,-1.500000000000000e-01,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+2.400000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00,+0.000000000000000e+00, +0.000000000000000e+00, +0.000000000000000e+00,
</code></pre>
<p>The main thing that needs work is the recipe factory code. It sprinkles logic about item types where it doesn't belong, and that really needs to be improved. I have some ideas about how to do that, but I'd like to hear from the community (on that, and any other wrinkles you find).</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T13:08:57.137",
"Id": "419868",
"Score": "4",
"body": "All the data is in machine readable lua files - even version-tagged in the official repository: https://github.com/wube/factorio-data. There's also existing python tooling to read the lua https://github.com/jcranmer/factorio-tools (not sure what state that it is in)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T15:03:57.983",
"Id": "419882",
"Score": "0",
"body": "Could you provide an example of what the output of this looks like?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T19:26:04.423",
"Id": "419907",
"Score": "0",
"body": "@SimonForsberg Added, though it's more helpful to just run the scripts and get the full output."
}
] | [
{
"body": "<ul>\n<li><p>You can simplify your 'verbose' multi-line regexes by using the <a href=\"https://docs.python.org/3/library/re.html#re.X\" rel=\"noreferrer\"><code>re.X</code> flag</a>.</p>\n\n\n\n<pre><code>var_re = re.compile(r'''\n ^\\s*\n (\\S+)\n \\s*=\\s*\n (.+?)\n \\s*$\n''', re.X)\n</code></pre></li>\n<li><blockquote>\n <p>The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation. - <a href=\"https://www.python.org/dev/peps/pep-0008/#maximum-line-length\" rel=\"noreferrer\">PEP 8</a></p>\n</blockquote>\n\n\n\n<pre><code>if (resource.mining_time\n or resource.title in {'Crude oil', 'Water'}):\n ...\n</code></pre>\n\n<p>Whilst it goes against the style in your code, I prefer the following:</p>\n\n<pre><code>if (resource.mining_time\n or resource.title in {'Crude oil', 'Water'}\n):\n ...\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T02:56:27.087",
"Id": "217049",
"ParentId": "217047",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "217049",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T02:14:47.040",
"Id": "217047",
"Score": "12",
"Tags": [
"python",
"parsing",
"numpy",
"scipy"
],
"Title": "Factorio analysis: data munging"
} | 217047 |
<p>The task:</p>
<blockquote>
<p>Write a function that rotates a list by k elements. For example, [1,
2, 3, 4, 5, 6] rotated by two becomes [3, 4, 5, 6, 1, 2]. Try solving
this without creating a copy of the list. How many swap or move
operations do you need?</p>
</blockquote>
<pre><code>const lst = [1, 2, 3, 4, 5, 6];
const rotateBy = 2;
</code></pre>
<p>The functional solution takes 2 operations (slice twice)?:</p>
<p>// I guess a <code>slice</code> is technically not a "copy of the list" but rather it's sub-elements, so it's allowed?</p>
<pre><code>const rotate = (lst, rotateBy) => [...lst.slice(rotateBy % lst.length), ...lst.slice(0, rotateBy % lst.length)];
console.log(rotate(lst, rotateBy));
console.log(rotate(lst, rotateBy));
</code></pre>
<p>The imperative solution takes as many operations as there are elements:</p>
<pre><code>function rotate(lst, rotateBy) {
const res = [];
for (let i = rotateBy % lst.length, len = lst.length; res.length < len; i = ++i % len) {
res.push(lst[i]);
}
return res;
}
console.log(rotate(lst, rotateBy));
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T11:45:59.360",
"Id": "419858",
"Score": "0",
"body": "The functional (declarative) approach may only take 2 calls but its about how much work the CPU is doing, not the selection of high level calls you make. If there was an array method `Array.rotate(2)` would that count as one operation? Also you are copying the array items with `slice` so total move ops is `2 * array.length`. 1 each for slice to temp array, then 1 each from temp array to new array. All your problem refer to lists, in many languages lists are linked, a linked list can be rotated in 2 operations (if it is indexed), or `2 + rotateBy` if no index"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T07:03:02.637",
"Id": "419953",
"Score": "0",
"body": "You should consider edge cases as well. Your solutions no longer work when the number of rotations exceeds the length of the array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T07:39:03.647",
"Id": "419955",
"Score": "0",
"body": "@TheDancingCode would you say that’s an edge case or error case? I would consider edge cases to be valid cases whereas error cases are invalid cases. I do agree though that both have to be caught"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T10:57:56.893",
"Id": "419978",
"Score": "0",
"body": "I'd argue it's an edge case. Rotating 7 times when you only have 6 elements isn't efficient, but it's not non-sensical."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T18:10:05.343",
"Id": "420052",
"Score": "0",
"body": "@TheDancingCode code updated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T18:15:34.267",
"Id": "420054",
"Score": "0",
"body": "Arguably, you haven't solved the challenge (\"Try solving this without creating a copy of the list.\") — and you probably can't do so in the functional programming paradigm, because one of the rules of FP is to avoid mutation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T18:20:14.817",
"Id": "420055",
"Score": "0",
"body": "@200_success but the imperative solution solved it, didn't it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T18:20:55.503",
"Id": "420056",
"Score": "0",
"body": "In the imperative solution, `res` is still a copy of the list."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T18:55:51.963",
"Id": "420061",
"Score": "0",
"body": "@200_success I guess I would mutate the list directly by, e.g. pushing the first elements to the list and then `splice` it at the position `rotateBy`?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T07:14:49.540",
"Id": "217056",
"Score": "1",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"functional-programming"
],
"Title": "Rotate a list by k elements"
} | 217056 |
<p>I need to make a UI where I can edit/insert/remove records of my SQL tables through my app. Edits and deletes of records works fine except of insertions when it comes to tables with auto-incremented PKs.
I created a combobox populated with the names of tables and by using the sql schema I try to generate dynamic code for each table. </p>
<p>This method returns the model for the box.</p>
<pre><code>public static String[] getPartType() {
ResultSet rs = null;
List<String> list = new ArrayList<String>();
list.add("None");
try {
stmt = ccd_db_connection.getConnection().prepareStatement(
"SELECT table_name FROM information_schema.tables t WHERE table_catalog = 'xxxx' AND t.TABLE_TYPE='BASE TABLE' ");
rs = stmt.executeQuery();
while (rs.next()) {
list.add(rs.getString(1));
}
stmt.close();
rs.close();
} catch (SQLException e) {
new ConnectionMessage(e);
}
return list.toArray(new String[0]);
}
</code></pre>
<p>After selecting the table I populate my custom JTable and project the corresponding records customizing just the FROM part of the query. To keep this post sort I'll jump right on insertion since everything else seems to be working.</p>
<p>This is the method where I do the insertion</p>
<pre><code>public static void insertParts(String tableName, Vector<String> colNames, Vector<Object> data) throws SQLException {
StringBuilder query = new StringBuilder("INSERT INTO " + tableName + " (");
for (int j = 0; j < colNames.size(); j++) {
query.append(colNames.get(j));
if (j != (colNames.size() - 1)) {
query.append(", ");
} else {
query.append(") VALUES(");
}
}
for (int i = 0; i < colNames.size(); i++) {
query.append("?");
if (i != (colNames.size() - 1)) {
query.append(", ");
} else {
query.append(")");
}
}
stmt = ccd_db_connection.getConnection().prepareStatement(query.toString());
for (int j = 0; j < colNames.size(); j++) {
stmt.setObject(j + 1, data.get(j));
}
stmt.execute();
stmt.close();
}
</code></pre>
<p>And here is the big Question(s) of mine. </p>
<ul>
<li>Am I trying to reinvent the wheel?</li>
<li>Is this dynamic usage of queries bad practice and should I code specific methods for each and every table separately?</li>
<li>If this code is acceptable ... The insertion works fine except on tables where there is a primary key with auto incrementation. and i think thats cause setObject sets null while the query should only have the explicit values. Is there any way to bypass that.</li>
</ul>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T08:42:48.607",
"Id": "217060",
"Score": "1",
"Tags": [
"java",
"sql"
],
"Title": "Fetching SQL table names and dynamicly insert values"
} | 217060 |
<p>I would like to do the following:<br>
I have a list <code>data</code> of 3-tuples that I need to go through, for each tuple <code>base_tuple</code> I want to know the index <code>index_max</code> of the maximum value held in <code>base_tuple</code> and replace <code>base_tuple</code> with a new 3-tuple <code>new_tuple</code> that only holds <code>0</code>s except for the value at index <code>index_max</code> which is set at a fixed value <code>fixed_value</code>.<br>
For instance, with a <code>fixed_value</code> of <code>127</code> and a <code>base_tuple</code> of <code>(12, 55, 27)</code>, I expect <code>new_tuple</code> to be <code>(0, 127, 0)</code>.</p>
<p>This is the code I use:</p>
<pre class="lang-py prettyprint-override"><code>fixed_value = 255
# data is the list of tuples
for i, base_tuple in enumerate(data):
index_max = base_tuple.index(max(base_tuple))
new_tuple = tuple(fixed_value*(i==index_max) for i in range(3))
data[i] = new_tuple
</code></pre>
<p>It works but it looks more like a hack than proper python... Any idea how to do this in a more pythonic way? </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T13:04:11.853",
"Id": "419865",
"Score": "0",
"body": "https://stackoverflow.com/questions/2474015/getting-the-index-of-the-returned-max-or-min-item-using-max-min-on-a-list"
}
] | [
{
"body": "<p><strong>Code organisation</strong></p>\n\n<p>At this moment, the code is there with no context. In order to make it easier to unerstand, reuse and test, you could try to define in a a function on its own.</p>\n\n<p>It could for instance:</p>\n\n<ul>\n<li>take <code>data</code> as a parameter</li>\n<li>take <code>fixed_value</code> as a parameter (with a default of 255 ?)</li>\n</ul>\n\n<p><strong>In-place changes</strong></p>\n\n<p>When trying to explain or test the function, things are make slighly harder by the fact that the input is modified. In your case, it may be just as easy to return a new list of values.</p>\n\n<p>Here is a <a href=\"https://twitter.com/raymondh/status/1055508781994594305\" rel=\"nofollow noreferrer\">tweet from Raymond Hettinger</a> (Python core developer and trainer):</p>\n\n<blockquote>\n <p>Today's super-easy #python student question.</p>\n \n <p>Q. What are the best practices for modifying a list while looping over it?</p>\n \n <p>A. Don't. Seriously, just make a new list and avoid hard-to-read code with hard-to-find bugs.</p>\n</blockquote>\n\n<p>At this stage, we have something like:</p>\n\n<pre><code>new_data = []\nfor i, base_tuple in enumerate(data):\n index_max = base_tuple.index(max(base_tuple))\n new_tuple = tuple(fixed_value*(i==index_max) for i in range(3))\n new_data.append(new_tuple)\nreturn new_data\n</code></pre>\n\n<p>But the call to <code>enumerate</code> is not required anymore and we can write:</p>\n\n<pre><code>new_data = []\nfor base_tuple in data:\n index_max = base_tuple.index(max(base_tuple))\n new_tuple = tuple(fixed_value*(i==index_max) for i in range(3))\n new_data.append(new_tuple)\nreturn new_data\n</code></pre>\n\n<p><strong>More functions</strong></p>\n\n<p>We could extract out the tuple computation in a function on its own.\nWe would have something like:</p>\n\n<pre><code>def get_new_tuple(base_tuple, fixed_value):\n index_max = base_tuple.index(max(base_tuple))\n return tuple(fixed_value*(i==index_max) for i in range(3))\n\ndef get_new_val(data, fixed_value = 255):\n # data is the list of tuples\n new_data = []\n for base_tuple in data:\n new_data.append(get_new_tuple(base_tuple, fixed_value))\n return new_data\n</code></pre>\n\n<p>(Documentation and function names should be improved).</p>\n\n<p>Now, this is a good occasion to use list comprehension in <code>get_new_val</code>.</p>\n\n<p>At this stage, renaming the function, the parameter and adding a simple test, we have:</p>\n\n<pre><code>def get_new_tuple(base_tuple, fixed_value):\n index_max = base_tuple.index(max(base_tuple))\n return tuple(fixed_value*(i==index_max) for i in range(3))\n\ndef get_new_tuples(tuples, fixed_value = 255):\n return [get_new_tuple(tup, fixed_value) for tup in tuples]\n\ndef test_get_new_tuples():\n # This could/should be written with a proper unit-test framework\n data = [(12, 55, 27), (260, 55, 27), (12, 55, 255)]\n output = get_new_tuples(data)\n assert output == [(0, 255, 0), (255, 0, 0), (0, 0, 255)]\n</code></pre>\n\n<p><strong>Improving <code>get_new_tuple</code></strong></p>\n\n<p>There is the <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic number</a> 3. It would make sense to be more generic and accept tuples of any length.</p>\n\n<p>For instance:</p>\n\n<pre><code>def get_new_tuple(base_tuple, fixed_value):\n index_max = base_tuple.index(max(base_tuple))\n return tuple(fixed_value*(i==index_max) for i in range(len(base_tuple)))\n</code></pre>\n\n<p>And we can test it with more unit tests:</p>\n\n<pre><code>def test_get_new_tuple():\n tup = (12, 55, 27)\n output = get_new_tuple(tup, 255)\n assert output == (0, 255, 0)\n tup = (12, 55, 27, 42)\n output = get_new_tuple(tup, 255)\n assert output == (0, 255, 0, 0)\n</code></pre>\n\n<p>Also, the pattern <code>range(len(foo))</code> usually suggests we could do things in a better way. For instance, we could use <code>enumerate</code>:</p>\n\n<pre><code>return tuple(fixed_value*(i==index_max) for i, _ in enumerate(base_tuple))\n</code></pre>\n\n<p><strong>Edge case</strong></p>\n\n<p>Another question we could ask ourselves is about the behavior of the function where the max value appears more than once. It probably deserves to be documented and properly tested. Based on what we want, we may have to change the implementation.</p>\n\n<p>Another edge case that could be tested/documented is how the empty tuple is handled.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T10:50:23.573",
"Id": "419850",
"Score": "0",
"body": "thank you for your feedback. I actually was more concerned about the way `new_tuple` is created (using kind of a 'logic mixed with arithmetic' hack), don't you think it looks like a poor way to do what's intended? Also, should I edit my question so that the code meets your Code organisation piece of advice?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T11:28:55.833",
"Id": "419856",
"Score": "0",
"body": "@Louisono: Do not edit your question after you have got an answer, especially if that edit would invalidate the answer. Include it in your code and ask a follow-up question if the changes are significant enough."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T10:05:07.403",
"Id": "217066",
"ParentId": "217063",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217066",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T08:59:19.120",
"Id": "217063",
"Score": "1",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "tuple initialization in a loop"
} | 217063 |
<blockquote>
<p>I'm not good at English.
It's gonna be hard to read.
I apologize in advance.</p>
</blockquote>
<p>I need expression parser for draw diagram(fault tree).
In order to do that I have to create data structure from custom expression</p>
<pre class="lang-none prettyprint-override"><code>( (123-A1) AND (123-A2) AND (123-A3) OR (123-A4 AND (123-A5 OR 123-A6)) )
</code></pre>
<p>The above example was written roughly as I thought.</p>
<ol>
<li>In some cases, parentheses are used for each variable for readability.</li>
<li>Read in order within the same parentheses.</li>
<li>Read in order if there are no parentheses.</li>
<li>Parentheses around the expression can be attached without meaning.</li>
<li>Operators use only <strong>AND</strong>, <strong>OR</strong> parentheses use only <strong>(</strong>, <strong>)</strong>.</li>
<li>I don't know which is the best way string to data structure.</li>
<li>The depth and order of parentheses and.. anything are all important because eventually I need to draw Diagram.</li>
</ol>
<pre><code> _________OR___________
| |
| ____AND____
| | |
______AND______ | ___OR___
| | | | | |
123-A1 123-A2 123-A3 123-A4 123-A5 123-A6
</code></pre>
<p><strong>Expression to Token</strong></p>
<pre><code>public class Token
{
public TokenType Type; // Operator, Parenthesis, Variable
public string Label;
public int Depth;
public int Group;
public Token(string label)
{
Label = label.Trim();
if (ExpressionParser.SupportedOperatorHashSet.Contains(label.ToUpper()))
{
Type = TokenType.Operator;
}
else if (ExpressionParser.SupportedParenthesesHashSet.Contains(label))
{
Type = TokenType.Parenthesis;
}
else
{
Type = TokenType.Variable;
}
}
}
public enum TokenType
{
Variable,
Operator,
Parenthesis
}
public static class ExpressionParser
{
private static Regex TokenRegex = new Regex(@"[\(\)]|[\d\w-]+");
internal static readonly HashSet<string> SupportedOperatorHashSet = new HashSet<string>() { AndGate, OrGate };
internal static readonly HashSet<string> SupportedParenthesesHashSet = new HashSet<string>() { OpenParenthesis, CloseParenthesis };
private static readonly List<Token> TokenList = new List<Token>();
internal const string AndGate = "AND";
internal const string OrGate = "OR";
internal const string OpenParenthesis = "(";
internal const string CloseParenthesis = ")";
public static List<Token> Parse(string expression)
{
try
{
// Get '(' ')' '123-A1' 'AND' 'OR'
MatchCollection matches = TokenRegex.Matches(expression); // @"[\(\)]|[\d\w-]+"
int depth = 0;
foreach (Match match in matches)
{
Token token = new Token(match.Value);
TokenList.Add(token);
// Increase depth when token is open parenthesis
if (token.Type == TokenType.Parenthesis && token.Label == OpenParenthesis)
{
depth += 1;
}
token.Depth = depth;
// Set group
if (TokenList.Count > 1)
{
Token prevToken = TokenList[TokenList.Count - 2];
if (prevToken.Depth == token.Depth)
{
token.Group = prevToken.Group;
}
else
{
token.Group = prevToken.Group + 1;
}
}
// Decrease depth after token is close parenthesis
if (token.Type == TokenType.Parenthesis && token.Label == CloseParenthesis)
{
depth -= 1;
}
}
// Remove parenthesis [ex. (123-ab)]
for (int i = 0; i < TokenList.Count; i++)
{
if (i + 2 < TokenList.Count &&
TokenList[i].Type == TokenType.Parenthesis && TokenList[i].Label == OpenParenthesis &&
TokenList[i + 2].Type == TokenType.Parenthesis && TokenList[i].Label == CloseParenthesis)
{
TokenList.RemoveAt(i + 2);
TokenList.RemoveAt(i);
}
}
return new List<Token>(TokenList);
}
finally
{
TokenList.Clear();
}
}
}
</code></pre>
<p><strong>Run</strong></p>
<pre><code>ExpressionParser.Parse("( (123-A1) AND (123-A2) AND (123-A3) OR (123-A4 AND (123-A5 OR 123-A6)) )");
</code></pre>
<p><strong>Result</strong></p>
<pre><code>OR
├ AND
│ ├ 123-A1
│ ├ 123-A2
│ └ 123-A3
└ AND
├ 123-A4
└ OR
├ 123-A5
└ 123-A6
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T11:25:36.240",
"Id": "419855",
"Score": "0",
"body": "Welcome to Code Review! Please add to your question whether and if so which aspects of the code (e.g. style, best practices, performance, ...) the reviewers should focus on. This will likely help you to get feedback that's more relevant to you."
}
] | [
{
"body": "<p>There are several problems with this code:</p>\n\n<ul>\n<li>There's no syntax validation:\n\n<ul>\n<li><code>\"))a\"</code> results in tokens with negative depth. It should be rejected as invalid.</li>\n<li><code>\"a AND b c\"</code> is not rejected either. Note the missing operator between <code>b</code> and <code>c</code>.</li>\n<li><code>\"a && b\"</code> results in only two tokens, <code>a</code> and <code>b</code>. The invalid <code>&&</code> part is ignored. I'd expect such input to be rejected.</li>\n</ul></li>\n<li><p>The removal of superfluous parenthesis is problematic:</p>\n\n<ul>\n<li>It's broken (you're missing a <code>+ 2</code> somewhere).</li>\n<li>It doesn't fix up the depth and group of subsequent tokens.</li>\n<li>It doesn't handle multiple levels, so it simplifies <code>\"(((a)))\"</code> to <code>\"((a))\"</code> instead of to <code>\"a\"</code>.</li>\n</ul></li>\n<li><p>Why does the <code>Token</code> constructor determine the token type? Why not let <code>ExpressionParser.Parse</code> determine the type, and pass it in via <code>Token</code>'s constructor?</p></li>\n<li>Marking fields as <code>readonly</code> prevents them from being reassigned, but it won't make a mutable object immutable. Other code in the same assembly can break the parser by calling <code>ExpressionParser.SupportedOperatorHashSet.Clear()</code>.</li>\n<li>Why does <code>Parse</code> store its results in a static field (<code>TokenList</code>) instead of using a local variable? I don't see any advantage to this (but several disadvantages).</li>\n<li>Why not expand <code>TokenType</code> with <code>ParenthesisOpen</code>, <code>ParenthesisClose</code>, <code>AndOperator</code> and <code>OrOperator</code>? That lets you simplify several checks.</li>\n</ul>\n\n<hr>\n\n<p>What you have written is a lexer, not a parser. Instead of assigning a depth and group number to each token, consider parsing the resulting list of tokens into an actual tree structure. One way to do that would be to use the Shunting Yard algorithm. The resulting structure would consist of expression nodes, with variable nodes containing the name of a variable, and operation nodes containing an operator (and/or) and a list of operand expressions (which are either variable or operation nodes).</p>\n\n<p>For example, <code>\"a AND (b OR c)\"</code> would produce the same result as:</p>\n\n<pre><code>new Operation(\n Operator.And,\n new Expression[] {\n new Variable(\"a\"),\n new Operation(\n Operator.Or,\n new Expression[] {\n new Variable(\"b\"),\n new Variable(\"c\")\n })\n });\n</code></pre>\n\n<p>Parenthesis influence how this tree is created, but they don't need to be stored in the tree. Groups can be found by looking for <code>Operation</code> nodes, and depth is determined by how many <code>Operation</code> 'parents' a node has.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T14:30:29.750",
"Id": "420014",
"Score": "0",
"body": "Thank you.\nI know most of the problems you're talking about.\n\nI've re-developed it a lot to implement this function, so I've made it simple.\n\n\"Instead of assigning a depth and group number to each token, consider parsing the resulting list of tokens into an actual tree structure.\"\nThis is the biggest problem for me.\nPlease advise me on this part."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T15:11:46.683",
"Id": "420025",
"Score": "0",
"body": "I'd recommend investigating the Shunting-yard algorithm."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T11:37:22.110",
"Id": "217127",
"ParentId": "217064",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T09:11:47.840",
"Id": "217064",
"Score": "2",
"Tags": [
"c#",
"parsing"
],
"Title": ".NET Custom hierarchical expression to treeview data structure"
} | 217064 |
<p>I need a function that checks how different are two different strings. I chose the Levenshtein distance as a quick approach, and implemented this function:</p>
<pre><code>from difflib import ndiff
def calculate_levenshtein_distance(str_1, str_2):
"""
The Levenshtein distance is a string metric for measuring the difference between two sequences.
It is calculated as the minimum number of single-character edits necessary to transform one string into another
"""
distance = 0
buffer_removed = buffer_added = 0
for x in ndiff(str_1, str_2):
code = x[0]
# Code ? is ignored as it does not translate to any modification
if code == ' ':
distance += max(buffer_removed, buffer_added)
buffer_removed = buffer_added = 0
elif code == '-':
buffer_removed += 1
elif code == '+':
buffer_added += 1
distance += max(buffer_removed, buffer_added)
return distance
</code></pre>
<p>Then calling it as:</p>
<pre><code>similarity = 1 - calculate_levenshtein_distance(str_1, str_2) / max(len(str_1), len(str_2))
</code></pre>
<p>How sloppy/prone to errors is this code? How can it be improved?</p>
| [] | [
{
"body": "<p>There is a module available for exactly that calculation, <a href=\"https://pypi.org/project/python-Levenshtein/\" rel=\"noreferrer\"><code>python-Levenshtein</code></a>. You can install it with <code>pip install python-Levenshtein</code>.</p>\n\n<p>It is implemented in C, so is probably faster than anything you can come up with yourself.</p>\n\n<pre><code>from Levenshtein import distance as levenshtein_distance\n</code></pre>\n\n<hr>\n\n<p>According to the <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"noreferrer\"><code>docstring</code> conventions</a>, your docstring should look like this, i.e. with the indentation aligned to the <code>\"\"\"</code> and the line length curtailed to 80 characters.</p>\n\n<pre><code>def calculate_levenshtein_distance(str_1, str_2):\n \"\"\"\n The Levenshtein distance is a string metric for measuring the difference\n between two sequences.\n It is calculated as the minimum number of single-character edits necessary to\n transform one string into another.\n \"\"\"\n ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T13:08:05.580",
"Id": "419867",
"Score": "14",
"body": "Just to note the module is licensed under GPL 2.0 so watch out if you're using it for work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T00:02:54.470",
"Id": "419932",
"Score": "1",
"body": "Just to point out a small nitpick to other people who may stumble upon this answer, as per [help center](https://codereview.stackexchange.com/help/how-to-answer): \"Every answer must make at least one insightful observation about the code in the question. Answers that merely provide an alternate solution with no explanation or justification do not constitute valid Code Review answers and may be deleted.\" While this answer does provide alternative and existing module suggestion, it also goes into some suggestions about improving code quality. So it's an example of a decent answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T08:21:50.337",
"Id": "419958",
"Score": "0",
"body": "Thanks! I did not know of this module. Will check it out"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T08:21:58.763",
"Id": "419959",
"Score": "1",
"body": "@SergiyKolodyazhnyy While I (obviously) agree, and that is one of the reasons I added that part, I would actually argue that \"It is implemented in C, so is probably faster than anything you can come up with yourself\" would get around the \"no explanation or justification\" clause"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-08T20:00:13.050",
"Id": "495956",
"Score": "0",
"body": "Upvoted because this answer came up first for _python levenshtein edit distance_ in Google and I'll want to find to find the library link again, but the code review itself could be improved by suggesting something about the algorithm in addition to the doc string formatting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-08T20:17:04.767",
"Id": "495957",
"Score": "0",
"body": "@user1717828 While I agree that the review could be improved upon, note that an answer here at Code Review is a valid answer as long as it gives at least one insight regarding the code in the OP, as also noted further up in the comments. I feel like my answer does that and the other answer is quite complementary to it and hits on other, also important points, so I'd rather not repeat the points made there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T14:07:14.893",
"Id": "505568",
"Score": "1",
"body": "As a faster alternative to python-Levenshtein that is more open licensed https://github.com/maxbachmann/RapidFuzz (rapidfuzz.string_metric.levenshtein) can be used"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T10:37:07.737",
"Id": "217067",
"ParentId": "217065",
"Score": "18"
}
},
{
"body": "<p>The code itself is rather clear. There are some smaller changes I would make</p>\n\n<h1>tuple unpacking</h1>\n\n<p>You can use tuple unpacking to do:</p>\n\n<pre><code>for code, *_ in ndiff(str1, str2):\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>for x in ndiff(str_1, str_2):\n code = x[0]\n</code></pre>\n\n<h1>dict results:</h1>\n\n<p>Instead of a counter for the additions and removals, I would keep it in 1 dict: <code>counter = ({\"+\": 0, \"-\": 0})</code></p>\n\n<pre><code>def levenshtein_distance(str1, str2, ):\n counter = {\"+\": 0, \"-\": 0}\n distance = 0\n for edit_code, *_ in ndiff(str1, str2):\n if edit_code == \" \":\n distance += max(counter.values())\n counter = {\"+\": 0, \"-\": 0}\n else: \n counter[edit_code] += 1\n distance += max(counter.values())\n return distance\n</code></pre>\n\n<h1>generators</h1>\n\n<p>A smaller, less useful variation, is to let this method be a generator, and use the builtin <code>sum</code> to do the summary. this saves 1 variable inside the function:</p>\n\n<pre><code>def levenshtein_distance_gen(str1, str2, ):\n counter = {\"+\": 0, \"-\": 0}\n for edit_code, *_ in ndiff(str1, str2):\n if edit_code == \" \":\n yield max(counter.values())\n counter = {\"+\": 0, \"-\": 0}\n else: \n counter[edit_code] += 1\n yield max(counter.values())\n\nsum(levenshtein_distance_gen(str1, str2))\n</code></pre>\n\n<hr>\n\n<h1>timings</h1>\n\n<p>The differences in timings between the original and both these variations are minimal, and within the variation of results. This is rather logical, since for simple strings (<code>aaabbbc</code> and <code>abcabcabc</code>) 90% of the time is spent in <code>ndiff</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T08:24:30.820",
"Id": "419960",
"Score": "0",
"body": "Awesome suggestions. I had not even considered the generator approach, but it looks very nice. Thanks"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T13:51:31.967",
"Id": "217074",
"ParentId": "217065",
"Score": "13"
}
}
] | {
"AcceptedAnswerId": "217067",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T10:01:11.183",
"Id": "217065",
"Score": "17",
"Tags": [
"python",
"edit-distance"
],
"Title": "Calculate Levenshtein distance between two strings in Python"
} | 217065 |
<p>I have an <code>app.config</code> file that contains some connection strings, this is accessed on a project-by-project basis</p>
<p>In my solution, I have the following projects:</p>
<ul>
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
</ul>
<p>Project A contains the <code>app.config</code> file, and a class called <code>ConnectionStringHelper</code></p>
<pre><code>public class ConnectionStringHelper
{
public string GetConnectionString(string index)
{
return ConfigurationManager.ConnectionStrings[index].ConnectionString;
}
}
</code></pre>
<p>Here is an example of how this is used (in project B):</p>
<pre><code>var connectionString = new ConnectionStringHelper().GetConnectionString("test");
</code></pre>
<p>Is there anything wrong with having a public method that returns the connection string?</p>
<p>This feels like a code smell, but I'm unsure how I would get around it?</p>
<p>EDIT: I do use dependency injection across the solution, however I had to write this method to be able to use it in some unit tests, as I can't use DI with them.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T10:08:15.183",
"Id": "419968",
"Score": "0",
"body": "I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. The example code that you have posted is not reviewable in this form because it leaves us guessing at your intentions. Unlike Stack Overflow, Code Review needs to look at concrete code in a real context. Please see [Why is hypothetical example code off-topic for CR?](//codereview.meta.stackexchange.com/q/1709)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T10:15:27.753",
"Id": "419971",
"Score": "1",
"body": "If you cannot use DI with your tests then your DI is off and is the real issue here, not the connection-string. You loose one of the main advantages of DI by not being able to use DI in tests."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T12:55:27.623",
"Id": "217071",
"Score": "1",
"Tags": [
"c#",
".net",
"asp.net-mvc"
],
"Title": "Querying connection string across solution"
} | 217071 |
<p>Being unable to easily read the output of /proc/net/tcp I made a small C# console app that modifies the output to be in decimal notation instead of the standard hexadecimal, show the corresponding enum states of the state code and added the ability to filter out remote addresses. With the ability to further tweak to your own needs/add custom messages.</p>
<p>By default /proc/net/tcp returns the result in the following format:</p>
<pre><code> 2: 6400A8C0:A21F 6400A8C0:ADC1 01 00000000:00000000 00:00000000 00000000 10296 0 802001 1 0000000000000000 25 4 0 21 -1
</code></pre>
<p>After running it through the assistant the output changes to:</p>
<pre><code>2: 192.168.0.100:41503 192.168.0.100:44481 ESTABLISHED 00000000:00000000 00:00000000 00000000 10296 0 802001 1 0000000000000000 25 4 0 21 -1
</code></pre>
<p>The following code (<a href="https://github.com/RemyRM/proc-net-tcp-assistant/blob/07fc6ecac3f84bdf144e763c55f07d72dc8713fd/ProcNetTcpConverter.cs" rel="nofollow noreferrer">github view</a>) works when run in the adb shell with any connected Android device:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Threading;
class ProcNetTcpConverter
{
//These values can either be hardcoded, or left empty. If left empty the programm will ask for the user to input manually.
static string filePath = @"";
internal static string[] remoteIPFilter = new string[] { "" };
static readonly string header = string.Format("{0, 5} {1, 20} {2, 20} {3, 12} {4, 5} {5} {6} {7, 5} {8, 10} {9, 7} {10, 8} {11}", "sl", "local_address", "rem_address", "state", "tx_queue", "rx_queue", "tr", "tm->when", "retrnsmt", "uid", "timeout", "inode");
static readonly string ipRegex = @"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}";
static void Main(string[] args)
{
while (true)
{
try
{
Console.SetWindowSize(220, 50);
if (filePath.Equals(""))
{
Console.WriteLine("Please specify file path");
filePath = Console.ReadLine();
}
if (remoteIPFilter.Length == 0)
{
Console.WriteLine("IPv4 Filters (seperated by space, leave blank if none):");
remoteIPFilter = Console.ReadLine().Split(' ');
if (remoteIPFilter[0] != "")
{
IPCheck();
}
}
Console.WriteLine("Press escape or ^c to pause");
do
{
while (!Console.KeyAvailable)
{
RunBatch();
Thread.Sleep(100);
}
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);
Console.WriteLine("\nPress any key to resume");
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e);
Console.ReadLine();
}
}
}
/// <summary>
/// Check if the given ip is valid.
/// Checks ip recursively after entering new IP.
/// </summary>
static void IPCheck()
{
for (int i = 0; i < remoteIPFilter.Length; i++)
{
var match = System.Text.RegularExpressions.Regex.Match(remoteIPFilter[i], ipRegex, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
if (!match.Success)
{
Console.WriteLine("{0} is not a valid ipv4 address, please re-enter, or leave blank to continue.", remoteIPFilter[i]);
remoteIPFilter[i] = Console.ReadLine();
if (remoteIPFilter[i] != "")
{
IPCheck();
}
}
}
}
/// <summary>
/// Run a batch script that checks for all open TCP connections on a connected device.
/// </summary>
static void RunBatch()
{
var process = new Process
{
StartInfo =
{
UseShellExecute = false,
RedirectStandardOutput = true,
FileName = filePath
}
};
process.Start();
string rawResult = process.StandardOutput.ReadToEnd();
ReplaceHexNotation(rawResult);
}
/// <summary>
/// Repalce the ip address + port that is in hex notation with an ip address + port that is in decimal notation
/// </summary>
/// <param name="rawResult"></param>
static void ReplaceHexNotation(string rawResult)
{
string[] splitResults = rawResult.Trim().Split('\n');
Console.WriteLine("\n" + splitResults[0]);
for (int i = 0; i < splitResults.Length; i++)
{
if (i == 1)
{
Console.WriteLine(header);
}
if (i > 2)
{
TCPResult result = new TCPResult(splitResults[i]);
string message = result.GetMessage();
if (message != null)
{
Console.WriteLine(message);
}
}
}
}
/// <summary>
/// Convert an ip address + port (format: 00AABB11:CD23) from hex notation to decimal notation.
/// Implementation taken from: https://stackoverflow.com/a/1355163/8628766
/// </summary>
/// <param name="input">Hex "ip:port" to convert</param>
/// <returns>Input ip as decimal string</returns>
static internal string ConvertFromInput(string input)
{
string[] ipPart = input.Split(':');
var ip = new IPAddress(long.Parse(ipPart[0], NumberStyles.AllowHexSpecifier)).ToString();
var port = long.Parse(ipPart[1], NumberStyles.AllowHexSpecifier).ToString();
return ip + ":" + port;
}
/// <summary>
/// Find the index of a character's n'th occurance
/// </summary>
/// <param name="s">Input string</param>
/// <param name="t">Character to check</param>
/// <param name="n">Occurance index</param>
/// <returns></returns>
internal static int GetNthIndex(string s, char t, int n)
{
int count = 0;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == t)
{
count++;
if (count == n)
{
return i;
}
}
}
throw new IndexOutOfRangeException("GetNthIndex Exception: Index was out of range.");
}
}
class TCPResult
{
private readonly string tcpResultMessage;
enum TcpStates
{
ESTABLISHED = 1,
SYN_SENT,
SYN_RECV,
FIN_WAIT1,
FIN_WAIT2,
TIME_WAIT,
CLOSE,
CLOSE_WAIT,
LAST_ACK,
LISTEN,
CLOSING,
NEW_SYN_RECV,
TCP_MAX_STATES
};
/// <summary>
/// Recreate the Tcp result message so we can re-format it with the new ip format
/// </summary>
/// <param name="rawInput">input string</param>
internal TCPResult(string rawInput)
{
rawInput = rawInput.Trim();
List<string> inputList = rawInput.Split(' ').ToList();
inputList.RemoveAll(o => o.Equals(""));
string sl = inputList[0];
string local_address = ProcNetTcpConverter.ConvertFromInput(inputList[1]);
string rem_address = ProcNetTcpConverter.ConvertFromInput(inputList[2]);
TcpStates st = ((TcpStates)Convert.ToInt32(inputList[3], 16));
string tx_queue = inputList[4].Substring(ProcNetTcpConverter.GetNthIndex(inputList[4], ':', 1) - 8, 8);
string rx_queue = inputList[4].Substring(ProcNetTcpConverter.GetNthIndex(inputList[4], ':', 1) + 1, 8);
string tr = inputList[5].Substring(ProcNetTcpConverter.GetNthIndex(inputList[5], ':', 1) - 2, 2);
string tmWhen = inputList[5].Substring(ProcNetTcpConverter.GetNthIndex(inputList[5], ':', 1) + 1, 8);
string retrnsmt = inputList[6];
string uid = inputList[7];
string timeout = inputList[8];
string inode = "";
//iNode doens't always have 8 parameters. Sometimes it only has 3
if (inputList.Count > 12)
{
inode = string.Format("{0, 6} {1, 3} {2, 16} {3, 3} {4, 3} {5, 3} {6, 3} {7,3} ", inputList[9], inputList[10], inputList[11], inputList[12], inputList[13], inputList[14], inputList[15], inputList[16]);
}
else
{
inode = string.Format("{0, 6} {1, 3} {2, 16} {3, 3} {4, 3} {5, 3} {6, 3} {7,3} ", inputList[9], inputList[10], inputList[11], "-1", "-1", "-1", "-1", "-1");
}
//return if the remote address is in the filter array
if (ProcNetTcpConverter.remoteIPFilter.Contains(rem_address.Substring(0, rem_address.IndexOf(':'))))
{
return;
}
tcpResultMessage = string.Format("{0, 5} {1, 20} {2, 20} {3, 12} {4, 5}:{5} {6}:{7, 5} {8, 10} {9, 7} {10, 8} {11}", sl, local_address, rem_address, st.ToString(), tx_queue, rx_queue, tr, tmWhen, retrnsmt, uid, timeout, inode);
if (Convert.ToInt32(tx_queue, 16) > 0 && st == TcpStates.ESTABLISHED)//Indicates this is the current active transmissiting connection
{
tcpResultMessage += " <= Active transmitting connection";
}
else if (Convert.ToInt32(rx_queue, 16) > 0 && st == TcpStates.ESTABLISHED)//Indicates this is the current active receiving connection
{
tcpResultMessage += " <= Active receiving connection";
}
}
internal string GetMessage()
{
return tcpResultMessage;
}
}
</code></pre>
<p>Running the following batch script:</p>
<pre><code>@echo off
echo %time%
adb.exe shell cat /proc/net/tcp
</code></pre>
<p>The program works. But I'm interested to learn if i'm using any bad practises, or doing other things wrong. Especially the <code>TCPResults</code> class/constructor could be implemented a lot better I think, but unable to come up with how myself.</p>
| [] | [
{
"body": "<h3>Regular expressions</h3>\n<p>You might <a href=\"https://stackoverflow.com/questions/9969158/when-not-to-use-regexoptions-compiled\">consider compiling</a> your regular expressions.</p>\n<pre><code>ipRegex = new Regex(@"[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"\n , RegexOptions.Compiled);\n</code></pre>\n<hr />\n<h3>Path normalization</h3>\n<blockquote>\n<pre><code>Console.WriteLine("Please specify file path");\nfilePath = Console.ReadLine();\n</code></pre>\n</blockquote>\n<p>-> append the following method to have some leverage on user input.</p>\n<pre><code>filePath = System.IO.Path.GetFullPath(filePath )\n</code></pre>\n<hr />\n<h3>New lines</h3>\n<blockquote>\n<p><code>rawResult.Trim().Split('\\n');</code></p>\n</blockquote>\n<p>Are you sure to use <code>\\n</code>? Perhaps this is fine. Maybe consider using <code>Environment.NewLine</code> instead. It depends how this tool encodes new lines.</p>\n<hr />\n<h3>Seperation of concerns</h3>\n<p>Method <code>ReplaceHexNotation</code> performs both tokenizing and outputting to the console. You should extract algorithms from output for better usability and maintainability.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-03T18:47:37.457",
"Id": "221604",
"ParentId": "217072",
"Score": "5"
}
},
{
"body": "<p>You don't need </p>\n\n<pre><code>System.Collections.Generic.List<string> inputList = rawInput.Split(' ').ToList();\ninputList.RemoveAll(o => o.Equals(\"\"));\n</code></pre>\n\n<p>Instead, you can do: </p>\n\n<pre><code>string[] inputList = rawInput.Split(' ', System.StringSplitOptions.RemoveEmptyEntries);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-17T12:29:51.230",
"Id": "230901",
"ParentId": "217072",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "221604",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T13:28:53.450",
"Id": "217072",
"Score": "4",
"Tags": [
"c#",
".net",
"formatting",
"io",
"ip-address"
],
"Title": "/proc/net/tcp results filter and converter"
} | 217072 |
<p>This is a c# class I use to implement web database applications with Microsoft IIS and Microsoft SQL server. It passes the http context to a selected SQL stored procedure, and writes a response based on the result sets generated by the stored procedure. Thus the entire application is coded as SQL stored procedures, apart from this c# code.</p>
<pre><code>using Data = System.Data;
using Net = System.Net;
using String = System.String;
using Object = System.Object;
/* WebServer which runs under IIS, passing requests to SQL server. Typical web.config file to pass all requests to WebServer is:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.web>
<customErrors mode="Off"/>
</system.web>
<system.webServer>
<handlers>
<add name="WebServer" path="*" verb="*" type="WebServer" />
</handlers>
</system.webServer>
</configuration>
Typical SQL declaration of tables passed to SQL:
CREATE TYPE [perfect].[InfoT] AS TABLE( Kind int NOT NULL, Name nvarchar(100) NOT NULL, Value nvarchar(max) NOT NULL,
PRIMARY KEY ( Name, Kind )
)
CREATE TYPE [perfect].[FileT] AS TABLE( id int NOT NULL, Name varchar(50) NOT NULL, ContentLength int NOT NULL,
ContentType nvarchar(max) NULL, FileName nvarchar(200) NOT NULL, [File] image NULL, PRIMARY KEY ( id ) )
)
*/
public class WebServer : System.Web.IHttpHandler
{
private static Data.SqlClient.SqlConnection GetConn( )
{
return new Data.SqlClient.SqlConnection
( "Initial Catalog=redacted;Data Source=(Local);Max Pool Size=500;User Id=redacted;Password=redacted" );
}
public void ProcessRequest( System.Web.HttpContext ctx )
{
// Each http request is handled by two SQL procedure calls. The first gets the name of the handling procedure, the second computes the response.
try
{
using ( Data.SqlClient.SqlConnection sqlconn = GetConn() )
using ( Data.SqlClient.SqlCommand cmd = new Data.SqlClient.SqlCommand( "perfect.GetHandler", sqlconn ) )
{
Data.SqlClient.SqlParameter p = null;
{ /* Set up table of info to be passed to stored procedure */
Data.DataTable t = new Data.DataTable( );
t.Columns.Add( "Kind", typeof( int ) );
t.Columns.Add( "Name", typeof( string ) );
t.Columns.Add( "Value", typeof( string ) );
AddToDataTable( t, 0, ctx.Request.QueryString );
AddToDataTable( t, 1, ctx.Request.Form );
AddToDataTable( t, 2, ctx.Request.Cookies );
t.Rows.Add( 3, "Host", ctx.Request.Url.Host );
t.Rows.Add( 3, "Path", ctx.Request.Path );
t.Rows.Add( 3, "PathAndQuery", ctx.Request.Url.PathAndQuery );
t.Rows.Add( 3, "IpAddress", ctx.Request.UserHostAddress );
p = cmd.Parameters.AddWithValue( "@Info", t );
p.SqlDbType = Data.SqlDbType.Structured;
}
sqlconn.Open();
cmd.CommandType = Data.CommandType.StoredProcedure;
cmd.CommandText = ( string ) cmd.ExecuteScalar();
if ( ctx.Request.Files.Count > 0 )
{
Data.DataTable ft = GetFileTable( ctx.Request.Files );
p = cmd.Parameters.AddWithValue( "@Files", ft );
p.SqlDbType = Data.SqlDbType.Structured;
}
Data.DataSet ds = new Data.DataSet( );
using ( Data.SqlClient.SqlDataAdapter da = new Data.SqlClient.SqlDataAdapter( cmd ) )
{
da.Fill( ds );
}
// Interpret the dataset
ctx.Response.ContentType = "text/html";
String ShowRecordCount = null;
for ( int i = 0; i < ds.Tables.Count; i += 1 )
{
Data.DataTable t = ds.Tables[i];
if ( ShowRecordCount != null )
{
PutUtf8( ctx, ShowRecordCount + t.Rows.Count );
ShowRecordCount = null;
}
for ( int j = 0; j < t.Rows.Count; j += 1 )
{
Data.DataRow r = t.Rows[j];
int code = 0;
Object value = r[0];
if ( r.ItemArray.Length > 1 )
{
code = (int) value;
value = r[1];
}
if ( code == 0 ) PutUtf8( ctx, (string) value );
else if ( code == 1 ) ctx.Response.ContentType = (string) value;
else if ( code == 2 )
{
byte[] b = (byte[]) value;
ctx.Response.OutputStream.Write( b, 0, b.Length );
}
else if ( code == 4 ) ctx.Response.Expires = (int) value;
else if ( code == 14 ) ctx.Response.StatusCode = (int) value;
else if ( code == 15 ) ctx.Response.Redirect( (string) value );
else if ( code == 16 )
{
System.Web.HttpCookie ck = new System.Web.HttpCookie( (string) value, (string) r[2] );
String Expires = (string) r[3];
if ( Expires != "" ) ck.Expires = System.DateTime.Parse( Expires );
ctx.Response.Cookies.Add( ck );
}
else if ( code == 17 ) ShowRecordCount = (string)value;
}
}
}
}
catch ( System.Exception e )
{
ctx.Response.Write( e );
}
}
public bool IsReusable { get { return true; } }
private void AddToDataTable( Data.DataTable dt, int Kind, System.Collections.Specialized.NameValueCollection nvc )
{
foreach ( string key in nvc.Keys )
if ( key != null ) dt.Rows.Add( Kind, key, nvc[key] );
}
private void AddToDataTable( Data.DataTable dt, int Kind, System.Web.HttpCookieCollection nvc )
{
foreach ( string key in nvc.Keys )
{
dt.Rows.Add( Kind, key, nvc[key].Value );
}
}
private Data.DataTable GetFileTable( System.Web.HttpFileCollection fc )
{
Data.DataTable ft = new Data.DataTable();
ft.Columns.Add( "id", typeof(int) );
ft.Columns.Add( "Name", typeof(string) );
ft.Columns.Add( "ContentLength", typeof(int) );
ft.Columns.Add( "ContentType", typeof(string) );
ft.Columns.Add( "FileName", typeof(string) );
ft.Columns.Add( "File", typeof(byte[]) );
for ( int id = 0; id < fc.Count; id += 1 )
{
System.Web.HttpPostedFile pf = fc[ id ];
int length = pf.ContentLength;
byte [] bytes = new byte[ length ];
pf.InputStream.Read( bytes, 0, length );
ft.Rows.Add( id, fc.GetKey(id), length, pf.ContentType, pf.FileName, bytes );
}
return ft;
}
// Output
private byte [] EncBuffer = new byte[512];
private static byte[] GetBuf( int need )
{ int n = 512; while ( n < need ) n *= 2; return new byte[n]; }
private void PutUtf8( System.Web.HttpContext ctx, String s )
{
int len = s.Length;
int need = System.Text.Encoding.UTF8.GetMaxByteCount( len );
if ( need > EncBuffer.Length ) EncBuffer = GetBuf( need );
int nb = System.Text.Encoding.UTF8.GetBytes( s, 0, len, EncBuffer, 0 );
ctx.Response.OutputStream.Write( EncBuffer, 0, nb );
}
// Logging
static WebServer()
{
System.AppDomain cd = System.AppDomain.CurrentDomain;
cd.UnhandledException += new System.UnhandledExceptionEventHandler( LogException );
Log( "Unhandled exception handler set" );
}
static void LogException( object sender, System.UnhandledExceptionEventArgs args )
{
System.Exception e = (System.Exception) args.ExceptionObject;
Log( "Unhandled exception: " + e.ToString() );
}
static void Log( String message )
{
using ( Data.SqlClient.SqlConnection sqlconn = GetConn() )
{
using ( Data.SqlClient.SqlCommand cmd = new Data.SqlClient.SqlCommand( "perfect.Log", sqlconn ) )
{
cmd.CommandType = Data.CommandType.StoredProcedure;
Data.SqlClient.SqlParameter p = cmd.Parameters.AddWithValue( "@Message", message );
p.SqlDbType = Data.SqlDbType.NVarChar;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
}
} // End class WebServer
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T20:28:49.870",
"Id": "420066",
"Score": "3",
"body": "`SqlDataAdapter`, `SqlCommand`, `SqlConnection` all implement `IDisposable` and should be disposed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T04:16:18.403",
"Id": "420084",
"Score": "0",
"body": "@BradM Thanks, it's interesting the Microsoft examples ( e.g. https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.executenonquery?view=netframework-4.7.2 ) only dispose SqlConnection."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T07:43:42.237",
"Id": "420091",
"Score": "1",
"body": "These examples are written by humans too - they might have made a mistake or they have purposely ommited it for brevity. Who knows."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T20:59:24.843",
"Id": "420171",
"Score": "0",
"body": "DataSet and DataTable also implement IDisposable. My suspicion is that it's only important to dispose of SqlConnection, and with the others it makes no difference, and that's why the Microsoft examples only dispose SqlConnection. But it's only a suspicion, so I decided to Dispose everything that is disposable!"
}
] | [
{
"body": "<h3>Main issues:</h3>\n\n<ul>\n<li>If the main purpose of this webserver is to call stored procedures, then I'd expect to see a <code>CallStoredProcedure</code> method somewhere. That should make it easier to understand the purpose of the code, and it lets you clean up <code>ProcessRequest</code>, so it can call procedures and prepare a response without getting bogged down in the details.</li>\n<li>There's no documentation about what sort of requests this webserver can handle, and how they should be formatted. The same goes for responses. Maybe you've got documentation elsewhere? Personally I prefer to keep it close to the code itself, to increase the likelyhood that it will be kept in sync.</li>\n<li>It's difficult to discern the meaning of <code>kind</code> and <code>code</code>. I'd use enums, or at least named constants, to make it apparent what values the code expects to handle, and what the meaning of those values is.</li>\n</ul>\n\n<h3>Inconsistencies:</h3>\n\n<p>There are a lot of inconsistencies in your code:</p>\n\n<ul>\n<li>Some type names use an alias, others are written out fully.</li>\n<li>Sometimes you're using C# aliases for basic types like <code>string</code> and <code>object</code>, sometimes not.</li>\n<li>Sometimes an inner scope is indented and put on a separate line, sometimes it's put on the same line.</li>\n<li>Sometimes an inner scope is surrounded by braces, sometimes not.</li>\n<li>Some names are abbreviated, some are not.</li>\n<li>Most parameter names are written in camelCase, as is usual, but a few are not.</li>\n</ul>\n\n<p>All of this makes the code harder to read and understand than it needs to be. Here's what I would change:</p>\n\n<ul>\n<li>Unless you have a specific reason for using namespace aliases the way you do, I'd do what everyone else does: <code>using System;</code>, <code>using System.Data;</code>, <code>using System.Data.SqlClient;</code>, and so on. With that, you don't need to write fully qualified names anywhere, which reduces clutter.</li>\n<li>Most people use <code>string</code> and <code>object</code> for variables, parameters and the like, and <code>String</code> and <code>Object</code> when they're calling a static method on one of those types.</li>\n<li>Always putting inner scopes on a separate line, and indenting them, makes control flow easier to see.</li>\n<li>Regarding braces, some people recommend always use braces, no matter what, to prevent certain kinds of bugs. I think that's a bit excessive for conditional <code>return</code> and <code>throw</code> statements, but I do try to be consistent.</li>\n<li><code>GetConnection</code>, <code>table</code>, <code>row</code>, <code>context</code>, <code>dataTable</code>, <code>collection</code>, <code>fileCollection</code> and so on should be easier to understand than <code>GetConn</code>, <code>t</code>, <code>r</code>, <code>ctx</code>, <code>dt</code>, <code>nvc</code> and <code>fc</code>, without being too long for comfort.</li>\n<li>Fields, parameter names and local variables are normally written in camelCase. PascalCase is used for type, method and property names.</li>\n</ul>\n\n<h3>Other notes:</h3>\n\n<ul>\n<li>Duplicate type annotations can be removed by relying on type inference: <code>var table = new DataTable();</code> is equivalent to <code>DataTable table = new DataTable();</code>.</li>\n<li><code>DataSet.Tables</code> and <code>DataTable.Rows</code> can be iterated directly with <code>foreach</code>.</li>\n<li><code>IsReusable</code> can be simplified to <code>public bool IsReusable => true;</code>.</li>\n<li><code>UnhandledException += new UnhandledExceptionEventHandler(LogException);</code> can be simplified to <code>UnhandledException += LogException;</code>.</li>\n<li><code>\"Unhandled exception: \" + ex.ToString()</code> can be simplified to <code>$\"Unhandled exception: {ex}\"</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T17:20:12.163",
"Id": "423055",
"Score": "0",
"body": "Thanks for the answer. There is no restriction on the requests or the responses, this is just a \"dumb\" adapter layer which passes any request to an SQL proc, and the response back to the http client. The SQL execution happens when ExecuteScalar and Fill are called, perhaps that could be explained in a comment."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T15:36:23.943",
"Id": "219027",
"ParentId": "217075",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "219027",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T13:56:40.403",
"Id": "217075",
"Score": "2",
"Tags": [
"c#",
"sql",
"sql-server"
],
"Title": "Web Server handler class to pass IIS http requests to SQL Server stored procedures"
} | 217075 |
<p>I'm writing a service for a ORPG and I expect traffic of about 10kb of packets per second from multiple clients. I just want to know if my approach is correct? Are there areas I can improve?</p>
<p>This is a bit basic the full app would have a lot more handlers and packet structs.</p>
<pre><code>package main
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"net"
)
var handlers map[uint16]func(conn net.Conn, data []byte)
var currDataVer uint16 = 100
type Packet struct {
Length, ID uint16
}
// 1000+ more packet types with different fields
type VersionPacket struct {
Packet
Client, Upgrade, Data uint16
}
func main() {
handlers = make(map[uint16]func(conn net.Conn, data []byte))
listener, err := net.Listen("tcp", "127.0.0.1:2222")
if err != nil {
return // or panic?
}
defer listener.Close()
// possibly up to 1000 handlers
handlers[300] = func(conn net.Conn, data []byte) {
var pVer VersionPacket
err := binary.Read(bytes.NewReader(data), binary.LittleEndian, &pVer)
if err != nil {
return
}
// if version does not match
if currDataVer != pVer.Data {
resp := bytes.NewBuffer(make([]byte, 2))
binary.Write(resp, binary.LittleEndian, uint16(100)) // packet id
binary.Write(resp, binary.LittleEndian, uint16(13)) // packet data
binary.Write(resp, binary.LittleEndian, uint16(35))
binary.Write(resp, binary.LittleEndian, uint16(0))
resb := resp.Bytes()
binary.LittleEndian.PutUint16(resb, uint16(len(resb)))
fmt.Println(resb)
conn.Write(resb)
} else {
resp := bytes.NewBuffer(make([]byte, 2))
binary.Write(resp, binary.LittleEndian, uint16(1001)) // packet id
binary.Write(resp, binary.LittleEndian, uint16(60)) // packet data
for i := 0; i < 2; i++ {
binary.Write(resp, binary.LittleEndian, uint16(i))
}
resb := resp.Bytes()
binary.LittleEndian.PutUint16(resb, uint16(len(resb)))
conn.Write(resb)
resp = bytes.NewBuffer(make([]byte, 2))
binary.Write(resp, binary.LittleEndian, uint16(1002)) // packet id
binary.Write(resp, binary.LittleEndian, uint16(61)) // packet data
for i := 0; i < 3; i++ {
binary.Write(resp, binary.LittleEndian, uint16(i))
}
resb = resp.Bytes()
binary.LittleEndian.PutUint16(resb, uint16(len(resb)))
conn.Write(resb)
}
}
for {
conn, err := listener.Accept()
if err != nil {
break
}
go process(conn)
}
}
func process(conn net.Conn) {
buffer := make([]byte, 2000)
for {
_, err := io.ReadFull(conn, buffer[:2])
if err != nil {
// error
break
}
length := binary.LittleEndian.Uint16(buffer)
if length > 2000 {
// error too long
// consume ignore continue
// or disconnect
conn.Close()
return
}
// length only packet (keepalive)
if length <= 2 {
continue
}
_, err = io.ReadFull(conn, buffer[2:length-2])
if err != nil {
break
}
packetID := binary.LittleEndian.Uint16(buffer[2:])
handler, ok := handlers[packetID]
if ok {
handler(conn, buffer[:length])
} else {
fmt.Println("packet with no handler:", packetID)
}
}
}
</code></pre>
<ul>
<li>Is creating a new goroutine per accepted client worth it? I'm expecting about 500-1000 daily unique clients. </li>
<li>Will using the handler <code>handlers[300]</code> from multiple go routines result in a race condition? </li>
<li>Can the creation of packets be improved (DRY)?</li>
<li>Should I check the length of a <code>[]byte</code> every time I try to access with an index to avoid getting a panic?</li>
<li>How about the error handling?</li>
</ul>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T15:06:26.877",
"Id": "217080",
"Score": "1",
"Tags": [
"go",
"server"
],
"Title": "client handling of tcp server in go"
} | 217080 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.