body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I am calling a rest API as follows. I wonder if there are ways to improve/optimize the code. Should I add time-out or cancellation token? Any help would be appreciated. </p>
<pre><code>public static async Task<HttpResponseMessage> CallTestRazer(GameRequest gameRequest, string url)
{
//FormUrlEncodedContent content = null;
HttpResponseMessage response = null;
//Transform GameRequest into ProductDTO
var config = new MapperConfiguration(cfg => { cfg.CreateMap<GameRequest, ProductRequestDto>(); });
var iMapper = config.CreateMapper();
var productRequest = iMapper.Map<GameRequest, ProductRequestDto>(gameRequest);
if (url == "Product/")
{
try
{
//HTTPWebRequest
var request = (HttpWebRequest) WebRequest.Create("http://test.com/store/" + url);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
var keyValueContent = productRequest.ToKeyValue();
var formUrlEncodedContent = new FormUrlEncodedContent(keyValueContent);
var urlEncodedString = await formUrlEncodedContent.ReadAsStringAsync();
using (var streamWriter = new StreamWriter(await request.GetRequestStreamAsync()))
{
streamWriter.Write(urlEncodedString);
}
HttpWebResponse httpResponse = (HttpWebResponse) (await request.GetResponseAsync());
response = new HttpResponseMessage
{
StatusCode = httpResponse.StatusCode,
Content = new StreamContent(httpResponse.GetResponseStream()),
};
return response;
}
catch (Exception ex)
{
Console.WriteLine(ex);
throw ;
}
}
else
{
try
{
//HTTPWebRequest
var request = (HttpWebRequest)WebRequest.Create("http://test.com/store/" + url);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
var keyValueContent = gameRequest.ToKeyValue();
var formUrlEncodedContent = new FormUrlEncodedContent(keyValueContent);
var urlEncodedString = await formUrlEncodedContent.ReadAsStringAsync();
using (var streamWriter = new StreamWriter(await request.GetRequestStreamAsync()))
{
streamWriter.Write(urlEncodedString);
}
HttpWebResponse httpResponse = (HttpWebResponse)(await request.GetResponseAsync());
string json;
using (Stream responseStream = httpResponse.GetResponseStream())
{
json = new StreamReader(responseStream).ReadToEnd();
}
response = new HttpResponseMessage
{
StatusCode = httpResponse.StatusCode,
Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json"),
};
return response;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
</code></pre>
<p>Here is the ToKeyValues:</p>
<pre><code>public static IDictionary<string, string> ToKeyValues(this object metaToken)
{
if (metaToken == null)
{
return null;
}
JToken token = metaToken as JToken;
if (token == null)
{
return ToKeyValues(JObject.FromObject(metaToken));
}
if (token.HasValues)
{
var contentData = new Dictionary<string, string>();
foreach (var child in token.Children().ToList())
{
var childContent = child.ToKeyValues();
if (childContent != null)
{
contentData = contentData.Concat(childContent).ToDictionary(k => k.Key, v => v.Value);
}
}
return contentData;
}
var jValue = token as JValue;
if (jValue?.Value == null)
{
return null;
}
var value = jValue?.Type == JTokenType.Date
? jValue?.ToString("o", CultureInfo.InvariantCulture)
: jValue?.ToString(CultureInfo.InvariantCulture);
return new Dictionary<string, string> {{token.Path, value}};
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T14:58:15.050",
"Id": "441968",
"Score": "0",
"body": "What happened to the rest of the code? Can you post the entire method?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T15:11:15.070",
"Id": "441972",
"Score": "1",
"body": "added the whole method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T18:24:17.273",
"Id": "441999",
"Score": "0",
"body": "@Fake I am curious as to why you are using `HttpWebRequest` yet still using `HttpResponseMessage`? Why not `HttpClient`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T18:35:10.853",
"Id": "442000",
"Score": "0",
"body": "@Nkosi, I was using `httpclient` but I got errors (`System.Threading.Tasks.TaskCanceledException: A task was canceled`) when I was load testing. One of the forums, somebody suggested me to use `HttpWebRequest`. After changing the code, the error didn't show up anymore. Long story short, I am sending HttpResponseMessage from service layer to controller. I am still using this logic in my code."
}
] |
[
{
"body": "<p>Looking at the code I would try to, make the code a bit more robust. Experiences has thought me that a perfectly good working web service sometimes fails or times-out. \nTo capture this you can update your web.config and add the following 2 sections.</p>\n\n<p>You can use <a href=\"https://docs.microsoft.com/en-us/dotnet/framework/network-programming/enabling-network-tracing\" rel=\"nofollow noreferrer\">this section</a> to log Trace.WriteLine, beats Console.WriteLine as normally no one is looking at a console on a webservice and if you would the trafic would make this go so fast that you'd get an expert in speed reading </p>\n\n<pre><code><system.diagnostics> \n <trace autoflush=\"true\" indentsize=\"4\"> \n <listeners> \n <add name=\"file\" type=\"System.Diagnostics.TextWriterTraceListener\" initializeData=\"trace.log\"/> \n </listeners> \n </trace> \n</system.diagnostics>\n</code></pre>\n\n<p>You can filter what you like to capture with this section</p>\n\n<pre><code><configuration> \n <system.diagnostics> \n <sources> \n <source name=\"System.Net\" tracemode=\"includehex\" maxdatasize=\"1024\"> \n <listeners> \n <add name=\"System.Net\"/> \n </listeners> \n </source> \n <source name=\"System.Net.Cache\"> \n <listeners> \n <add name=\"System.Net\"/> \n </listeners> \n </source> \n <source name=\"System.Net.Http\"> \n <listeners> \n <add name=\"System.Net\"/> \n </listeners> \n </source> \n <source name=\"System.Net.Sockets\"> \n <listeners> \n <add name=\"System.Net\"/> \n </listeners> \n </source> \n <source name=\"System.Net.WebSockets\"> \n <listeners> \n <add name=\"System.Net\"/> \n </listeners> \n </source> \n </sources> \n <switches> \n <add name=\"System.Net\" value=\"Verbose\"/> \n <add name=\"System.Net.Cache\" value=\"Verbose\"/> \n <add name=\"System.Net.Http\" value=\"Verbose\"/> \n <add name=\"System.Net.Sockets\" value=\"Verbose\"/> \n <add name=\"System.Net.WebSockets\" value=\"Verbose\"/> \n </switches> \n <sharedListeners> \n <add name=\"System.Net\" \n type=\"System.Diagnostics.TextWriterTraceListener\" \n initializeData=\"network.log\"\n traceOutputOptions=\"ProcessId, DateTime\" \n /> \n </sharedListeners> \n <trace autoflush=\"true\"/> \n </system.diagnostics> \n</configuration>\n</code></pre>\n\n<p>Unfortunately I do not have the time to go over all your code however here are some thoughts, I added some comments.</p>\n\n<pre><code>//update to capture lower case url as well as speed up Comparison\nif (url.Equals(\"Product/\", StringComparison.OrdinalIgnoreCase))\n{\n int retryCount = 0;\n RETRY:\n try\n {\n retryCount++;\n\n //HTTPWebRequest works better with a URI then with a string as it would make the site more secure avoiding URL exploits\n var request = (HttpWebRequest)WebRequest.Create(\"http://test.com/store/\" + url);\n\n request.ContentType = \"application/x-www-form-urlencoded\";\n request.Method = \"POST\";\n\n var keyValueContent = productRequest.ToKeyValue();\n var formUrlEncodedContent = new FormUrlEncodedContent(keyValueContent);\n var urlEncodedString = await formUrlEncodedContent.ReadAsStringAsync();\n\n using (var streamWriter = new StreamWriter(await request.GetRequestStreamAsync()))\n {\n streamWriter.Write(urlEncodedString);\n }\n\n HttpWebResponse httpResponse = (HttpWebResponse)(await request.GetResponseAsync());\n\n response = new HttpResponseMessage\n {\n StatusCode = httpResponse.StatusCode,\n Content = new StreamContent(httpResponse.GetResponseStream()),\n };\n\n //make sure you release the resource\n httpResponse.Close();\n\n //make sure you dispose this!\n return response;\n\n }\n catch (Exception ex)\n {\n if (retryCount < 3)\n goto RETRY;\n\n Console.WriteLine(ex);\n throw;\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T10:29:52.273",
"Id": "442955",
"Score": "0",
"body": "It would be better if I add `Task.Delay(retryInterval).Wait(); ` some delay in case there might be some network issue or etc."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T07:23:08.407",
"Id": "227297",
"ParentId": "227181",
"Score": "2"
}
},
{
"body": "<p>Some quick remarks:</p>\n\n<ul>\n<li><p>There's no need to convert the <code>gameRequest</code> to a <code>productRequest</code>, so the three lines that do that should be inside the <code>if (url == \"Product/\")</code>.</p></li>\n<li><p>IMHO each of the <code>if</code>... <code>else</code> blocks should be a class of their own. Considering that significant parts of those blocks are identical, those separate classes should inherit from a base class where you have a method that receives the <code>url</code> and the <code>keyValueContent</code> as parameters, and returns a <code>httpResponse</code>.</p></li>\n<li><p>Don't do <code>Console.WriteLine(ex);</code>. Instead, <a href=\"https://github.com/NLog/NLog/wiki/Trace-target\" rel=\"nofollow noreferrer\">use <code>Trace</code> combined with NLog</a>, or <a href=\"https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.ilogger\" rel=\"nofollow noreferrer\">pass an <code>ILogger</code></a>.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T11:30:27.500",
"Id": "230030",
"ParentId": "227181",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T14:54:50.287",
"Id": "227181",
"Score": "3",
"Tags": [
"c#",
"asp.net-web-api"
],
"Title": "Calling rest API with HTTPWebRequest"
}
|
227181
|
<p>So I have a system that uses multiple threads to process data. These data could be processed individually but it would be better to process them in batches.</p>
<p>Lets assume we have a class <code>Data</code>, a class <code>OtherData</code> and a class <code>Processor</code> which implements <code>Function<List<Data>, List<OtherData>></code>.</p>
<p>To process objects of type <code>Data</code> from multiple threads I designed two classes <code>System</code> and <code>Evaluator</code>.</p>
<pre class="lang-java prettyprint-override"><code>public class System {
private final Evaluator evalThread;
private final Object sync = new Object();
private Function<List<Data>, List<OtherData>> processor;
private Map<Object, Data> inputMap;
private Map<Object, CompletableFuture<OtherData>> futureMap;
private List<Object> idList;
public System() {
processor = new Processor();
inputMap = new HashMap<>();
futureMap = new HashMap<>();
idList = new LinkedList<>();
evalThread = new Evaluator(processor, inputMap, futureMap, idList, sync);
Thread thread = new Thread(evalThread, "EvalThread");
thread.start();
}
public CompletableFuture<OtherData> process(Data data) {
Object id = new Object();
final CompletableFuture<OtherData> completableFuture = new CompletableFuture<>();
synchronized (sync) {
inputMap.put(id, data);
futureMap.put(id, completableFuture);
idList.add(id);
if (idList.size() >= 32) {
sync.notifyAll();
}
}
return completableFuture;
}
}
public class Evaluator implements Runnable {
private final Function<List<Data>, List<OtherData>> processor;
private final Map<Object, Data> inputMap;
private final Map<Object, CompletableFuture<OtherData>> futureMap;
private final List<Object> idList;
private final Object sync;
private AtomicBoolean keepRunning = new AtomicBoolean(true);
public Evaluator(Function<List<Data>, List<OtherData>> processor, Map<Object, Data> inputMap, Map<Object,
CompletableFuture<OtherData>> futureMap, List<Object> idList, Object sync) {
this.processor = processor;
this.inputMap = inputMap;
this.futureMap = futureMap;
this.idList = idList;
this.sync = sync;
}
@Override
public void run() {
synchronized (sync) {
while(keepRunning.get()) {
if (idList.size() > 0) {
List<Data> input = new LinkedList<>();
for (int i = 0; i < idList.size(); i++) {
input.add(inputMap.get(idList.get(i)));
}
List<OtherData> output = processor.apply(input);
for (int i = 0; i < idList.size(); i++) {
futureMap.get(idList.get(i)).complete(output.get(i));
}
idList.clear();
inputMap.clear();
futureMap.clear();
}
try {
sync.wait(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
</code></pre>
<p>My idea was that any one can call <code>process</code> with singular data but the data will (if there are enough) be processed together with other <code>Data</code> objects.</p>
<p>Any suggestions for improvements or are there systems in the Java-framework that would fit this task better?
Do you might see problems according to deadlocks, etc.?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T18:48:39.823",
"Id": "443289",
"Score": "0",
"body": "Can you explain the motivation for batching these tasks? If I read this correctly, you're running batches of 32, no more or less regardless of the request timing, which seems weird to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T10:43:11.700",
"Id": "443329",
"Score": "0",
"body": "That is not correct. If an call to `process` insertes the 32th element to be processed. The eveluation thread wil be awoken to process all scheduled data and then will call `sync.wait(20)`. So if in the next 20ms under 32 elements got scheduled, the thread will nontheless be awoken and process the scheduled data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T13:29:28.650",
"Id": "443342",
"Score": "0",
"body": "I think I understand it now. Still, can you talk about _why_ the tasks are better batched?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T06:45:54.253",
"Id": "443412",
"Score": "0",
"body": "Perhaps use Runnable instead of Thread"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T08:47:40.050",
"Id": "443417",
"Score": "0",
"body": "@ShapeOfMatter the data gets processed by an neuralnet which can faster evaluate multiple data at once compare to processing each data item on it own"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T09:05:22.493",
"Id": "443419",
"Score": "0",
"body": "@PPann the `Evaluator`-Class is an `Runnable` or what is it what you are suggesting"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T11:30:34.100",
"Id": "443429",
"Score": "0",
"body": "@Ackdari, yes, looks to me a better fit? what do you think?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T07:07:06.020",
"Id": "443520",
"Score": "0",
"body": "@PPann like I said, it _is_ a `Runnable`, so what change are you suggesting?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T23:28:36.920",
"Id": "443675",
"Score": "0",
"body": "I might not understand but your code seems overly complicated for what it does. If all you need to do is process elements every 20ms, then every 20ms dump the data processor into an `Executor` or `ExecutorService`. Seems like most of the complication goes away at that point."
}
] |
[
{
"body": "<p>Well, technically you should really post complete code and not have\nmissing definitions. Especially since <code>Data</code> and <code>OtherData</code> could\ninstead be generic type arguments perhaps, or interfaces, so that it's\nactually clear what's happening. I'm just gonna imagine they're\nbasically both <code>Object</code>s. Also <code>Processor</code> is undefined. If it was\nreally not important just pass it in as an argument to <code>System</code>, as it\nis, this is incomplete too.</p>\n\n<hr>\n\n<p>In <code>System</code> having a separate <code>idList</code> is pointless, the <code>inputMap</code>\nalready has the right size for implementing back pressure (I wanted to find a good definition, but right now at least Wikipedia doesn't have one under that term; basically if the input can grow unlimited, the system might not be able to catch up if processing takes too long and you might end up with a congested (read: out of memory) system).</p>\n\n<hr>\n\n<p>In <code>Evaluator</code>, <code>x.size() > 0</code> could be <code>!x.isEmpty()</code>, that might\npotentially be cheaper, but it also expresses intent a bit more clearly:\nThe check is really whether the map \"isn't empty\", not about how many\nitems are in the container exactly.</p>\n\n<p><code>InterruptedException</code> is for control flow,\n<a href=\"https://stackoverflow.com/questions/3976344/handling-interruptedexception-in-java\">don't just print a stack trace</a>.</p>\n\n<p>Also now that I read it, why's there three containers, <code>inputMap</code>,\n<code>futureMap</code> and <code>idList</code> all related to the same task? It'd be much\neasier if there was just a sequence of tuples, <code>Tuple<Input, Future></code>,\nand then work through them. Then replace the <code>List</code> with a\n<a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/BlockingQueue.html\" rel=\"nofollow noreferrer\"><code>BlockingQueue<Tuple<Input, Future>></code></a> and it's already supporting the\nwaiting / back pressure too. An <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ArrayBlockingQueue.html\" rel=\"nofollow noreferrer\"><code>ArrayBlockingQueue</code></a> could be used to\nlimit the number of elements, while a <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/LinkedBlockingQueue.html\" rel=\"nofollow noreferrer\"><code>LinkedBlockingQueue</code></a> could have\nan unbounded size (that's really not advisable though).</p>\n\n<p>Lastly instead of <code>keepRunning</code> a tombstone object could then be\ninserted to cancel the thread, then there's also no need for polling via\n<code>wait</code>. That is, insert a <code>new Tuple<>()</code> (same as the IDs at the\nmoment via <code>new Object()</code>) and when dequeuing from the input, check\nwhether this element was inserted, due to the object identity being\nunique that's then safe to do.</p>\n\n<p>So without spelling it all out, the main thread would look like this\nperhaps:</p>\n\n<pre><code>public void run() {\n while (true) {\n Tuple<Input, Future> tuple = input.take();\n if (tuple == tombstone) {\n return;\n }\n tuple.getFuture().complete(processor.apply(tuple.getInput()));\n }\n}\n</code></pre>\n\n<p>With some implementation of <code>Tuple</code> of course; a custom class would work\ntoo.</p>\n\n<hr>\n\n<p>For the other questions: I can't see it deadlocking right now, the check for 32 and the <code>notifyAll</code> are a bit odd though.</p>\n\n<p>Other tools in the Java tool set? Yes, I'd suggest starting with reading through the <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/package-summary.html\" rel=\"nofollow noreferrer\"><code>java.util.concurrent</code> namespace</a>. In particular the <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ExecutorService.html\" rel=\"nofollow noreferrer\"><code>ExecutorService</code></a> perhaps.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T21:29:48.250",
"Id": "227811",
"ParentId": "227187",
"Score": "1"
}
},
{
"body": "<p>Use a <code>CyclicBarrier</code> with only the neural-net thread waiting, and decrement it after adding an item to the queue (which should probably be a <code>ConcurrentLinkedQueue</code>). Then it will automatically trigger after every 32 entries, at which point it should pop exactly 32 entries from the head of the queue (an operation that won't block if it's the queue's only consumer).</p>\n\n<p>You can probably eliminate the <code>synchronized</code> block in <code>process</code> if you also replace both <code>HashMap</code> instances with <code>ConcurrentHashMap</code>. This will improve performance when <code>process</code> is called from more than a small constant number of threads (probably on the order of 2 or 3).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T01:33:01.257",
"Id": "228819",
"ParentId": "227187",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "227811",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T16:45:05.063",
"Id": "227187",
"Score": "5",
"Tags": [
"java",
"multithreading"
],
"Title": "Process multiple request from different threads in batches on one processing thread"
}
|
227187
|
<p>I have situation where user has got options to select, and after selected any option will appear next options. For example :
1 - Add car
2 - Add motorcycle.
3 - Print cars
4 - Print motorcycles</p>
<p>And after selected for example "1" console will show options like :
1 - Add passenger car,
2 - Add light commercial car.
At this moment i have two enum classes in two separated files that has got almost the same code inside, and same methods <code>createFromInt()</code> which returns Options according to int provided by the user, and <code>toString()</code>.Exmple one of two enums(The second one is almost the same except the fields) : </p>
<pre><code>enum Option {
ADD_CAR(0,"Add car"),
ADD_MOTORCYCLE(1,"Add motorcycle"),
PRINT_CARS(2,"Print cars"),
PRINT_MOTORCYCLES(3, "Print motorcyces"),
private int value;
private String description;
Option(int value, String description) {
this.value = value;
this.description = description;
}
@Override
public String toString() {
return value + "-" + description;
}
public static Option createFromInt(int option) throws NoSuchOptionException {
try {
return Option.values()[option];
}catch (ArrayIndexOutOfBoundsException ex) {
throw new NoSuchOptionException("Brak opcji o ID: " + option);
}
}
</code></pre>
<p>}</p>
<p>I was just wondering is it corectly locate these enums in two files or exists any more elegant way for example one file with two enums , or nested enums (if something like that at all exists). </p>
|
[] |
[
{
"body": "<p>At first, I think you don't need the <code>value</code> field. Indeed, as shown in <code>createFromInt</code>, you refer to enum values with their position (<code>Option.values()[option]</code>).</p>\n\n<p>I suggest the following refactoring.</p>\n\n<pre><code>enum Option {\n ADD_CAR(\"Add car\"),\n ADD_MOTORCYCLE(\"Add motorcycle\"),\n PRINT_CARS(\"Print cars\"),\n PRINT_MOTORCYCLES(\"Print motorcycles\");\n\n private String description;\n\n Option(String description) {\n this.description = description;\n }\n\n @Override\n public String toString() {\n return this.ordinal() + \"-\" + description;\n }\n\n public static Option getFromIndex(int optionIndex) throws NoSuchOptionException {\n if (optionIndex >= 0 && optionIndex < values().length) {\n return Option.values()[optionIndex];\n }\n throw new NoSuchOptionException(\"Brak opcji o ID: \" + optionIndex);\n }\n}\n</code></pre>\n\n<p>I prefer <code>getFromIndex</code> because the argument is an index or a <em>value</em> and you don't create new instances of the enum.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T03:51:38.730",
"Id": "442311",
"Score": "1",
"body": "You should protect against negative `optionIndex` values in `getFromIndex()`, not just too large values."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T10:28:11.023",
"Id": "227216",
"ParentId": "227191",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T18:23:52.103",
"Id": "227191",
"Score": "2",
"Tags": [
"java",
"console",
"enum"
],
"Title": "The most elegant way to locate two enums"
}
|
227191
|
<p>Below is my solution to LC #494: Target Sum (given a list of numbers and a target integer, find out how many different ways the numbers can be subtracted from the total sum to result in the target sum).</p>
<p>There's one very common pattern in Python here that I question, and it's the use of <code>for num in nums[1:]:</code>. Iterating over <code>nums[1:]</code> is very explicit and readable, but it results in the creation of a whole new array when that really isn't our intention. That also means additional wasted time and wasted memory.</p>
<p>I used to always do <code>for i in range(1, len(nums)):</code> in these situations, but I see most other people using <code>nums[1:]</code>. Would love to hear thoughts on that.</p>
<p>And if there's a cleaner way to write this without having to initialize the <code>counts</code> hash from <code>nums[0]</code> separately from the body of the loop, that'd be great too. I couldn't think of a cleaner way.</p>
<pre class="lang-py prettyprint-override"><code>class Solution:
def findTargetSumWays(self, nums: List[int], S: int) -> int:
counts = {nums[0]: 1, -nums[0]: 1}
if nums[0] == 0:
counts[0] += 1
for num in nums[1:]:
keys = list(counts)
new = {}
for key in keys:
if key + num not in new:
new[key + num] = 0
if key - num not in new:
new[key - num] = 0
new[key + num] += counts[key]
new[key - num] += counts[key]
counts = new
return counts[S] if S in counts else 0
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p><code>for num in nums[1:]</code> is the prefered way to iterate over a partition of an array; if you are worried about performance, it actually is faster, because accessing by index is more expensive in python than copying then iterating values (you can play with snippets of timeit to verify that claim, but I'm fairly sure of that - accessing by index in python involves way more checks and operations than it does in a language like C).</p>\n\n<p>The performance issue with your program, if there is one, isn't there. The copy is just done once in the outter loop, and since it is repeated by num your inner loop is way more costy. Mind this: since every iteration can in the worst case double the number of items in <code>keys</code>, your program is actually of complexity <code>O(2^n)</code> where n is the array length.</p>\n\n<p>In a matter of using more efficient structures you can also use <code>Counter</code> from <code>collections</code> that saves a bit of verbosity (it has zero as default value) and computation time (it is optimized C structure).</p>\n\n<p>Without optimizing the algorithm, which I believe is part of the challenge :</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from collections import Counter\n\nclass Solution:\n\n def findTargetSumWays(self, nums: List[int], S: int) -> int:\n counts = Counter()\n counts[-nums[0]] += 1\n counts[nums[0]] += 1\n for num in nums[1:]:\n new = Counter()\n for key in counts.keys():\n new[key + num] += counts[key]\n new[key - num] += counts[key]\n counts = new\n return counts[S]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T00:15:24.760",
"Id": "442029",
"Score": "0",
"body": "Your base solution is not bad, adding a small optimization I was able to best 87.82% of submitted solutions in run time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T12:54:29.377",
"Id": "442099",
"Score": "0",
"body": "Can I ask what your optimization was? Also, what do you think about using `collections.defaultdict(int)` instead of `collections.Counter` (since we're only using the default value feature)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T18:26:42.177",
"Id": "442149",
"Score": "0",
"body": "@user107870 I believe Counter is more optimized because it's less generic but I have no idea if it really is. The optimization was 1- sort nums in descending order and 2- remove keys in counts if they are distant of S of more than the sum of remaining nums."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T23:34:11.807",
"Id": "227199",
"ParentId": "227193",
"Score": "2"
}
},
{
"body": "<p>List objects are iterables. A <code>for</code> loop implicitly calls <code>iter()</code> on the list, but you can do it yourself, too.</p>\n\n<pre><code>nums_iter = iter(nums)\nnum0 = next(nums_iter)\nfor num in nums_iter:\n # ...\n</code></pre>\n\n<p>The list is not copied, and the <code>for</code> loop will begin with the second item, as required.</p>\n\n<p>However, this is far less clear than <code>for num in nums[1:]:</code></p>\n\n<hr>\n\n<p>Much clearer is to leverage <code>itertools</code>, specifically <a href=\"https://docs.python.org/3/library/itertools.html?highlight=islice#itertools.islice\" rel=\"nofollow noreferrer\"><code>itertools.islice()</code></a>:</p>\n\n<pre><code>for num in islice(nums, 1, None):\n # ...\n</code></pre>\n\n<p>However, <code>islice()</code> also allows a <code>step</code> greater than one, which means you probably lose performance to the code that supports this unneeded capability.</p>\n\n<p>Copying the array might be a smaller performance penalty. You’ll want to profile each approach, and evaluate the trade off between readability and performance.</p>\n\n<hr>\n\n<p>Speaking of unnecessary copies:</p>\n\n<pre><code>keys = list(counts)\n</code></pre>\n\n<p><code>counts</code> is not changed in the loop below, so memorizing the list of keys is an unnecessary copy. You could simply use:</p>\n\n<pre><code>for key in counts:\n # ...\n</code></pre>\n\n<hr>\n\n<p><code>counts[key]</code> is an unnecessary lookup. And you are doing it twice. Better is to retrieve the value with the key during the iteration process. </p>\n\n<pre><code>for key, val in counts.items():\n # ...\n</code></pre>\n\n<hr>\n\n<p>And, as mentioned in @ArthurHavlicek’s answer, use <code>collections.Counter</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T12:38:03.447",
"Id": "442096",
"Score": "0",
"body": "After reading docs, I can see `islice` might be useful if we were using a single iterator in multiple contexts, but is it adding anything over `range` / `xrange` when we're just doing a single loop through?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T15:51:27.883",
"Id": "442260",
"Score": "0",
"body": "The documentation says “Roughly equivalent to”, and then a blob of Python code. Don’t get fooled; it **is not implemented in Python**. It will be implemented directly in C, (assuming CPython), and may approach the performance of looping over the list directly, but without the penalty of copying the list."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T05:45:24.537",
"Id": "227209",
"ParentId": "227193",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T19:38:12.380",
"Id": "227193",
"Score": "3",
"Tags": [
"python",
"algorithm",
"python-3.x",
"programming-challenge"
],
"Title": "LeetCode #494: Target Sum (Python)"
}
|
227193
|
<p>Below is the database design that I created for a basic image sharing social website.</p>
<ul>
<li>When a user signup his username, email, password save in <code>users</code></li>
<li>When the user setup his profile his information will be saved in <code>profile</code> against <code>username</code></li>
<li>When the user create a post it will be saved in <code>posts</code> against <code>username</code></li>
<li>When a comment is made on a post it will be stored in <code>comments</code> against <code>postid</code>.</li>
</ul>
<pre><code>-- phpMyAdmin SQL Dump
-- version 4.9.0.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Aug 31, 2019 at 08:46 AM
-- Server version: 10.4.6-MariaDB
-- PHP Version: 7.3.8
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `pakart`
--
-- --------------------------------------------------------
--
-- Table structure for table `comments`
--
CREATE TABLE `comments` (
`commentid` int(10) UNSIGNED NOT NULL,
`commenttext` text NOT NULL,
`commenttime` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`postid` int(10) UNSIGNED NOT NULL,
`username` varchar(25) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `posts`
--
CREATE TABLE `posts` (
`postid` int(10) UNSIGNED NOT NULL,
`username` varchar(25) NOT NULL,
`posttitle` varchar(50) DEFAULT NULL,
`posttag` varchar(25) DEFAULT NULL,
`imageurl` varchar(255) NOT NULL,
`posttime` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`likecount` int(10) UNSIGNED DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `profile`
--
CREATE TABLE `profile` (
`profileid` int(10) UNSIGNED NOT NULL,
`username` varchar(25) NOT NULL,
`firstname` varchar(25) NOT NULL,
`lastname` varchar(25) NOT NULL,
`gender` char(1) NOT NULL,
`dateofbith` date NOT NULL,
`pictureurl` varchar(255) NOT NULL,
`bio` text NOT NULL,
`joindate` date NOT NULL,
`rating` int(10) UNSIGNED DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`username` varchar(25) NOT NULL,
`usermail` varchar(50) NOT NULL,
`userpass` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `comments`
--
ALTER TABLE `comments`
ADD PRIMARY KEY (`commentid`),
ADD KEY `postid` (`postid`),
ADD KEY `username` (`username`);
--
-- Indexes for table `posts`
--
ALTER TABLE `posts`
ADD PRIMARY KEY (`postid`),
ADD UNIQUE KEY `imageurl` (`imageurl`),
ADD KEY `username` (`username`);
--
-- Indexes for table `profile`
--
ALTER TABLE `profile`
ADD PRIMARY KEY (`profileid`),
ADD UNIQUE KEY `pictureurl` (`pictureurl`),
ADD KEY `username` (`username`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`username`),
ADD UNIQUE KEY `usermail` (`usermail`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `comments`
--
ALTER TABLE `comments`
MODIFY `commentid` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `posts`
--
ALTER TABLE `posts`
MODIFY `postid` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `profile`
--
ALTER TABLE `profile`
MODIFY `profileid` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `comments`
--
ALTER TABLE `comments`
ADD CONSTRAINT `Comments_ibfk_1` FOREIGN KEY (`postid`) REFERENCES `posts` (`postid`),
ADD CONSTRAINT `Comments_ibfk_2` FOREIGN KEY (`username`) REFERENCES `users` (`username`);
--
-- Constraints for table `posts`
--
ALTER TABLE `posts`
ADD CONSTRAINT `Posts_ibfk_1` FOREIGN KEY (`username`) REFERENCES `users` (`username`);
--
-- Constraints for table `profile`
--
ALTER TABLE `profile`
ADD CONSTRAINT `Profile_ibfk_1` FOREIGN KEY (`username`) REFERENCES `users` (`username`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
</code></pre>
<p>I need recommendations related <code>datatypes</code>, <code>data redundancy</code> and <code>normalization</code> if any.
<a href="https://i.stack.imgur.com/WonM2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/WonM2.png" alt="Database Design"></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T05:14:29.047",
"Id": "442047",
"Score": "5",
"body": "Since this is Code Review, please repost this question in code form (`CREATE TABLE` statements)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T07:00:18.683",
"Id": "442059",
"Score": "5",
"body": "@200_success i have added Database Export."
}
] |
[
{
"body": "<p>By default you will have a numeric userId as well. Using the numeric userId rather than the username will probably perform better and reduce the size of the other tables. The userId will be a foreign key in 3 of the 4 tables and you need to consider the restraints that apply in each of the tables. </p>\n\n<p>Naming a picture in the user's profile <code>pictureurl</code> could be confusing, I originally thought there were 2 instances of the post image URL. Any URL fields should probably be at least 1024 characters.</p>\n\n<p>Decide what the most important fields in the profile are and put them in the table. You can use a JOIN to get all of the fields in the profile together, but by default I doubt the the user will use all the fields in the profile. Limit the size of the BIO, they shouldn't need any more than 1024 characters for the bio.</p>\n\n<p>Limit the size of the comment text.</p>\n\n<p>You may want to have a separate table of tags and include the tagId instead of the tag text. Post titles and post tags may require a larger size then is allowed for.</p>\n\n<p>In the profile what is the rating and how is it calculated? You may want to have a floating point value rather than an integer value.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T20:48:52.153",
"Id": "442162",
"Score": "2",
"body": "That first paragraph is the most important one. Picking the correct PK allows you to model against future changes. If UserName is a PK, how would you handle when a user changes their UserName?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T17:28:35.950",
"Id": "227225",
"ParentId": "227194",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "227225",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T20:11:56.640",
"Id": "227194",
"Score": "7",
"Tags": [
"beginner",
"sql",
"mysql",
"database"
],
"Title": "Database design for a very basic image-sharing social website"
}
|
227194
|
<p>I am trying to split and assign the url's to the variable, I am getting the desired result but I know there is a way where I can improvise the current code. </p>
<p><strong>JSON FILE</strong> </p>
<pre><code>{
"Result": [
"Url::Link::Url1",
"Url::Link::Url2",
"Url::Link::Url3",
"Url::Link::Url4",
"Url::Link::Url5",
"Url::Link::Url6",
"Url::Link::Url7"
],
"Record": [
"Record::Label::Music1",
"Record::Label::Music2",
"Record::Label::Music3"
],
}
</code></pre>
<pre><code>import requests
import json
url = "http:mywebsite.com"
headers = {
'User-Agent': "PostmanRuntime/7.15.2",
'Accept': "*/*",
'Cache-Control': "no-cache"
}
result= requests.get("GET", url, headers=headers).json()
url1 = []
url2 = []
url3 = []
for i in result['Result'][0:1]:
url1.append(i.split('::')[2])
for i in result['Result'][1:2]:
url1.append(i.split('::')[2])
for i in result['Result'][2:3]:
url1.append(i.split('::')[2])
</code></pre>
<p><strong>Output</strong><br>
url1=Url1<br>
url2=Url2<br>
... </p>
|
[] |
[
{
"body": "<p>As long as there's nothing special about the <em>n</em>th URL, you can just store the URLs in one list:</p>\n\n<pre><code>urls = []\n\nfor result_string in result[\"Result\"]:\n url = result_string.split(\"::\")[2]\n urls.append(url)\n</code></pre>\n\n<p>If there is something unique information you want to capture about the <em>n</em>th URL, you could store the URLs in a dictionary to map the URL to its type.</p>\n\n<pre><code>def url_type(n):\n \"\"\"returns the type of url given its index n in the response\"\"\"\n\n #example\n if n == 1:\n return 'url-type-a'\n\n return 'url-type-b' \n\n\nurls = {\n \"url-type-a\": [],\n \"url-type-b\": []\n}\n\n\nfor i, result_string in enumerate(result[\"Result\"]):\n\n url = result_string.split(\"::\")[2]\n urls[url_type(i)].append(url)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T21:52:02.733",
"Id": "227196",
"ParentId": "227195",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T20:31:13.557",
"Id": "227195",
"Score": "1",
"Tags": [
"python",
"json"
],
"Title": "Python nested json parsing and splitting the values"
}
|
227195
|
<p>Lets say I have the following interfaces</p>
<pre><code>interface IRealm
{
Tile GetTile(int x, int y);
bool SetTile(int x, int y, Tile tile);
}
interface IRealmSize
{
int TilesWide { get; }
int TilesHigh { get; }
}
</code></pre>
<p>The intefaces are separate as I have both infinite realms with no size and bounded realms with a fixed size.
One class uses these realms, but requires that the realm has a fixed size.</p>
<pre><code>class RealmRenderer<T> where T : IRealm, IRealmSize
{
public RealmRenderer(T realm) { ... }
}
</code></pre>
<p>Is there any drawbacks to doing it like this?</p>
<p>I could see an alternative like the following</p>
<pre><code>interface IBoundedRealm : IRealm, IRealmSize { /* intentionally empty */ }
class RealmRenderer
{
public RealmRenderer(IBoundedRealm realm) { ... }
}
</code></pre>
<p>But this creates a stricter requirement for the various realm types to implement this specific interface just to satisfy the renderer, where using generics leaves this specific requirement out of the realm implementation.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T00:15:55.683",
"Id": "442030",
"Score": "1",
"body": "While your question is quite interesting, unfortunately it is off-topic for code review. We can only review working code here and this is a design question that is hypothetical. There is a stack exchange site called Software Engineering that does look at software design but I don't know if it would be on topic there either (https://softwareengineering.stackexchange.com/). We would love to review any working code that you care to show us. https://codereview.stackexchange.com/help/dont-ask https://codereview.stackexchange.com/help/how-to-ask"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T00:29:01.703",
"Id": "442031",
"Score": "0",
"body": "Ah, I am very sorry. The working code would be quite a lot to put up, which is why I wanted to focus on the question the design itself. I'll look at the other site. Should I do anything to close this or just wait for enough close votes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T13:17:40.927",
"Id": "442100",
"Score": "1",
"body": "*The code **is** the design* - CR posts accept double the maximum of any other SE site (60K vs 30K chars), so if your project is modularized (seems to be), then it should be possible to post a set of related classes & interfaces, and then reviewers can (and will) provide feedback on every aspect of it, *including* any smelly interface or generics usage. e.g. you could have `IRealm`, `IRealmSize`, one or two implementations, a base class, and the renderer, and then reviewers would have something to chew on ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T13:18:46.900",
"Id": "442101",
"Score": "0",
"body": "FWIW the alternative empty interface at the bottom is a *marker interface*, and *that* is generally considered a code smell."
}
] |
[
{
"body": "<p>Having multiple interface constraints on a single generic parameter isn't a code smell; it can make sense in a number of cases. </p>\n\n<p>However, for the two interfaces you mention, does it make sense to have an IRealmSize that isn't part of an IRealm? It may make be more appropriate to use:</p>\n\n<pre><code>interface IBoundedRealm : IRealm\n{\n int TilesWide { get; }\n int TilesHigh { get; }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T00:29:40.703",
"Id": "442032",
"Score": "0",
"body": "That was a small mistake on my part, I do actually have some more interfaces. I was trying to make a small example, but now I see that I forgot the part that actually prompted me to do the setup with generics. Sadly, it appears that this question is off topic for the site, so I'll hold off updating until I see if it gets closed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T00:42:05.430",
"Id": "442033",
"Score": "0",
"body": "I posted the question on the sister site, as it appears to be on topic there: https://softwareengineering.stackexchange.com/questions/396767/is-using-generics-like-this-a-type-of-code-smell"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T06:19:48.993",
"Id": "442052",
"Score": "3",
"body": "@WilliamMariager unless you show people the real API all _reviews_ on every site will end up in you saying _I do actually have some more interfaces._ - do everyone a favor and do not change your code, both here and there if you want to get realistic and useful feedback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T11:07:05.437",
"Id": "442094",
"Score": "0",
"body": "@t3chb0t understood."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T00:17:01.810",
"Id": "227201",
"ParentId": "227200",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T23:57:09.407",
"Id": "227200",
"Score": "-2",
"Tags": [
"c#",
"design-patterns"
],
"Title": "Is using generics like this a type of code smell?"
}
|
227200
|
<p>I wrote a little bash script that displays the transaction info in json:</p>
<pre class="lang-bsh prettyprint-override"><code>#!/usr/bin/env bash
set -e
set -o errexit
function process_block() {
date --rfc-3339=ns
bhash=${1:-$(bitcoin-cli getbestblockhash)}
block=$(bitcoin-cli getblock $bhash)
pbhash=$(echo "$block" | jq -r .previousblockhash)
height=$(echo "$block" | jq -r .height)
echo "height: $height"
nTx=$(echo "$block" | jq -r .nTx)
echo "$nTx transactions"
Tx=$(echo "$block" | jq -r .tx[])
IFS=$'\n'
for txhash in $Tx; do
txjson=$(bitcoin-cli getrawtransaction $txhash 1 $bhash)
addresses=$(echo "$txjson" | jq -r '.vout[].scriptPubKey | select(.type == "pubkeyhash") | .addresses | .[]')
for a in $addresses; do
if [[ $a == ${2} ]]; then
echo "$txjson"
fi
done
done
process_block $pbhash ${2}
}
process_block "" ${1}
</code></pre>
<p>Can be used as:</p>
<pre class="lang-bsh prettyprint-override"><code>./btc.sh 1...
</code></pre>
<p>I ran bitcoind in pruned mode to get a blockchain. I downloaded the latest snapshot like this:</p>
<pre class="lang-bsh prettyprint-override"><code>aria2c http://utxosets.blob.core.windows.net/public/$(curl https://raw.githubusercontent.com/btcpayserver/btcpayserver-docker/master/contrib/FastSync/utxo-sets | grep -F mainnet | tail -n 1 | grep -Po utxo.*)
</code></pre>
<p>The only problem is that it is really slow. It takes about a minute to process about 1k transactions. Any advice how the things could be speed up?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T20:43:54.977",
"Id": "442161",
"Score": "0",
"body": "I am currently rebuilding the whole blockchain with **-txindex** option. But I don't know how many days/weeks it can take."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T16:40:25.717",
"Id": "442428",
"Score": "0",
"body": "Wait a second. Actually I was rebuilding with **-reindex** option and **-txindex** is incompatible with prune mode. I interrupted the process to check it out, then resumed it and it is started from the beginning of the blockchain basically ruining 3 days of servers's work. I guess I have to wait till the end without any interruption with **-reindex** option to see if it will help.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T16:49:20.217",
"Id": "442432",
"Score": "0",
"body": "Nah. It is unlikely it will help anyhow w/o txindex. I should probably find other ways how to speed up my explorer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T15:08:15.257",
"Id": "442586",
"Score": "0",
"body": "Alright. We got getblock with verbosity = 2 here. :) https://github.com/bitcoin/bitcoin/issues/12651#issuecomment-527418478"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T18:11:06.150",
"Id": "227202",
"Score": "2",
"Tags": [
"performance",
"json",
"bash",
"cryptocurrency",
"blockchain"
],
"Title": "Bash bitcoin blockchain explorer"
}
|
227202
|
<p>I have a large file that I want to search for text as fast as possible. There is not a memory contraint, so I am loading the entire file into memory so that I can use the rayon parallelism crate in order to improve performance (so I don't get blocked by an IO thread). I have the following code (I've indented the benchmark lines to stand out from the functional code):</p>
<pre><code>extern crate rayon;
use rayon::prelude::*;
use std::io;
use std::io::prelude::*;
use std::fs::File;
use std::time::Instant;
fn main() -> io::Result<()> {
let now = Instant::now();
let mut f = File::open("words_huge.txt")?;
let time_to_open = now.elapsed().as_millis();
let mut whole_file = String::new();
let n = f.read_to_string(&mut whole_file)?;
let time_to_read = now.elapsed().as_millis() - time_to_open;
let mut lines = whole_file.par_lines(); // Split it into lines
let time_to_line_split = now.elapsed().as_millis() - time_to_read;
let mut results: Vec<&str> = lines.filter(|l| l.contains("test")).collect();
let time_to_process = now.elapsed().as_millis() - time_to_line_split;
for r in results
{
println!("{}", r);
}
let time_to_print = now.elapsed().as_millis() - time_to_process;
println!("Time to open: {}", time_to_open);
println!("Time to read: {}", time_to_read);
println!("Time to line split: {}", time_to_line_split);
println!("Time to process: {}", time_to_process);
println!("Time to print: {}", time_to_print);
println!("Total time elapsed: {}", now.elapsed().as_millis());
Ok(())
}
</code></pre>
<p>Please provide feedback on how this could be further optimized. Could I be performing fewer memory operations in the name of speed? Is there too much overhead to threading here? Note that words_huge.txt is a text file with over 10 million lines of text from the English dictionary repeated over about 20 times.</p>
<p>Note: This is going to be machine and even run-dependent, but the current version above does execute quite fast... processing time takes 172-185ms on my machine... Pretty good for 10 million lines! But can we do better?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T21:04:37.973",
"Id": "442298",
"Score": "1",
"body": "You are processing 10 million lines faster then the human reaction time. Come back and ask for optimization help when you have task that you actually have to wait for."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T02:50:27.187",
"Id": "227204",
"Score": "1",
"Tags": [
"performance",
"strings",
"multithreading",
"rust",
"search"
],
"Title": "Fast text search in Rust"
}
|
227204
|
<pre><code>class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
longest = ''
max_len = 0
for key,value in enumerate(s):
if value in longest:
longest = longest[longest.index(value)+1:] + value
else:
longest+=value
max_len = max(max_len,len(longest))
return max_len
</code></pre>
<p>Here is my solution for leetcode's "longest-substring-without-repeating-characters question". I don't quite understand why my time complexity is so efficient (99% out of all python submissions). Since strings are immutable in python, assuming a strength of length n, won't my algorithm be <span class="math-container">$$ 1+2+3+...n-1+n = O(n^2)$$</span> time? But the optimal solution is on <span class="math-container">\$O(n)\$</span> yet the runtime from the testcases says my solution is just as good as the optimal one provided?Am I missing something. Also I am having a hard time proving the space complexity for my solution as well.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T06:19:59.763",
"Id": "442053",
"Score": "0",
"body": "Since you only use `value`, you could even use `range` instead of `enumerate` (I doubt that this will improve performance though)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T07:53:13.407",
"Id": "442060",
"Score": "0",
"body": "It could be there is no/few big strings in test cases. This would make the simpler algorithm more efficient because they are faster on small entries than an algorithm optimized for big entries."
}
] |
[
{
"body": "<p>The linearity of your approach is due to the fact that your <code>longest</code> could never be longer than the size of the alphabet (otherwise it'd have a duplicate for sure). It means that your code runs at <span class=\"math-container\">\\$O(N * A)\\$</span>, where <span class=\"math-container\">\\$N\\$</span> is a length of the string, and <span class=\"math-container\">\\$A\\$</span> is a size of alphabet. Since the latter is a constant, you may safely take it out of the big-O, yielding <span class=\"math-container\">\\$O(N)\\$</span>.</p>\n\n<p>The asymptotic constant is still a little bit too large (I don't know what alphabet is used in the test cases, but it is safe to assume at least 26), so there is a room for improvement. You correctly noticed that the immutability of the strings may hurt performance; try to get rid of them. A most obvious approach is to preallocate a list (of the alphabet size), and use it as a circular buffer.</p>\n\n<p>In fact, even that is suboptimal. Try to get rid of the explicit buffer at all (hint: two indices into the original string).</p>\n\n<p>It also <em>may</em> be beneficial to keep a dictionary indexed by letters currently present in the buffer with the values being their corresponding indices. This way you can do a constant time lookup rather than linear search in the buffer. Keep in mind however that such a dictionary may itself be costly; I expect it to improve performance if the alphabet is quite large. Try and profile it.</p>\n\n<p>As for the code, it is simple and clean. Not much to say.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T20:12:28.303",
"Id": "442156",
"Score": "0",
"body": "ah, I oversaw the length <=26. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T15:36:20.550",
"Id": "227221",
"ParentId": "227205",
"Score": "2"
}
},
{
"body": "<p>Maybe the code is time efficient because you are lucky. Maybe the code is time efficient because you have good intuitions. This review is about moving toward luck playing less of a role in the performance of your code and/or reaching good intuitive conclusions by a more formal path.</p>\n<h2>Top Down</h2>\n<p>The code seems to be written bottom up from loops rather than top down from the specification. That makes it hard to reason about how it solves the problem. <a href=\"https://channel9.msdn.com/Events/Build/2014/3-642\" rel=\"nofollow noreferrer\">Leslie Lamport recommends starting with a specification</a>.</p>\n<pre><code>f (arrayOfCharacters: I, alphabet: A) -> positiveInteger: Result\nResult = Max(S)\nS = Sequence of positiveIntegers (S0,S1...Sk):\n where Sk is the length of the k'th substring of I\n</code></pre>\n<p>This is enough to reason about the <em>best</em> case performance. Let <code>N = I.size</code>. If all the characters in I are the same then there are only N-1 <strong>character lookups</strong> and:</p>\n<pre><code>Result = 1\nS.size = I.size\n</code></pre>\n<p>The running time depends on the character of <strong>character lookups</strong>.</p>\n<h2>The intution for O(n<sup>2</sup>)</h2>\n<p>It is possible to have an input <code>I</code> that takes <code>I.length^2</code> time to run.</p>\n<pre><code>A is the alphabet\nI is the input stream of characters\nN is the length of I\nA has more than N characters.\nEach character in I is unique.\n</code></pre>\n<p>In that case the longest substring without repeating characters is I and each character of I has to be compared against every other character.</p>\n<h2>On the other hand</h2>\n<p>The alphabet <code>A</code> is bounded. That's what makes it an alphabet and the input <code>I</code> a string. For character <em>C<sub>i</sub></em> in input I, the maximum number of comparisons is the size of the alphabet <code>A</code>. The size of the alphabet is a constant and the worst case runtime is:</p>\n<pre><code>Min(N*N, N*A.size)\n</code></pre>\n<p>The worst case is <code>N*A.size</code> when <code>N < A.size</code>. In Big-O notation though <code>N*A.size</code> is O(n) implementing an O(n<sup>2</sup>) may be better when the <code>A.size</code> is large. For example when <code>A</code> is the set of <em>all possible</em> unicode codepoints (1,114,112) and <code>N</code> is 1000.</p>\n<h2>Going further</h2>\n<p>The actual number of <em>assigned</em> unicode codepoints (<300,000) is less than the set of <em>all possible</em> unicode codepoints (1,114,112). Using assigned rather than possible code points might improve speed about 3x.</p>\n<p>Similarly, the actual number of unique unicode codepoints when <code>I.length = 1000</code> is less than 1001. So the worst case for <code>I</code> becomes:</p>\n<pre><code>Min(N*N, N*A.size, N*I.unique.size)\n</code></pre>\n<p><code>I.unique.size</code> is not larger than <code>A.size</code>. But because <code>I.unique.size</code> is of order <code>N</code> the Big-O is O(n<sup>2</sup>). Again, O(n<sup>2</sup>) may be better than guaranteed O(n). It will be faster when the cost of determining uniques is less than the cost of scanning the entire alphabet for each substring. Or from a practical standpoint when benchmarks against actual data show it is faster. That's engineering versus computer science. Without actual inputs <code>I</code> and without knowing the alphabet for <code>A</code> we have to go with computer science.</p>\n<h2>Recursion</h2>\n<p>The question mentions proofs. Often, proofs are inductive. Because there is a mapping between induction and recursing a list, a recursive procedure may be easier to reason about for a person comfortable with proofs. In particular recursion can be applied to the generation of the list of substring lengths <code>S</code>:</p>\n<pre><code># List(character), List(Int), Substring -> List(Int)\ndefine Loop(I, S, substring)\n # no more input\n if I = []\n return S\n # end of substring\n else if I.first in substring \n Loop(I.rest,\n S.append(substring.size),\n New substring)\n else\n Loop(I.rest,\n S,\n substring.append(I.first)\nend define\n</code></pre>\n<p>This makes the top level call:</p>\n<pre><code># List(character) -> Integer\ndefine maxSubstringLength(I)\n return max(Loop(I.rest, [], New Substring.append(I.first)))\nend define\n</code></pre>\n<p>The top level call looks a lot like the top level of the specification and the Loop looks a lot like the interior of the specification. It's somewhat obvious that both run in O(n) time in and of themselves.</p>\n<h2>Localizing bottlenecks</h2>\n<p>All of the variation in performance is the implementation of <code>in substring</code> within <code>Loop</code> at:</p>\n<pre><code> # end of substring\n else if I.first in substring\n</code></pre>\n<p>And we are free to implement it whatever way works best for whatever particular combination of data and alphabet we are actually dealing with. For example <code>New Substring</code> might return <code>""</code> or it might return a bitmap of <code>A.size</code> bits or it might return a balanced tree of 32 width or it might return a <code>key:value</code> store etc. Again, it's software engineering versus computer science.</p>\n<h2>Review Points</h2>\n<ul>\n<li>Reasoning about the problem first may facilitate writing code that is easier to reason about.</li>\n<li>As pointed out the accepted answer, attention to features of the specific problem domain (alphabets) is likely to provide better insights into performance than a generic solution.</li>\n<li>Tweeking performance requires engineering research. The memory requirement for <code>in substring</code> can be reduced at least to <code>A.size</code> bits when the membership test is based on a bitmap. In ASCII that's fifteen bytes. For Unicode it's about 125 kilobytes.</li>\n<li>Is encoding the entire space of Unicode into a bitmap good or bad engineering? 125k sounds like a lot of memory compared to pushing 2-4 byte characters into an array. But 125k will often fit into the cache of the CPU. It is harder to reason about data locality when building arrays of seen characters.</li>\n<li>It might be hard to really engineer a robust solution to a Leetcode problem if the solution needs to be written in twenty minutes.</li>\n</ul>\n<p><strong>Aside:</strong> <em>{In so far as recursion makes reasoning about the algorithm easier for you, Python may be a suboptimal choice. Iteration is idiomatic Python and recursion not idiomatic Python. Recursion is not idiomatic in Python because Python does not have tail recursion and recursive method calls may crash on large inputs when iterative methods would progress.}</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T02:37:39.847",
"Id": "227492",
"ParentId": "227205",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227221",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T02:57:35.303",
"Id": "227205",
"Score": "5",
"Tags": [
"python",
"algorithm",
"programming-challenge",
"strings",
"complexity"
],
"Title": "Leetcode longest substring with no duplicates"
}
|
227205
|
<h2>LINQ Extension</h2>
<p>I present a <a href="https://github.com/microsoft/referencesource/blob/master/System.Core/System/Linq/Enumerable.cs" rel="noreferrer">LINQ</a> method <code>ArgBy</code> that returns the item of a sequence that corresponds to the predicate specified. Two additional methods <code>MinBy</code>, <code>MaxBy</code> are provided as specific cases. Its specification how to handle null is the same as the existing LINQ methods (see link).</p>
<p>The purpose is to replace a two-pass function:</p>
<pre><code>var max = collection.Max(item => item.Value);
var argMax = collection.First(item => item.Value == max);
</code></pre>
<p>by a single-pass function:</p>
<pre><code>var argMax = collection.MaxBy(x => x.Value);
</code></pre>
<h2>Questions</h2>
<ul>
<li>Is this method usable in practice?</li>
<li>Is this correct LINQ style?</li>
<li>Am I compliant to the existing LINQ specification of equivalent methods?</li>
<li>Are there edge cases or optimisations that require more thought?</li>
</ul>
<h2>Source Code</h2>
<p><code>ArgBy</code> iterates the source sequence and tests each item against a predicate. Any match on the predicate overwrites the referenence to test against for remaining items. The last match is returned. As with the existing LINQ implementation (see reference source <code>Min</code> for instance) there is slightly different behavior for value types vs null-asssignable types. There is additional complexity over existing methods, since we include a key selector, and a key itself could also be either a value type or null-assignable.</p>
<pre><code>public static class LinqExtension
{
public static TSource ArgBy<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
Func<(TKey Current, TKey Previous), bool> predicate)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (keySelector == null) throw new ArgumentNullException(nameof(keySelector));
if (predicate == null) throw new ArgumentNullException(nameof(predicate));
var value = default(TSource);
var key = default(TKey);
if (value == null)
{
foreach (var other in source)
{
if (other == null) continue;
var otherKey = keySelector(other);
if (otherKey == null) continue;
if (value == null || predicate((otherKey, key)))
{
value = other;
key = otherKey;
}
}
return value;
}
else
{
bool hasValue = false;
foreach (var other in source)
{
var otherKey = keySelector(other);
if (otherKey == null) continue;
if (hasValue)
{
if (predicate((otherKey, key)))
{
value = other;
key = otherKey;
}
}
else
{
value = other;
key = otherKey;
hasValue = true;
}
}
if (hasValue) return value;
throw new InvalidOperationException("Sequence contains no elements");
}
}
}
</code></pre>
<p>Two additional methods are provided to get the item with respectively minimum or maximum value given a key selector.</p>
<pre><code>public static TSource MinBy<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
IComparer<TKey> comparer = null)
{
if (comparer == null) comparer = Comparer<TKey>.Default;
return source.ArgBy(keySelector, lag => comparer.Compare(lag.Current, lag.Previous) < 0);
}
public static TSource MaxBy<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
IComparer<TKey> comparer = null)
{
if (comparer == null) comparer = Comparer<TKey>.Default;
return source.ArgBy(keySelector, lag => comparer.Compare(lag.Current, lag.Previous) > 0);
}
</code></pre>
<h2>Unit Tests</h2>
<p>Let's create both a struct and class.</p>
<pre><code>struct Tag
{
public readonly ValueProvider ValueProvider;
public readonly string Description;
public Tag(ValueProvider valueProvider, string description)
=> (ValueProvider, Description) = (valueProvider, description);
}
class ValueProvider : IComparable<ValueProvider>
{
public readonly int Value;
public ValueProvider(int value) => Value = value;
public int CompareTo(ValueProvider other)
{
return Value.CompareTo(other.Value);
}
}
</code></pre>
<p>And perform some basic tests:</p>
<pre><code>[TestMethod]
public void MinByClass()
{
var sequence = new[]
{
null,
new ValueProvider(1),
new ValueProvider(0),
null,
new ValueProvider(2),
};
var min = sequence.MinBy(x => x.Value);
var max = sequence.MaxBy(x => x.Value);
Assert.AreEqual(0, min.Value);
Assert.AreEqual(2, max.Value);
}
[TestMethod]
public void MinByStruct()
{
var sequence = new[]
{
new Tag(new ValueProvider(1), "B"),
new Tag(new ValueProvider(0), "A"),
new Tag(null, "D"),
new Tag(new ValueProvider(2), "C"),
};
var min = sequence.MinBy(x => x.ValueProvider);
var max = sequence.MaxBy(x => x.ValueProvider);
Assert.AreEqual("A", min.Description);
Assert.AreEqual("C", max.Description);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T08:25:02.230",
"Id": "442061",
"Score": "0",
"body": "Could you add an exmple that would yield different results for `Min` and `MinBy` or `Max` and `MaxBy`? Currently they are the same and I'm having a hard time wrapping my head around it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T08:27:08.773",
"Id": "442063",
"Score": "1",
"body": "@t3chb0t Have a look now, _Tag_ is no longer comparabe, it uses a key selector now to perform the comparison."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T08:30:42.793",
"Id": "442064",
"Score": "0",
"body": "One of us made a mistake... I now get the `ArgumentException: At least one object must implement IComparable.` mhmm. I was thinkig of a test where you do both operations like `source.Min(x => x); // <-- 2` and `source.MinBy(x => x); // <-- 4` or I completely miss the point of these extensions hehe."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T08:35:16.260",
"Id": "442066",
"Score": "0",
"body": "@t3chb0t It should work now. The point is to get Min or Max of T, by comparing on TKey in a single pass. I've added the purpose in the description."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T08:42:04.763",
"Id": "442067",
"Score": "1",
"body": "The explanation you've just added makes it pefectly clear now ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T08:53:19.577",
"Id": "442071",
"Score": "2",
"body": "You're a good student, I love this one `var value = default(TSource);` :P and I forgive you that one `bool hasValue = false;`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T08:54:49.250",
"Id": "442073",
"Score": "0",
"body": "@t3chb0t Oh boy, now you noticed I started with LINQ reference source, and extended the code :p"
}
] |
[
{
"body": "<blockquote>\n<pre><code> public static TSource ArgBy<TSource, TKey>(\n</code></pre>\n</blockquote>\n\n<p><code>MinBy</code> and <code>MaxBy</code> are very intelligible names, but <code>ArgBy</code> doesn't say much to me. Really this is a specialised <code>Aggregate</code> (and I wonder whether an implementation using <code>Aggregate</code> might be simpler - or, indeed, whether the existence of <code>Aggregate</code> makes <code>ArgBy</code> unnecessary).</p>\n\n<hr>\n\n<blockquote>\n<pre><code> Func<(TKey Current, TKey Previous), bool> predicate)\n</code></pre>\n</blockquote>\n\n<p>I presume that you chose <code>Func<(TKey Current, TKey Previous), bool></code> instead of <code>Func<TKey, TKey, bool></code> because it lets you name the arguments? Whatever the reason, it would be worth documenting.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if (value == null)\n {\n foreach (var other in source)\n {\n if (other == null) continue;\n var otherKey = keySelector(other);\n if (otherKey == null) continue;\n</code></pre>\n</blockquote>\n\n<p>Those two <code>continue</code>s would also be worth documenting. I might want <code>null</code> to sort before everything else rather than be discarded.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if (value == null)\n {\n ...\n return value;\n }\n else\n {\n bool hasValue = false;\n ...\n if (hasValue) return value;\n throw new InvalidOperationException(\"Sequence contains no elements\");\n }\n</code></pre>\n</blockquote>\n\n<p>That inconsistency is a big gotcha. I see from your reference that <code>System.Linq</code> does the same, but I wouldn't expect it and I definitely think it should be documented.</p>\n\n<p>Also, the exception message might not be true: maybe the sequence contained elements, but their keys were <code>null</code>.</p>\n\n<p>Note that Linq predates some of the type constraints we have now. Perhaps it would be worth handling the two cases by having two implementations, one with <code>where TSource : class</code> and one with <code>where TSource : struct</code>. That way the method-level comments don't have to case split on the type parameter (<code><exception cref=\"InvalidOperationException\">Thrown when the sequence is empty and the element type is a struct.</exception></code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T08:48:33.797",
"Id": "442069",
"Score": "0",
"body": "(1) _Func<(TKey Current, TKey Previous), bool>_ yes this is my way of documenting the tuple. (2) _the exception message might not be true_ you are right, it should be consistent with LINQ and be \"Sequence contains no matching elements\" (3) _two seperate methods for struct and class_, I considered this and perhaps it would be more clean code indeed (4) it does require documentation in general, as does the existing LINQ API :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T08:51:54.043",
"Id": "442070",
"Score": "2",
"body": "@dfhwze .net is probably not the best example of consistency. If everyone would try to mimic their conventions of _KeyNotFoundException_ without naming the key (which immutables now do) we would just throw exceptions like _you know, there's an error, good luck finding it, I won't tell you more about it_ :-]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T08:53:45.390",
"Id": "442072",
"Score": "0",
"body": "@t3chb0t Yeah I also feel, because I tried to be as consistent as possible with LINQ's reference source, it hurts readability and lacks documentation of specification."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T09:08:22.867",
"Id": "442074",
"Score": "1",
"body": "Thinking about all the possible null-handling preferences (source items null allowed, null preferred, keys null allowed, null preferred), perhaps there is a good reason LINQ does not provide a MinBy. This method would become really cluttered."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T08:23:55.207",
"Id": "442334",
"Score": "1",
"body": "@dfhwze, IMO the way to handle that is to include no special casing for `null` at all: if the caller needs to include a `Where(elt => elt != null)` in the chain, they can."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T08:45:17.687",
"Id": "227212",
"ParentId": "227211",
"Score": "6"
}
},
{
"body": "<p>I think in general <code>MinBy</code> and <code>MaxBy</code> are useful but handling all the <code>null</code> cases might be tricky, and indeed it is seeing the repeated logic and two similar loops. For this reason I also think that it'd be easier if we do not handle them at all but let the user decide what he wants to do with them and implement both simply with <code>OrderBy(Descending).First()</code></p>\n\n<pre><code>public static TSource MinBy<TSource, TKey>\n(\n this IEnumerable<TSource> source,\n Func<TSource, TKey> keySelector,\n IComparer<TKey> comparer = null\n)\n{\n return \n source\n .OrderBy(s => keySelector(s), comparer ?? Comparer<TKey>.Default)\n //.OrderByDescending() // for MaxBy\n .First();\n}\n</code></pre>\n\n<p>If the user wants <code>null</code>s to be sorted then he'd just call it with <code>.?</code></p>\n\n<pre><code>sequence.MinBy(x => x?.Value);\n</code></pre>\n\n<p>and if not, then he can filter them out:</p>\n\n<pre><code>sequence.Where(x => x != null).MinBy(x => x.Value);\n</code></pre>\n\n<p>Now, he has all the freedom and we no longer need to decide for him or document any possibe <em>tricks</em> or hidden features. If he doesn't filter <code>null</code>s out and doesn't use <code>.?</code> it'll just throw.</p>\n\n<hr>\n\n<p><strong>Don't use <code>SortedSet</code></strong> It turns out that it isn't the right tool for <strong>this</strong> job. <code>OrderBy[Descending]</code> however, is performing quite well (even much better than expected) and only marginally left behind by the single-pass approach. </p>\n\n<p><sup>(Tested with extendend benchmarks with 100k shuffled items where the filter value was a random number between 0-100)</sup></p>\n\n<hr>\n\n<p><sup>obsolete</sup></p>\n\n<p><strike>In performance critical scenarios I'd use a <code>SortedSet</code> with a custom wrapper-comparer (also because I'm lazy). Its complexitiy is <strong>O(log n)</strong> according to <a href=\"https://www.c-sharpcorner.com/UploadFile/0f68f2/comparative-analysis-of-list-hashset-and-sortedset/\" rel=\"nofollow noreferrer\">Comparative Analysis of List, HashSet and SortedSet</a> which is better than <strong>O(n)</strong> according to <a href=\"https://stackoverflow.com/a/2307314/235671\">What does O(log n) mean exactly?\n</a>. The disadvantage might be that the set needs aditional memory to hold the items but maybe this can be neglected and the faster search outweighs the memory usage.</strike></p>\n\n<pre><code>private class MinComparer<TSource, TKey> : IComparer<TSource>\n{\n public IComparer<TKey> Comparer { get; set; }\n public Func<TSource, TKey> KeySelector { get; set; }\n public int Compare(TSource x, TSource y)\n {\n return Comparer.Compare(KeySelector(x), KeySelector(y))\n }\n}\n\npublic static TSource MinBy<TSource, TKey>\n(\n this IEnumerable<TSource> source,\n Func<TSource, TKey> keySelector,\n IComparer<TKey> comparer = null\n)\n{\n var c = new MinComparer<TSource, TKey>\n {\n KeySelector = keySelector,\n Comparer = comparer ?? Comparer<TKey>.Default,\n };\n\n return new SortedSet<TSource>(source, c).First(); \n}\n</code></pre>\n\n<p>Another <code>MaxComparer</code> could order the items in descending order so that we still could use <code>First</code> with it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T10:02:56.283",
"Id": "442081",
"Score": "0",
"body": "@dfhwze there is one more possibility with a `SortedSet`, this one is _O(log n)_"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T10:09:09.990",
"Id": "442083",
"Score": "0",
"body": "I noticed your edit, so I removed my obsolete comment :p I could re-iterate that I find your solution compact and elegant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T11:09:10.947",
"Id": "442095",
"Score": "1",
"body": "@HenrikHansen I call this _oops_ ;-] fixed"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T13:19:04.203",
"Id": "442102",
"Score": "2",
"body": "`SortedSet` is not a high performance alternative: it's \\$\\Theta(\\lg n)\\$ per `Add`, which means that `new SortedSet<TSource>(source, c)` takes \\$\\Theta(n \\lg n)\\$."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T06:26:21.703",
"Id": "442191",
"Score": "1",
"body": "@dfhwze I tuned the posted benchmarks and there is virtually not difference between single run and `OrderBy[Descending]`. The difference averages to `~0.030 ms` for `100k` items in random order (`1.209 ms` vs `1.245 ms`). `SortedSet` really sucks haha. I'll have to update the question but it's not the worst one :P `MinByA` and `MaxByA` had to be excluded from the tests because I wanted them to complete today lol"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T07:13:31.683",
"Id": "442198",
"Score": "0",
"body": "I didn't expect these benchmark results to be so close. But I still haven't figured out a good way to refactor. The struct vs class approach seems the way to go, but then we need to include special cases for nullable structs, and maybe as Henrik Hansen stated, also for IComparable classes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-21T20:24:06.547",
"Id": "489486",
"Score": "0",
"body": "I would like to see those benchmarks, because you can not sort random array in linear time. Unless `.OrderBy.First` is fused into `MinBy` by system, this approach would performance-wise suck on larger inputs (it is 25x slower for 100k items than linear algorithm)."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T09:27:02.027",
"Id": "227214",
"ParentId": "227211",
"Score": "3"
}
},
{
"body": "<ul>\n<li><em>AggByA:</em> baseline two-pass method presented by the OP.</li>\n<li><em>AggByB:</em> one-pass method using <code>Aggregate</code> suggested by @PeterTaylor</li>\n<li><em>AggByC:</em> one-pass method implemented by hand</li>\n</ul>\n\n<p>I left most error handling to the reader since I personally don't believe it is necessary, or even helpful, in something this abstracted. If the caller wants extra safety then they can easily add whatever checks they desire through the <code>selector</code> and <code>predicate</code> arguments.</p>\n\n<p><strong>Q&A:</strong></p>\n\n<ul>\n<li>Is this method usable in practice? <em>Of course, it just is not ideal.</em></li>\n<li>Is this correct LINQ style? <em>Opinion-based, but I'd say 'No.' primarily because <code>ArgBy</code> seems to be unnecessary (as pointed out by @PeterTaylor). That said, depending on the <code>Aggregate</code> method ends up being slower than the naive alternative.</em></li>\n</ul>\n\n<p><strong>Benchmark Results:</strong></p>\n\n<p><img src=\"https://i.stack.imgur.com/5vPXJ.png\" alt=\"\"></p>\n\n<p><strong>Benchmark Code:</strong></p>\n\n<pre><code>public readonly struct SomeStructure\n{\n private readonly int m_count;\n private readonly string m_name;\n\n public int Count => m_count;\n public string Name => m_name;\n\n public SomeStructure(int count, string name) {\n m_count = count;\n m_name = name;\n }\n}\n\npublic class Race\n{\n private static SomeStructure[] m_data;\n\n [GlobalSetup]\n public void Setup() {\n m_data = new[] {\n new SomeStructure(0, \"A\"),\n new SomeStructure(1, \"B\"),\n new SomeStructure(2, \"C\"),\n };\n }\n\n [Benchmark]\n public SomeStructure MinByA() => Program.MinByA(m_data, a => a.Count);\n [Benchmark]\n public SomeStructure MinByB() => Program.MinByB(m_data, a => a.Count);\n [Benchmark]\n public SomeStructure MinByC() => Program.MinByC(m_data, a => a.Count);\n [Benchmark]\n public SomeStructure MaxByA() => Program.MaxByA(m_data, a => a.Count);\n [Benchmark]\n public SomeStructure MaxByB() => Program.MaxByB(m_data, a => a.Count);\n [Benchmark]\n public SomeStructure MaxByC() => Program.MaxByC(m_data, a => a.Count);\n}\n\nclass Program\n{\n static void Main(string[] args) {\n var summary = BenchmarkRunner.Run<Race>();\n\n Console.ReadKey();\n }\n\n public static TElement AggByA<TElement, TSelector>(IEnumerable<TElement> items, Func<TElement, TSelector> selector, Func<TSelector, TSelector, bool> predicate, Func<Func<TElement, TSelector>, TSelector> aggregator) =>\n items.First(acc => predicate(selector(acc), aggregator(selector)));\n public static TElement AggByB<TElement, TSelector>(IEnumerable<TElement> items, Func<TElement, TSelector> selector, Func<TSelector, TSelector, bool> predicate) =>\n items.Aggregate((acc, cur) => (predicate(selector(acc), selector(cur)) ? cur : acc));\n public static TElement AggByC<TElement, TSelector>(IEnumerable<TElement> items, Func<TElement, TSelector> selector, Func<TSelector, TSelector, bool> predicate) {\n TElement accumulator;\n var enumerator = items.GetEnumerator();\n\n try {\n if (!enumerator.MoveNext()) {\n throw new InvalidOperationException(\"no elements to enumerate\");\n }\n\n accumulator = enumerator.Current;\n\n while (enumerator.MoveNext()) {\n var current = enumerator.Current;\n\n if (predicate(selector(accumulator), selector(current))) {\n accumulator = current;\n }\n }\n }\n finally {\n enumerator.Dispose();\n }\n\n return accumulator;\n }\n public static TElement MaxByA<TElement, TSelector>(IEnumerable<TElement> items, Func<TElement, TSelector> selector) where TSelector : IComparable<TSelector> =>\n AggByA(items, selector, (acc, cur) => (0 == acc.CompareTo(cur)), items.Max);\n public static TElement MaxByB<TElement, TSelector>(IEnumerable<TElement> items, Func<TElement, TSelector> selector) where TSelector : IComparable<TSelector> =>\n AggByB(items, selector, (acc, cur) => (0 > acc.CompareTo(cur)));\n public static TElement MaxByC<TElement, TSelector>(IEnumerable<TElement> items, Func<TElement, TSelector> selector) where TSelector : IComparable<TSelector> =>\n AggByC(items, selector, (acc, cur) => (0 > acc.CompareTo(cur)));\n public static TElement MinByA<TElement, TSelector>(IEnumerable<TElement> items, Func<TElement, TSelector> selector) where TSelector : IComparable<TSelector> =>\n AggByA(items, selector, (acc, cur) => (0 == acc.CompareTo(cur)), items.Min);\n public static TElement MinByB<TElement, TSelector>(IEnumerable<TElement> items, Func<TElement, TSelector> selector) where TSelector : IComparable<TSelector> =>\n AggByB(items, selector, (acc, cur) => (0 < acc.CompareTo(cur)));\n public static TElement MinByC<TElement, TSelector>(IEnumerable<TElement> items, Func<TElement, TSelector> selector) where TSelector : IComparable<TSelector> =>\n AggByC(items, selector, (acc, cur) => (0 < acc.CompareTo(cur)));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T05:59:09.103",
"Id": "442189",
"Score": "0",
"body": "These tests are broken. `AggByC` doesn't dispose the enumerator; `MinByA` and `MaxByA` both enumerate `items` twice. Also these tests only test three already sorted items. Run them with `100_000` **shuffled** items and `OrderBy[Descending]` wins them all or is so close to `MinByC` that the results are barely comparable. `MinByA` and `MaxByA` have to be excluded because they need so long. `SortedSet` is not the slowest one... `MinByA` and `MaxByA` are."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T06:02:47.897",
"Id": "442190",
"Score": "0",
"body": "+1 for creating these test but -1 for broken ones, non realistic conditions and not testing all approaches so the result is 0."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T07:02:05.673",
"Id": "442195",
"Score": "0",
"body": "@t3chb0t I explicitly mentioned that `AggByA` is two passes; it is the baseline that the OP is trying to beat. Of course it's slowest! The `SortedSet` implementation wastes memory and doesn't play nice with large inputs; why bother using it at all? As for the lack of dispose, a simple oversight that I have corrected."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T07:56:28.567",
"Id": "442204",
"Score": "1",
"body": "_why bother using it at all_ - for the sake of science and proof :P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T13:13:50.783",
"Id": "442250",
"Score": "0",
"body": "@t3chb0t We don't even need to perform a benchmark in order to prove that any solution that involves extra memory is going to be inherently slower than any reasonably intelligent algorithm that accumulates \"in-place.\" Science tells us that such implementations are objectively awful before we even write a single line of code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T13:22:17.137",
"Id": "442252",
"Score": "0",
"body": "_than any reasonably intelligent algorithm that accumulates_ - ok mr _I know everything_, so why did you test the other algorithms? Especially the two-passes one? According to the _reasonably intelligent algorithm_ theory this wasn't necessary and actually the same _reasonably intelligent algorithm_ theory tells us that none of these tests were required. Objectively we knew this from the beginning."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T14:38:52.357",
"Id": "442257",
"Score": "0",
"body": "@t3chb0t You're right, any two-pass algorithm isn't worth testing either. The only reason ArgByA was included is simply because it is the baseline that we have to beat; our hypothesis is that the baseline will lose handily and the benchmark exists to demonstrate just how much of a margin it loses by. Think of it as a sort of unit test, if our competing implementation isn't nearly twice as fast then in likely needs improvement. The reasonably intelligent comment was only made to exclude trivial counter-examples that are one-pass but perform unnecessary work; it wasn't meant to demean anyone."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T23:02:47.900",
"Id": "227242",
"ParentId": "227211",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227212",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T08:07:47.390",
"Id": "227211",
"Score": "8",
"Tags": [
"c#",
"linq",
"iterator",
"extension-methods"
],
"Title": "LINQ Extension methods MinBy and MaxBy"
}
|
227211
|
<p>I have some functions and structs for loading and drawing an image with OpenGL. The two main places I would like feedback are:</p>
<ol>
<li><p>I've tried to separate the OpenGL-specific code into the implementation so the caller doesn't have to know what rendering API I'm using. Can I do a better job of separating the OpenGL-specific code from the code necessary to specify the image?</p></li>
<li><p>I'm not happy with my <code>convert_pixels_to_render_coordinates</code> function. It works, it's just klunky. Passing 7 floats is just begging for mis-use. Is there any way I can simplify things, or make it easier to use? I show my usage at the end.</p></li>
</ol>
<p>image.h</p>
<pre class="lang-c prettyprint-override"><code>#ifndef IMAGE_H
#define IMAGE_H
struct rectangle
{
float x, y, width, height;
};
void rectangle_vertices(const struct rectangle *rectangle,
float *vertices);
/*
* Calculate the y_start and height of an image in
* render coordinates by "glueing" two points on
* the image to two points on the coordinate system
*/
void convert_pixels_to_render_coordinates(
float image_height,
float px_0, float px_1,
float coord_0, float coord_1,
float *y_offset,
float *height);
struct image
{
struct rectangle rect;
void *render_data;
};
void set_position(struct image *image,
float new_x, float new_y);
void load_image(struct image *image,
const char *pathname);
void render_image(struct image *image);
#endif
</code></pre>
<p>image.c</p>
<pre class="lang-c prettyprint-override"><code>include "image.h"
#include "gl_header.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include <stdbool.h>
void rectangle_vertices(const struct rectangle *rectangle,
float *vertices)
{
vertices[0] = rectangle->x;
vertices[1] = rectangle->y;
vertices[2] = rectangle->x + rectangle->width;
vertices[3] = rectangle->y;
vertices[4] = rectangle->x + rectangle->width;
vertices[5] = rectangle->y - rectangle->height;
vertices[6] = rectangle->x;
vertices[7] = rectangle->y - rectangle->height;
}
void convert_pixels_to_render_coordinates(
float image_dim,
float px_0, float px_1,
float coord_0, float coord_1,
float *offset,
float *length)
{
const float px_delta = px_1 - px_0;
const float coord_delta = coord_0 - coord_1;
/* Get the size of the image in render coordinates by solving the equation
px_delta *length
----------- = -------------
image_dim coord_delta
*/
*length = image_dim * coord_delta / px_delta;
/* Solving this equation gives us the offset to our first point:
image_dim offset
----------- = --------
px_0 *length
And then we need to apply the coord offset
*/
*offset = coord_0 + (px_0 * (*length) / image_dim);
}
static const struct rectangle FULL_UV_COORDS = {0.f, 0.f, 1.f, 1.f};
struct image_impl
{
GLuint texture;
GLuint buffers[2];
};
#define VERTEX_BUFFER buffers[0]
#define UV_BUFFER buffers[1]
void load_image(struct image *image, const char *pathname)
{
stbi_set_flip_vertically_on_load(true);
image->render_data = malloc(sizeof(struct image_impl));
if (!image->render_data)
{
fprintf(stderr, "Out of memory\n");
exit(1);
}
struct image_impl *impl = (struct image_impl *)image->render_data;
glGenBuffers(2, impl->buffers);
int width_px, height_px, channels;
unsigned char *pixels = stbi_load(pathname, &width_px, &height_px, &channels, 0);
set_position(image, image->rect.x, image->rect.y);
const struct rectangle *texture_rect = &FULL_UV_COORDS;
GLfloat note_uv[8] = {};
rectangle_vertices(texture_rect, note_uv);
glBindBuffer(GL_ARRAY_BUFFER, impl->UV_BUFFER);
glBufferData(GL_ARRAY_BUFFER, sizeof(note_uv), note_uv, GL_STATIC_DRAW);
glGenTextures(1, &impl->texture);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, impl->texture);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width_px, height_px,
0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
glGenerateMipmap(GL_TEXTURE_2D);
stbi_image_free(pixels);
}
void render_image(struct image *image)
{
struct image_impl *impl = (struct image_impl *)image->render_data;
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, impl->texture);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, impl->VERTEX_BUFFER);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, impl->UV_BUFFER);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
}
void set_position(struct image *image,
float new_x, float new_y)
{
image->rect.x = new_x;
image->rect.y = new_y;
struct image_impl *impl = (struct image_impl *)image->render_data;
GLfloat note_vertices[8] = {};
rectangle_vertices(&image->rect, note_vertices);
glBindBuffer(GL_ARRAY_BUFFER, impl->VERTEX_BUFFER);
glBufferData(GL_ARRAY_BUFFER, sizeof(note_vertices), note_vertices, GL_STATIC_DRAW);
}
#undef VERTEX_BUFFER
#undef UV_BUFFER
</code></pre>
<p>Usage:</p>
<pre class="lang-c prettyprint-override"><code>convert_pixels_to_render_coordinates(
256,
0.f, 74.f,
.5f, .45f,
&state->bass_clef.rect.y,
&state->bass_clef.rect.height);
state->bass_clef.rect.x = -1.f;
state->bass_clef.rect.width = .1f;
load_image(&state->bass_clef,
"./res/bass-clef.png");
</code></pre>
<p>And to try to explain where all these numbers are coming from, here's a (marked) image that I'm trying to load with this:</p>
<p><a href="https://i.stack.imgur.com/IP9N6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IP9N6.png" alt="example bass clef with markings"></a></p>
<p>The two red dots are the y-coordinates (0.f, 74.f) (manually extracted
by looking at it in GIMP) where the clef needs to intersect lines on the staff. (See the below image for how these points need to line up in context)</p>
<p><a href="https://i.stack.imgur.com/ikJwj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ikJwj.png" alt="enter image description here"></a></p>
<p>The .5f and .45f are the y-values in OpenGL coordinates [-1..1] of the lines on the staff those dots need to touch. From this we calculate the y offset and height of the image rectangle for the clef.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T15:32:53.637",
"Id": "442113",
"Score": "0",
"body": "What version of C are you using? Hopefully C99 or later?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T15:41:09.327",
"Id": "442114",
"Score": "0",
"body": "@Reinderien C99"
}
] |
[
{
"body": "<h2><code>typedef</code> is your friend</h2>\n\n<p>You're using C99, so <code>typedef struct { ... } rectangle;</code> instead of the older style.</p>\n\n<h2>Additional structs</h2>\n\n<p>If you want to tighten up some of your code, one potential way is to make a coordinate struct. This would halve the number of members of <code>rectangle</code>, for instance. Such nesting would not have a performance impact. It would also be used instead of <code>new_x</code> / <code>new_y</code> (for instance).</p>\n\n<h2>Failure handling</h2>\n\n<p>The old-school C behaviour for <code>malloc</code> failure is to not only return <code>null</code>, but to set <code>errno</code>. This should not be ignored. Have a read through <a href=\"http://pubs.opengroup.org/onlinepubs/009695399/functions/perror.html\" rel=\"nofollow noreferrer\">http://pubs.opengroup.org/onlinepubs/009695399/functions/perror.html</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T20:08:34.440",
"Id": "442155",
"Score": "0",
"body": "I prefer to see `struct` when I use a struct. That's just a matter of taste, not something \"old\"."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T19:18:23.130",
"Id": "227230",
"ParentId": "227217",
"Score": "2"
}
},
{
"body": "<p>Kudos on using modern OpenGL for this! We see a lot of OpenGL code around here relying on deprecated functionality, so this is a breath of fresh air.</p>\n<h1>Naming</h1>\n<p>I think your naming needs some work. The name <code>convert_pixels_to_render_coordinates</code> is highly confusing. When I think of pixels, I generally think of an array of RGB(A) values (or possibly in some other color space). While I have seen OpenGL code that stuffs x,y,z coordinates into an image, this code doesn't appear to be doing that. So the name just seems wrong. It's not converting pixels to anything. It appears to be converting some sort of length from one coordinate system to another.</p>\n<p>Next are the arguments to the function. The header calls the first parameter <code>image_height</code>. The implementation calls it <code>image_dim</code>. I'm guessing that since the other parameters have names like <code>y_offset</code> and <code>height</code> that you expect it to be used for calculating something related to height. The comment that goes with the function doesn't illuminate much for me as a reader who has never seen this code. What are "render coordinates"? Are these world coordinates? Normalized device coordinates? Object coordinates? I can't tell from your usage example what these various coordinates and dimensions are supposed to be. You pass in 256 for the <code>image_height</code>, but you haven't loaded the image yet. How do you know it's 256 pixels high? Then you pass 0 and 74 for the <code>px_0</code> and <code>px_1</code> values. Is that the width? Given the ratios you calculate, I can't tell at all what this is doing. Are you just trying to calculate normalized texture coordinates from the size of the image? Is this getting something out of a texture atlas? Suffice to say, I can't tell what's going on from the name of the function or the arguments.</p>\n<p>In the <code>struct image</code>, the <code>render_data</code> pointer has a meaningless name. In general, you should avoid using words like data, info, record, object, etc. in the names of types because those words describe all types. That leaves "render" which is equally meaningless because all of this code is related to rendering. What you're passing here are vertex attributes, so I recommend calling it <code>vertex_attributes</code> or something like that.</p>\n<p>The function name <code>rectangle_vertices()</code> is also not very descriptive. I suggest something along the lines of <code>image_coordinates_to_vertex_coordinates()</code>, or <code>object_coordinates_to_vertex_coordinates()</code>. (Note that the use of <code>object</code> here is not in a type definition, so the above rule doesn't apply. "Object Space" is a term commonly used to refer to a rendered object's local coordinate space.)</p>\n<h1>Constants</h1>\n<p>It's nice to see you using named constants for some things rather than magic numbers. I recommend you change these macros to be just indexes, though:</p>\n<pre><code>#define VERTEX_BUFFER buffers[0]\n#define UV_BUFFER buffers[1]\n</code></pre>\n<p>Rather than making them macros, I'd define them as an enum, like this:</p>\n<pre><code>typedef enum {\n VERTEX_BUFFER = 0,\n UV_BUFFER = 1\n};\n</code></pre>\n<p>And then you can use them like this:</p>\n<pre><code>glBindBuffer(GL_ARRAY_BUFFER, impl->buffers [ VERTEX_BUFFER ]);\n</code></pre>\n<p>That's more idiomatic C.</p>\n<h1>Your Questions</h1>\n<p>To answer your questions, I think you've done fine separating the interface from the implementation. I just think your interface could be better. I can't comment more on <code>convert_pixels_to_render_coordinates</code> because I don't know what it's doing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T23:04:53.997",
"Id": "442165",
"Score": "0",
"body": "Great suggestions, the enum solution is definitely much better. I've edited more explanation to the bottom of my question to try to explain where the numbers are coming from and what they're trying to do. Maybe that would help suggest a better name? I definitely agree mine is not great."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T23:19:57.937",
"Id": "442167",
"Score": "1",
"body": "Ah, I see. Maybe something like `calculate_clef_scale_and_offset()`? Or if it's used for other types of glyphs like notes, etc., maybe `calculate_glyph_scale_and_offset()`?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T22:43:52.367",
"Id": "227241",
"ParentId": "227217",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227241",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T11:56:29.580",
"Id": "227217",
"Score": "4",
"Tags": [
"c",
"graphics",
"opengl"
],
"Title": "Loading and drawing an image"
}
|
227217
|
<p>The task of the code that is presented for review is to prepare all the data for the export of the selected contract and create a file on this basis. </p>
<p>This is one of the first experiences with a large (for me) program. So I put the tag begginer. In this regard, please use the terms from my code and avoid general description of some concepts without an example (it is difficult for me to understand it).</p>
<h2>Context</h2>
<p>There are two documents. <code>Contracts</code> is the main document. <code>ActCompletion</code> is derived from <code>Contracts</code>. It contains some already known data from <code>Contracts</code> and adds its own. <code>Contracts</code> describes a table in the database. <code>ActCompletion</code> takes existing <code>Contracts</code> and runtime receives their individual data from the user. They are not stored anywhere in the database. In both cases, the user selects some <code>Contracts</code> from table. Then clicks the export button on either <code>Contracts</code> or <code>ActCompletion</code>.</p>
<p><code>Contracts</code> and <code>ActCompletion</code> have a <code>template</code> MS Word with <code>MergeFields</code>. After receiving all the necessary data, the dictionary creation is called. The dictionary contains a <code>key</code> as the <code>MergeField name</code> and a <code>value</code> as the <code>text</code> to be inserted instead of <code>MergeField</code>.</p>
<p>In this way, has two variants:</p>
<ul>
<li><p>Event from the "export contract" button, loading the selected
contract from the database, request a path to save, create a
dictionary, create a file.</p></li>
<li><p>Event of the button "export act", loading the selected contract from
the database, request additional data for <code>ActCompletion</code>, request a
path to save, create dictionary, create a file.</p></li>
</ul>
<h2>Elements</h2>
<ul>
<li><code>Exporter</code> is a class that combines the two implementations of the
<code>DocumentContract</code> and <code>DocumentActCompletion</code></li>
<li><code>DocumentContract</code> and <code>DocumentActCompletion</code> are encapsulate own model: <code>ModelContract</code> and <code>ModelActCompletion</code>to hide public fields and methods, leaving only one available method.Inherit interface <code>IDocument</code> to force the <code>Export()</code> method to be implemented.</li>
<li><code>ModelContract</code> and <code>ModelActCompletion</code> extend the base class implementation <code>ExporterModel</code>. The model contains the <code>Export()</code> method, which performs the steps described by me after the word "has two variables".</li>
<li><code>ConverterContract</code> and <code>ConverterActCompletion</code> are encapsulate own implementation of <code>ConverterBase</code>. Both override <code>Convert()</code> method in its own way. Engaged in the creation of a dictionary.</li>
<li><code>ShaperField</code> is auxiliary static class. Contains methods for formatting data into string.</li>
<li><code>WordProvider</code> is сreates a file based on the dictionary, template and output path.</li>
</ul>
<p><strong>File structure</strong></p>
<p><a href="https://i.stack.imgur.com/qlVTh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qlVTh.png" alt="enter image description here"></a></p>
<h2>Example</h2>
<pre><code>int id = 22; // some id of selected contract from user
Exporter exporter = new Exporter();
exporter.Contract.Export(id);
// or
// exporter.ActCompletion.Export(id);
</code></pre>
<h2>UPDATE</h2>
<p>I created a database in <code>MS Access</code> (with the extension <code>.accdb</code>). The provider to work with this <a href="https://github.com/bubibubi/EntityFrameworkCore.Jet" rel="nofollow noreferrer">EntityFrameworkCore.Jet</a>. </p>
<h2>Code</h2>
<p><strong>Contracts</strong> and <strong>ActCompletion</strong></p>
<pre><code>public partial class Contracts
{
public Contracts(int id = 0)
{
this.Id = id;
ListKindWorks = new HashSet<ListKindWorks>();
ListSubjects = new HashSet<ListSubjects>();
}
public int Id { get; set; }
public string Num { get; set; }
public DateTime DateConclusion { get; set; }
public int Worker { get; set; }
public DateTime DateStartWork { get; set; }
public DateTime DateEndWork { get; set; }
public double Salary { get; set; }
public virtual Workers WorkerNavigation { get; set; }
public virtual ICollection<ListKindWorks> ListKindWorks { get; set; }
public virtual ICollection<ListSubjects> ListSubjects { get; set; }
}
public class ActCompletion
{
public Contracts Contract { get; set; }
public double Salary { get; set; }
public Dates Dates { get; private set; }
public ActCompletion()
{
Dates = new Dates();
}
}
public class Dates
{
public DateTime DateConclusion { get; set; }
public DateTime DateStart { get; set; }
public DateTime DateEnd { get; set; }
}
</code></pre>
<p><strong>Exporter</strong></p>
<pre><code>class Exporter
{
public DocumentContract Contract { get; private set; }
public DocumentActCompletion ActCompletion { get; private set; }
public Exporter()
{
Contract = new DocumentContract();
ActCompletion = new DocumentActCompletion();
}
}
</code></pre>
<p><strong>IDocument</strong>, <strong>DocumentContract</strong> and <strong>DocumentActCompletion</strong></p>
<pre><code>interface IDocument
{
void Export(int id);
}
class DocumentContract : IDocument
{
private readonly ModelContract model;
public DocumentContract()
{
model = new ModelContract();
}
public void Export(int id)
{
model.Export(id);
}
}
class DocumentActCompletion : IDocument
{
private readonly ModelActCompletion model;
public DocumentActCompletion()
{
model = new ModelActCompletion();
}
public void Export(int id)
{
model.Export(id);
}
}
</code></pre>
<p><strong>ModelContract</strong> </p>
<pre><code>class ModelContract : ExporterModel
{
private readonly ConverterContract converter;
public ModelContract()
{
converter = new ConverterContract();
SelectTemplate();
}
public void Export(int id)
{
LoadContract(id);
if (!RequestDocumentPath(FormatDocumentName()))
{
return;
}
CreateDictionary();
CreateDocument();
}
private string FormatDocumentName()
{
return Properties.Settings.Default.WordTemplate_Contract_DefaultName
.Replace(
Properties.Settings.Default.WordTemplate_PatternName,
ShaperField.ShapeShortName(Contract.WorkerNavigation.FullName));
}
private void SelectTemplate()
{
PathTemplate = Properties.Settings.Default.WordTemplate_Contract_Path;
}
private void CreateDictionary()
{
Dict = converter.Convert(Contract);
}
}
</code></pre>
<p><strong>ModelActCompletion</strong> </p>
<pre><code>class ModelActCompletion : ExporterModel
{
private readonly ConverterActCompletion converter;
private ActCompletion ActCompletion;
public ModelActCompletion()
{
converter = new ConverterActCompletion();
ActCompletion = new ActCompletion();
SelectTemplate();
}
public void Export(int id)
{
LoadContract(id);
if (!RequestActCompletion()
|| !RequestDocumentPath(FormatDocumentName()))
{
return;
}
CreateDictionary();
CreateDocument();
}
private bool RequestActCompletion()
{
using (ActCompletionForm form = new ActCompletionForm(Contract))
{
if (form.ShowDialog() == DialogResult.OK)
{
ActCompletion = form.Act;
return true;
}
else
{
ActCompletion = new ActCompletion();
return false;
}
}
}
private string FormatDocumentName()
{
return Properties.Settings.Default.WordTempleate_ActCompletion_DefaultName
.Replace(
Properties.Settings.Default.WordTemplate_PatternName,
ShaperField.ShapeShortName(Contract.WorkerNavigation.FullName));
}
private void SelectTemplate()
{
PathTemplate = Properties.Settings.Default.WordTemplate_ActCompletion_Path;
}
private void CreateDictionary()
{
Dict = converter.Convert(ActCompletion);
}
}
</code></pre>
<p><strong>ExporterModel</strong></p>
<pre><code>class ExporterModel
{
private Logger logger = NLog.LogManager.GetCurrentClassLogger();
private WordProvider wordProvider;
private string pathDocument;
private string pathTemplate;
public string PathTemplate
{
get
{
return pathTemplate;
}
set
{
pathTemplate = Environment.CurrentDirectory + value;
}
}
public Contracts Contract { get; private set; }
public Dictionary<string, string> Dict { get; set; }
public ExporterModel()
{
Contract = new Contracts();
wordProvider = new WordProvider();
}
public void LoadContract(int id)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
using (ModelContext model = new ModelContext())
{
Contract = model.Contracts
.Where(c => c.Id == id)
.Include(w => w.WorkerNavigation)
.ThenInclude(w => w.IssuedNavigation)
.Include(w => w.WorkerNavigation)
.ThenInclude(w => w.BankNavigation)
.Include(lkw => lkw.ListKindWorks)
.ThenInclude(lkw => ((ListKindWorks)lkw).IdKindWorkNavigation)
.Include(ls => ls.ListSubjects)
.ThenInclude(ls => ((ListSubjects)ls).IdSubjectNavigation)
.Single();
}
stopwatch.Stop();
logger.Debug("Загрузка договора для экспорта: {0}", stopwatch.Elapsed);
}
public bool RequestDocumentPath(string documentName)
{
using (SaveFileDialog sfd = new SaveFileDialog())
{
sfd.Filter = "Документы Word (*.docx)|*.docx";
sfd.AddExtension = true;
sfd.RestoreDirectory = true;
sfd.FileName = documentName;
if (sfd.ShowDialog() == DialogResult.OK)
{
pathDocument = sfd.FileName;
return true;
}
else
{
pathDocument = string.Empty;
return false;
}
}
}
public void CreateDocument()
{
wordProvider.CreateDocument(Dict, PathTemplate, pathDocument);
}
}
</code></pre>
<p><strong>ConverterContract</strong></p>
<pre><code>class ConverterContract
{
private readonly Converter converter;
public ConverterContract()
{
converter = new Converter();
}
public Dictionary<string, string> Convert(Contracts contract)
{
return converter.Convert(contract);
}
private class Converter : ConverterBase
{
public override Dictionary<string, string> Convert(object obj)
{
Contracts c = obj as Contracts;
InitializeDict(c, c.Salary);
AddKindWork(c.ListKindWorks);
AddSubject(c.ListSubjects);
AddDates(c.DateStartWork, c.DateEndWork);
AddPassport(c.WorkerNavigation);
AddBank(c.WorkerNavigation);
return Dict;
}
private void AddKindWork(ICollection<ListKindWorks> list)
{
Dict.Add(Fields["KIND_WORK"], ShaperField.ShapeKindWork(list));
}
private void AddSubject(ICollection<ListSubjects> list)
{
Dict.Add(Fields["SUBJECT"], ShaperField.ShapeSubject(list));
}
private void AddDates(DateTime start, DateTime end)
{
Dict.Add(Fields["DATE_START_CONTRACT"], ShaperField.ShapeDate(start));
Dict.Add(Fields["DATE_END_CONTRACT"], ShaperField.ShapeDate(end));
}
private void AddPassport(Workers w)
{
Dict.Add(Fields["ADDRESS"], ShaperField.ShapeAddress(w.Address));
Dict.Add(Fields["PASSPORT"], ShaperField.ShapePassport(w));
Dict.Add(Fields["PASSPORT_NUMBER"], ShaperField.ShapePassportNumber(w.PassportNumber));
}
private void AddBank(Workers w)
{
Dict.Add(Fields["BANK"], ShaperField.ShapeBank(w));
}
}
}
</code></pre>
<p><strong>ConverterActCompletion</strong></p>
<pre><code>class ConverterActCompletion
{
private readonly Converter converter;
public ConverterActCompletion()
{
converter = new Converter();
}
public Dictionary<string, string> Convert(ActCompletion act)
{
return converter.Convert(act);
}
private class Converter : ConverterBase
{
public override Dictionary<string, string> Convert(object obj)
{
ActCompletion act = obj as ActCompletion;
InitializeDict(act.Contract, act.Salary);
AddDates(act.Dates);
return Dict;
}
private void AddDates(Dates dates)
{
Dict.Add(Fields["DATE_FILL_ACT_COMPLETION"], ShaperField.ShapeDate(dates.DateConclusion));
Dict.Add(Fields["DATE_START_ACT_COMPLETION"], ShaperField.ShapeDate(dates.DateStart));
Dict.Add(Fields["DATE_END_ACT_COMPLETION"], ShaperField.ShapeDate(dates.DateEnd));
}
}
}
</code></pre>
<p><strong>ConverterBase</strong></p>
<pre><code>using Newtonsoft.Json;
abstract class ConverterBase
{
public Dictionary<string, string> Fields { get; private set; }
public Dictionary<string, string> Dict { get; private set; }
public ConverterBase()
{
Dict = new Dictionary<string, string>();
Fields = JsonConvert.DeserializeObject<Dictionary<string, string>>
(Properties.Settings.Default.MergeFieldDictionaryAsString);
}
public void InitializeDict(Contracts c, double salary)
{
Dict.Clear();
AddGeneralField(c);
AddSalary(salary);
}
public abstract Dictionary<string, string> Convert(object obj);
private void AddGeneralField(Contracts c)
{
Dict.Add(Fields["NUM_CONTRACT"], ShaperField.ShapeNum(c.Num));
Dict.Add(Fields["DATE_FILL_CONTRACT"], ShaperField.ShapeDate(c.DateConclusion));
Dict.Add(Fields["FULL_NAME"], ShaperField.ShapeFullName(c.WorkerNavigation.FullName));
Dict.Add(Fields["SHORT_NAME"], ShaperField.ShapeShortName(c.WorkerNavigation.FullName));
}
private void AddSalary(double salary)
{
ConvertSalary cs = new ConvertSalary();
cs.setSalaryWithTax(salary);
Dict.Add(Fields["SALARY_GROSS"], cs.GetSalaryWithTax());
Dict.Add(Fields["INCOME_TAX_PROCENT"], Properties.Settings.Default.ConvertSalary_IncomeTaxProcent.ToString());
Dict.Add(Fields["INCOME_TAX_SUM"], cs.GetIncomeTaxValue());
Dict.Add(Fields["INSURANCE_TAX_PROCENT"], Properties.Settings.Default.ConvertSalary_InsuranceTaxProcent.ToString());
Dict.Add(Fields["INSURANCE_TAX_SUM"], cs.GetInsuranceTaxValue());
}
}
</code></pre>
<p><strong>ShaperField</strong></p>
<pre><code>static class ShaperField
{
public static string ShapeNum(string value)
{
return value;
}
public static string ShapeDate(DateTime value)
{
return value.ToLongDateString();
}
public static string ShapeFullName(string value)
{
return value;
}
// TODO: зачем в KindWork и Subject - ToArray()
public static string ShapeKindWork(ICollection<ListKindWorks> list)
{
return string.Join(", ", list.Select(x => "«" + x.IdKindWorkNavigation.Title + "»").ToArray());
}
public static string ShapeSubject(ICollection<ListSubjects> list)
{
return string.Join(", ", list.Select(x => "«" + x.IdSubjectNavigation.Title + "»").ToArray());
}
public static string ShapeAddress(string value)
{
return value;
}
public static string ShapePassport(Workers w)
{
return string.Format("{0} выдан {1} {2} г.", w.PassportSeries, w.IssuedNavigation.Title, w.DateIssued.ToString("dd.MM.yyyy"));
}
public static string ShapePassportNumber(string value)
{
return value;
}
public static string ShapeBank(Workers w)
{
return string.Format("{0}\nв {1}", w.BankAccount, w.BankNavigation.Title);
}
public static string ShapeShortName(string fullName)
{
string[] name = fullName.Split(' ');
if (TryFormatShortName(name))
{
return FormatShortName(name);
}
else
{
ShowMessage.Error(string.Format("Во время получения инициалов от полного ФИО произошла ошибка. " +
"Возможно ФИО не содержит трех слов.\nВ случае продолжения, сокращенное имя получит значение \"{0}\"",
fullName));
return fullName;
}
}
private static bool TryFormatShortName(string[] name)
{
try
{
string shortName = FormatShortName(name);
}
catch (Exception ex)
{
return false;
}
return true;
}
private static string FormatShortName(string[] name, string pattern = "{0}.{1}. {2}")
{
return string.Format(pattern, name[1][0], name[2][0], name[0]);
}
}
</code></pre>
<p><strong>WordProvider</strong></p>
<pre><code>using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
class WordProvider
{
private WordprocessingDocument document;
private Dictionary<string, string> _dict;
private string _templatePath;
private string _outputPath;
private string _tempPath;
public void CreateDocument(Dictionary<string, string> dict, string templatePath, string outputPath)
{
_dict = dict;
_templatePath = templatePath;
_outputPath = outputPath;
_tempPath = GetTempPath();
Create();
}
private string GetTempPath()
{
return Path.GetTempPath() + Path.GetFileName(_outputPath);
}
private void Create()
{
File.Copy(_templatePath, _tempPath, true);
document = WordprocessingDocument.Open(_tempPath, true);
document.ChangeDocumentType(WordprocessingDocumentType.Document);
FillMergeFields();
document.MainDocumentPart.Document.Save();
document.Close();
File.Copy(_tempPath, _outputPath, true);
File.Delete(_tempPath);
}
private void FillMergeFields()
{
string fieldName;
foreach (FieldCode field in document.MainDocumentPart.RootElement.Descendants<FieldCode>())
{
fieldName = GetFieldName(field);
// TODO: пропуски в лог
if (_dict.ContainsKey(fieldName))
{
ReplaceMergeFieldWithText(field, _dict[fieldName]);
}
}
}
private string GetFieldName(FieldCode field)
{
return field.Text.Substring(11, field.Text.IndexOf("\\") - 11).Trim();
}
private void ReplaceMergeFieldWithText(FieldCode field, string replacementText)
{
// Разбор алгоритма кода
// https://stackoverflow.com/a/57180496/11563179
if (field == null || replacementText == string.Empty)
{
return;
}
Run rFldParent = (Run)field.Parent;
List<Run> runs = new List<Run>();
runs.Add(rFldParent.PreviousSibling<Run>()); // begin
runs.Add(rFldParent.NextSibling<Run>()); // separate
runs.Add(runs.Last().NextSibling<Run>()); // text
runs.Add(runs.Last().NextSibling<Run>()); // end
runs.ForEach(r => r.Remove());
field.Remove(); // instrText
rFldParent.Append(new Text(replacementText));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T16:14:17.653",
"Id": "442116",
"Score": "0",
"body": "The `Contracts` is `partial` but the other part is missing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T16:16:47.067",
"Id": "442117",
"Score": "0",
"body": "@t3chb0t `Contracts` generated by the database provider. As well as the rest of the code concerning work with database."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T16:18:22.023",
"Id": "442118",
"Score": "0",
"body": "I understand yet, you still should include it because your code is using these fields/properties and they are nowhere defined. Could you also add a proper tag for the database technology you use, entity framework or ef-core, or ado.net etc?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T16:19:28.513",
"Id": "442119",
"Score": "0",
"body": "Or do you mean this is the generated class and not your custom one?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T16:22:17.600",
"Id": "442120",
"Score": "0",
"body": "@t3chb0t I have a database in MS Access. I gave it to the provider and got a number of classes describing the tables and the model to work with them. My, custom code in this there is no. All generated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T16:24:12.423",
"Id": "442121",
"Score": "0",
"body": "@t3chb0t `ActCompletion` does not apply to the database. As stated in the post, its data is obtained in runtime from the user."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T16:24:25.773",
"Id": "442122",
"Score": "0",
"body": "oh, ok. Its non-default constructor confused me because this is not what is usually generated and I thought you posted the customized part. But I am right about you having had modified it? The field initialization, this is your work, right? ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T16:26:51.553",
"Id": "442123",
"Score": "0",
"body": "@t3chb0t yes) I have added the ID equating to zero by default"
}
] |
[
{
"body": "<p>My observations...</p>\n\n<p><strong>Leave generated classes alone</strong> You have modified <code>Contracts</code> by adding a custom constructor to it. You'll loose this changes when you regenerate the model. This class is <code>partial</code> not without a purpose. If you want to customize it then you should create another file in the same project and within the same namespace and define your own <code>partial class Contract</code>. This one will survive the model generation process.</p>\n\n<p>As far as the changes are concerned initiailzing <code>Id</code> to <code>0</code> is unnecessary because the default value for <code>int</code>s is already <code>0</code>.</p>\n\n<p><strong>Do not initialize ICollection with HashSet</strong> Initializing the other two collections with <code>HashSet</code>s is something you should definitely document. I usually wouldn't expect these <code>ICollection</code>s to be sets and when they are retrieved from the database the most probably aren't so your model behaves inconsistently. It has different functionality when created with <code>new Contracts</code> because you can only add unique items to it and allows adding non-unique items when retrieved with linq. If these fields are always sets then their type should most probably be <code>ISet</code> but I'm not really sure it is supported by Entity Framework. Anyways, this should be documented somewhere and be consistent.</p>\n\n<p><strong>Initialize either everything or nothing</strong> The implementation of <code>ActCompletion</code> is also inconsistent as it initializes only <code>Dates</code> to an instance and leaves <code>Contract</code> as <code>null</code>. I find this is strange and should be documented if it serves any purpose.</p>\n\n<p><strong>Change which classes implement <code>IDocument</code></strong> Both classes <code>DocumentContract</code> and <code>DocumentActCompletion</code> redirect the call to <code>Export</code> to another <code>Export</code>. This looks like the other two classes <code>ModelContract</code> and <code>ModelActCompletion</code> should implement this interface. They already can do what the interfaces specifies. There is no need to create a wrapper that doesn't add anything.</p>\n\n<p><strong><code>ConverterBase</code> should have a more specific name</strong> Seeing the code it's difficult to figure out what that converter is for. I see it does something with dictionaries but I'm not sure what. You should use names that are clear about the purpose of a class. This one looks rather like a factory but it's hard to say. It even uses the json-serializer so maybe it's even some serializer... mhmm, who knows.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T16:59:27.503",
"Id": "227223",
"ParentId": "227220",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227223",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T14:12:57.360",
"Id": "227220",
"Score": "5",
"Tags": [
"c#",
"beginner",
"object-oriented",
"entity-framework-core"
],
"Title": "Prepare and export data to MS Word file"
}
|
227220
|
<p>Printing the lyrics of "Twelve Days of Christmas" seems to be a fairly popular programming challenge.</p>
<p>As I've successfully attempted it, I was wondering if the code can be simplified even further (say no loops)?</p>
<p>Any feedback in regards to style and/or logic would be greatly appreciated.</p>
<pre><code>#!/usr/bin/env python3
verses = {
1: ["first", "and a Partridge in a Pear Tree."],
2: ["second", "two Turtle Doves, "],
3: ["third", "three French Hens, "],
4: ["fourth", "four Calling Birds, "],
5: ["fifth", "five Gold Rings, "],
6: ["sixth", "six Geese-a-Laying, "],
7: ["seventh", "seven Swans-a-Swimming, "],
8: ["eighth", "eight Maids-a-Milking, "],
9: ["ninth", "nine Ladies Dancing, "],
10: ["tenth", "ten Lords-a-Leaping, "],
11: ["eleventh", "eleven Pipers Piping, "],
12: ["twelfth", "twelve Drummers Drumming, "]
}
def get_verses(line):
verse = f"On the {verses[line][0]} day of Christmas " + \
"my true love gave to me: "
for i in range(line, 0, -1):
verse += f"{verses[i][1]}"
return verse.replace("and ", "") if line == 1 else verse
def recite(start_verse, end_verse):
return "\n".join([get_verses(line) for line
in range(start_verse, end_verse + 1)])
print(recite(1, 12))
</code></pre>
|
[] |
[
{
"body": "<p>You're storing your verses in a format that's a little more complicated than necessary. If you have a dictionary that you're keying by a continuous range of number (and you don't need to handle removals), you likely shouldn't be using a dictionary. Just use a list here:</p>\n\n<pre><code>verses = [[\"first\", \"and a Partridge in a Pear Tree.\"],\n [\"second\", \"two Turtle Doves, \"],\n [\"third\", \"three French Hens, \"],\n [\"fourth\", \"four Calling Birds, \"],\n [\"fifth\", \"five Gold Rings, \"],\n [\"sixth\", \"six Geese-a-Laying, \"],\n [\"seventh\", \"seven Swans-a-Swimming, \"],\n [\"eighth\", \"eight Maids-a-Milking, \"],\n [\"ninth\", \"nine Ladies Dancing, \"],\n [\"tenth\", \"ten Lords-a-Leaping, \"],\n [\"eleventh\", \"eleven Pipers Piping, \"],\n [\"twelfth\", \"twelve Drummers Drumming, \"]]\n</code></pre>\n\n<p>If you think about, lists are already indexed by number. Now you don't need to manually increment the number keys if you add a new verse. The change just requires tweaking some numbers to account for 0-based indexing (which I think is more appropriate anyways):</p>\n\n<pre><code>def get_verses(line):\n verse = f\"On the {verses[line][0]} day of Christmas, my true love gave to me: \"\n for i in range(line, -1, -1): # -1 stop\n verse += f\"{verses[i][1]}\"\n return verse.replace(\"and \", \"\") if line == 0 else verse # line 0 now\n\ndef recite(start_verse, end_verse):\n return \"\\n\".join([get_verses(line)\n for line in range(start_verse, end_verse + 1)])\n</code></pre>\n\n<p>I also changed how you're splitting up the last list comprehension. If you wanted to split it, I would keep the iteration part all on one line, and <code>get_verses</code> on another. I also don't think the line in <code>get_verses</code> needed to be split. It isn't that line.</p>\n\n<p>I'd still change some more things though:</p>\n\n<ul>\n<li><p>In <code>get_verses</code>, you named the parameter <code>line</code>. It isn't a line though, it's a line <em>number</em>. I'd change it to, at the very least, <code>line_n</code>.</p></li>\n<li><p>You don't need a strict list comprehension in <code>recite</code>. You can get rid of a pair of brackets by making it a generator expression that uses <code>join</code>'s brackets.</p></li>\n<li><p>The imperative loop in <code>get_verse</code> could be changed to a <code>join</code>ed generator expression.</p></li>\n</ul>\n\n<p>I ended up with this:</p>\n\n<pre><code>verses = [[\"first\", \"and a Partridge in a Pear Tree.\"],\n [\"second\", \"two Turtle Doves, \"],\n [\"third\", \"three French Hens, \"],\n [\"fourth\", \"four Calling Birds, \"],\n [\"fifth\", \"five Gold Rings, \"],\n [\"sixth\", \"six Geese-a-Laying, \"],\n [\"seventh\", \"seven Swans-a-Swimming, \"],\n [\"eighth\", \"eight Maids-a-Milking, \"],\n [\"ninth\", \"nine Ladies Dancing, \"],\n [\"tenth\", \"ten Lords-a-Leaping, \"],\n [\"eleventh\", \"eleven Pipers Piping, \"],\n [\"twelfth\", \"twelve Drummers Drumming, \"]]\n\ndef get_verses(line):\n opener = f\"On the {verses[line][0]} day of Christmas, my true love gave to me: \"\n verse = \"\".join(str(verses[i][1]) for i in range(line, -1, -1))\n return opener + (verse.replace(\"and \", \"\") if line == 0 else verse)\n\ndef recite(start_verse, end_verse):\n return \"\\n\".join(get_verses(line_n)\n for line_n in range(start_verse, end_verse + 1))\n\nprint(recite(0, 11))\n\nOn the first day of Christmas, my true love gave to me: a Partridge in a Pear Tree.\nOn the second day of Christmas, my true love gave to me: two Turtle Doves, and a Partridge in a Pear Tree.\nOn the third day of Christmas, my true love gave to me: three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\nOn the fourth day of Christmas, my true love gave to me: four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\nOn the fifth day of Christmas, my true love gave to me: five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\nOn the sixth day of Christmas, my true love gave to me: six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\nOn the seventh day of Christmas, my true love gave to me: seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\nOn the eighth day of Christmas, my true love gave to me: eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\nOn the ninth day of Christmas, my true love gave to me: nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\nOn the tenth day of Christmas, my true love gave to me: ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\nOn the eleventh day of Christmas, my true love gave to me: eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\nOn the twelfth day of Christmas, my true love gave to me: twelve Drummers Drumming, eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n</code></pre>\n\n<hr>\n\n<p>Some further things though:</p>\n\n<ul>\n<li><p>The <code>verse.replace(\"and \", \"\") if line == 0 else verse</code> seems like a code smell. It would probably be cleaner to <em>not</em> have \"and\" in the saved verse, and to add it when needed, instead of removing it in the special case.</p></li>\n<li><p>Instead of using <code>range(line, -1, -1)</code> to get reversed indices, you could probably use <code>reversed</code> and <code>islice</code> from <code>itertools</code> to get a sliced reversed iterator of the verses. That way you wouldn't need to index the list.</p></li>\n</ul>\n\n<p>I'd elaborate, but I need to get going. Good luck.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T18:30:26.367",
"Id": "442151",
"Score": "0",
"body": "Shouldn't I now subtract one from `start verse` instead of adding to `end_verse`? Otherwise, I'm getting `index out of range` error."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T18:50:19.817",
"Id": "442152",
"Score": "1",
"body": "@baduker I'm calling it as `recite(0, 11)`. That's what I meant by switching to 0-based indexing. I'll clarify when I get to my computer. I think the code itself should start at 0. If you had client-facing code that uses `recite`, and you wanted to use 1-based indexing there, you could make indexing adjustments then."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T17:29:42.997",
"Id": "227226",
"ParentId": "227222",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227226",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T16:41:51.497",
"Id": "227222",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"programming-challenge"
],
"Title": "Twelve Days of X-mas in Python"
}
|
227222
|
<p>I have a class that is used for serializing and deserializing global application variables. I would like to know if there is anything that I can improve. I know I could inject a dependency to support multiple different serializing formats, but that is not my concern. I would especially want to know if my locking does anything since I am not very proficient in locking.</p>
<p><code>CurrentLanguage</code> and <code>PointsCount</code> are the data that I serialize.</p>
<pre><code>public static class GlobalSettings
{
private static CultureInfo _currentLanguage;
public static CultureInfo CurrentLanguage
{
get { lock (Sync) return _currentLanguage; }
set { lock (Sync) _currentLanguage = value; }
}
public static IEnumerable<CultureInfo> AllLanguages => new List<CultureInfo>
{
new CultureInfo("en-US"),
new CultureInfo("pl-PL")
};
public static string DbPath => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data.db");
private static int _pointsCount;
public static int PointsCount
{
get { lock (Sync) return _pointsCount; }
set { lock (Sync) _pointsCount = value; }
}
public static bool LoadedSuccessfully = true;
public static Exception LoadedWithException = null;
private static bool _isLoaded;
private static readonly object Sync = new object();
private static readonly string SettingsFilePath;
static GlobalSettings()
{
var settingsRelativeFilePath = ConfigurationManager.AppSettings["SettingsRelativeFilePath"];
SettingsFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, settingsRelativeFilePath);
}
public static void Save()
{
lock (Sync)
{
if (!_isLoaded)
throw new InvalidOperationException("Load settings first");
var serializer = new XmlSerializer(typeof(GlobalSettingsStorage));
using (var file = File.Create(SettingsFilePath))
{
var settings = new GlobalSettingsStorage
{
CurrentLanguageShortName = CurrentLanguage.Name,
PointsCount = PointsCount
};
serializer.Serialize(file, settings);
}
}
}
public static bool TryLoad()
{
lock (Sync)
{
try
{
var fileExists = File.Exists(SettingsFilePath);
var deserializer = new XmlSerializer(typeof(GlobalSettingsStorage));
using (var reader = File.Open(SettingsFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
GlobalSettingsStorage settings = null;
if (!fileExists)
{
settings = new GlobalSettingsStorage();
deserializer.Serialize(reader, settings);
}
else
{
settings = (GlobalSettingsStorage)deserializer.Deserialize(reader);
}
_currentLanguage = new CultureInfo(settings.CurrentLanguageShortName);
_pointsCount = settings.PointsCount;
}
_isLoaded = true;
}
catch (InvalidOperationException ex) when (ex.InnerException is XmlException)
{
LoadedSuccessfully = false;
LoadedWithException = new SettingsLoadingException("XML settings file corrupted", ex);
return false;
}
catch (UnauthorizedAccessException ex)
{
LoadedSuccessfully = false;
LoadedWithException = new SettingsLoadingException("You do not have access to the settings file.", ex);
return false;
}
catch (Exception ex) when (ex is PathTooLongException || ex is DirectoryNotFoundException || ex is IOException)
{
LoadedSuccessfully = false;
LoadedWithException = new SettingsLoadingException("Failed to load settings file", ex);
return false;
}
return true;
}
}
}
[Serializable]
public sealed class GlobalSettingsStorage
{
public string CurrentLanguageShortName { get; set; }
public int PointsCount { get; set; }
public GlobalSettingsStorage()
{
CurrentLanguageShortName = ConfigurationManager.AppSettings["DefaultLanguage"];
PointsCount = int.Parse(ConfigurationManager.AppSettings["DefaultPointsCount"]);
}
}
</code></pre>
<p>I have property <code>LoadedSuccessfully</code>, because in WPF I want to show a user information if settings were not properly loaded and I show it as a popup.</p>
<pre><code>public async void OnDialogHostLoaded()
{
if (!GlobalSettings.LoadedSuccessfully)
{
var ex = GlobalSettings.LoadedWithException;
var message = string.Join(": ", ex.Message, ex.InnerException?.Message);
var popup = new PopupBoxView
{
DataContext = new PopupBoxViewModel(PopupBoxType.Ok, message, true)
};
NLog.LogManager.GetCurrentClassLogger().Fatal(ex);
await DialogHost.Show(popup, "RootHost");
Application.Current.Shutdown();
return;
}
}
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n<pre><code>public static int PointsCount\n{\n get { lock (Sync) return _pointsCount; }\n set { lock (Sync) _pointsCount = value; }\n}\n</code></pre>\n</blockquote>\n\n<p>I wonder why this property has a <code>public</code> setter? Is there a scenario where setting this form the <em>outside</em> would make sense?</p>\n\n<hr>\n\n<p>Other things...</p>\n\n<p>I like your exceptions. They clearly tell me what went wrong so I would instantly know how to fix that. You even have created a custom one <code>SettingsLoadingException</code>, kudos!</p>\n\n<p>I would however change how you handle this:</p>\n\n<blockquote>\n<pre><code>public static bool LoadedSuccessfully = true;\n</code></pre>\n</blockquote>\n\n<p>Make it <code>false</code> by default and set it to <code>true</code> only once when <code>TryLoad</code> succeeded. Currently you set it three time to <code>false</code> instead.</p>\n\n<p>You could also flip the logic with <code>return true</code> and do it onyl once before the first <code>catch</code>, this is, inside the <code>try</code> and do <code>return false</code> only once at the end of the method.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T18:09:39.813",
"Id": "227228",
"ParentId": "227227",
"Score": "2"
}
},
{
"body": "<p>You don't show how you actually call <code>TryLoad()</code>. So with that in mind here are some comments:</p>\n\n<blockquote>\n<pre><code>public static bool LoadedSuccessfully = true;\npublic static Exception LoadedWithException = null;\n\nprivate static bool _isLoaded;\n</code></pre>\n</blockquote>\n\n<p>What is the difference between <code>LoadedSuccessfully</code> and <code>_isLoaded</code>? The one is initially set to true, while the other is set to false, but they both indicate if the load was successful or not. I think you can remove one of them.</p>\n\n<p>Another issue is that <code>LoadedSuccessfully</code> and <code>LoadedWithException</code> are public settable. If they are of any use - see next comment - I would change them to private settable properties instead.</p>\n\n<p>These three fields have only meaning for the state of the object in the load process, because - as I read <code>OnDialogHostLoaded()</code> - you close the application in a following step in the load process, if loading the settings went wrong. In other words: you probably don't have a running application with <code>GlobalSettings.LoadedSuccessfully = false</code>. I think, I would remove these fields and reconsider the load process so you close the application immediately if <code>TryLoad()</code> fails like:</p>\n\n<pre><code>void OnLoad() // Or what ever you call it\n{\n try\n {\n GlobalSettings.Load();\n }\n catch (SettingsLoadingException ex)\n {\n // TODO: log and exit application\n // Maybe fire an event to let the main app notify user via UI\n }\n catch (Exception ex)\n {\n // TODO: log and exit application\n // Maybe fire an event to let the main app notify user via UI\n }\n}\n</code></pre>\n\n<p>Here <code>TryLoad()</code> is renamed to just <code>Load()</code> because it doesn't return a boolean but only throws on failure:</p>\n\n<pre><code>public static void Load()\n{\n lock (Sync)\n {\n try\n {\n var fileExists = File.Exists(SettingsFilePath);\n\n var deserializer = new XmlSerializer(typeof(GlobalSettingsStorage));\n using (var reader = File.Open(SettingsFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))\n {\n GlobalSettingsStorage settings = null;\n if (!fileExists)\n {\n settings = new GlobalSettingsStorage();\n deserializer.Serialize(reader, settings);\n }\n else\n {\n settings = (GlobalSettingsStorage)deserializer.Deserialize(reader);\n }\n\n _currentLanguage = new CultureInfo(settings.CurrentLanguageShortName);\n _pointsCount = settings.PointsCount;\n }\n }\n catch (InvalidOperationException ex) when (ex.InnerException is XmlException)\n {\n throw new SettingsLoadingException(\"XML settings file corrupted\", ex);\n }\n catch (UnauthorizedAccessException ex)\n {\n throw new SettingsLoadingException(\"You do not have access to the settings file.\", ex);\n }\n catch (Exception ex) when (ex is PathTooLongException || ex is DirectoryNotFoundException || ex is IOException)\n {\n throw new SettingsLoadingException(\"Failed to load settings file\", ex);\n }\n catch (Exception ex)\n {\n throw new SettingsLoadingException(\"General exception occured\", ex);\n }\n }\n}\n</code></pre>\n\n<p>I've added a general catch clause to catch all unknown exceptions by, so that you can rethrow a <code>SettingsLoadeingException</code> for them as well.</p>\n\n<hr>\n\n<p>I imagine that the reason for having <code>LoadedSuccessfylly</code> is that you postpone handling a possible failure in <code>GlobalSettings.TryLoad()</code> to <code>OnDialogHostLoaded()</code>. IMO you handle the settings failure in the wrong place: what have loading the settings to do with loading the \"dialog host\"? </p>\n\n<hr>\n\n<p>You only catch specific exceptions. What happens to more general exceptions or special exceptions that don't meet the conditions in your catch clauses?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> GlobalSettingsStorage settings = null;\n if (!fileExists)\n {\n settings = new GlobalSettingsStorage();\n deserializer.Serialize(reader, settings);\n }\n else\n</code></pre>\n</blockquote>\n\n<p>Why is it necessary to save an empty settings file, if it doesn't exist when trying to load it? You somehow break the single responsibility principle here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T07:43:59.710",
"Id": "227256",
"ParentId": "227227",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T17:33:50.153",
"Id": "227227",
"Score": "3",
"Tags": [
"c#",
"wpf",
"configuration"
],
"Title": "Static global settings class with serializing"
}
|
227227
|
<p>Recentely I have started teaching myself some basic AI concepts and this was my first attemp at using a random forest in order to classify the iris data set. It would be great if anyone could give me any sort of feedback on the code, specifically the style and readability. I apologize if the code block is formatted incorrectly (this is my first time using stack exchange). Thank you!</p>
<pre><code>import numpy as np
from sklearn.model_selection import cross_validate
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
# Data goes through preprocessing, Label encoding is used to map
# String identifiers to float
def data_processor(input_file):
data = []
with open(input_file, 'r') as f:
for line in f:
line = line.strip().split(',')
if line[-1] == 'Iris-setosa':
line[-1] = 0
elif line[-1] == 'Iris-versicolor':
line[-1] = 1
elif line[-1] == 'Iris-virginica':
line[-1] = 2
data.append(line)
return np.array(data, dtype=float)
# create array of data and array of index
x, y = data_processor('iris.txt')[:, :-1], data_processor('iris.txt')[:, -1]
# create training and test data set, 80% training 20% test
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.20,
random_state=5)
# params used to create classifier
# number of trees - 150, node depth - 5, random seed
params = {'n_estimators': 150, 'max_depth': 5, 'random_state': 10}
classifier = ExtraTreesClassifier(**params)
classifier.fit(x_train, y_train)
# make prediction
y_test_pred = classifier.predict(x_test)
# output info on model performance
class_names = ['Setosa', 'Versicolor', 'Virginica']
print("Training dataset results\n")
print(classification_report(y_train, classifier.predict(x_train),
target_names=class_names))
print("Testing dataset results\n")
print(classification_report(y_test, y_test_pred, target_names=class_names))
</code></pre>
|
[] |
[
{
"body": "<p>First of all, pandas, scikit-learn, numpy, keras and tf come with a lot of data loading utilities. </p>\n\n<ul>\n<li>Your <code>data_processor(input_file)</code> can be replaced with <code>pandas.read_csv()</code>.</li>\n<li>Alternatively, IRIS dataset is avaiable at <code>sklearn.datasets.load_iris()</code></li>\n</ul>\n\n<p>I would advise to have a look at <a href=\"https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html#examples-using-sklearn-datasets-load-iris\" rel=\"nofollow noreferrer\">Scikit-learn's example of analyzing IRIS</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T16:23:07.637",
"Id": "442420",
"Score": "0",
"body": "Hi,\nThank you for your reply and suggestions!\nThe reason i did not use the pandas module was because the input file was in txt format. I know that this is convertable to csv, however I wanted to work on the original file.\nIn regards to the iris data set that comes with sklearn, I did not want to import the data for the same reason, mainly to create a reusable function to work on text files of this format.\nI suppose that this may make the process computaionally slower, however I did not consider this a hinderance for a small data sample."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T14:41:47.380",
"Id": "227336",
"ParentId": "227229",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T18:44:18.290",
"Id": "227229",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"ai"
],
"Title": "FIrst time trying tree classifier in python"
}
|
227229
|
<p>I have solved the following exercise and would like to get some feedback on my implementation.</p>
<blockquote>
<p>Create a function that uses futures to parallelize the task of downloading random quotes from <a href="https://www.braveclojure.com/random-quote" rel="nofollow noreferrer">https://www.braveclojure.com/random-quote</a> using <code>(slurp "http://www.braveclojure.com/random-quote")</code>. The futures should update an atom that refers to a total word count for all quotes. The function will take the number of quotes to download as an argument and return the atom’s final value. Keep in mind that you’ll need to ensure that all futures have finished before returning the atom’s final value.</p>
</blockquote>
<pre><code>(defn quote-word-count
[quote-count]
(->> quote-count
(range)
(map (fn [_] (fetch-quote)))
(pmap (comp count-words deref))
(apply merge-with +)
(atom)))
(defn fetch-quote
[]
(future (slurp "https://www.braveclojure.com/random-quote")))
(defn update-word
[word-counts word]
(update word-counts word (comp inc zero)))
(defn zero
[number]
(if (= nil number) 0 number))
(defn count-words
[quote]
(let [cleaned-quote (clean-input quote)]
(reduce update-word {} (clojure.string/split cleaned-quote #" "))))
(defn clean-input
[input]
((comp remove-commas remove-author clojure.string/lower-case) input))
(defn remove-author
[quote]
(clojure.string/replace quote #".\n-- .*\n" ""))
(defn remove-commas
[quote]
(clojure.string/replace quote #"," ""))
</code></pre>
<p>Things I am not sure about:</p>
<ol>
<li>the <code>range</code> then <code>map</code> to create the calls</li>
<li>the top-down order of functions</li>
<li>the atom. the exercise says to return an atom but I don't understand why I would need that</li>
</ol>
<p>Any feedback is appreciated.</p>
|
[] |
[
{
"body": "<p>For <code>quote-word-count</code>, there's a few things to note.</p>\n\n<p>I think this is a good use of <code>->></code>. Personally, I would have started the threading with <code>(range quote-count)</code> instead of splitting that though. From my experience, needlessly elongating the thread call just hurts readability. I also recommend maintaining the same type of object being threaded all the way down. I find it makes the thread much easier to understand. If you're threading collections like you are here, I'd prefer that every object being threaded is a collection (whereas <code>quote-count</code> is a number).</p>\n\n<p>It isn't a good idea to use <code>map</code> to run side effects (like starting a <code>future</code> task). <code>map</code> doesn't run its effect immediately, so the futures aren't started when <code>(map (fn [_] (fetch-quote)))</code> runs, they're started when the <code>pmap</code> begins requesting elements. I'd switch to <code>mapv</code> which is strict, so the future's are started right away.</p>\n\n<p>I don't think that <code>map</code>ping a <code>range</code> is the right approach here though; which is hinted at by your use of a wrapper <code>(fn [_])</code> function. <a href=\"https://clojuredocs.org/clojure.core/repeatedly\" rel=\"nofollow noreferrer\"><code>repeatedly</code></a> would be a better candidate for this situation. It's lazy though, so I'd probably add a call to <code>vec</code> after it to realize it right away.</p>\n\n<hr>\n\n<p>Your <code>zero</code> is actually unnecessary. <a href=\"https://clojuredocs.org/clojure.core/fnil\" rel=\"nofollow noreferrer\"><code>fnil</code></a> can be used here instead:</p>\n\n<pre><code>(update word-counts word (fnil inc 0)))\n</code></pre>\n\n<hr>\n\n<p>I wouldn't have parameters called <code>quote</code> ideally. <code>quote</code> is a rather important built-in, and it's a good idea to avoid shadowing built-ins.</p>\n\n<hr>\n\n<p>I'd probably use <code>->></code> in <code>count-words</code>:</p>\n\n<pre><code>(defn count-words\n [quote]\n (let [cleaned-quote (clean-input quote)]\n (->> (clojure.string/split cleaned-quote #\" \")\n (reduce update-word {}))))\n</code></pre>\n\n<p>I personally find that to be much more readable than the nested version.</p>\n\n<p>I'll note too that Clojure has the built-in <a href=\"https://clojuredocs.org/clojure.core/frequencies\" rel=\"nofollow noreferrer\"><code>frequencies</code></a> that can do the work here:</p>\n\n<pre><code>(defn count-words\n [quote]\n (let [cleaned-quote (clean-input quote)]\n (->> (clojure.string/split cleaned-quote #\" \")\n (frequencies))))\n</code></pre>\n\n<hr>\n\n<p>In <code>clean-input</code>, I wouldn't use <code>comp</code>. I think it would be much neater using <code>-></code>:</p>\n\n<pre><code>(defn clean-input\n [input]\n (->> input\n (clojure.string/lower-case)\n (remove-author)\n (remove-commas)))\n</code></pre>\n\n<p>I really only like <code>comp</code> when it's being passed to another function. Writing out <code>((comp g f) x)</code> just seems like an overly complicated way of applying <code>x</code> to <code>f</code> then <code>g</code>.</p>\n\n<hr>\n\n<p>Your functions are in reverse order for some reason. I'm not sure where you're running this that's allowing for functions to be used before they're declared.</p>\n\n<hr>\n\n<p>Personally, I like having the parameter vector on the first line unless I have a doc string. I find the functions look noisy otherwise.</p>\n\n<hr>\n\n<p>You're writing <code>clojure.string/</code> a fair amount. You may want to <code>require</code> that module to avoid verbose, qualified function calls. While you're at it, you might as well add a <a href=\"https://clojuredocs.org/clojure.core/ns\" rel=\"nofollow noreferrer\"><code>ns</code></a> macro call, since each file should really have one anyways:</p>\n\n<pre><code>(ns your.file.path.here\n (:require [clojure.string :as s]))\n</code></pre>\n\n<p>Now, <code>clojure.string/split</code> can be written as <code>s/split</code>.</p>\n\n<hr>\n\n<p>And for 3.:</p>\n\n<blockquote>\n <p>The function will take the number of quotes to download as an argument and return the <strong>atom’s final value</strong>.</p>\n</blockquote>\n\n<p>It wants you to return the value of the atom, not the atom itself. They want you to update an atom inside the futures; although I don't think that's necessary, or even preferable.</p>\n\n<hr>\n\n<hr>\n\n<p>Here's the final code I ended up with:</p>\n\n<pre><code>(ns your.file.path.here\n (:require [clojure.string :as s]))\n\n(defn remove-author [quote]\n (s/replace quote #\".\\n-- .*\\n\" \"\"))\n\n(defn remove-commas [quote]\n (s/replace quote #\",\" \"\"))\n\n(defn clean-input [input]\n (->> input\n (s/lower-case)\n (remove-author)\n (remove-commas)))\n\n(defn count-words [quote]\n (let [cleaned-quote (clean-input quote)]\n (->> (s/split cleaned-quote #\" \")\n (frequencies))))\n\n(defn fetch-quote []\n (future (slurp \"https://www.braveclojure.com/random-quote\")))\n\n(defn quote-word-count [quote-count]\n (->> (repeatedly quote-count fetch-quote)\n (vec) ; To ensure futures start before pmap begins processing chunks\n (pmap (comp count-words deref))\n (apply merge-with +)))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T08:42:13.210",
"Id": "442213",
"Score": "0",
"body": "Thank you, all of this is really helpful"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T22:10:05.977",
"Id": "227238",
"ParentId": "227231",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "227238",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T19:54:21.160",
"Id": "227231",
"Score": "3",
"Tags": [
"concurrency",
"clojure"
],
"Title": "Count Words in Quotes Fetched from Website"
}
|
227231
|
<p>I'm wondering if there's a better way to write the ApiService and the CategoryService so that CategoryService is basically just a call to extend ApiService with the string 'category' and the base type 'ICategory' or if this is the best that I can get from typescript and angular? There will be many more endpoint services in the final app</p>
<p>Any other general comments on code style etc are also very welcome (or if anyone knows how to tell Webstorm to not put the constructor closing braces on the next line!!)</p>
<p>ApiService</p>
<pre><code>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '../../environments/environment';
const baseUrl = environment.serverBaseUrl;
const apiEndpoint = environment.apiEndpoint || '/api/v1/';
const apiUrl = `${baseUrl}${apiEndpoint}`;
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) {
}
private createTokenOptions() {
return {headers: new HttpHeaders().set('Authorization', `Bearer ${localStorage.getItem('access_token')}`)};
}
get<T>(serviceEndpoint: string, id?: number): Observable<T> {
let url = `${apiUrl}${serviceEndpoint}`;
if (id) {
url += `/${id}`;
}
return this.http.get<T>(url, this.createTokenOptions());
}
create<T>(serviceEndpoint, item: T): Observable<object> {
const options = this.createTokenOptions();
options.headers = options.headers.append('Content-Type', 'application/json');
return this.http.post(`${apiUrl}${serviceEndpoint}`, JSON.stringify(item), options);
}
delete<T>(serviceEndpoint: string, id: number): Observable<T> {
return this.http.delete<T>(`${apiUrl}${serviceEndpoint}/${id}`, this.createTokenOptions());
}
}
</code></pre>
<p>CategoryService</p>
<pre><code>import { Injectable } from '@angular/core';
import { ApiService } from './api.service';
import { Observable } from 'rxjs';
import { ICategory } from '../interfaces/category.model';
@Injectable({
providedIn: 'root'
})
export class CategoryService {
private serviceEndpoint = 'category';
constructor(private api: ApiService) {
}
getCategories() {
return this.api.get<ICategory[]>(this.serviceEndpoint);
}
getCategory(id: number): Observable<ICategory> {
return this.api.get<ICategory>(this.serviceEndpoint, id);
}
createCategory(category: ICategory) {
return this.api.create<ICategory>(this.serviceEndpoint, category);
}
deleteCategory(id: number) {
return this.api.delete<ICategory>(this.serviceEndpoint, id);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I think you can use <a href=\"https://medium.com/@ryanchenkie_40935/angular-authentication-using-the-http-client-and-http-interceptors-2f9d1540eb8\" rel=\"nofollow noreferrer\">HTTP Interceptors</a> to simplify the code.</p>\n\n<h3>For the authorization</h3>\n\n<pre><code>@Injectable()\nexport class AuthorizationInterceptor implements HttpInterceptor {\n\n constructor() {\n }\n\n intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {\n\n // skip requests for local assets\n if (request.url.indexOf(\"assets/\") >= 0) {\n return next.handle(request);\n }\n\n const apiReq = request.clone({\n url: request.url,\n headers: request.headers.set('Authorization', `Bearer ${localStorage.getItem('access_token')}`)\n });\n return next.handle(apiReq);\n }\n}\n</code></pre>\n\n<h3>For the base url</h3>\n\n<p>Something along the line</p>\n\n<pre><code>@Injectable()\nexport class BaseUrlInterceptor implements HttpInterceptor {\n\n constructor(\n @Inject(\"BASE_API_URL\") private baseUrl: string) {\n }\n\n intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {\n\n // skip requests for local assets\n // maybe put extra condition to allow for multiple API usage\n if (request.url.indexOf(\"assets/\") >= 0) {\n return next.handle(request);\n }\n\n const apiReq = request.clone({\n url: `${this.baseUrl}${request.url}`\n });\n return next.handle(apiReq);\n }\n}\n</code></pre>\n\n<p>Of course, the module should define the interceptors:</p>\n\n<pre><code> providers: [\n {\n provide: HTTP_INTERCEPTORS,\n useClass: AuthorizationInterceptor,\n multi: true\n }\n ]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T16:45:03.573",
"Id": "442269",
"Score": "1",
"body": "Thanks great suggestion for the interceptors. I went with just checking if the url has the baseurl for my rest service in there and to add the bearer token if so. \n\nI did keep the base api and the various rest endpoints as I think there's a lot to be said for it being easy to follow, I would love a way to do something like a spring jpa repo in java where I could just declare class CategoryService extends ApiService<'category', Category>"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T20:52:47.827",
"Id": "227233",
"ParentId": "227232",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "227233",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T20:23:42.183",
"Id": "227232",
"Score": "3",
"Tags": [
"generics",
"typescript",
"angular-2+"
],
"Title": "Angular Rest API generic service and implementation service"
}
|
227232
|
<p>This is a snake game I made, </p>
<p><strong>Note:</strong> at this point, I would like to hear <strong>any</strong> thoughts/ reviews about it.</p>
<p>Thank you</p>
<p><a href="https://i.stack.imgur.com/sBEuN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sBEuN.png" alt="The game"></a></p>
<p><strong>Game class:</strong></p>
<pre><code>package snake;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable{
public static final int WIDTH = 720;
public static final int HEIGHT = 720;
public static final int BLOCK_SIZE = 30; //Do not change - size of the food and snake body part
//as well as their images
private Thread thread;
private boolean running;
private Snake snake;
private Food food;
public Game(){
initializeWindow();
snake = new Snake(this);
food = new Food();
food.generateLocation(snake.getCopyOfEmptySpaces());
initializeKeyAdapter();
start();
}
private synchronized void start() {
thread = new Thread(this);
running = true;
thread.start();
this.requestFocus();
}
public void run() {
double amountOfTicks = 10d; //ticks amount per second
double nsBetweenTicks = 1000000000 / amountOfTicks;
double delta = 0;
long lastTime = System.nanoTime();
while(running) {
long now = System.nanoTime();
delta += (now - lastTime) / nsBetweenTicks;
lastTime = now;
while (delta >= 1) {
tick();
delta--;
}
render();
}
}
public void tick() {
if (snake.isDead()) {
running = false;
}
else {
if (isEating()) {
food.generateLocation(snake.getCopyOfEmptySpaces());
}
snake.tick();
}
}
public void render() {
if (running) {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, Game.WIDTH, Game.HEIGHT);
food.render(g);
snake.render(g);
if (snake.isDead()) {
g.setColor(Color.white);
g.setFont(new Font("Tahoma", Font.BOLD, 75));
g.drawString("Game Over", Game.WIDTH / 2 - 200 , Game.HEIGHT / 2);
}
g.dispose();
bs.show();
}
}
public boolean isEating() {
return snake.getHeadCoor().equals(food.getCoor());
}
private JFrame initializeWindow() {
JFrame frame = new JFrame("Snake Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(this);
this.setPreferredSize(new Dimension(Game.WIDTH, Game.HEIGHT));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
return frame;
}
private void initializeKeyAdapter() {
//this is how to game gets keyboard input
//the controls are wasd keys
class MyKeyAdapter extends KeyAdapter{
private int velocity = Snake.DEFAULT_SPEED; //move a whole block at a time
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ESCAPE) {
System.exit(0);
}
//after a key has been pressed we check if the snake goes the opposite way
//if so, we ignore the press
if (key == KeyEvent.VK_S) {
if (snake.getVelY() != -velocity) {
snake.setVel(0, velocity);
}
}
else if (key == KeyEvent.VK_W) {
if (snake.getVelY() != velocity) {
snake.setVel(0, -velocity);
}
}
else if (key == KeyEvent.VK_D) {
if (snake.getVelX() != -velocity) {
snake.setVel(velocity, 0);
}
}
else if (key == KeyEvent.VK_A) {
if (snake.getVelX() != velocity) {
snake.setVel(-velocity, 0);
}
}
}
}
this.addKeyListener(new MyKeyAdapter()); //adding it to the game
}
public static void main(String[] args) {
Game g = new Game();
}
}
</code></pre>
<p><strong>Snake class:</strong> </p>
<pre><code>package snake;
import java.awt.Graphics;
import java.awt.Image;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
import javax.swing.ImageIcon;
public class Snake {
public static final int DEFAULT_SPEED = Game.BLOCK_SIZE;
private Game game;
private int velX;
private int velY;
private LinkedList<Coor> body; //snake's body
private Set<Coor> emptySpaces; //valid spots for food- spots without snake parts
private boolean dead;
private Image img; //img of other body parts
/*
* @pre: Game.HEIGHT / Game.BLOCK_SIZE == 0 && Game.WIDTH / Game.BLOCK_SIZE == 0
* @pre: Game.HEIGHT % 2 == 0
* @pre: Game.WIDTH > 3 * Game.BLOCK_SIZE
* @post: the snake starts at the middle of the screen
*/
Snake(Game game){
this.game = game;
body = new LinkedList<Coor>();
//starting snake
int halfScreenHeight = Game.HEIGHT / 2;
body.add(new Coor(2 * Game.BLOCK_SIZE, halfScreenHeight)); //head block
body.add(new Coor(Game.BLOCK_SIZE, halfScreenHeight)); //middle block
body.add(new Coor(0, halfScreenHeight)); //last block
velX = DEFAULT_SPEED;
initializeEmptySpaces();
initializeImage();
}
public void tick() { //updating the body and checking for death
/* Updating body:
* Explanation: the Coor of the n-th body part is the Coor of the head n ticks ago
* Execution: adding the current head Coor to the body, and pushing all other
* Coors one place. If the snake hasn't eat this turn than we will remove
* the last Coor in the body. Oterwise, it has eat and needs to grow,
* in that case we'll keep it
* Result: the body will be: [Coor now, before 1 tick, before 2 ticks, ...]
*/
int prevHeadX = body.getFirst().getX();
int prevHeadY = body.getFirst().getY();
body.push(new Coor(prevHeadX + velX, prevHeadY + velY)); //new head Coor
if (!game.isEating()) {
Coor lastCoor = body.getLast();
body.removeLast();
emptySpaces.add(lastCoor); //now there is no body part on it
}
emptySpaces.remove(getHeadCoor());
checkDeath();
}
public void render(Graphics g) {
for (Coor curr : body) {
g.drawImage(img, curr.getX(), curr.getY(), null);
}
}
private void checkDeath() {
Coor h = getHeadCoor();
if (h.getX() < 0 || h.getX() > Game.WIDTH - Game.BLOCK_SIZE) { //invalid X
dead = true;
}
else if (h.getY() < 0 || h.getY() > Game.HEIGHT - Game.BLOCK_SIZE) { //invalid Y
dead = true;
}
else {
dead = false;
for (int i = 1; i < body.size(); i++) { //compare every non-head body part's coor with head's corr
if (getHeadCoor().equals(body.get(i))) { //head touched a body part
dead = true;
}
}
}
}
public void setVel(int velX, int velY) {
this.velX = velX;
this.velY = velY;
}
public int getVelX() {
return velX;
}
public int getVelY() {
return velY;
}
public boolean isDead() {
return dead;
}
public Set<Coor> getCopyOfEmptySpaces() {
return new HashSet<Coor>(emptySpaces);
}
private void initializeEmptySpaces() {
emptySpaces = new HashSet<Coor>();
for (int i = 0; i * Game.BLOCK_SIZE < Game.WIDTH; i++) {
for (int j = 0; j * Game.BLOCK_SIZE < Game.HEIGHT; j++) {
emptySpaces.add(new Coor(i * Game.BLOCK_SIZE, j * Game.BLOCK_SIZE));
}
}
emptySpaces.removeAll(body); //remove the starting snake parts
}
private void initializeImage() {
ImageIcon icon = new ImageIcon("src/res/snake.png");
img = icon.getImage();
}
public Coor getHeadCoor() {
return body.getFirst();
}
}
</code></pre>
<p><strong>Food class:</strong></p>
<pre><code>package snake;
import java.awt.Graphics;
import java.awt.Image;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;
import javax.swing.ImageIcon;
public class Food {
private Image img;
private Coor coor;
Food(){
initializeImages();
}
public void render(Graphics g) {
g.drawImage(img, coor.getX(), coor.getY(), null);
}
public void generateLocation(Set<Coor> set) { //picking a random coordinate for the food
int size = set.size();
Random rnd = new Random();
int rndPick = rnd.nextInt(size);
Iterator<Coor> iter = set.iterator();
for (int i = 0; i < rndPick; i++) {
iter.next();
}
Coor chosenCoor = iter.next();
coor = chosenCoor;
}
private void initializeImages() {
ImageIcon icon = new ImageIcon("src/res/food.png");
img = icon.getImage();
}
public Coor getCoor() {
return coor;
}
}
</code></pre>
<p><strong>Coor class:</strong> </p>
<pre><code>package snake;
public class Coor { //coordinates
//we divide the screen to rows and columns, distance
//between two rows or two columns is Game.BLOCK_SIZE
private int x;
private int y;
Coor(int x, int y){
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
@Override
public int hashCode() {
return x * Game.WIDTH + y;
}
@Override
public boolean equals(Object o) {
Coor c = (Coor) o;
if (x == c.getX() && y == c.getY()) {
return true;
}
return false;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T09:26:59.763",
"Id": "442218",
"Score": "0",
"body": "Hello, have you checked [Point](https://docs.oracle.com/javase/8/docs/api/java/awt/Point.html) class for coordinates?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T09:42:27.883",
"Id": "442221",
"Score": "0",
"body": "I have, didn't want to cast to int every time I use getx() and getY() methods."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T10:06:02.170",
"Id": "442225",
"Score": "0",
"body": "Ok one question, you are overriding `equals` and `hashCode` methods in the Coor class. normally `instanceof` is present in `equals` method, have the system (ide, etc.) generated them ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T10:23:03.973",
"Id": "442226",
"Score": "0",
"body": "@dariosicily Actually I don't know (I think yes).. maybe someone else will answer it."
}
] |
[
{
"body": "<p><code>Coor</code> has the comment <code>coordinates</code> ... yeah, that's exactly what the\nname should be then. But actually, <code>Point</code> seems easier and doesn't\nhave to be abbreviated, or perhaps be more general and say <code>Vector</code>, or\n<code>Vec2</code>, that seems fairly common for games (despite it being an\nabbreviation). Not using the AWT class makes sense to me too.</p>\n\n<p>The <code>hashCode</code> method\n<a href=\"https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/Object.html#hashCode()\" rel=\"nofollow noreferrer\">is okay</a>,\nthough it could probably be a bit more random in its output (not that it\nmatters for such small numbers of it.</p>\n\n<p>The <code>equals</code> method\n<a href=\"https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/Object.html#equals(java.lang.Object)\" rel=\"nofollow noreferrer\">could be more safe</a>\nand also consider passing in arbitrary objects (or <code>null</code>) for\ncomparison. Violating this is probably okay for this limited scope, but\nin general that shouldn't be skipped.</p>\n\n<p>Also the return statement can be simplified.</p>\n\n<pre><code>@Override\npublic boolean equals(Object o) {\n if (o == null || !(o instanceof Coor)) {\n return false;\n }\n Coor c = (Coor) o;\n return x == c.getX() && y == c.getY();\n}\n</code></pre>\n\n<hr>\n\n<p>The <code>Food</code> class uses these abbreviated names, <code>img</code>, <code>rnd</code>, etc. I'd\nsuggest writing them out and giving them some more descriptive names in\ngeneral.</p>\n\n<p>The loop in <code>generateLocation</code> seems a bit bogus to me, why skip a\nrandom number of random numbers before picking one? If you have\nproblems getting repeated numbers each run of the program you should\nperhaps initialise it from a truly random source.</p>\n\n<hr>\n\n<p><code>Snake</code> has <code>velX</code> and <code>velY</code> - that's exactly where a <code>Vector</code> would\ncome in handy again. After all it's exactly that, a 2-tuple exactly\nlike what <code>Coor</code> is.</p>\n\n<p><code>checkDeath</code> could use a <code>for (x : body) ...</code> for the death check, plus,\nonce <code>dead = true</code> was set, a <code>break</code> would also be good.</p>\n\n<hr>\n\n<p>Okay, so generally, I'd suggest not carrying around a set of empty\nspaces. Keeping the taken coordinates for the snake and for the food is\nfine. Using those you can immediately see which coordinates are empty\n... all the ones that aren't taken. Given the few food items and the\nlength of the snake the list of coordinates that's easy enough to check\nagainst.</p>\n\n<p>Apart from that <code>MyKeyAdapter</code> (well that should be <code>MyKeyAdaptor</code>) is a\nbit weird how it's just inline there like that. And that goes for the\nother classes too, it's all mixing the representation via Swing with the\ngame state and that's, at least for bigger games/projects, not\nadvisable. Then again, it's snake. Just consider how you'd handle\nextending this code to encompass more features, like different kinds of\nobjects, or how e.g. customisable key bindings would work.</p>\n\n<p>So, it'd perhaps make sense to have a <code>Renderable</code> interface for the\n<code>render</code> method, then keep a list of objects to render in a more generic\nfashion, or even combine it with the <code>tick</code> method (perhaps with a\ndefault implementation on the interface) to update all game objects.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T12:36:49.483",
"Id": "443258",
"Score": "0",
"body": "About the name abbreviation- wouldn't it make the code just longer? I guess it's true about coor since it's a class, but aren't img (image) and rnd (random) common abbreviations?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T12:58:37.790",
"Id": "443262",
"Score": "0",
"body": "[I wanted to pm this one but apparently it's impossible]\nAbout the hashCode- I thought its role is to sort the same objects together (if easily done). since there is fairly easy way of doing so in that case I didn't want to use randoms. \nAbout generateLocation- can you explain \"you should perhaps initialise it from a truly random source\"? Since the hashCode isn't random the coordinates in the set will be in same order, so I wanted to skip some (random amount) of coors.\n*Would you use the same type for both coors and (velX, velY)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T13:06:32.547",
"Id": "443265",
"Score": "0",
"body": "*I didn't use foreach loop in checkDeath because I wanted to skip the head.\n*Doesn't using break is a bad practice? I thought you shuld use booleans for that.\n*(Last one) Should have I place the keyAdeptor in its own class even though it only used in the game?\n\n*** **Thank you** very much for the review. I totally agree on the before-last paragraph- is there a game-dev guide you recommend?\nAlso if you could answer even some of my followup questions it would be great.\nbtw sorry for my English :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T13:54:44.110",
"Id": "443345",
"Score": "0",
"body": "Re abbreviation: Yes, there's different opinions on it. IMO, `img` for `image` isn't saving me much reading, as is `rnd` for `random`. One could argue single letter variables are even better then and indeed lots of Go or Haskell code uses single letter variables for better or worse. If you decide to keep it, just apply it consistently."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T14:01:33.027",
"Id": "443346",
"Score": "0",
"body": "`hashCode` is for ... hashing, if all objects had the same `hashCode` value they'd still need to be sortable according to `equals`. \"... the coordinates in the set will be in the same order\": okay, misunderstood the intent; well if the set is small (as it is here) this is the right approach. However, you'll obviously run into problems if your set is getting bigger and bigger. And lastly, yes, same data type for coordinates and velocity, both can just be (2-element) vectors (of `int`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T14:09:04.573",
"Id": "443347",
"Score": "0",
"body": "\"I wanted to skip the head\" - right, I'm sure there's a helper somewhere to skip the first element of a traversal. Anyway, if that's the reason, fine. `break` is absolutely fine, if you don't want to use it, make `dead` part of the `for` loop condition: `!dead && i < body.size()` to abort as early as possible. `MyKeyAdapter`, well I'd say yes, considering it's going to get bigger, also simply saying `new MyKeyAdapter(snake)` should already get you there mostly. Anyway, it's not the biggest deal. Your English is just fine!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T23:43:43.883",
"Id": "227609",
"ParentId": "227234",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "227609",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T20:53:56.790",
"Id": "227234",
"Score": "6",
"Tags": [
"java",
"object-oriented",
"game",
"snake-game"
],
"Title": "java - Basic snake game"
}
|
227234
|
<pre><code>public final class App extends javafx.application.Application {
@Override
public void start(Stage primaryStage) {
var rectangle = new Rectangle(150, 100, Color.BLACK);
var text = new Text("START");
text.setFill(Color.WHITE);
var vbox2 = new VBox(text);
vbox2.setAlignment(Pos.CENTER);
var array = new ArrayList<Circle_color>() {
{
add(new Circle_color("RED1", "RED2", 1, 2, Color.RED));
add(new Circle_color("GREEN1", "GREEN2", 3, 4, Color.GREEN));
add(new Circle_color("BLUE1", "BLUE2", 5, 6, Color.BLUE));
}
};
var array2 = new ArrayList<Circle_white>() {
{
add(new Circle_white("RED1", "RED2", 1));
add(new Circle_white("GREEN1", "GREEN2", 3));
add(new Circle_white("BLUE1", "BLUE2", 5));
add(new Circle_white("CYAN1", "CYAN2", 7));
}
};
var vbox = new VBox();
vbox.getChildren().addAll(array);
vbox.getChildren().addAll(array2);
Stream.concat(array.stream(), array2.stream()).forEach((t) -> {
set(t, rectangle, vbox2);
});
var stack_pane = new StackPane(rectangle, vbox2);
stack_pane.setLayoutX(250);
stack_pane.setLayoutY(100);
primaryStage.setScene(new Scene(new Pane(stack_pane, vbox), 800, 800));
primaryStage.show();
}
public void set(My_circle circle, Rectangle rectangle, VBox vbox) {
circle.setOnMouseEntered((event) -> {
event.consume();
var effect = new BoxBlur(0, 0, 1);
vbox.getChildren().forEach((t) -> {
t.setEffect(effect);
});
var fill = new FillTransition(Duration.seconds(1), rectangle, (Color) rectangle.getFill(), (Color) circle.getFill());
var timeline = new Timeline(
new KeyFrame(Duration.millis(500),
new KeyValue(effect.widthProperty(), 10),
new KeyValue(effect.heightProperty(), 10)
)
);
timeline.setOnFinished((event2) -> {
vbox.getChildren().clear();
vbox.getChildren().addAll(circle.get());
vbox.getChildren().forEach((t) -> {
t.setEffect(effect);
});
new Timeline(
new KeyFrame(Duration.millis(500),
new KeyValue(effect.widthProperty(), 0),
new KeyValue(effect.heightProperty(), 0)
)
).play();
});
new ParallelTransition(fill, timeline).play();
});
}
public static void main(String[] args) {
launch(args);
}
}
...
public final class Circle_color extends My_circle implements Get {
public String text, text2;
public int number, number2;
public Circle_color(String text, String text2, int number, int number2, Color color) {
super(50, color);
this.text = text;
this.text2 = text2;
this.number = number;
this.number2 = number2;
}
@Override
public ArrayList<Text> get() {
return new ArrayList<>() {
{
add(new Text(text));
add(new Text(text2));
add(new Text(String.valueOf(number)));
add(new Text(String.valueOf(number2)));
}
};
}
}
...
public final class Circle_white extends My_circle implements Get {
String text, text2;
int number;
public Circle_white(String text, String text2, int number) {
super(50, Color.WHITE);
this.text = text;
this.text2 = text2;
this.number = number;
setStroke(Color.BLACK);
}
@Override
public ArrayList<Text> get() {
return new ArrayList<>() {
{
add(new Text(text));
add(new Text(text2));
add(new Text(String.valueOf(number)));
}
};
}
}
...
public abstract class My_circle extends javafx.scene.shape.Circle implements Get {
public My_circle(int number, Color color) {
super(number, color);
}
}
...
public interface Get {
ArrayList<Text> get();
}
</code></pre>
<p>I hastily created an example presenting my problem.</p>
<p>This is the code for five files - 4 classes (<code>App</code>, <code>My_Circle</code>, <code>Circle_white</code>, <code>Circle_color</code>) and <code>Get</code> interface.</p>
<p>The program creates 3 <code>Circle_color</code> objects and 4 <code>Circle_white</code> objects and adds them all to the <code>VBox</code>.</p>
<p>And these objects, when you hover over them, create an animation to change the color of the rectangle and change the text.</p>
<p>Better to try.</p>
<p>The program works, but there are a few problems.</p>
<p><strong>1.</strong> The <code>set</code> method was originally in both classes (<code>Circle_white</code> and <code>Circle_color</code>)</p>
<p>Since they only differed in the fields used, otherwise they were identical, so I deleted them and created only one in the <code>App</code> class.</p>
<p>The problem was two things</p>
<p><strong>1.1</strong> The method must accept objects of both classes.</p>
<p>That was easy, both classes are extends from the same class, so I used that class as the parameter type.</p>
<p><strong>1.2</strong> Use of fields.
For both classes, I created a <code>get</code> method that returns them in the desired form.</p>
<p>Unfortunately, thanks to the solution in <strong>1.1</strong>, these methods cannot be used, so I have to create a <code>Get</code> interface. However, it cannot be implemented in the <code>javafx.scene.shape.Circle</code> class, so I have to create <code>My_circle</code> class that is extends from the <code>javafx.scene.shape.Circle</code> and from it are extends of the <code>Circle_color</code> and <code>Circle_white</code> class.</p>
<p>It's simple and functional, but I still want to ask if this is the ideal solution?</p>
<p><strong>2.</strong> Using the <code>VBox</code>.</p>
<p>Although this is only part of the example, I still want to ask.</p>
<p><strong>2.1</strong> There is a way to initialize a <code>VBox</code> while adding <code>ArrayList</code> to it. <code>VBox</code> does not have such a constructor.</p>
<p><strong>2.2</strong> How to replace all elements with <code>ArrayList</code>?</p>
<p><strong>3.</strong> Code of the set method or the animation itself.</p>
<p><strong>3.1</strong> I have no idea how an animation should behave if I move to another element without completing the current animation. The color always changes from the current color, but how should the text behave?</p>
<p><strong>3.2</strong> If after the text animation is finished, I first replace all elements and call another animation. Both last half a second, which coincides with a one-second color change. Still, I want to make sure that both animations end at the same time.</p>
<p>Please help.</p>
<p>Thank you</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T21:57:40.333",
"Id": "227237",
"Score": "2",
"Tags": [
"java",
"animation",
"javafx",
"layout"
],
"Title": "Optimize animation, use parameters for different types of objects and work with VBox"
}
|
227237
|
<p>This program prompts the user to enter a file name and displays the occurrences of each letter in the file.
Is there a simpler and more efficient way to do this? Please, help me figure this out. Thanks!</p>
<pre><code>import java.io.*;
import java.util.Scanner;
public class OccurenceOfEachLetter {
public static void main(String[] args) {
//declares variables
String[] sentence = new String [23];
int countA = 0;
int countB = 0;
int countC = 0;
int countD = 0;
int countE = 0;
int countF = 0;
int countG = 0;
int countH = 0;
int countI = 0;
int countJ = 0;
int countK = 0;
int countL = 0;
int countM = 0;
int countN = 0;
int countO = 0;
int countP = 0;
int countQ = 0;
int countR = 0;
int countS = 0;
int countT = 0;
int countU = 0;
int countV = 0;
int countW = 0;
int countX = 0;
int countY = 0;
int countZ = 0;
char words;
//Get user input
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a Filename: ");
String filename = keyboard.nextLine();
//Open file for reading
Scanner inputStream = null;
//catch exception
try
{
inputStream = new Scanner(new File(filename));
}
catch(FileNotFoundException e)
{
System.out.print("Error opening the " + filename);
System.exit(0);
}
//read form file and store in an array
while(inputStream.hasNextLine())
{
for (int i = 0; i < sentence.length; i++)
{
sentence[i] = inputStream.nextLine();
//counts the occurrence of each letter in each line of gettysburg.txt
for(int j = 0; j < sentence[i].length() ;j++)
{
words = sentence[i].charAt(j);
if(words == 'A' || words == 'a')
{
countA++;
}
if(words == 'B' || words == 'b')
{
countB++;
}
if(words == 'C' || words == 'c')
{
countC++;
}
if(words == 'D' || words == 'd')
{
countD++;
}
if(words == 'E' || words == 'e')
{
countE++;
}
if(words == 'F' || words == 'f')
{
countF++;
}
if(words == 'G' || words == 'g')
{
countG++;
}
if(words == 'H' || words == 'h')
{
countH++;
}
if(words == 'I' || words == 'i')
{
countI++;
}
if(words == 'J' || words == 'j')
{
countJ++;
}
if(words == 'K' || words == 'k')
{
countK++;
}
if(words == 'L' || words == 'l')
{
countL++;
}
if(words == 'M' || words == 'm')
{
countM++;
}
if(words == 'N' || words == 'n')
{
countN++;
}
if(words == 'O' || words == 'o')
{
countO++;
}
if(words == 'P' || words == 'p')
{
countP++;
}
if(words == 'Q' || words == 'q')
{
countQ++;
}
if(words == 'R' || words == 'r')
{
countR++;
}
if(words == 'S' || words == 's')
{
countS++;
}
if(words == 'T' || words == 't')
{
countT++;
}
if(words == 'U' || words == 'u')
{
countU++;
}
if(words == 'V' || words == 'v')
{
countV++;
}
if(words == 'W' || words == 'w')
{
countW++;
}
if(words == 'X' || words == 'x')
{
countX++;
}
if(words == 'Y' || words == 'y')
{
countY++;
}
if(words == 'Z' || words == 'z')
{
countZ++;
}
}
}
}//end while
//close file
inputStream.close();
//Displays results
System.out.println("The file gettysburg.txt contains the following: ");
for(char i = 65 ; i <= 90;)
{
int[] count = {countA, countB, countC, countD, countE, countF, countG, countH, countI, countJ, countK, countL, countM, countN, countO, countP, countQ, countR, countS, countT, countU, countV, countW, countX, countY, countZ};
for(int j = 0; j< count.length;)
{
System.out.println("Number of " + i +"'s: " + count[j]);
j++;
i++;
}
}
}//ends main
}//ends class
</code></pre>
|
[] |
[
{
"body": "<p>Welcome to CodeReview! Especially as a beginner programmer, it takes bravery to show your code to the internet, but you've taken the first step.</p>\n\n<p>This code has a long way to go, but I think it'll be a good learning experience for you.</p>\n\n<pre><code>//declares variables\n</code></pre>\n\n<p>Keep in mind that this isn't 1989-era C, so you don't need to predeclare all of your variables at the top of methods. Declare them where they're actually used.</p>\n\n<pre><code>String[] sentence = new String [23];\n</code></pre>\n\n<p>What is the number 23? This is a so-called magic number. If it really needs to be in the program, it should be put in its own named constant. However, I suspect that this is the number of lines of input. First: you already have logic to quit once you find the end of the file. Also: why store every line? You only need to store the results of letter summation, not the raw input. So this array is not necessary.</p>\n\n<pre><code>inputStream = new Scanner(new File(filename)); \n</code></pre>\n\n<p>Google \"try-with-resources\". This will make it so that your program will close the file even if something goes wrong in the middle.</p>\n\n<pre><code>for (int i = 0; i < sentence.length; i++) \n</code></pre>\n\n<p>This loop can go away entirely. The <code>while</code> above it already iterates through the lines of the file.</p>\n\n<pre><code>int countA = 0;\n</code></pre>\n\n<p>You should not have each of these as individual values. You arrived at the right idea later on with the <code>count</code> array. All of those individual letter count variables should go away and you should operate on the array directly.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T01:55:38.090",
"Id": "227247",
"ParentId": "227244",
"Score": "4"
}
},
{
"body": "<p>I focus on the operation of storing occurrences of single letters of a sentence in an array of ints and after print the number of occurrences for every single letter, I'm assuming that we are using the english alphabet:</p>\n\n<pre><code>int[] occurrences = new int[26];\n</code></pre>\n\n<p>Now start to examine a sentence and convert it to a char array:</p>\n\n<pre><code>String sentence = \"Gettysburg, PA\";\nchar[] arr = sentence.toCharArray();\nfinal char initial = 'a';\n</code></pre>\n\n<p>You want to store only letters as case insensitive so for example occurrences of chars <code>A</code> and <code>a</code> will be stored in the same position of the occurrences array, you can do in this way:</p>\n\n<pre><code>for (char ch : arr) {\n if (Character.isLetter(ch)) {\n char ch_lower = Character.toLowerCase(ch);\n ++occurrences[ch_lower - initial];\n }\n}\n</code></pre>\n\n<p>You can refer to <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html\" rel=\"nofollow noreferrer\">Character</a> documentation for further details about methods I used in the loop. Now you can print all the occurrences in the array:</p>\n\n<pre><code>String format = \"Number of %c: %d\";\nfor(int i = 0; i < 26; ++i) {\n System.out.println(String.format(format, initial + i, occurrences[i]));\n}\n</code></pre>\n\n<p>I used the method <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#format-java.lang.String-java.lang.Object...-\" rel=\"nofollow noreferrer\">String.format</a> for improve readibility of print code.\nBelow the code you can test:</p>\n\n<pre><code>public static void main(String[] args) {\n\n int[] occurrences = new int[26];\n\n\n final char initial = 'a'; \n String sentence = \"Gettysburg, PA\";\n char[] arr = sentence.toCharArray();\n for (char ch : arr) {\n if (Character.isLetter(ch)) {\n char ch_lower = Character.toLowerCase(ch);\n ++occurrences[ch_lower - initial];\n }\n }\n String format = \"Number of %c: %d\";\n for(int i = 0; i < 26; ++i) {\n System.out.println(String.format(format, initial + i, occurrences[i]));\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T12:07:30.090",
"Id": "442247",
"Score": "0",
"body": "This is not equivalent. You need to open a file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T14:04:12.383",
"Id": "442253",
"Score": "0",
"body": "@Reinderien Hello, I wrote at the start of my answer that my focus is about storing occurrences of single letters of a sentence in an array of ints and after print them."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T09:18:51.537",
"Id": "227260",
"ParentId": "227244",
"Score": "2"
}
},
{
"body": "<p>Perhaps the next piece of code may be overwhelming for a Java beginner, due to the fact that it uses advanced features of the language such as streams, lambdas, and try-with-resource clauses. However, just for showing a different approach using functional programming, your program could be rewritten as follows:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> public static void main(String[] args) {\n try (Scanner scanner = new Scanner(System.in)) {\n System.out.print(\"Enter a Filename: \");\n Path file = Paths.get(scanner.next());\n try (Stream<String> lines = Files.lines(file)) {\n System.out.println(\"The file \"+file+\" contains the following: \");\n lines\n .flatMapToInt(String::chars)\n .filter(Character::isAlphabetic)\n .map(Character::toLowerCase)\n .mapToObj(c->(char)c)\n .collect(Collectors.groupingBy(Function.identity(),Collectors.counting()))\n .forEach((letter,count)->System.out.println(\"Number of \"+letter+\"'s: \"+count));\n } catch (IOException e) {\n System.out.println(\"Error opening the file \"+file);\n System.exit(0);\n }\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T11:09:54.380",
"Id": "227458",
"ParentId": "227244",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227247",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T00:03:46.557",
"Id": "227244",
"Score": "4",
"Tags": [
"java",
"beginner"
],
"Title": "Count the occurrence of each letter in a file in Java"
}
|
227244
|
<p>I need to write a method that will print the integers from <code>[1, maxValue]</code> in a pyramid where the <code>nth</code> row contains <code>n</code> numbers like so (for <code>printChart(24)</code>):</p>
<pre><code>1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24
</code></pre>
<p>I am wondering if there is a way to optimize my code for functionality, simplicity, or computational complexity (although I doubt the latter, because I think this runs at <span class="math-container">\$O(n)\$</span> time).</p>
<p>It has one helper function, which returns a boolean value representing whether or not a given integer, <code>n</code>, is a perfect square.</p>
<pre><code>public boolean isPerfectSquare(int n){
int root = (int) Math.sqrt(n);
return root * root == n;
}
public void printChart(int maxValue) {
int number = 1;
while (number <= maxValue) {
System.out.print(number + " ");
/* A number n can be determined to be triangular iff
8n+1 is a perfect square; if n is a triangular number,
print a line after it*/
if(isPerfectSquare(8*number+1)) { System.out.println(); }
number++;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T06:45:03.750",
"Id": "442193",
"Score": "2",
"body": "Your example is misleading, the sixth row contains 9 numbers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T08:03:28.377",
"Id": "442206",
"Score": "1",
"body": "Hello, I executed your code, and numbers 22, 23, 24 appear below the last row that ends with number 21."
}
] |
[
{
"body": "<p>You're doing things quite the hard way. You don't need to call <code>sqrt</code>, or determine perfect squares at all. Simply track <code>y</code>, and as soon as the row's <code>x</code> == <code>y</code>, make a newline, increment <code>y</code> and set <code>x</code> = 0.</p>\n\n<p>The following examples show different results from what you've described:</p>\n\n<pre><code>import java.io.StringWriter;\nimport java.lang.Math;\n\nclass Pyramid {\n interface ChartMethod {\n abstract void run(int n);\n }\n\n static boolean isPerfectSquare(int n){\n int root = (int) Math.sqrt(n);\n return root * root == n;\n }\n\n static void chart_squares(int maxValue) {\n int number = 1;\n while (number <= maxValue) {\n System.out.print(number + \" \");\n\n /* A number n can be determined to be triangular iff\n 8n+1 is a perfect square; if n is a triangular number,\n print a line after it*/\n if (isPerfectSquare(8*number + 1))\n System.out.println();\n number++;\n }\n\n System.out.println();\n }\n\n static void chart_coords(int maxValue) {\n int number = 1, y = 0, x = 0;\n while (number <= maxValue) {\n System.out.print(number + \" \");\n\n if (x == y) {\n x = 0;\n y++;\n System.out.println();\n }\n else\n x++;\n\n number++;\n }\n System.out.println();\n }\n\n static void chart_coordloop(int maxValue) {\n int number = 1;\n for (int y = 0;; y++) {\n for (int x = 0; x <= y; x++) {\n System.out.print(number + \" \");\n if (number++ >= maxValue) {\n System.out.println();\n return;\n }\n }\n System.out.println();\n }\n }\n\n static void chart_incr(int maxValue) {\n int increment = 2, next = 1;\n for (int number = 1; number <= maxValue; number++) {\n System.out.print(number + \" \");\n if (number == next) {\n next += increment;\n increment++;\n System.out.println();\n }\n }\n System.out.println();\n }\n\n static void chart_buf(int maxValue) {\n StringWriter sw = new StringWriter();\n int increment = 2, next = 1;\n for (int number = 1; number <= maxValue; number++) {\n sw.write(number + \" \");\n if (number == next) {\n next += increment;\n increment++;\n sw.write('\\n');\n }\n }\n System.out.println(sw.toString());\n }\n\n static final ChartMethod[] methods = new ChartMethod[] {\n Pyramid::chart_squares,\n Pyramid::chart_coords,\n Pyramid::chart_coordloop,\n Pyramid::chart_incr,\n Pyramid::chart_buf\n };\n\n static void test(ChartMethod method) {\n method.run(7);\n }\n\n static void time(ChartMethod method) {\n long start = System.nanoTime();\n final int N = 200000;\n method.run(N);\n long dur = System.nanoTime() - start;\n\n System.err.println(String.format(\"%.3f us\", dur / 1e3 / N));\n }\n\n public static void main(String[] args) {\n for (ChartMethod method: methods)\n time(method);\n }\n}\n</code></pre>\n\n<p>This shows:</p>\n\n<pre><code>1.381 us\n1.196 us\n1.157 us\n1.140 us\n0.234 us\n</code></pre>\n\n<p>The most important thing is to buffer the output before writing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T01:36:03.880",
"Id": "442171",
"Score": "0",
"body": "As I understand it, that does not work here. Could you possibly show an example code so I can better understand what you mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T01:42:24.293",
"Id": "442172",
"Score": "0",
"body": "Edited. The only potential edge case is if the maximum number produces what would be a smaller row at the bottom. If, as your illustration shows, you need the bottom row to always be the widest, you'll need to add another clause to that `if`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T02:04:36.053",
"Id": "442173",
"Score": "0",
"body": "actually still works in the edge case you mentioned. Weirdly enough, my slightly more complex method (which I would expect to take longer to run?) tends to take around .3 seconds fewer to perform the same 1000 operations than your method. Any idea why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T02:09:32.053",
"Id": "442174",
"Score": "0",
"body": "Tough to say. `sqrt` might be using a highly-efficient processor instruction that takes less time than the additional complexity of having more variables in the loop that are affected by conditional logic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T02:13:43.620",
"Id": "442175",
"Score": "0",
"body": "I wrote an alternate implementation; I'd be interested to hear how it compares"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T02:18:17.367",
"Id": "442176",
"Score": "0",
"body": "I actually had an implementation very similar to this previously, and aside from being slightly more difficult to read, it was not as efficient (around .6 seconds slower for 1000 operations). Not the same implementation though, so this could be an improvement?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T04:21:42.760",
"Id": "442180",
"Score": "1",
"body": "So in my test, `sqrt` came out last."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T01:28:50.847",
"Id": "227246",
"ParentId": "227245",
"Score": "2"
}
},
{
"body": "<p>Not sure how using roots help you, but here is my solution to the porblem (a pyramid, n-th row has length of n):</p>\n\n<p>EDIT: I assumed that if the number won't be a perfect pyramid (like 24) then print until the number. If you want to print the biggest pyramid possible it simplifies the code a bit.</p>\n\n<pre><code>public static String pyr(int n) { //n is the target num\n String str = \"\";\n int currNum = 1;\n int rowLength = 1;\n while (currNum <= n) {\n for (int i = 0; i < rowLength; i++) {\n if (currNum <= n) { \n //we want to go until n (not the end of this line)\n System.out.print(currNum + \" \");\n currNum++;\n }\n }\n rowLength++;\n System.out.println();\n }\n return str;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T18:15:29.907",
"Id": "227427",
"ParentId": "227245",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T01:20:35.813",
"Id": "227245",
"Score": "2",
"Tags": [
"java",
"console",
"formatting",
"complexity"
],
"Title": "Print Integers in a Pyramid"
}
|
227245
|
<p>This is a script to check the sequence number (8 bit unsigned integer) in a binary file and make sure it is incrementing till the end and not missing any sequence number in between. Sequence number is some 'x' bytes from a sentinel found in the binary file. The fixed size packet (some audio data) in binary file gets repeated and this aforementioned packet also has the sentinel along with other audio data.</p>
<p>I am new to python so I'd appreciate a code review.</p>
<pre><code>#!/usr/bin/python
import sys,getopt
def parse_arguments():
def usage():
print("python script to check missing sequence number in a binary file")
print("pass filename, packet_size(optional) and sequence offset where sequence number is found in the packet")
print("python %s -f filename -s packet_size -i sequence_offset"% (sys.argv[0]))
filename, packet_size, sequence_offset = None, 0, None
try:
opts,args = getopt.getopt(sys.argv[1:],'ha:f:i:s:', ['help', 'filename', 'index'])
except getopt.GetoptError as err:
print(err)
sys.exit(2)
if len(opts) != 0:
for (o, a) in opts:
if o in ('-h', '--help'):
usage()
sys.exit()
elif o in ('-f', '--filename'):
filename = a
elif o in ('-s', '--packet_size'):
packet_size = int(a)
elif o in ('-i', '--sequence_offset'):
sequence_offset = int(a)
else:
usage()
sys.exit(2)
else:
usage()
sys.exit(2)
return filename, packet_size, sequence_offset
def is_sequence_missing(filename, packet_size = 5392, sequence_offset = 11):
def get_sequence_idx(filename, sentinel = ['0x4f', '0x5f', '0x4d', '0x41']):
blob = None
with open(filename,"rb") as f:
blob = f.read()
len_sentinel = len(sentinel)
for i in range(len(blob)):
if i + len_sentinel < len(blob) and sentinel == [hex(ord(j)) for j in blob[i:i+len_sentinel]]:
return (blob, i)
return (blob, None)
missing, start, counter = False, True, 0
blob, idx = get_sequence_idx(filename)
if not idx:
print("sentinel not found")
return not missing
print("sentinel starting at 0x%x"% (idx))
for i in range(idx - sequence_offset, len(blob), packet_size):
v = ord(blob[i])
if start:
print("started with sequence number 0x%x"% (v))
start = False
counter = v + 1
continue
if counter == v:
counter += 1
if counter == 256:
counter = 0
else:
print("not matching expected: 0x%x receieved: 0x%x at 0x%x"% (counter, v, i))
counter = v + 1
missing = True
return missing
if __name__ == "__main__":
filename, packet_size, sequence_offset = parse_arguments()
print("passed filename %s packet_size %d sequence_offset %d"% (filename, packet_size, sequence_offset))
if is_sequence_missing(filename, packet_size, sequence_offset) == True:
print("sequence is missing")
else:
print("sequence is not missing")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T16:01:07.780",
"Id": "442263",
"Score": "0",
"body": "I don't get it, you compute `idx` and don't use it afterwards. What's its use then?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T18:40:45.383",
"Id": "442297",
"Score": "0",
"body": "@MathiasEttinger: Thanks, I forgot to update the updated code."
}
] |
[
{
"body": "<h1>Style</h1>\n\n<p>Python comes with an <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">official style guide</a> (often just called PEP8) which is commonly accepted among Python programmers. Since you said you are new to Python, I wholeheartedly recommend to read and follow it. </p>\n\n<p>E.g. one of the recommendations of the style guide is to indent code by <a href=\"https://www.python.org/dev/peps/pep-0008/#indentation\" rel=\"nofollow noreferrer\">4 spaces per indentation level</a>, while you have a mix of 2 and four spaces. Even if you decide to stick with 2 spaces: be consistent!</p>\n\n<p>Another very widely accepted convention is to have no whitespace around <code>=</code> if used in keyword-arguments to functions, e.g. instead of</p>\n\n<blockquote>\n<pre><code>def is_sequence_missing(filename, packet_size = 5392, sequence_offset = 11): \n</code></pre>\n</blockquote>\n\n<p>use </p>\n\n<pre><code>def is_sequence_missing(filename, packet_size=5392, sequence_offset=11):\n</code></pre>\n\n<h1>Outdated Python</h1>\n\n<p>Your code uses some parts of the Python language which have become a bit \"rusty\", i.e. have been superseded in later versions of the language. Especially in the light of <a href=\"https://pythonclock.org/\" rel=\"nofollow noreferrer\">soon to come end-of-life of Python 2.7</a>, I would highly recommend to have a look at Python 3 or at least use \"more current\" features of Python 2.7.</p>\n\n<p>A few examples:</p>\n\n<h2>Command-line arguments</h2>\n\n<p>Your code uses <code>getopt</code> to parse command-line arguments. <code>getopt</code> has been superseded by <a href=\"https://docs.python.org/2/library/optparse.html\" rel=\"nofollow noreferrer\"><code>optparse</code></a>, which in turn has been marked as deprecated starting from Python 2.7 to be replaced by <a href=\"https://docs.python.org/2/library/argparse.html\" rel=\"nofollow noreferrer\"><code>argparse</code></a> (see also <a href=\"https://stackoverflow.com/a/3217687/5682996\">this SO post</a> from 2010!) from there on. Apart from being easier to use, <code>argparse</code> will e.g. also generate and show usage instructions if the user fails to give the correct arguments.</p>\n\n<p><strong>Further reading:</strong> The official and reasonably comprehensive <a href=\"https://docs.python.org/2/howto/argparse.html\" rel=\"nofollow noreferrer\">tutorial</a> on <code>argparse</code>.</p>\n\n<h2>String formatting</h2>\n\n<p>String output is generated using the old <code>%</code> formatting. As of Python 2.6, the recommended way is to use <code>str.format</code> for string formatting. If you happen to have access to Python 3.6 and later, also so called f-strings are available to you which make the whole thing even more comfortable. An example from your code:</p>\n\n<pre><code>\"not matching expected: 0x%x received: 0x%x at 0x%x\"% (counter, v, i)\n\"not matching expected: 0x{:x} received: 0x{:x} at 0x{:x}\".format(counter, v, i) # Python 2.6+\nf\"not matching expected: 0x{counter:x} received: 0x{v:x} at 0x{i:x}\" # Python 3.6+\n</code></pre>\n\n<p><strong>Further reading:</strong> <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\">This blog post</a> has a nice comparison of all three variants and their possibilities.</p>\n\n<h1>General recommendations</h1>\n\n<h2>Variable definition</h2>\n\n<p>Usually it's always a good idea to define your variables as close as possible to where they are needed, and also arguably define one variable per line. This helps to avoid unused or uninitialized variables, although the later part is not so critical here in Python as it would be e.g. in C or C++.</p>\n\n<h2>Documentation</h2>\n\n<p>Also not strictly specific to Python: Do yourself (and possible also others) a favor and document your code. Maybe in a few months time where you have done something different you will (have to) come back and wonder why the default value for <code>sequence_offset</code> is <code>11</code>. Python has a feature called <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">docstrings</a> which are also described in the style guide (and in more detail in <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">PEP 257</a>) and are very commonly found in Python code. docstrings are essentially <code>\"\"\"triple quoted strings\"\"\"</code> placed immediately after the function definition, trying to describe what to expect from the function. As an example:</p>\n\n<pre><code>def is_sequence_missing(filename, packet_size=5392, sequence_offset=11):\n \"\"\"Check file for gaps in the sequence number\n\n read up binray data from filename and check for ascending\n sequence numbers starting sequence_offset (default: 11) bytes away\n from the sentinel value\n \"\"\"\n # rest of the code here\n</code></pre>\n\n<p>Documentation written using docstrings will be picked up by Python's built-in <code>help(...)</code> as well as by most Python IDEs.</p>\n\n<hr>\n\n<p><strike>That's all for now. Maybe I can spare some time tomorrow to have a closer look at the actual algorithm.</strike> <strong>Edit:</strong> See the <a href=\"https://codereview.stackexchange.com/a/227356/92478\">second answer</a> for a more detailed feedback on the actual algorithm.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T18:29:53.213",
"Id": "442444",
"Score": "0",
"body": "Possible to review my logic and reduce the amount of code as I think it is still c style code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T18:31:34.307",
"Id": "442445",
"Score": "0",
"body": "@nomanpouigt: Looking into it at the moment."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T21:59:35.310",
"Id": "227286",
"ParentId": "227251",
"Score": "2"
}
},
{
"body": "<p>This answer covers the algorithmic aspect of the code. If you feel this second answer goes against the spirit of the Stack Exchange network, consider voting on the <a href=\"https://codereview.stackexchange.com/a/227286/92478\">first answer</a> instead or leaving a comment to express your judgement.</p>\n\n<hr>\n\n<h1>The algorithm</h1>\n\n<p>Since your question to me seems a bit vague on some parts of the data, there is a little bit of guesswork involved in the following sections, so take them with a grain of salt. I think they will nevertheless help you get an idea what to look for.</p>\n\n<h2><code>get_sequence_idx</code></h2>\n\n<p>If I understood the intent of the code correctly, its purpose is to look for some kind of sentinel value in binary data to tell where the sequence started. For that purpose, you iterate over your input file byte by byte, convert a slice of sentinel's byte length to its hex representation and compare it against the sentinel. That seems a little bit overkill to me. You will have to check this, but I think the following piece of code is actually functionaly equivalent:</p>\n\n<pre><code>def get_sequence_idx(filename, sentinel=\"\\x4f\\x5f\\x4d\\x41\"):\n \"\"\"Read the binary data and find the position of the sentinel\n\n This function returns the binary data as present in the file as well as\n the sentinel's (given as byte-string) position in the file. If the\n sentinel value was not found, the second return value is None.\n \"\"\"\n with open(filename, \"rb\") as f:\n blob = f.read()\n idx = blob.find(sentinel)\n return blob, idx if idx > 0 else None\n</code></pre>\n\n<p>So what has happend here? I converted <code>sentinel</code> from a list of hexadecimal values to a \"byte\"-string (the term is a bit inaccurate in Python 2)<sup>1</sup>. That allows us to use <a href=\"https://docs.python.org/2/library/string.html#string.find\" rel=\"nofollow noreferrer\"><code>.find(...)</code></a> on the input data to look for the sequence instead of doing it manually. <code>.find(...)</code> returns the index of the first instance where the search string was found, and <code>-1</code> if it was not found. So if you were to return <code>-1</code> instead of <code>None</code> in case of no sentinel value, the little <a href=\"https://docs.python.org/2/reference/expressions.html#conditional-expressions\" rel=\"nofollow noreferrer\">ternary expression</a> would not be necessary and you could just <code>return blob, blob.find(sentinel)</code>. Since you did not provide test data you will have to verify yourself that it's actually working in your specific use-case.</p>\n\n<h2><code>is_sequence_missing</code></h2>\n\n<p>Now let's look at <code>is_sequence_missing</code> piece by piece:</p>\n\n<blockquote>\n<pre><code>missing, start, counter = False, True, 0\n</code></pre>\n</blockquote>\n\n<p>cries \"C code\"! That aspect was already covered in the general recommendations section of the previous answer.</p>\n\n<blockquote>\n<pre><code>if not idx:\n print(\"sentinel not found\")\nreturn not missing\n</code></pre>\n</blockquote>\n\n<p>Since you actually want to take action in case <code>idx</code> has the value <code>None</code>, you should likely also do that <code>if idx is None:</code>. This is also in-line with the <a href=\"https://www.python.org/dev/peps/pep-0008/#programming-recommendations\" rel=\"nofollow noreferrer\">Programming Recommendations</a> section of PEP8, which recommends to compare singleton values (like <code>None</code>) using <code>is</code>. The intent of <code>return not missing</code> can also be made more clear simply by doing <code>return True</code>. This also allows you to narrow down the scope of <code>missing</code> since it will only ever be needed if you pass this initial check.</p>\n\n<p>The rest of the code is IMHO mostly as straightforward as it gets, so there are only a few minor points that may improve the readability of your code. First, you can get rid of the <code>continue</code> if you use <code>if ...: elif ...: else:</code> instead of <code>if ...: if ...: else:</code>. If you stick with your current branch structure, putting a blank line after the first <code>if</code> statement can make it clearer that this is actually a seperate block that is not to be seen as part of the later \"condition chain\". Regarding the <code>else</code> branch: I think here is a opportunity to stop the loop early. If I'm not mistaken, there is no chance <code>missing</code> will ever become <code>False</code> again once you have set it to <code>True</code>. So if you don't need to have all the discontinued sequence numbers to be printed to stdout, a simple <code>break</code> there would allow the loop to end the first time you entered the <code>else</code> branch. In that case <code>missing</code> could also be omitted altogether to be replaced by <code>return True</code> in the <code>else</code> branch and by <code>return False</code> at the end of the function.</p>\n\n<h2><code>if __name__ == \"__main__\":</code></h2>\n\n<p>Using <code>if __name__ == \"__main__\":</code> is considered good practice in Python to clearly mark what code is supposed to be run if the file is used as a script. Often, programmers go even further and wrap the code that is surrounded by <code>if __name__ == \"__main__\":</code> into a <code>main()</code> function. That way no variables pollute the global namespace if you run the script in an interactive Python interpreter.</p>\n\n<pre><code>def main():\n filename, packet_size, sequence_offset = parse_arguments()\n print(\"passed filename %s packet_size %d sequence_offset %d\" %\n (filename, packet_size, sequence_offset))\n if is_sequence_missing(filename, packet_size, sequence_offset):\n print(\"sequence is missing\")\n else:\n print(\"sequence is not missing\")\n\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n\n<hr>\n\n<p><sup>1</sup> Python 3 is more specific in that regard so there is a chance that you will end up with something like <code>sentinel=b\"\\x4f\\x5f\\x4d\\x41\"</code> or some encoding/decoding.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T20:37:49.057",
"Id": "442466",
"Score": "0",
"body": "thanks for the review. I voted this answer as I was looking for my code structure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T03:21:59.110",
"Id": "442490",
"Score": "0",
"body": "find also works perfectly."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T20:11:07.010",
"Id": "227356",
"ParentId": "227251",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227356",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T05:31:53.730",
"Id": "227251",
"Score": "3",
"Tags": [
"python",
"beginner",
"parsing"
],
"Title": "script to check sequence number in a binary file"
}
|
227251
|
<p>I have this code which is a third-party transfer for ATM console app. For best practice, should I just put all the code into one try block or with multiply try block like below?</p>
<pre><code>class ATMConsoleApp
{
internal void Execute()
{
// todo: to replace these below with a automated test case - start
// Notes: Since login module is not ready, below code is temporary used to test
// the function.
BankAccount bankAccount;
using (AppDbContext db = new AppDbContext())
{
Console.WriteLine("Enter account id: ");
int id = int.Parse(Console.ReadLine());
bankAccount = db.BankAccounts.Find(id);
}
if (bankAccount == null)
{
Console.WriteLine("Account not found");
return;
}
// todo: to replace these below with a automated test case - end
BankAccountService accountService = new BankAccountService();
while (true)
{
int amount = 0;
Console.WriteLine("1. Check balance");
Console.WriteLine("2. Deposit");
Console.WriteLine("3. Withdraw");
Console.WriteLine("4. Third-Party Transfer");
Console.WriteLine("0. Exit Program");
Console.Write("Enter option: ");
string opt = Console.ReadLine();
switch (opt)
{
case "1":
Console.WriteLine($"Your balance is ${accountService.CheckBalanceAmount(bankAccount.Id)}");
break;
case "2":
amount = GetAmount();
try
{
accountService.DepositAmount(bankAccount, amount);
Console.WriteLine($"Deposited RM {amount} successfully.");
}
catch (Exception ex)
{
// todo: write ex.stacktrace into text file for programmer to do troubleshooting.
Console.WriteLine(ex.Message);
}
break;
case "3":
amount = GetAmount();
try
{
accountService.WithdrawAmount(bankAccount, amount);
Console.WriteLine($"Withdrew RM {amount} successfully. Please collect your RM {amount} cash. ");
}
catch (Exception ex)
{
// todo: write ex.stacktrace into text file for programmer to do troubleshooting.
Console.WriteLine(ex.Message);
}
break;
case "4":
amount = GetAmount();
BankAccount recipientAccount;
var accountNumber = GetAccountNo();
try
{
// Validation
recipientAccount = accountService.FindAccountName(accountNumber);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
break;
}
Console.WriteLine($"Account Name: {recipientAccount.AccountName}");
Console.Write("Enter 1 to confirm or 0 to cancel: ");
string confirm = Console.ReadLine();
switch (confirm)
{
case "1":
// Withdraw
try
{
accountService.WithdrawAmount(bankAccount, amount);
// Deposit
accountService.DepositAmount(recipientAccount, amount);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
break;
}
break;
default:
break;
}
break;
default:
break;
}
}
}
}
</code></pre>
<p>class BankAccountService</p>
<pre><code>public void DepositAmount(BankAccount bankAccount, int amount)
{
using (var ctx = new AppDbContext())
{
using (var trans = ctx.Database.BeginTransaction())
{
try
{
bankAccount.Balance += amount;
ctx.BankAccounts.Update(bankAccount);
var transaction = new Transaction()
{
BankAccountId = bankAccount.Id,
Amount = amount,
TransactionDateTime = DateTime.Now,
TransactionType = TransactionType.Deposit
};
ctx.Transactions.Add(transaction);
ctx.SaveChanges();
trans.Commit();
}
catch
{
trans.Rollback();
}
}
}
}
public void WithdrawAmount(BankAccount bankAccount, int amount)
{
if (amount > bankAccount.Balance)
{
throw new Exception("Withdraw amount exceed account balance.");
}
using (var ctx = new AppDbContext())
{
using (var trans = ctx.Database.BeginTransaction())
{
try
{
bankAccount.Balance -= amount;
ctx.BankAccounts.Update(bankAccount);
var transaction = new Transaction()
{
BankAccountId = bankAccount.Id,
Amount = amount,
TransactionDateTime = DateTime.Now,
TransactionType = TransactionType.Withdraw
};
ctx.Transactions.Add(transaction);
ctx.SaveChanges();
trans.Commit();
}
catch
{
trans.Rollback();
throw;
}
}
}
}
</code></pre>
<p>Bank Account Domain Model Entity</p>
<pre><code> public class BankAccount
{
public int Id { get; set; }
public int AccountNumber { get; set; }
public string AccountName { get; set; }
public string CardNumber { get; set; }
public string CardPin { get; set; }
public decimal Balance { get; set; }
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T07:32:33.737",
"Id": "442199",
"Score": "2",
"body": "I would post more code, so we get an idea what you are doing exactly. Also, could you describe the business case of this code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T07:55:15.020",
"Id": "442202",
"Score": "0",
"body": "okay, I have added more code already"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T08:03:44.630",
"Id": "442207",
"Score": "1",
"body": "Okay, done. It is pretty long though. That's why I extracted it out earlier."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T08:04:31.170",
"Id": "442208",
"Score": "2",
"body": "It's better long than too short. We rarely encounter 'too long' here ;-) It's on-topic now if you'd ask me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T09:25:41.727",
"Id": "442216",
"Score": "5",
"body": "_That's why I extracted it out earlier._ - let us decide ourselfs what is important next time and just dump your code as is. The devil is in the details and if you keep them from us, so has the feedback the same simplified character."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T10:58:33.183",
"Id": "442230",
"Score": "1",
"body": "Your question title should explain what your code does, not your question about the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T01:03:20.633",
"Id": "442301",
"Score": "0",
"body": "I assume you don't have more specific exceptions?"
}
] |
[
{
"body": "<p>In general, you could use some proper validation of the user input...</p>\n\n<hr>\n\n<blockquote>\n<pre><code> Console.WriteLine(\"0. Exit Program\");\n</code></pre>\n</blockquote>\n\n<p>I don't think that entering \"0\" actually exit the program. It just goes to <code>default</code> in the switch statement and continues the outer while-loop.</p>\n\n<hr>\n\n<p>If you should have one general try-catch block in the loop or dedicated ones must depend on what you want to do after an exception is thrown/caught in each case. In your code one single block should be sufficient, because you in all cases break the switch and reenter the outer while loop.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T10:15:25.377",
"Id": "227263",
"ParentId": "227253",
"Score": "2"
}
},
{
"body": "<p>A try catch block is there to "Catch" a condition, some conditions you can solve yourself in code, some need to bobble up the stack to the user in form of a message, some end the application.</p>\n<p>A sample for user exception would be that a transaction crashed due to a network transport layer error, never becouse the user entered 0 to withdrawal. If however you leave the UI layer and you're in the business layer and you're asked to payout a negative number then you should throw a "negative withdrawal exception" as the business layer has no way to ask for a user correction, it's the consuming code that should check for exception and work with the exception if one occurs.</p>\n<p>Here is a sample from your code that I modified to demonstrate what I tried to explain</p>\n<pre><code>case "2":\namount = GetAmount();\n\ntry\n{\n if (accountService.DepositAmount(bankAccount, amount, out string error))\n {\n\n Console.WriteLine($"Deposited RM {amount} successfully.");\n }\n else\n {\n Console.WriteLine($"Sorry transaction failed due to :{error}");\n }\n\n}\ncatch (AccountClosedException)\n{ \n Console.WriteLine("Dear customer, please contract your account manager, your transaction was canceled, please collect your funds");\n}\ncatch (CounterfaitFundsException)\n{\n Console.WriteLine("Dear customer, please contract your account manager, we have found some issues with your funds");\n}\ncatch (ServiceDownException exs)\n{\n Console.WriteLine($"Dear customer, we are finding having issues with {exs.ServiceLayer} this ATM, please take your funds and try another ATM");\n}\ncatch (Exception ex)\n{\n // todo: write ex.stacktrace into text file for programmer to do troubleshooting.\n\n Console.WriteLine(ex.Message);\n}\n\nbreak;\n</code></pre>\n<p>Then, a side note, you never would like to present the user with a stacktrace, you can log it for sure but never the user.</p>\n<p>When working at NCR we used a logger that logged, depending the log level set all methods and parameter values. We had users cut money in half and glue the other half of the bill with fake/paper tricking a sensor with the sensors finding 50% of the bills validations and making a 200USD deposit from 100USD. Have paperclips or rubber bands on the bills etc.. Have a look at <a href=\"https://openbanking.atlassian.net/wiki/spaces/DZ/pages/11272675/ATM+API+Specification+-+v2.1.1\" rel=\"noreferrer\">this link</a> for what you need to support. ATM's have a proprietary dialect/ standard of the global standard so there is no generic api that you can implement, also the vendors like NCR, Diebold Nixdorf, etc. have different sensors for manipulation, money validation, cameras. then the cassettes that hold funds can be recyclers (they take and dispense the funds that where payed in) and some that can only pay out. you need to account how much money was taken out of the cassettes and send an alarm if a re-fill is needed, the sensors that keep track all do this a little different.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T16:05:22.483",
"Id": "442264",
"Score": "0",
"body": "Thanks for the thorough exception handling which mimic a real-life system."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T16:22:08.073",
"Id": "442266",
"Score": "3",
"body": "@SteveNgai, that's what code review is for, glad to help"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T15:55:42.550",
"Id": "227276",
"ParentId": "227253",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "227276",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T07:19:17.380",
"Id": "227253",
"Score": "5",
"Tags": [
"c#",
"console",
"error-handling"
],
"Title": "Single vs Multiple Try Catch"
}
|
227253
|
<p><sub>I didn't find an implementation on CR of the circular doubly linked list, using generators. Hence, I tried it myself.</sub></p>
<h3>Description</h3>
<blockquote>
<p>The class <code>Deck</code> represents a circular doubly linked list, only
referencing the <code>head</code> node. The <code>tail</code> node is derived as
<code>head.previous</code>. The <code>length</code> of the list is evaluated from iterating
the nodes. Adding, removing and peeking from either side of the list takes
<span class="math-container">\$O(1)\$</span> time complexity, while it takes <span class="math-container">\$O(N)\$</span> time complexity in the
middle.</p>
</blockquote>
<h3>Questions</h3>
<ul>
<li>Is this class usable, does it comply to collection standards and conventions?</li>
<li>Are the class, method, property names stating clearly what they do?</li>
<li>Is the use of comments optimal, too verbose or still insufficient?</li>
<li>I don't have much experience with generators and iterators. Is this idiomatic Javascript?</li>
</ul>
<h3>Code</h3>
<p>A deck chains nodes to form a collection.</p>
<pre><code>// A node is a value container, linked to its previous and next node.
// Because of its circular nature, previous and next will never be null.
// A head's previous node is the tail and the tail's next node is the head.
// A sole node has a self reference both previous as next.
class Node {
// Constructor specifying the contained value.
constructor(value) {
this.value = value;
this.previous = this.next = this;
}
// The specified node gets inserted after this node.
// @returns this node.
append(node) {
node.next = this.next;
node.previous = this;
this.next.previous = node;
this.next = node;
return this;
}
// The specified node gets inserted before this node.
// @returns this node.
prepend(node) {
node.previous = this.previous;
node.next = this;
this.previous.next = node;
this.previous = node;
return this;
}
// This node removes itself from its siblings, but keeps
// the references in case it gets restored.
// The value remains untouched.
// @returns this node.
cloack() {
this.previous.next = this.next;
this.next.previous = this.previous;
return this;
}
// This node removes itself fomr its siblings, and clears
// all references to its siblings.
// The value gets reset to null.
// @returns this node.
remove() {
this.cloack();
this.previous = this.next = this;
this.value = null;
return this;
}
}
</code></pre>
<p>The deck itself with its head node.</p>
<pre><code>// A deck is a collection of values with support to add and remove
// values at both sides as well as in the middle.
// Because its a doubly linkes list, adding and removing values at
// the sides has O(1) time complexity, while in middle O(n).
// Because of its circular nature, only the head is stored, the tail
// can be derived by taking head.previous.
class Deck {
// Constructor optionally specifying the initial values.
constructor(values = null) {
this.head = null;
if (values !== null) {
for (const value of values) {
this.push(value);
}
}
}
// Inserts a value at the tail.
// @returns this deck.
push(value) {
const node = new Node(value);
if (this.empty()) {
this.head = node;
} else {
this.tail.append(node);
}
return this;
}
// Inserts a value at the head.
// @returns this deck.
unshift(value) {
const node = new Node(value);
if (this.any()) {
this.head.prepend(node);
}
this.head = node;
return this;
}
// Inserts a value at the specified index.
// @returns a boolean indicating success; no success when out of bounds.
insertAt(index, value) {
const node = new Node(value);
if (index === 0) {
this.unshift(value);
return true;
} else {
const previous = this.entryAt(index - 1);
if (previous) previous.node.append(node);
return previous !== null;
}
}
// Removes the value at the tail.
// @returns the value at the tail; or undefined when empty.
pop() {
if (this.empty()) return undefined;
const tail = this.tail;
const becomesEmpty = this.head === tail;
const value = tail.value;
tail.remove();
if (becomesEmpty) this.head = null;
return value;
}
// Removes the value at the head.
// @returns the value at the head; or undefined when empty.
shift() {
if (this.empty()) return undefined;
const newHead = this.head.next === this.head ? null : this.head.next;
const value = this.head.value;
this.head.remove();
this.head = newHead;
return value;
}
// Removes the value at the specified index.
// @returns the value at the specified index; or undefined when out of bounds.
removeAt(index) {
if (index === 0) {
return this.shift();
} else {
const entry = this.entryAt(index);
if (entry === null) return undefined;
const value = entry.node.value;
entry.node.remove();
return value;
}
}
// Removes the first occurence of the specified value.
// @returns a boolean indicating whether a value was removed.
remove(value) {
var entry = this.entry(value);
if (entry === null) return false;
if (this.head === entry.node) {
this.shift();
} else {
entry.node.remove();
}
return true;
}
// Removes all values from the deck.
// @returns this deck.
clear() {
for (const node of this.nodes()) {
node.remove();
}
this.head = null;
return this;
}
// Checks whether the specified value is contained.
// @returns a boolean indicating whether the specified value is contained.
contains(value) {
return this.indexOf(value) > -1;
}
// Gets the index of the first occurence of the specified value.
// @returns the index of the first occurence; or -1 when not found.
indexOf(value) {
var entry = this.entry(value);
return entry === null ? -1 : entry.index;
}
// Gets the value at the head.
// @returns the value at the head; or undefined when empty.
first() {
return this.any() ? this.head.value : undefined;
}
// Gets the value at the tail.
// @returns the value at the tail; or undefined when empty.
last() {
return this.any() ? this.tail.value : undefined;
}
// Gets the value at the specified index.
// @returns the value at the specified index; or null when out of bounds.
peek(index) {
const entry = this.entryAt(index);
return entry === null ? null : entry.node.value;
}
// Gets the entry at the specified index.
// @returns the entry at the specified index; or null when out of bounds.
entryAt(index) {
return (index < 0) ? null : [...this.entries()].find(n => n.index === index) || null;
}
// Gets the entry matching the first occurence of the specified value.
// @returns the entry matching the first occurence of the specified value;
// or null when out of bounds.
entry(value) {
return [...this.entries()].find(n => n.node.value === value) || null;
}
// Maps the values given the specified selector.
// @returns the values mapped given the specified selector.
map(selector) {
return this.values.map(selector);
}
// Finds the first value given the specified condition.
// @returns the first value given the specified condition.
find(condition) {
return this.values.find(condition);
}
// Filters the values given the specified condition.
// @returns the values filtered given the specified condition.
filter(condition) {
return this.values.filter(condition);
}
// Reduces the values given the specified aggregator and seed.
// @returns the values reduced given the specified aggregator and seed.
reduce(aggregator, seed) {
return this.values.reduce(aggregator, seed);
}
// Gets whether at least one value matches the condition.
// @returns a boolean indicating at least one value matches the condition;
// false when empty.
some(condition) {
return this.values.some(condition);
}
// Gets whether all values matche the condition.
// @returns a boolean indicating all values match the condition;
// true when empty.
every(condition) {
return this.values.every(condition);
}
// Gets whether the deck contains any values.
// @returns a boolean indicating whether any values are contained.
any() {
return this.head !== null;
}
// Gets whether the deck is empty.
// @returns a boolean indicating whether the deck is empty.
empty() {
return !this.any();
}
// Iterates the deck.
// @returns an iterator over the values.
*[Symbol.iterator]() {
for (const node of this.nodes())
yield node.value;
}
// Iterates the nodes.
// @returns an iterator over the nodes.
*nodes() {
for (const entry of this.entries())
yield entry.node;
}
// Iterates the entries.
// @returns an iterator over the entries.
*entries() {
if (this.any()) {
let i = 0;
let node = this.head;
do {
yield { index: i++, node: node };
node = node.next;
} while (node !== this.head);
}
}
// Gets the number of values.
// @returns the number of values.
get length() {
return this.values.length;
}
// Gets the values as array.
// @returns the values as array.
get values() {
return Array.from(this);
}
// Gets the tail.
// @returns the tail.
get tail() {
return this.any() ? this.head.previous : null;
}
}
</code></pre>
<p>And some unit tests to show the behavior.</p>
<pre><code>function print(deck) {
console.log("// values: " + [...deck]);
console.log("// first: " + deck.first());
console.log("// last: " + deck.last());
console.log("// map: " + deck.map(n => n * 10));
console.log("// filter: " + deck.filter(n => n > 1));
console.log("// reduce: " + deck.reduce((m, n) => m += n, 0));
console.log("// any: " + deck.any());
console.log("// some: " + deck.some(n => n > 1));
console.log("// every: " + deck.every(n => n > 1));
console.log("// --------------------");
}
var deck = new Deck();
print(deck);
// values:
// first: undefined
// last: undefined
// map:
// filter:
// reduce: 0
// any: false
// some: false
// every: true
// --------------------
deck.push(1);
deck.push(2);
deck.push(3);
deck.unshift(0);
deck.unshift(-1);
deck.insertAt(0, -2);
deck.insertAt(deck.length, 4);
print(deck);
// values: -2,-1,0,1,2,3,4
// first: -2
// last: 4
// map: -20,-10,0,10,20,30,40
// filter: 2,3,4
// reduce: 7
// any: true
// some: true
// every: false
// --------------------
deck.pop();
deck.shift();
deck.removeAt(1);
deck.remove(-1);
print(deck);
// values: 1,2,3
// first: 1
// last: 3
// map: 10,20,30
// filter: 2,3
// reduce: 6
// any: true
// some: true
// every: false
// --------------------
deck.clear();
print(deck);
// values:
// first: undefined
// last: undefined
// map:
// filter:
// reduce: 0
// any: false
// some: false
// every: true
// --------------------
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T09:08:44.817",
"Id": "442215",
"Score": "1",
"body": "Very comprehensive, but the class syntax breaks the fundamental OO design principle of encapsulation, it has none. Eg `list = new Deck([1,2]); list.tail.next = list.tail; [...list];` will crash the page, will not throw, making it too dangerous to use. You need to protect the Node links."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T11:03:37.597",
"Id": "442231",
"Score": "1",
"body": "# isn't implemented at the moment. You'll have to use private Maps inside a function closure to do something like that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T17:45:32.023",
"Id": "442277",
"Score": "2",
"body": "Naming is confusing. `Deck` usually means something like a deck of cards. OTOH \"a collection of values with support to add and remove values at both sides\" is a `deque` (aka Double Ended Queue)."
}
] |
[
{
"body": "<p>As @BlindMan67 commented, the Nodes themselves are not protected.\nApart from that, I don't see many glaring problems. Below is a short example of how to fix that (However, it does use a function closure, which may not be your style)</p>\n\n<pre><code>const [Deck, Node] = (function() {\n // Class definition for nodes, not included\n const NodeHeads = new Map(),\n NodeTails = new Map();\n // A deck is a collection of values with support to add and remove\n // values at both sides as well as in the middle.\n // Because its a doubly linkes list, adding and removing values at\n // the sides has O(1) time complexity, while in middle O(n).\n // Because of its circular nature, only the head is stored, the tail\n // can be derived by taking head.previous.\n class Deck {\n\n // Constructor optionally specifying the initial values.\n constructor(values = null) {\n NodeHeads.set(this, null);\n if (values !== null) {\n for (const value of values) {\n this.push(value);\n }\n }\n }\n\n // Inserts a value at the tail.\n // @returns this deck.\n push(value) {\n const node = new Node(value);\n if (this.empty()) {\n NodeHeads.set(this, node);\n } else {\n NodeTails.get(this).append(node);\n }\n return this;\n }\n get head() {\n return NodeHeads.get(this).value;\n }\n // ...etc...\n\n }\n return [Deck, Node]\n})();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T11:15:25.913",
"Id": "442233",
"Score": "0",
"body": "It's indeed not my preferred style, but it's a neat trick nevertheless to workaround this encapsulation problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T11:16:25.857",
"Id": "442234",
"Score": "1",
"body": "@dfhwze It wasn't mine either for quite a while until I realized it was the most reasonable of most of them to me. Most other methods seemed kinda hacky. Now, I'll be honest with you, it would be kinda asking for the same trouble BlindMan mentioned if you return the Node class. Instead, I wouldn't return it, and would just leave it as is with the JSDoc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T11:17:03.273",
"Id": "442235",
"Score": "1",
"body": "Perhaps I should post an updated version of this class once # is implemented :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T11:18:27.370",
"Id": "442236",
"Score": "1",
"body": "Yes, you could do that. I'm currently working on a language that is very very similar to JS (Not FreezeFlame... I forgot about that one tbh...), I actually didn't think about the proposed functionality for #, i instead set it to `this`... I might make it a macro in the future."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T11:19:44.340",
"Id": "442237",
"Score": "0",
"body": "Another thing I'm missing currently is the _null propagation operator_. I'd have to resort to ternary operators for now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T10:44:46.573",
"Id": "442359",
"Score": "1",
"body": "@dfhwze That's what it ends up being in the end anyhow xd"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T11:43:39.857",
"Id": "442378",
"Score": "0",
"body": "haha yes, but with a somewhat cleaner (more compact) syntax."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T11:13:13.737",
"Id": "227265",
"ParentId": "227254",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227265",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T07:23:14.243",
"Id": "227254",
"Score": "2",
"Tags": [
"javascript",
"linked-list",
"complexity",
"circular-list",
"generator"
],
"Title": "Circular Doubly Linked List with generators"
}
|
227254
|
<p>This program is a clock that only displays minutes passed since midnight. This program is supposed to be really simple but because of some "aesthetic bug", I wrote quite a lot if-else statements that I think can be simplified.</p>
<hr>
<blockquote>
<p>Format Input</p>
<p>The first line will contain an integer <code>T</code>, the number of test cases.
Each test case will contain an number <code>N</code>, the number displayed by the
strange clock.</p>
<p>Format Output</p>
<p>For each test case, print “Case X: “ (X starts with 1) and then print
what time it is in 24 hours HH:MM format.</p>
<p>Constraints</p>
<p>1 <= <code>T</code> <= 1000</p>
<p>0 <= <code>N</code> <= 1439</p>
</blockquote>
<pre><code>#include <stdio.h>
int main()
{
int T;
scanf("%d", &T);
for (int i = 1; i <= T; i++) {
int N;
scanf("%d", &N);
int hours = N / 60;
int minutes = N % 60;
printf("Case #%d: ", i);
if (N < 10) {
printf("00:0%d\n", N);
} else if (N > 10 && N < 60) {
printf("00:%d\n", N);
} else if (N > 60 && N < 600) {
if (minutes == 0) {
printf("0%d:00\n", hours);
} else if (minutes > 0 && minutes < 10) {
printf("0%d:0%d\n", hours, minutes);
} else {
printf("0%d:%d\n", hours, minutes);
}
} else {
if (minutes == 0) {
printf("%d:00\n", hours);
} else if (minutes > 0 && minutes < 10) {
printf("%d:0%d\n", hours, minutes);
} else {
printf("%d:%d\n", hours, minutes);
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T09:32:59.070",
"Id": "442349",
"Score": "0",
"body": "As I understand it, N is the number the clock must display, I.e. when N=1439, the clock should display 14:39. You should divide by 100 and not 60."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T18:57:52.330",
"Id": "442448",
"Score": "0",
"body": "@Édouard since a day has 1440 minutes, it's more likely that N is the number of minutes since midnight. This crucial information is missing from the instructions, which probably prepares the students to real-life situations, which are very similar."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T19:00:25.117",
"Id": "442449",
"Score": "0",
"body": "Or, the instructions may have included the definition of the \"strange clock\", and Elvan just didn't post this part."
}
] |
[
{
"body": "<p>Following @Martin R's comment, I'll make my comment above a solution:</p>\n\n<p><code>printf</code> already supports what you're trying to achieve with your if-then-else jungle:</p>\n\n<pre><code>#include <stdio.h>\n\nint main()\n{\n int T;\n scanf(\"%d\", &T);\n\n for (int i = 1; i <= T; i++) {\n\n int N;\n scanf(\"%d\", &N);\n\n int hours = N / 60;\n int minutes = N % 60;\n\n printf(\"Case #%d: %02d:%02d\\n\", i, hours, minutes);\n }\n}\n</code></pre>\n\n<p>You're also missing to check the return value of <code>scanf</code>. It is used to report errors in the input. What is the purpose of the first <code>scanf</code>?</p>\n\n<p><strong>Edit</strong></p>\n\n<p>From @chux's comment: you should validate the constraints of <code>N</code> after the input.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>Note: additional variables should indeed have no influence on performance and are a good way to document meaning of your code, so please ignore my initial statement about \"saving variables\". </p>\n\n<p>Old version was:</p>\n\n<blockquote>\n <p>Also, I'd change the variable naming. Use <code>minutes</code> instead of <code>N</code> to\n communicate clearly what you're handling in the variable. You can then\n write the computation directly in the parameter list of printf, saving\n you two additional variables.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T12:56:00.720",
"Id": "442249",
"Score": "6",
"body": "\"saving you two additional variables\" - in this case, I think the separated variables are actually a good idea. They shouldn't incur a performance drop, and they help to self-document the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T12:52:33.763",
"Id": "442383",
"Score": "0",
"body": "_\"Use `minutes` instead of N to communicate clearly what you're handling in the variable.\"_ The symbol N is explicitly defined in the problem statement. However, the word `minutes` could mean either N or the \"minutes\" field in the output."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T22:02:44.197",
"Id": "442474",
"Score": "1",
"body": "Note that with input like `-61`, Output of `-01:00` might be preferred over this answer's `\"-01:-01\"`. Yet with \"0 <= N <= 1439\" and \"minutes passed since midnight\", we might not worry about yesterday."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T09:26:57.430",
"Id": "227261",
"ParentId": "227255",
"Score": "15"
}
},
{
"body": "<p>If your code is checked by an automated process, you will probably fail all test cases because your code prints a <code>#</code>, which was not asked for. You should better remove it. Just print \"Case %d\" instead of \"Case #%d\".</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T18:09:05.033",
"Id": "227279",
"ParentId": "227255",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "227261",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T07:42:14.023",
"Id": "227255",
"Score": "10",
"Tags": [
"beginner",
"algorithm",
"c",
"datetime",
"formatting"
],
"Title": "Converting time in number of minutes past midnight to HH:MM format"
}
|
227255
|
<p>Some backup <em>Bash</em> script on my machine copies a specific directory entries filenames into a text file. Entries that no longer exist have to be kept (entries added during a previous run).</p>
<p>The script makes sure that entries which still exist will not be inserted twice in the backup file using <em>sort</em> and <em>uniq</em>.</p>
<pre><code>local file=~/bar-entries.txt
touch "$file" "${file}_"
find ~/foo/bar -maxdepth 1 -type d \! -name bar | cat <"$file" - | sort | uniq > "${file}_"
mv "${file}_" "$file"
</code></pre>
<p>Can this code be optimized? Like can this scenario be achieved without relying on a temporary file? Any other improvement is welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T23:50:42.530",
"Id": "443063",
"Score": "0",
"body": "Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 3 → 2"
}
] |
[
{
"body": "<p>Use sort's <code>-u</code> and <code>-o</code> switches:</p>\n\n<pre><code>find … | sort -u - $file -o $file\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T12:06:32.553",
"Id": "227267",
"ParentId": "227266",
"Score": "2"
}
},
{
"body": "<p>I don't think you need the temporary file, if you open for append (i.e. <code>>></code>), and use <code>comm</code> to find the non-duplicate lines (after sorting).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T12:18:19.040",
"Id": "227319",
"ParentId": "227266",
"Score": "0"
}
},
{
"body": "<p>Just maybe <code>rsync</code> for <strong>remote synchronisation</strong> might be attractive.</p>\n\n<pre><code>rsync --dryrun ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T13:47:45.837",
"Id": "442389",
"Score": "0",
"body": "Code in the question is part of a backup script which actually executes _rsync_ at some point. But prior to any rsync call, some commands have to be run like the one above which append entries from ~/foo/bar to the file not yet inserted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T13:51:44.130",
"Id": "442390",
"Score": "0",
"body": "Okay, so I did not need to mention rsync. (`-n` or.`--dryrun` has its uses.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T13:55:13.103",
"Id": "442392",
"Score": "0",
"body": "I am only looking for a way to avoid the use of a tempory file involved in the supplied few lines. _(That said, improvements of any kind are welcome)_"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T13:13:28.310",
"Id": "227321",
"ParentId": "227266",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227267",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T11:34:36.643",
"Id": "227266",
"Score": "2",
"Tags": [
"bash",
"file-system",
"shell"
],
"Title": "Write directory new entries to file periodically, keeping the ones that existed in the past"
}
|
227266
|
<p>Given sentence for example: <code>ala ma kota, kot koduje w Javie kota</code> I should to every letter occurring in the sentence I should map every string that this letter contains. So the output should be: </p>
<pre><code>{a=[ala, javie, kota, ma], d=[koduje], e=[javie, koduje], i=[javie], j=[javie, koduje], k=[koduje, kot, kota], l=[ala], m=[ma], o=[koduje, kot, kota], t=[kot, kota], u=[koduje], v=[javie], w=[w]}
</code></pre>
<p>I have written algorithm for it, but I think that there is a better way do to this using streams (or somehow else).
Code; </p>
<pre><code>String sentence = "ala ma kota, kot koduje w Javie kota .kota";
String purifiedLowerCaseSentence = getPurifiedLowerCaseSentence(sentence);
Set<Character> characters = getEveryCharacterOccurringInSentence(purifiedLowerCaseSentence);
String[] splittedSentence = purifiedLowerCaseSentence.split("\\s");
Map<Character, Set<String>> characterWithAccordingWord = new LinkedHashMap<>();
for (char iteratedCharacter : characters) {
for (String iteratedWord : splittedSentence) {
if (iteratedWord.indexOf(iteratedCharacter) >= 0) {
characterWithAccordingWord.computeIfAbsent(iteratedCharacter, k -> new TreeSet<>());
characterWithAccordingWord.get(iteratedCharacter).add(iteratedWord);
}
}
}
</code></pre>
<p>And these two methods which are placed in other class: </p>
<pre><code>static String getPurifiedLowerCaseSentence(String sentence) {
return sentence.replaceAll("\\p{P}", "").toLowerCase();
}
static Set<Character> getEveryCharacterOccurringInSentence(String sentence) {
return sentence.chars()
.mapToObj(e -> (char) e).collect(Collectors.toSet());
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T18:35:39.663",
"Id": "442296",
"Score": "0",
"body": "I have rolled back your latest edit. You cannot update the question with feedback obtained from answers, as this invalidates those answers. See [what should I do when someone answers my question](https://codereview.stackexchange.com/help/someone-answers) in particular the “what should I not do” section."
}
] |
[
{
"body": "<p>You actually have three nested loops there, while two would suffice (the indexOf loops the characters in the word).</p>\n\n<pre><code>For each word in the sentence\n For each character in the word\n Add the word to the set associated to the character\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T15:56:47.473",
"Id": "442414",
"Score": "0",
"body": "I have already updated my algorithm and it looks like this: https://github.com/must1/CharacterToWordsMapper/blob/master/src/main/java/CharacterToWordsMapCreator.java what do you think?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T14:13:15.007",
"Id": "227271",
"ParentId": "227268",
"Score": "1"
}
},
{
"body": "<p>The solution is inefficient. </p>\n\n<p>First of all, there is absolutely no need to calculate the set of characters in advance. you can iterate over the sentence and build the map during this iteration. you don't need to know the keys in advance. </p>\n\n<p>Furthermore, for each distinct character, you iterate over the entire sentence. there is really no need for this Cartesian-type processing. the map can be calculated with just one iteration over the sentence. This is providing you can parse the words without the need for <code>split()</code></p>\n\n<p>while we are in this subject, split by whitespace will leave the words with punctuation marks, so you would get \"kota,\" in the output, not to mention your example sentence contains two occurrences of \"kota\" that will appear in the output, so you need to decide if that's what you want.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T14:58:38.193",
"Id": "442258",
"Score": "0",
"body": "Isn't it more clearer to know the keys in advance? Tbh, I do not know how I can make it other way. Your last acapit is completely false. In output I have only one `kota`. I won't have any punctuation marks as I'm using method that purify the sentence from punctuation marks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T08:35:51.007",
"Id": "442337",
"Score": "0",
"body": "What is clear and what is not is opinion based. Performance can be argued using facts. To me your algorithm was not clear as I was looking for the O(n^2) solution."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T14:42:42.210",
"Id": "227272",
"ParentId": "227268",
"Score": "1"
}
},
{
"body": "<p>Not sure about its efficiency or whether or not it improves your algorithm, but since you want to use streams, this would be an option:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n String sentence = \"ala ma kota, kot koduje w Javie kota .kota\";\n String sanitizedSentence = sentence.replaceAll(\"[^A-Za-z ]\", \"\").toLowerCase();\n String[] words = sanitizedSentence.split(\" \");\n Map<String,List<String>> result = sanitizedSentence\n .chars()\n .filter(Character::isAlphabetic)\n .distinct()\n .sorted()\n .mapToObj(c->(char)c)\n .map(Object::toString)\n .collect(Collectors.toMap(\n Function.identity(), \n c->Stream.of(words).distinct().filter(word -> word.contains(c)).sorted().collect(Collectors.toList()),\n (a,b)->a,\n LinkedHashMap::new // <- to ensure they are shown in order when printing\n ));\n System.out.println(result);\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T15:35:25.660",
"Id": "227339",
"ParentId": "227268",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T12:09:23.167",
"Id": "227268",
"Score": "2",
"Tags": [
"java",
"strings",
"combinatorics"
],
"Title": "Mapping words to letters which contains"
}
|
227268
|
<p>So I made this calculator in c# console, I'm pretty nooby-ish in programming. I want to know if I can make it better, because my coding skills suck. Pretty sure my logic sucks too. </p>
<p>Any advice and tips? </p>
<pre><code> public static void Main() {
bool returnToStart;
do {
returnToStart = Calc();
} while(returnToStart == true);
Console.ReadLine();
}
public static bool Calc() {
ExitProgram();
Console.Clear();
float firstNumber; float secondNumber; float result;
string operation;
Console.Write("First number: ");
firstNumber = float.Parse(Console.ReadLine());
Console.Write("Choose your operator: addition(+), subtraction(-), " +
"multiplication(*) or division(/): ");
operation = Console.ReadLine();
Console.Write("Second number: ");
secondNumber = float.Parse(Console.ReadLine());
Console.Clear();
switch(operation) {
case "+":
result = (firstNumber + secondNumber);
Console.WriteLine("Calculation: {0}", result);
break;
case "-":
result = (firstNumber - secondNumber);
Console.WriteLine("Calculation: {0}", result);
break;
case "*":
result = (firstNumber * secondNumber);
Console.WriteLine("Calculation: {0}", result);
break;
case "/":
if(firstNumber == 0) {
Console.WriteLine("Cant divide by zero!");
} else {
result = (firstNumber / secondNumber);
Console.WriteLine(result);
}
break;
default:
Console.WriteLine("Error! Try again.");
break;
}
return true;
}
public static bool ExitProgram() {
string exit = "Exit";
Console.WriteLine("If you're done with your calculations,\nthen you can exit this program by simply typing in 'Exit' ");
Console.Write("Want to quit the program?: ");
exit = Console.ReadLine();
if(exit == "Exit") {
Environment.Exit(0);
}return true;
}
}
</code></pre>
<p>}</p>
|
[] |
[
{
"body": "<p><strong>Keep It Simple For the User</strong>\nRather than making the user type the word <code>Exit</code> it might be better to ask the user\n<code>Are you done yet(y/n)?</code> and accept a simple yes/no answer. It also might be better if the answer was not case sensitive so accept <code>Y</code>, <code>y</code>, <code>N</code> and <code>n</code>.</p>\n\n<p><strong>Exit From Main() When Possible</strong>\nThe Main() function may contain clean up code so exiting from the <code>ExitProgram()</code> function may not be the best idea. A second problem I see with the <code>ExitProgram()</code> function is that it is called before the user ever enters a calculation. There are two possible ways to handle this, one would be to move the call to <code>ExitProgram()</code> to after the calculation is performed, the other would be to have a function that contains a <code>do while</code> loop that calls <code>Calc</code> within the loop and tests <code>ExitProgram()</code> in the while condition.</p>\n\n<p><strong>Function Complexity</strong><br>\nThe function <code>Calc()</code> is overly complex (it does too much) and should be multiple functions. One of the functions should get the user input, and a second function should do the calculation. This would be applying two programming principles, the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"noreferrer\">Single Responsibility Principle</a> and the KISS Principle.</p>\n\n<p>The Single Responsibility Principle states: </p>\n\n<blockquote>\n <p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n\n<p>The <a href=\"https://en.wikipedia.org/wiki/KISS_principle\" rel=\"noreferrer\">Keep It Simple (KISS) Principle</a> is an engineering principle that predates computers, basically it is keep the implementation as simple as possible.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T15:12:49.533",
"Id": "227274",
"ParentId": "227269",
"Score": "7"
}
},
{
"body": "<h2>Use Intention-Revealing Names</h2>\n<p>Based on naming alone, the intent of the <code>Calc()</code> method is not clear. As the reader of your code, I have to look at the implementation details of this method to understand what we are calculating.</p>\n<h2>Method Characteristics</h2>\n<p>Pay careful attention to your method signatures.</p>\n<p>Do <code>ExitProgram()</code> and <code>Calc()</code> need to both be static? If <code>Calc()</code> no longer used the console to display I/O information and had a dependency on something else used for display, unit testing becomes much more difficult due to it being a static method.</p>\n<p>Should <code>ExitProgram()</code> be public? If this was used in a larger application, would you want others to call this method? It seems like the answer is no, as the UI output of this method is coupled with information about the calculations.</p>\n<h2>Control Flow and Validation</h2>\n<p>Ideally, main should delegate all processing elsewhere. In the <code>Calc()</code> method, we should be performing validation on user input. If I enter an invalid operation, I get the message "Error! Try again." without knowing exactly what I did wrong. I am also forced to re-enter all inputs if I want to try again. This may be an opportunity to practice throwing and catching exceptions for cleaner code and a better user experience.</p>\n<h2>Conclusion</h2>\n<p>I like the way you have started to separate your methods into ways that make sense. I also appreciate the line breaks within your methods to further separate things into logical groupings. I will leave a link to my live code review below and I hope this feedback helps!</p>\n<p>Live code review: <a href=\"https://www.youtube.com/watch?v=bFVBYoTrTiM\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=bFVBYoTrTiM</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-28T16:13:47.567",
"Id": "231417",
"ParentId": "227269",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "227274",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T12:16:18.233",
"Id": "227269",
"Score": "6",
"Tags": [
"c#",
"beginner",
"console",
"calculator"
],
"Title": "Made my own simple calculator"
}
|
227269
|
<p>I made this two player TicTacToe game as a challenge i was given in class. The game starts where the first player chooses where their X will be placed. Each area in the array has been given a number starting from 1 and ending at 9. After X chooses their area, the game will let the user know who's turn it is, and they will keep playing until one of them wins.</p>
<p>As of right now, the game doesn't let you know that nobody won, but that's another update i have to make.</p>
<p>Please do review the code and let me know how i can make it more efficient and i am also open for suggestions, so please be honest as much as possible as this is the first time i write in Javascript using Nodejs, and i would love to get better. </p>
<pre><code> //user input and format
let input = process.stdin;
input.setEncoding("utf-8");
console.log("You will start with X");
console.log("Please choose a box number from 1 to 9 to place your X");
//initializing an array of 9 fields where each one contains * as a start
let gameboard = []; // = ["*", "*", "*", "*", "*", "*", "*", "*", "*"];
let symbol = "*";
for (let i = 0; i < 9; i++) {
gameboard[i] = symbol;
}
//determining who's turn it is and the players' symbols
let player1isplaying = true;
let player1 = "X";
let player2 = "O";
//Game loop
input.on("data", function(data) {
console.clear();
//bad input
if (parseInt(data) > 9 || parseInt(data) < 1 || isNaN(data)) {
console.log("Please enter a number between 1 and 9");
} else if (gameboard[parseInt(data) - 1] != symbol) {
console.log("The spot you're trying to fill is already taken.");
}
//which player's turn
else if (player1isplaying) {
gameboard[parseInt(data) - 1] = player1;
player1isplaying = false;
} else if (!player1isplaying) {
gameboard[parseInt(data) - 1] = player2;
player1isplaying = true;
}
showboard(gameboard);
checkforXwin(gameboard);
checkforOwin(gameboard);
if (player1isplaying) {
console.log(player1 + "'s turn");
} else {
console.log(player2 + "'s turn");
}
});
//winner validation
function checkforXwin(array) {
if (
(array[0] == player1 && array[1] == player1 && array[2] == player1) ||
(array[3] == player1 && array[4] == player1 && array[5] == player1) ||
(array[6] == player1 && array[7] == player1 && array[8] == player1) ||
(array[0] == player1 && array[4] == player1 && array[8] == player1) ||
(array[2] == player1 && array[4] == player1 && array[6] == player1) ||
(array[0] == player1 && array[3] == player1 && array[6] == player1) ||
(array[1] == player1 && array[4] == player1 && array[7] == player1) ||
(array[2] == player1 && array[5] == player1 && array[8] == player1)
) {
console.log(player1 + " wins");
process.exit();
}
}
//winner validation
function checkforOwin(array) {
if (
(array[0] == player2 && array[1] == player2 && array[2] == player2) ||
(array[3] == player2 && array[4] == player2 && array[5] == player2) ||
(array[6] == player2 && array[7] == player2 && array[8] == player2) ||
(array[0] == player2 && array[4] == player2 && array[8] == player2) ||
(array[2] == player2 && array[4] == player2 && array[6] == player2) ||
(array[0] == player2 && array[3] == player2 && array[6] == player2) ||
(array[1] == player2 && array[4] == player2 && array[7] == player2) ||
(array[2] == player2 && array[5] == player2 && array[8] == player2)
) {
console.log(player2 + " wins");
process.exit();
}
}
//showing the board in 3 rows and 3 columns
function showboard(array) {
console.log("---------");
console.log(array.slice(0, 3).join(" "));
console.log("");
console.log(array.slice(3, 6).join(" "));
console.log("");
console.log(array.slice(6, 9).join(" "));
console.log("---------");
}
</code></pre>
|
[] |
[
{
"body": "<p>First the really easy advice:</p>\n\n<ul>\n<li>use strict mode <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode</a></li>\n<li>use <code>const</code> instead of <code>let</code> for stuff you know you're not supposed to change (symbol, player1, player2); declaring it const helps you keep some assumptions later</li>\n<li>use <code>===</code> instead of <code>==</code> generally; I think the only legitimate use for <code>==</code> is for using it with <code>null</code> when you allow undefined or results of <code>typeof</code> if you feel like you're a JS human minifier :)</li>\n<li>prefer camel case since JS already does it and it would look weird to have two casing strategies in the same codebase</li>\n<li>use better naming in general: I'm talking about <em>array</em> in <code>function checkforOwin(array)</code> - <em>array</em> is extremely generic (what array?!?) I would call it <em>board</em> so I know what I'm dealing with; the fact that it's implemented as an array is a detail</li>\n<li>I'd also like a function named <code>checkforOwin</code> to just check and return true/false than exit the process xD</li>\n<li>who's <code>O</code> in this same function name? I thought we're comparing with the variable <code>player1</code>; stick to one or the other, not both; you'd have to update quite a bit of code if you change the initial statement of <code>let player1 = \"X\"</code></li>\n</ul>\n\n<p>...and the more involved:</p>\n\n<ul>\n<li>I would use nested arrays for the board because I can't easily picture what <code>board[7]</code> is; but I can picture what <code>board[2][1]</code> is</li>\n<li>those really long if statements look very repetitive; they look a lot like patterns on a board so instead let's turn that code into data so we can manage it easier; we can rewrite the patterns like this:</li>\n</ul>\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 isOWinner = [\n [0, 1, 2],\n [3, 4, 5],\n [6, 7, 8],\n [0, 4, 8],\n// ...\n].some((indices) => indices.every((index) => board[index] === player1))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>That big condition blob in your if statements can be rewritten like this. Because it's an array you can store it somewhere; load it; merge with other patterns or extend or whatever you can do with arrays. Code that looks like data should be represented as data.\nIn fact let's use the same data in both functions and merge them into one:</p>\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>function checkForWin (board, player) {\n const isWinner = [\n [0, 1, 2],\n [3, 4, 5],\n [6, 7, 8],\n [0, 4, 8],\n // ...\n ].some((indices) => indices.every((index) => board[index] === player))\n\n if (isWinner) {\n console.log(player + 'wins')\n process.exit()\n }\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>And now you just call <code>checkForWin(board, player1)</code> or <code>checkForWin(board, player2)</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T07:41:04.847",
"Id": "442522",
"Score": "0",
"body": "Thanks for the feedback!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T20:36:09.627",
"Id": "227357",
"ParentId": "227270",
"Score": "3"
}
},
{
"body": "<p>There is good advice in <a href=\"https://codereview.stackexchange.com/a/227357/120114\">the answer by adrianton3</a>. I noticed one other thing:</p>\n\n<p>You may have already updated the structure of the board based on adrianton3's answer but instead of this:</p>\n\n<blockquote>\n<pre><code>let gameboard = []; // = [\"*\", \"*\", \"*\", \"*\", \"*\", \"*\", \"*\", \"*\", \"*\"];\nlet symbol = \"*\";\n\nfor (let i = 0; i < 9; i++) {\n gameboard[i] = symbol;\n}\n</code></pre>\n</blockquote>\n\n<p>it could be simplified to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill\" rel=\"nofollow noreferrer\"><code>Array.fill()</code></a>:</p>\n\n<pre><code>const symbol = \"*\";\nconst gameboard = Array(9).fill(symbol);\n</code></pre>\n\n<p>That way there is no need to loop through the board when initializing the default values.</p>\n\n<hr>\n\n<p>It likely won't be an issue when users input numbers 0-9 but something to be aware of is that calls to <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt\" rel=\"nofollow noreferrer\"><code>parseInt()</code></a> without a <code>radix</code> parameter may yield unexpected results if the input happens to contain a leading zero (or else hex prefix: <code>0x</code>). </p>\n\n<blockquote>\n <p>If the <code>radix</code> is <code>undefined</code>, 0, or unspecified, JavaScript assumes the following:</p>\n \n <ol>\n <li>If the input <code>string</code> begins with <code>\"0x\"</code> or <code>\"0X\"</code> (a zero followed by lowercase or uppercase X), radix is assumed to be 16 and the rest of the string is parsed as a hexidecimal number.</li>\n <li>If the input <code>string</code> begins with <code>\"0\"</code> (a zero), radix is assumed to be 8 (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 clarifies that 10 (decimal) should be used, but not all browsers support this yet. For this reason <strong>always specify a radix when using <code>parseInt</code></strong>.</li>\n <li>If the input <code>string</code> begins with any other value, the radix is 10 (decimal).<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#Description\" rel=\"nofollow noreferrer\">1</a></sup></li>\n </ol>\n</blockquote>\n\n<p>See <a href=\"https://stackoverflow.com/q/16880327/1575353\">this post</a> for more information.</p>\n\n<p><sup>1</sup><sub><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#Description\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#Description</a></sub></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T20:48:11.247",
"Id": "444936",
"Score": "0",
"body": "Bounty worthy answer. Too bad bounties can't be awarded directly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T20:50:13.300",
"Id": "444937",
"Score": "0",
"body": "Sam, perhaps it would be better to point out the relevant section on the already linked MDN docs on that instead of a page on SO?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T20:44:39.283",
"Id": "228932",
"ParentId": "227270",
"Score": "1"
}
},
{
"body": "<p>Extending on <a href=\"https://codereview.stackexchange.com/a/227357/120114\">adrianton3's answer</a>:</p>\n\n<p>The following example not only reads better, but avoids re-creating the array of winning patterns every time you call the function:</p>\n\n<pre><code>const winningPatterns = [\n [0, 1, 2],\n [3, 4, 5],\n [6, 7, 8],\n [0, 4, 8],\n // ...\n]\nfunction checkForWin (board, player) {\n const isWinner = winningPatterns.some((indices) => indices.every((index) => board[index] === player))\n\n if (isWinner) {\n console.log(player + 'wins')\n process.exit()\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T21:00:50.623",
"Id": "228933",
"ParentId": "227270",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227357",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T12:48:44.947",
"Id": "227270",
"Score": "5",
"Tags": [
"javascript",
"game",
"node.js",
"console",
"tic-tac-toe"
],
"Title": "TicTacToe in Javascript"
}
|
227270
|
<p>This topic is about the same project as <a href="https://codereview.stackexchange.com/q/226773/207094">this previous one</a>.</p>
<p>I think posting the full project was a bit too much, so here I post again only three functions, which are the core of my program, with a few modification from the comments I already had.</p>
<p>The goal is to generate words that sounds similar to a language. In order to do that, we first analyze a dictionary of this language, then generate the words.<br>
The analysis takes the word, as a <code>Qstring</code>, and notes each occurrence of each possible letter chain. It depends on a 'coherence length', which means the size of the chain. For example, on the word 'test' with a coherence length of 3 we have to note the occurrence of <code>"void, void, t"</code>, <code>"void, t, e"</code>, <code>"t, e, s"</code>, <code>"e, s ,t"</code>, <code>"s, t, end"</code>.</p>
<p>This is stored in <code>charmap</code>: the key of the map is a vector of <code>Qchar</code> (a.k.a, the character chain, e.g. <code>"t, e, s"</code>), and the value is a pair where first is the number of occurrence and the second is a probability associated to each key (handled outside of the function).</p>
<p>On this function, I construct the <code>charmap</code> word after word:</p>
<pre><code>void QanalyzeWord(const QString &word, map<vector<QChar>, pair<int,double>> &charmap, uint lcoh, int &nb) {
vector<QChar> letterChain(lcoh,'\0');
for(int i=0; i<word.size(); i++) {
letterChain[lcoh-1]=word.at(i);
charmap[letterChain].first++;
nb++;
for(uint j=0; j<lcoh-1; j++) {
letterChain[j]=letterChain[j+1];
}
}
//Indicates last character is void
letterChain[lcoh-1]='\0';
charmap[letterChain].first++;
return;
}
</code></pre>
<p>Once the full dictionary has been analyzed, we still have to give, to each letter chain, a probability of occurrence. This means completing the <code>second</code> of the pair in the <code>charmap</code>.</p>
<p>I didn't manage to explain this part clearly, so the best is with the simplest example:</p>
<p>If the <code>charmap</code> indicates that <code>thi</code> has been encountered 6 times, <code>the</code> 3 times and <code>tho</code> 1 time, and no other letter is possible after <code>th</code>, then we want to gives a probability of 0.6 to <code>thi</code>, 0.3 to <code>the</code> and 0.1 to <code>tho</code>. In addition, we will be doing cumulative probability, so since <code>the</code> comes before <code>thi</code> then <code>tho</code> in the map, we will have <code>charmap["the"].second=0.3</code> <code>charmap['thi'].second=0.3+0.6</code> and <code>charmap['tho'].second=0.3+0.6+0.1</code> (always sums up to one).</p>
<pre><code>std::map<std::vector<QChar>, std::pair<int,double>>::iterator it = charmap.begin() , cePrBegin , cePrEnd;
//cePrBegin and cePrFin are iterators to the beginning and the end of the letter chain currently on the scope
while(it!=charmap.end()) {
std::vector<QChar> cePr(&it->first[0], &it->first[lcoh-1]);
cePrBegin = it;
int nbPosLet = 0; //number of possible letters after 'cePr'
//We go from cePrBeging to cePrEnd 2 times:
//1st: counting occurence of each chain
while( (it!=charmap.end()) && (cePr==std::vector<QChar>(&it->first[0], &it->first[lcoh-1])) ) {
nbPosLet += it->second.first; //it->second = the pair in the charmap / then .first = the 'int'= nb of occurences
it++;
}
cePrEnd = it;
//2nd: dividing occurence number / total + add (we are doing cumulative probability)
for(std::map<std::vector<QChar>, std::pair<int,double>>::iterator secondPass = cePrBegin; secondPass!=cePrEnd && secondPass!=charmap.end(); ++secondPass) {
secondPass->second.second = double(secondPass->second.first) / nbPosLet;
if (secondPass != cePrBegin && secondPass!=charmap.begin() )
secondPass->second.second += prev(secondPass)->second.second; //prev() = previous element
}
}
</code></pre>
<p>We may now generate a word. We want to find, letter after letter, which letter we should append to the word. For this, we get a random number r in [0,1]. From the previous example, if r < 0.3 we append a <code>e</code> to <code>th</code>, if 0.3 < r < 0.9 it's an <code>i</code> and if 0.9 < r < 1 it's an <code>o</code>.</p>
<p>For this, we have two iterators representing <code>th\firsPossibleCharacter</code> and <code>th\lastPossibileCharacter</code> and go from one to the other, comparing r to the second of the pair each time.</p>
<p>Note that end of word if a character like any other, but we can force the size of the word, it if ever it gets to long.</p>
<pre><code>string Qgenerateur(std::map<std::vector<QChar>, pair<int,double>> &charmap, uint lcoh, uint maxsize) {
QString myword="";
vector<QChar> cePr(lcoh-1,'\0'); //represents the chain of previous characters
vector<QChar> cePrMin, cePrMax; //represents the chain of previous character + the first (resp. last) possible character
cePrMin.reserve(lcoh); cePrMax.reserve(lcoh);
map<vector<QChar>, pair<int,double>>::iterator it, itLow, itHigh;
//itLow : iterator to the first element of the map having this chain of previous character (=cePr)
//itHigh: iterator to the element after the last element of the map having this chain of previous character (=cePr)
do {
cePrMin=cePr; cePrMin.push_back(QChar::Null);
cePrMax=cePr; cePrMax.push_back(QChar::LastValidCodePoint);
itLow = charmap.lower_bound(cePrMin);
itHigh = charmap.upper_bound(cePrMax);
it = itLow;
double r = double(rand())/ RAND_MAX; // 0 < r < 1
while (r > it->second.second && it != itHigh) { //places iterator to the 1st caracter having a probability less than r
it++;
}
myword += QString(it->first.back()); //append this caracter to the word
//it.first is the vector of QChar, representing the letter chain. We append its last letter to our word (the previous letters are already in the word)
for(uint i=0; i<cePr.size()-1; i++) {
cePr[i] = cePr[i+1];
}
cePr[cePr.size()-1] = it->first.back();
} while ( (it->first.back()!='\0') && uint(myword.size()) <= maxsize);
return myword.toStdString();
}
</code></pre>
<p>Here it is, we have invented a word. It's a bit complicated (for myself at least, I got confused multiple times). I do not especially expect a review from the algorithmic point of view, more for the code itself, for improvement or clarity.</p>
<p>Note the use of Qt <code>Qstring</code> and <code>Qchar</code>. This is the best solution I found to handle accentuated letter (I'm messed up with <code>wchar_t</code>, didn't manage to did it easily), but maybe there is another solution?</p>
<p>I also had one question: I wanted to monitor the progress of the analysis, so I added the <code>nb</code> parameter to <code>QanalyzeWord</code>. Is there a solution to do this debugging without modifying the function prototype (e.g. don't have <code>nb</code> in the prototype), knowing that this is only for debugging, not final release?</p>
<p>And also: should I have used <code>auto</code> instead of these awfully long iterator type?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T16:00:01.303",
"Id": "442262",
"Score": "0",
"body": "Are the any changes in this code from the original question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T16:40:34.180",
"Id": "442268",
"Score": "1",
"body": "I applied the suggested modification (English only, consistent syntax), but the difference is its only 3 (very small) parts and not the whole program"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T17:39:57.957",
"Id": "442275",
"Score": "0",
"body": "Do you have a GitHub or GitLab account or some other repository that you could provide a link to. I didn't see one on the other question either. It might be good as hiring employers might like to view your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T06:51:46.020",
"Id": "442321",
"Score": "1",
"body": "I'm not really sure I wantpotential employer to see _that_, first I would like to know about its quality... Anyway I would set up one, it will allow to test it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T17:09:47.087",
"Id": "443466",
"Score": "0",
"body": "it's done, full project can be found [here on Github](https://github.com/Sayanel01/GeMot)"
}
] |
[
{
"body": "<p>I find your code very dense and difficult to skim. I think you can help it quite a bit by making sure each statement is on a line by itself; that there's whitespace around your operators; and that you use <code>std::</code> qualification on standard library types and functions. More controversially, I would say \"don't abuse <code>foo++</code> to mean <code>foo += 1</code>\" — the shorthand operator should be used only in idioms such as <code>for</code>.</p>\n\n<p>Also, I'd avoid cryptic abbreviations like <code>uint</code> for <code>unsigned</code> — and in fact, I'd avoid <code>unsigned</code> types in APIs altogether!</p>\n\n<p>You also write <code>word.at(i)</code> where <code>word[i]</code> would suffice; and in fact you don't need <code>i</code> at all if you just use a plain old ranged for loop <code>for (QChar ch : word)</code>.</p>\n\n<p>So where you had</p>\n\n<pre><code>void QanalyzeWord(const QString &word, map<vector<QChar>, pair<int,double>> &charmap, uint lcoh, int &nb) {\n vector<QChar> letterChain(lcoh,'\\0');\n\n for(int i=0; i<word.size(); i++) {\n letterChain[lcoh-1]=word.at(i);\n charmap[letterChain].first++;\n nb++;\n for(uint j=0; j<lcoh-1; j++) {\n letterChain[j]=letterChain[j+1];\n }\n }\n\n //Indicates last character is void\n letterChain[lcoh-1]='\\0';\n charmap[letterChain].first++;\n return;\n}\n</code></pre>\n\n<p>I would write</p>\n\n<pre><code>void QanalyzeWord(\n const QString& word,\n std::map<std::vector<QChar>, std::pair<int, double>>& charmap,\n int lcoh,\n int& nb)\n{\n std::vector<QChar> letterChain(lcoh, '\\0');\n\n for (QChar ch : word) {\n charmap[letterChain].first += 1;\n nb += 1;\n letterChain[lcoh - 1] = ch;\n for (int j = 0; j < lcoh - 1; ++j) {\n letterChain[j] = letterChain[j+1];\n }\n }\n\n letterChain[lcoh-1] = '\\0';\n charmap[letterChain].first += 1;\n}\n</code></pre>\n\n<hr>\n\n<p>The next thing to look at is that inner loop (<code>for (int j...)</code>). It looks wrong at a glance, because it seems to be \"shifting down\" every letter in the array... but we've already overwritten one of the letters in the array with a new value! It looks like what we meant to write was</p>\n\n<pre><code> for (int j = 0; j < lcoh - 1; ++j) {\n letterChain[j] = letterChain[j+1];\n }\n letterChain[lcoh - 1] = ch;\n</code></pre>\n\n<p>or more concisely,</p>\n\n<pre><code> std::copy(letterChain.begin() + 1, letterChain.end(), letterChain.begin());\n letterChain.back() = ch;\n</code></pre>\n\n<p>or more concisely,</p>\n\n<pre><code> QChar *first = &letterChain[0];\n *first = ch;\n std::rotate(first, first + lcoh, first + 1);\n</code></pre>\n\n<hr>\n\n<p>The line <code>charmap[letterChain].first += 1;</code> also wants some attention. What is <code>.first</code>? Well, we can look at the function signature and find that <code>charmap[letterChain]</code> is a <code>std::pair<int, double></code>. But we don't know what the <code>int</code> and the <code>double</code> represent. So it would help the reader understand the code if we created a custom data type:</p>\n\n<pre><code>struct MapEntry {\n int occurrences = 0;\n double not_sure_what_this_is = 0.0;\n};\n</code></pre>\n\n<p>And then we could write</p>\n\n<pre><code>charmap[letterChain].occurrences += 1;\n</code></pre>\n\n<p>which is a little bit clearer. I suspect that the names <code>charmap</code> and <code>MapEntry</code> both could be improved. Naming is important!</p>\n\n<hr>\n\n<p>I didn't really look at the other snippets in your question, but I did notice this part:</p>\n\n<pre><code>if (cePr==std::vector<QChar>(&it->first[0], &it->first[lcoh-1])) ...\n</code></pre>\n\n<p>Heap-allocating a vector just to do a comparison seems like overkill. You should look into the <a href=\"https://en.cppreference.com/w/cpp/algorithm/equal\" rel=\"nofollow noreferrer\"><code>std::equal</code></a> algorithm</p>\n\n<pre><code>if (std::equal(cePr.begin(), cePr.end(), it->first.begin(), it->first.end() - 1)) ...\n</code></pre>\n\n<p>or just write a helper function that can compare two ranges for you.</p>\n\n<pre><code>if (vector_begins_with(it->first, cePr)) ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T14:20:00.470",
"Id": "443273",
"Score": "0",
"body": "Thanks for for review! I learnt some there. What would be a suitable name for `charmap` (it is, after all, a map in which characters are the keys)? Also the double in the pair is a probability (of seeing this key occur), it is handled in the second block of code in the post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T17:15:26.880",
"Id": "443277",
"Score": "0",
"body": "\"What would be a suitable name for `charmap` (it is, after all, a map in which characters are the keys)\" — Right, I can see that it's a map of char to double just based on the type. But what does it _represent?_ From your comment it sounds like maybe it's a frequency or probability histogram, such that `charmap[k]` represents the probability of character `k`? In that case, `probability_of_character[k]` would be a pretty self-descriptive name."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T21:19:27.287",
"Id": "227485",
"ParentId": "227273",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T14:47:50.997",
"Id": "227273",
"Score": "4",
"Tags": [
"c++",
"c++11"
],
"Title": "Generating words sounding similar to the ones given in a wordlist -- Core program only"
}
|
227273
|
<p>I'm currently making an app for my side project and I was looking to get some insight on the main js file, what can I improve, the error handling, what am I doing wrong, etc. I'm mostly confused about the error handling.</p>
<p>This is the main javascript file: </p>
<pre class="lang-js prettyprint-override"><code>import express from 'express'
import cors from 'cors'
import dotenv from 'dotenv'
dotenv.config()
const morgan = require('morgan')
const app = express()
// Require routes
const usersRouter = require('./routes/users')
// Configs
require('./cfg/mongoose')
// Express middlewares / settings
app.set('port', process.env.PORT || 3000)
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
// Environment specific middlewares
if (app.get('env') === 'production') {
app.use(morgan('combined'))
} else {
app.use(morgan('dev'))
}
// Routing
app.use('/users', usersRouter)
app.get('/', (req, res) => {
res.status(200).send({
message: 'Welcome to the API! '
})
})
// Handles 404
app.use((req, res, next) => {
res.status(404).send({ error: 'Invalid endpoint' })
})
// Generic error handler
app.use((err, req, res, next) => {
if (err.errors) {
let errors = {}
for (const errorName in err.errors) {
errors = { ...errors, [errorName]: err.errors[errorName].message }
}
res.status(400).send({ errors })
} else {
res.status(err.output.statusCode).send({
message: err.message || 'Internal server error'
})
}
})
// Server
app.listen(app.get('port'), () => {
console.log(`Server listening on port ${app.get('port')}`)
})
</code></pre>
<p>And this is the users route: </p>
<pre class="lang-js prettyprint-override"><code>import express from 'express'
import mongoose from 'mongoose'
import User from '../models/User'
import boom from '@hapi/boom'
const router = express.Router()
router.post('/', async (req, res, next) => {
const { phone_number, email, password, name } = req.body
try {
const newUser = await User.create({
name,
email,
phone_number,
password,
})
res.status(201)
.set('Location', `${req.hostname}${req.baseUrl}/${newUser.id}`)
.send(newUser.id)
} catch (err) {
next(boom.boomify(err, { statusCode: 400 }))
}
})
router.get('/', async (req, res, next) => {
let users
try {
users = await User.find({}, 'name email').lean()
Object.values(users).map(user => {
user.profile_url = `${req.hostname}${req.baseUrl}/${user._id}`
})
if (!users.length) next(boom.notFound('Cannot find any users'))
res.status(200).send(users)
} catch (err) {
next(boom.badImplementation())
}
})
router.get('/:id', async (req, res, next) => {
try {
const user = await User.findById(
req.params.id,
'name email phone_number'
)
res.status(200).send(user)
} catch (err) {
next(boom.notFound('User not found'))
}
})
router.delete('/:id', async (req, res, next) => {
try {
await User.deleteOne({ _id: mongoose.Types.ObjectId(req.params.id) })
res.sendStatus(204)
} catch (err) {
next(boom.notFound('User not found'))
}
})
router.put('/:id', async (req, res, next) => {
let user
try {
const { email, phone_number, password, name } = req.body
user = await User.findOneById(req.params.id, '-__v')
user.email = email || user.email
user.phone_number = phone_number || user.phone_number
user.password = password || user.password
user.name = name || user.name
let updatedUser = await user.save()
res.status(200).send(updatedUser)
} catch (err) {
next(boom.notFound('User not found'))
}
})
module.exports = router
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T16:21:14.227",
"Id": "442265",
"Score": "1",
"body": "I wouldn't think that a database error should cause a status of 400 as the route was found just fine. Probably should be 5xx for an internal server error."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-13T19:41:03.697",
"Id": "471685",
"Score": "0",
"body": "I don't have much comment regarding the error handling, like @jfriend00 said the status of 400 makes more sense if it was 5xx. \n\nOn another note: I havent used boom but I do like to create a global response object that I can always return in all my requests. I make sure it has a few properties like data, status and mabye error object. \n\nThis way my front-end that consumes the API will always know exactly what to expect. I know that any data i request, will always be under the data property or any errors will be under my error property."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T15:52:53.593",
"Id": "227275",
"Score": "2",
"Tags": [
"javascript",
"node.js",
"mongodb",
"express.js",
"mongoose"
],
"Title": "Writing error handling and users routing for my JSON RESTful API"
}
|
227275
|
<p>I've written some utilities to read text from streams. One of these, the <code>ReadTo</code> method, is to read text from a specified stream until a given text is encountered, behaving like <code>string.IndexOf</code>, but with streams.<br>
Really, it's quite fast. But I'd like to know if anyone knows any way to make it even faster, as it's used in a very performance-critical part of a program I'm developing.</p>
<pre><code>/// <summary>
/// Provides utilities to manage streams.
/// </summary>
public static class StreamUtils
{
private const int DefaultBufferSize = 1024;
/// <summary>
/// Enumerate buffers from a specified stream.
/// </summary>
/// <param name="stream">The stream to read.</param>
/// <param name="bufferSize">The size of each buffer.</param>
/// <param name="count">How many bytes to read. Negative values mean read to end.</param>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="IOException"></exception>
/// <exception cref="NotSupportedException"></exception>
/// <exception cref="ObjectDisposedException"></exception>
public static IEnumerable<byte[]> EnumerateBuffers(this Stream stream, int bufferSize = DefaultBufferSize, long count = -1)
{
byte[] buffer = new byte[bufferSize];
do
{
long read = stream.Read(buffer, 0, bufferSize);
if (read < 1)
break;
if (count > -1)
{
count -= read;
if (count < 0)
read += count;
}
if (read == bufferSize)
yield return buffer;
else
{
byte[] newBuffer = new byte[read];
Buffer.BlockCopy(buffer, 0, newBuffer, 0, (int)read);
yield return newBuffer;
break;
}
} while (true);
}
/// <summary>
/// Enumerate substrings from a specified stream.
/// </summary>
/// <param name="stream">The stream to read.</param>
/// <param name="bufferSize">The length of each substring.</param>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="IOException"></exception>
/// <exception cref="DecoderFallbackException"></exception>
/// <exception cref="NotSupportedException"></exception>
/// <exception cref="ObjectDisposedException"></exception>
public static IEnumerable<string> EnumerateSubstrings(this Stream stream, int bufferSize = DefaultBufferSize) => stream.EnumerateSubstrings(Encoding.Default, bufferSize);
/// <summary>
/// Enumerate substrings from a specified stream.
/// </summary>
/// <param name="stream">The stream to read.</param>
/// <param name="encoding">The encoding to use.</param>
/// <param name="bufferSize">The length of each substring.</param>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="IOException"></exception>
/// <exception cref="DecoderFallbackException"></exception>
/// <exception cref="NotSupportedException"></exception>
/// <exception cref="ObjectDisposedException"></exception>
public static IEnumerable<string> EnumerateSubstrings(this Stream stream, Encoding encoding, int bufferSize = DefaultBufferSize) => from byte[] buffer in stream.EnumerateBuffers(bufferSize) select encoding.GetString(buffer);
/// <summary>
/// Read the current stream until a specified string is encountered.
/// </summary>
/// <param name="stream">The source stream.</param>
/// <param name="separator">The string that marks the end.</param>
/// <param name="bufferSize">The size of the buffers.</param>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="IOException"></exception>
/// <exception cref="DecoderFallbackException"></exception>
/// <exception cref="NotSupportedException"></exception>
/// <exception cref="ObjectDisposedException"></exception>
public static string ReadTo(this Stream stream, string separator, int bufferSize = DefaultBufferSize) => stream.ReadTo(separator, Encoding.Default, bufferSize);
/// <summary>
/// Read the current stream until a specified string is encountered.
/// </summary>
/// <param name="stream">The source stream.</param>
/// <param name="separator">The string that marks the end.</param>
/// <param name="encoding">The encoding to use.</param>
/// <param name="bufferSize">The size of the buffers.</param>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="IOException"></exception>
/// <exception cref="DecoderFallbackException"></exception>
/// <exception cref="NotSupportedException"></exception>
/// <exception cref="ObjectDisposedException"></exception>
public static string ReadTo(this Stream stream, string separator, Encoding encoding, int bufferSize = DefaultBufferSize)
{
// This method requires seeking, so ensure that the specified stream supports it.
if (!stream.CanSeek)
throw new NotSupportedException();
// This StringBuilder will build the resulting text. Using this to avoid too many string reallocations.
StringBuilder text = new StringBuilder();
bool hasSuffix = false;
string endingSeparator = null;
// Retrieve how many bytes is the specified separator long. This will be necessary to handle some seekings on the stream.
int separatorByteLength = encoding.GetByteCount(separator);
// Iterate through each substring in the stream. Each one is a buffer converted to a string using a specified encoding.
foreach (string substring in stream.EnumerateSubstrings(encoding, bufferSize))
{
// Retrieve how many bytes is the current substring long. Again, useful for seekings.
int substringByteLength = encoding.GetByteCount(substring);
// Check out whether the previous substring had a suffix.
if (hasSuffix)
{
// If it had, then verify whether the current substring starts with the remaining part of the separator.
if (substring.StartsWith(separator.Substring(endingSeparator.Length)))
{
// In that case, seek till before the separator and break the loop.
stream.Seek(substringByteLength - encoding.GetByteCount(endingSeparator), SeekOrigin.Current);
break;
}
// If the code reached here, then the previous suffix were not part of a separator, as the whole of the separator cannot be found.
hasSuffix = false;
text.Append(endingSeparator);
}
// If the current substring starts with the separator, just skip it and break the loop, so the StringBuilder will only contain previous substrings.
if (substring.StartsWith(separator))
break;
{
// Check out whether the current substring contains the separator.
int separatorIndex = substring.IndexOf(separator);
if (separatorIndex != -1)
{
// If that's the case, take this substring till the previously found index, ...
string newSubstring = substring.Remove(separatorIndex);
// ...then seek the current stream before the separator, ...
stream.Seek(encoding.GetByteCount(newSubstring) - substringByteLength, SeekOrigin.Current);
/// ...and finally append the new substring (the one before the separator) to the StringBuilder.
text.Append(newSubstring);
break;
}
}
// Check out whether the current substring ends with the specified separator.
if (substring.EndsWith(separator))
{
// If it does, go back as many bytes as the separator is long within the stream.
stream.Seek(-separatorByteLength, SeekOrigin.Current);
// Then, append this substring till before the specified separator to the StringBuilder.
text.Append(substring.Remove(substring.Length - separator.Length));
break;
}
// Sometimes, it might happen that the separator is divided between the current substring and the next one.
// So, see whether the current substring ends with just one part (even one only character) of the separator.
endingSeparator = separator;
do
// Remove the last character from the 'ending separator'.
endingSeparator = endingSeparator.Remove(endingSeparator.Length - 1);
// If the ending separator isn't empty yet and the current substring doesn't end with it,
// continue the loop.
while (!(endingSeparator.Length == 0 || substring.EndsWith(endingSeparator)));
// At this time, the ending separator will be an initial part of the specified separator,
// which is a 'suffix' of the current substring.
// Push the length of the suffix on the stack, so I'll avoid to call the Length getter accessor multiple times.
int suffixLength = endingSeparator.Length;
// If the suffix is empty, that means the current string doesn't end with even just a part of the separator.
// Therefore, just append the current string to the StringBuilder.
if (suffixLength == 0)
text.Append(substring);
else
{
// If rather the suffix isn't empty, then mark this with the boolean hasSuffix and
// append the current substring only till before the suffix.
hasSuffix = true;
text.Append(substring.Remove(substring.Length - suffixLength));
}
}
return text.ToString();
}
}
</code></pre>
<p>Usage sample:</p>
<pre><code>string text = "Hello world, this is a test";
Encoding encoding = Encoding.UTF8;
using (Stream stream = new MemoryStream(encoding.GetBytes(text)))
{
string substring = stream.ReadTo(", this", encoding);
// substring == "Hello world"
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T15:10:22.757",
"Id": "442587",
"Score": "0",
"body": "You must not edit the code when answers have been posted. It can and usually does invalidate them. I rolled back your last couple of edits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T15:12:01.507",
"Id": "442589",
"Score": "0",
"body": "Ok, I didn't know. Thanks"
}
] |
[
{
"body": "<p>By altering/ specifying the string comparer from the default StringComparison.CurrentCulture to StringComparison.Ordinal you can win a lot.</p>\n\n<p>Also note that sometimes Buffer.BlockCopy(buffer, 0, newBuffer, 0, (int)read) is slower than Array.Copy(buffer, 0, newBuffer, 0, (int)read).</p>\n\n<p>I ran your code with a Stopwatch, added these small changes and ran it as few times again and again and averaged on.\noriginal 401986 ticks\nupdated 101224 ticks</p>\n\n<p>If you like to really know if you gain something instrument it with <a href=\"https://www.nuget.org/packages/BenchmarkDotNet/\" rel=\"nofollow noreferrer\">BenchmarkDotNet</a>, cool nuget package that shows where \"it hurts\"</p>\n\n<p>This is by no means all you could do, I would start to look at removing things that cause \"newing up classes\" as that takes a lot of time and work with span or even ReadOnlySpan. The linq method you use is such class that generates a class in memory that needs to be taken to the GC, over time this starts to slow things down.</p>\n\n<p>Here is your code with the small tweeks</p>\n\n<pre><code>public static class StreamUtils\n{\n\n private const int DefaultBufferSize = 1024;\n\n /// <summary>\n /// Enumerate buffers from a specified stream.\n /// </summary>\n /// <param name=\"stream\">The stream to read.</param>\n /// <param name=\"bufferSize\">The size of each buffer.</param>\n /// <param name=\"count\">How many bytes to read. Negative values mean read to end.</param>\n /// <returns></returns>\n /// <exception cref=\"ArgumentException\"></exception>\n /// <exception cref=\"ArgumentNullException\"></exception>\n /// <exception cref=\"IOException\"></exception>\n /// <exception cref=\"NotSupportedException\"></exception>\n /// <exception cref=\"ObjectDisposedException\"></exception>\n public static IEnumerable<byte[]> EnumerateBuffers(this Stream stream, int bufferSize = DefaultBufferSize, long count = -1)\n {\n byte[] buffer = new byte[bufferSize];\n do\n {\n long read = stream.Read(buffer, 0, bufferSize);\n if (read < 1)\n break;\n if (count > -1)\n {\n count -= read;\n if (count < 0)\n read += count;\n }\n if (read == bufferSize)\n yield return buffer;\n else\n {\n byte[] newBuffer = new byte[read];\n Array.Copy(buffer, 0, newBuffer, 0, (int)read);\n //Buffer.BlockCopy(buffer, 0, newBuffer, 0, (int)read);\n yield return newBuffer;\n break;\n }\n } while (true);\n }\n\n // A very simple and efficient memmove that assumes all of the\n // parameter validation has already been done. The count and offset\n // parameters here are in bytes. If you want to use traditional\n // array element indices and counts, use Array.Copy.\n [System.Security.SecuritySafeCritical] // auto-generated\n [ResourceExposure(ResourceScope.None)]\n [MethodImplAttribute(MethodImplOptions.InternalCall)]\n internal static extern void InternalBlockCopy(Array src, int srcOffsetBytes,\n Array dst, int dstOffsetBytes, int byteCount);\n\n\n /// <summary>\n /// Enumerate substrings from a specified stream.\n /// </summary>\n /// <param name=\"stream\">The stream to read.</param>\n /// <param name=\"bufferSize\">The length of each substring.</param>\n /// <returns></returns>\n /// <exception cref=\"ArgumentException\"></exception>\n /// <exception cref=\"ArgumentNullException\"></exception>\n /// <exception cref=\"IOException\"></exception>\n /// <exception cref=\"DecoderFallbackException\"></exception>\n /// <exception cref=\"NotSupportedException\"></exception>\n /// <exception cref=\"ObjectDisposedException\"></exception>\n public static IEnumerable<string> EnumerateSubstrings(this Stream stream, int bufferSize = DefaultBufferSize) \n => stream.EnumerateSubstrings(Encoding.Default, bufferSize);\n\n /// <summary>\n /// Enumerate substrings from a specified stream.\n /// </summary>\n /// <param name=\"stream\">The stream to read.</param>\n /// <param name=\"encoding\">The encoding to use.</param>\n /// <param name=\"bufferSize\">The length of each substring.</param>\n /// <returns></returns>\n /// <exception cref=\"ArgumentException\"></exception>\n /// <exception cref=\"ArgumentNullException\"></exception>\n /// <exception cref=\"IOException\"></exception>\n /// <exception cref=\"DecoderFallbackException\"></exception>\n /// <exception cref=\"NotSupportedException\"></exception>\n /// <exception cref=\"ObjectDisposedException\"></exception>\n public static IEnumerable<string> EnumerateSubstrings(this Stream stream, Encoding encoding, int bufferSize = DefaultBufferSize) \n => from byte[] buffer in stream.EnumerateBuffers(bufferSize) select encoding.GetString(buffer);\n\n\n\n /// <summary>\n /// Read the current stream until a specified string is encountered.\n /// </summary>\n /// <param name=\"stream\">The source stream.</param>\n /// <param name=\"separator\">The string that marks the end.</param>\n /// <param name=\"bufferSize\">The size of the buffers.</param>\n /// <returns></returns>\n /// <exception cref=\"ArgumentException\"></exception>\n /// <exception cref=\"ArgumentNullException\"></exception>\n /// <exception cref=\"IOException\"></exception>\n /// <exception cref=\"DecoderFallbackException\"></exception>\n /// <exception cref=\"NotSupportedException\"></exception>\n /// <exception cref=\"ObjectDisposedException\"></exception>\n public static string ReadTo(this Stream stream, string separator, int bufferSize = DefaultBufferSize) => stream.ReadTo(separator, Encoding.Default, bufferSize);\n\n /// <summary>\n /// Read the current stream until a specified string is encountered.\n /// </summary>\n /// <param name=\"stream\">The source stream.</param>\n /// <param name=\"separator\">The string that marks the end.</param>\n /// <param name=\"encoding\">The encoding to use.</param>\n /// <param name=\"bufferSize\">The size of the buffers.</param>\n /// <returns></returns>\n /// <exception cref=\"ArgumentException\"></exception>\n /// <exception cref=\"ArgumentNullException\"></exception>\n /// <exception cref=\"IOException\"></exception>\n /// <exception cref=\"DecoderFallbackException\"></exception>\n /// <exception cref=\"NotSupportedException\"></exception>\n /// <exception cref=\"ObjectDisposedException\"></exception>\n public static string ReadTo(this Stream stream, string separator, Encoding encoding, int bufferSize = DefaultBufferSize)\n {\n // This method requires seeking, so ensure that the specified stream supports it.\n if (!stream.CanSeek)\n throw new NotSupportedException();\n // This StringBuilder will build the resulting text. Using this to avoid too many string reallocations.\n StringBuilder text = new StringBuilder();\n bool hasSuffix = false;\n string endingSeparator = null;\n // Retrieve how many bytes is the specified separator long. This will be necessary to handle some seekings on the stream.\n int separatorByteLength = encoding.GetByteCount(separator);\n // Iterate through each substring in the stream. Each one is a buffer converted to a string using a specified encoding.\n foreach (string substring in stream.EnumerateSubstrings(encoding, bufferSize))\n {\n // Retrieve how many bytes is the current substring long. Again, useful for seekings.\n int substringByteLength = encoding.GetByteCount(substring);\n // Check out whether the previous substring had a suffix.\n if (hasSuffix)\n {\n // If it had, then verify whether the current substring starts with the remaining part of the separator.\n if (substring.StartsWith(separator.Substring(endingSeparator.Length),StringComparison.Ordinal))\n {\n // In that case, seek till before the separator and break the loop.\n stream.Seek(substringByteLength - encoding.GetByteCount(endingSeparator), SeekOrigin.Current);\n break;\n }\n // If the code reached here, then the previous suffix were not part of a separator, as the whole of the separator cannot be found.\n hasSuffix = false;\n text.Append(endingSeparator);\n }\n // If the current substring starts with the separator, just skip it and break the loop, so the StringBuilder will only contain previous substrings.\n if (substring.StartsWith(separator,StringComparison.Ordinal))\n break;\n {\n // Check out whether the current substring contains the separator.\n int separatorIndex = substring.IndexOf(separator,StringComparison.Ordinal);\n if (separatorIndex != -1)\n {\n // If that's the case, take this substring till the previously found index, ...\n string newSubstring = substring.Remove(separatorIndex);\n // ...then seek the current stream before the separator, ...\n stream.Seek(encoding.GetByteCount(newSubstring) - substringByteLength, SeekOrigin.Current);\n /// ...and finally append the new substring (the one before the separator) to the StringBuilder.\n text.Append(newSubstring);\n break;\n }\n }\n // Check out whether the current substring ends with the specified separator.\n if (substring.EndsWith(separator,StringComparison.Ordinal))\n {\n // If it does, go back as many bytes as the separator is long within the stream.\n stream.Seek(-separatorByteLength, SeekOrigin.Current);\n // Then, append this substring till before the specified separator to the StringBuilder.\n text.Append(substring.Remove(substring.Length - separator.Length));\n break;\n }\n // Sometimes, it might happen that the separator is divided between the current substring and the next one.\n // So, see whether the current substring ends with just one part (even one only character) of the separator.\n endingSeparator = separator;\n do\n // Remove the last character from the 'ending separator'.\n endingSeparator = endingSeparator.Remove(endingSeparator.Length - 1);\n // If the ending separator isn't empty yet and the current substring doesn't end with it,\n // continue the loop.\n while (!(endingSeparator.Length == 0 || substring.EndsWith(endingSeparator,StringComparison.Ordinal)));\n // At this time, the ending separator will be an initial part of the specified separator,\n // which is a 'suffix' of the current substring.\n // Push the length of the suffix on the stack, so I'll avoid to call the Length getter accessor multiple times.\n int suffixLength = endingSeparator.Length;\n // If the suffix is empty, that means the current string doesn't end with even just a part of the separator.\n // Therefore, just append the current string to the StringBuilder.\n if (suffixLength == 0)\n text.Append(substring);\n else\n {\n // If rather the suffix isn't empty, then mark this with the boolean hasSuffix and\n // append the current substring only till before the suffix.\n hasSuffix = true;\n text.Append(substring, 0, substring.Length - suffixLength);\n }\n }\n return text.ToString();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T16:57:26.250",
"Id": "442434",
"Score": "1",
"body": "_sometimes Buffer.BlockCopy is slower than Array.Copy_ - can you provide some information to support this so far theory? OP should use `ReadOnlySpan` in place of what exactly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T17:02:21.893",
"Id": "442436",
"Score": "1",
"body": "_BenchmarkDotNet, cool nuget package that shows where \"it hurts\"_ - by doing what? Is it better than a profiler?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T19:09:47.910",
"Id": "442450",
"Score": "0",
"body": "@t3chb01, Well it's a different tool, shows different information. I like it when I tune code have a look at the documentation https://benchmarkdotnet.org/articles/overview.html"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T13:46:40.520",
"Id": "227329",
"ParentId": "227278",
"Score": "2"
}
},
{
"body": "<blockquote>\n<pre><code> if (read == bufferSize)\n yield return buffer;\n else\n</code></pre>\n</blockquote>\n\n<p>Be aware that repeatedly <code>yield return</code> the same buffer is rather risky. Imagine the following use case where all returned buffers are cached for later use for some reason:</p>\n\n<pre><code> List<byte[]> buffers = new List<byte[]>();\n using (FileStream stream = File.OpenRead(path))\n {\n foreach (byte[] buffer in stream.EnumerateBuffers(1024))\n {\n buffers.Add(buffer);\n }\n }\n</code></pre>\n\n<p>The result is that all items in <code>buffers</code> are references to the same buffer, hence they all have the same (the last returned with full length) set of bytes.</p>\n\n<p>I think you should go with a much simpler approach:</p>\n\n<pre><code>public static IEnumerable<byte[]> EnumerateBuffers(this Stream stream, int bufferSize = DefaultBufferSize, long count = -1)\n{\n long read;\n while (true)\n {\n byte[] buffer = new byte[bufferSize];\n read = stream.Read(buffer, 0, bufferSize);\n if (read > 0)\n yield return buffer;\n else\n break;\n } \n}\n</code></pre>\n\n<hr>\n\n<p><strong>Update</strong></p>\n\n<p>Have you tested performance against reading char-by-char using a <code>StreamReader</code>like:</p>\n\n<pre><code>public static string ReadTo(this Stream stream, string separator, Encoding encoding)\n{\n if (!stream.CanSeek)\n throw new NotSupportedException(\"The stream must be seekable\");\n\n StringBuilder text = new StringBuilder();\n int index = 0;\n bool searching = false;\n int sepIndex = 0;\n char cur;\n\n using (StreamReader reader = new StreamReader(stream, encoding, false, 1024, true))\n {\n int res;\n while ((res = reader.Read()) != -1)\n {\n cur = (char)res;\n if (!searching && cur == separator[0])\n {\n searching = true;\n sepIndex = 1;\n }\n else if (searching && sepIndex < separator.Length && cur == separator[sepIndex])\n {\n sepIndex++;\n }\n else\n {\n if (sepIndex == separator.Length)\n {\n break;\n }\n\n searching = false;\n sepIndex = 0;\n }\n\n text.Append(cur);\n\n index++;\n }\n }\n\n if (sepIndex == separator.Length && text.Length >= sepIndex)\n text.Length -= sepIndex;\n\n return text.ToString();\n}\n</code></pre>\n\n<p>This is more than ten times faster than the original for a data set of 7600 kb and finding the last four chars as the <code>separator</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T15:45:34.247",
"Id": "442407",
"Score": "0",
"body": "I know that it is risky, but I need extreme performances, and re-allocating as many buffers as chunks would be even more risky when it comes to performances. My method is not meant to cache buffers, but to immediately read from a stream. Indeed, the right way to cache a stream is to copy it to a MemoryStream, not adding buffers to a list. It would be a bad practice, and if bad practices don't work, it's not my issue!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T15:52:19.613",
"Id": "442411",
"Score": "2",
"body": "@DavideCannizzo: OK, it's your code, but maybe you should document the behavior then."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T16:15:26.097",
"Id": "442418",
"Score": "0",
"body": "Right, @Henrik Hansen. I'll do as soon as possible"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T16:58:54.997",
"Id": "442435",
"Score": "1",
"body": "_a much simpler approach_ - could you explain what is so special about this approach?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T17:03:57.113",
"Id": "442437",
"Score": "1",
"body": "@t3chb0t: It's you, that use the word \"special\" - not I. I call it simpler (than the original). But it is - according to Davides comment - irrelevant as he wants to keep his own version :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T17:14:32.227",
"Id": "442438",
"Score": "0",
"body": "@Henrik Hansen, I agree with you that your way is much simpler, and it was the first thing that came up to my mind. However, I forgot to mention that I'm using these utilities with Sockets, and so, reading character by character would be extremely slow, as each character would be downloaded separately from the next ones. So, my approach was to work with buffers, which aim to be properly sized (but this is not a matter to discuss here - I already optimized the buffer sizes up), so that it can be as much fast as possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T17:16:28.030",
"Id": "442439",
"Score": "0",
"body": "I'd like it if someone could speed up my idea or tell me about another that uses buffers as well. But your idea, which is optimal for most purposes, unfortunately, it's not the right one for my use case. I'll update my question to specify that I'm working with sockets. Regarding how streams could be related to Receive calls on the sockets, I use my own implementation of them (which, under the hood, uses the .NET standard implementation of sockets), which provides a stream to avoid Receive and Send calls."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T17:17:27.860",
"Id": "442440",
"Score": "0",
"body": "However, thank you anyway for sharing your solution, @Henrik Hansen. I upvoted your answer for your contribution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T19:12:58.967",
"Id": "442451",
"Score": "0",
"body": "I think using span would be faster as you do not need to copy buffers at all"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T15:41:27.403",
"Id": "227341",
"ParentId": "227278",
"Score": "2"
}
},
{
"body": "<h3>Problems:</h3>\n\n<ul>\n<li><code>EnumerateSubstrings</code> and <code>ReadTo</code> do not work correctly with variable-width encodings, multi-byte encodings and surrogate pairs, because they do not take into account that characters can be split across buffer boundaries. This can cause a variety of problems.</li>\n<li>In some cases, <code>ReadTo</code> fails to find the separator if it's longer than the buffer size (this always happens if the separator is more than twice as long).</li>\n<li><code>ReadTo</code> also fails to detect matches across buffer boundaries when <code>separator</code> contains a prefix of itself and there's both a partial and a full match across the boundary. For example, try reading up to <code>\"aab\"</code> in <code>\"..aaab..\"</code> with a buffer size of 4. </li>\n</ul>\n\n<h3>Performance:</h3>\n\n<ul>\n<li>As has been pointed out already, <code>StringComparison.Ordinal</code> is a lot faster - because it just compares code point values without taking culture-specific rules into account. For example, a culture-aware comparison will see that <code>\"\\u00E9\"</code> and <code>\"e\\u0301\"</code> both represent an <code>é</code>, but an ordinal comparison will treat them as unequal. Which one to choose first and foremost depends on the behavior you need.</li>\n<li>The <code>StartsWith</code> and <code>EndsWith</code> checks are useless - <code>substring.IndexOf(separator)</code> already takes care of those situations.</li>\n<li>For long separators, the <code>do-while</code> loop that checks if the buffer ends with a prefix of the given separator involves a fair amount of string allocations. If you need culture-specific string comparisons then it might be faster to combine the end of the last buffer with the current buffer so you can keep using <code>IndexOf</code>. If ordinal comparisons are fine for your purposes, then a modified Knuth-Morris-Pratt algorithm could be useful here. Both of these should also help with solving the cross-boundary partial matches problem.</li>\n<li>Using an 8KB buffer is roughly 25% faster on my system. I'd recommend testing different sizes before deciding on a good (default) size.</li>\n<li>Instead of first creating a substring with <code>string.Remove</code>, use the <code>StringBuilder.Append(string, int, int)</code> overload.</li>\n</ul>\n\n<h3>Other notes:</h3>\n\n<ul>\n<li>The encoding returned by <code>Encoding.Default</code> depends on system settings, which means you can get different results on different systems. <code>Encoding.UTF8</code> would be a safer default.</li>\n<li>It would be nice if the <code>NotSupportedException</code> exception contained a message that said what exactly it doesn't support.</li>\n<li>If you're going to guard against invalid parameters, then also be sure to check that the separator isn't null or empty. I'd also set the encoding and buffer size to some sane default value if they're null or too low, respectively.</li>\n<li><code>ReadTo</code> contains a lot of superfluous comments. For example, the first check already makes it obvious that the method requires seeking, and the whole purpose of a <code>StringBuilder</code> is to build up strings efficiently. Repeating that in comments is just adding clutter.</li>\n<li>I'd recommend using <code>var</code> to cut down on typename repetition.</li>\n<li>Add some empty lines to break up long parts of code and to make it easier to distinguish between different 'blocks' of code (such as unrelated if statements).</li>\n<li>Inconsistent use of braces makes it more difficult to see control flow, which makes it easier to make mistakes.</li>\n<li>It's good to see methods being documented. A few minor things: 'the length of each substring' sounds like it's measured in characters, but it's actually the number of bytes. 'The size of the buffers' suggests that the methods use multiple buffers internally, so I'd make that singular instead.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T15:11:36.290",
"Id": "442588",
"Score": "0",
"body": "I updated the code in my question as per some of your and other's suggestions. However, I cannot figure out how could some of your points be true: I've just noticed, as you pointed out, that my method would fail on if the specified separator is twice of more longer than the specified buffer size, but how could it fail on with separators just longer than the buffer size (less long than twice the buffer size)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T15:14:09.970",
"Id": "442591",
"Score": "0",
"body": "The user @t3chb0t just rolled out my last changes. He was right, indeed. I was unaware of edits invalidating answers. Anyway, I don't understand how my method could fail on with separators that are longer than the buffer size and less long than twice it. Can you please explain me?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T15:18:38.620",
"Id": "442593",
"Score": "1",
"body": "It happens when a match stretches across 3 buffers, which can be achieved with a separator that's `bufferSize + 2` long. Try finding `\"abbbbc\"` in `\"aaaabbbbcccc\"`, with a buffer size of 4."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T15:25:29.810",
"Id": "442595",
"Score": "0",
"body": "I got that. I was referring to the case where the separator is longer than the buffer size, but shorter than twice as long."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T15:30:23.720",
"Id": "442598",
"Score": "1",
"body": "`\"abbbbc\"` is longer than 4, but shorter than 8."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T15:33:35.663",
"Id": "442601",
"Score": "0",
"body": "Right. I'll try to debug it as soon as possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T16:20:51.467",
"Id": "442627",
"Score": "0",
"body": "I just debugged it, @Pieter Witvoet, and I'm trying to solve the issue."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T16:55:48.610",
"Id": "442635",
"Score": "0",
"body": "I now fixed all the issues related to the length of the separator."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T16:59:39.173",
"Id": "442636",
"Score": "0",
"body": "Why wouldn't my method work with variable-width encoding? I repeatedly used encoding.GetByteCount to get the length of a text as per the specified encoding. Can you please explain it to me, @Pieter Witvoet?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T17:24:03.240",
"Id": "442642",
"Score": "0",
"body": "That problem has to do with `EnumerateSubstrings`. Try calling it on `\"你好世界\"` (UTF-8 encoded) with a buffer size of 4. Or try it on a UTF-16 encoded string while using an odd buffer size."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T17:33:16.307",
"Id": "442646",
"Score": "0",
"body": "Thanks, @Pieter Witvoet for having pointed out such a bug. I just remembered I immediately thought of it when writing that method, without even having to test it out, but I couldn't find any way to fix it and then I forgot it. Do you have any idea to make that method working?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T17:38:35.963",
"Id": "442650",
"Score": "0",
"body": "I just found a trick that I admit it's not the best solution, but which actually works: rather than using the specified buffer size, I'll use encoding.GetMaxByteCount(bufferSize)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T19:16:44.003",
"Id": "442686",
"Score": "0",
"body": "Multiplying the buffer size won't solve the problem for variable-width encodings. If it weren't for the stream 'rewinding' I would've just used a `StreamReader` to take care of the buffering and decoding."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T14:57:22.350",
"Id": "227406",
"ParentId": "227278",
"Score": "3"
}
},
{
"body": "<p>If you're not scared of a little bit of <code>unsafe</code> code then you can get rid of the copying of the buffer entirely as there is a <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.text.encoding.getstring?view=netframework-4.8#System_Text_Encoding_GetString_System_Byte__System_Int32_\" rel=\"nofollow noreferrer\"><code>GetString</code></a> overlaod that accepts a length of the buffer. Or <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.text.encoding.getstring?view=netframework-4.8#System_Text_Encoding_GetString_System_Byte___System_Int32_System_Int32_\" rel=\"nofollow noreferrer\">another overload</a> that doesn't require unsafe code</p>\n\n<p>The loop in <code>ReadTo</code> could begin like this:</p>\n\n<pre><code> foreach (var (buffer, length) in stream.EnumerateBuffers(bufferSize))\n {\n var substring = default(string);\n unsafe\n {\n fixed (byte* p_buffer = buffer)\n {\n substring = encoding.GetString(p_buffer, length);\n }\n } \n\n // or\n\n substring = encoding.GetString(buffer, 0, length);\n</code></pre>\n\n<p>where <code>EnumerateBuffers</code> now returns tuples with the buffer and its length:</p>\n\n<pre><code>public static IEnumerable<(byte[] Buffer, int Length)> EnumerateBuffers(this Stream stream, int bufferSize = DefaultBufferSize, long count = -1)\n{\n byte[] buffer = new byte[bufferSize];\n do\n {\n long read = stream.Read(buffer, 0, bufferSize);\n if (read < 1)\n {\n break;\n }\n if (count > -1)\n {\n count -= read;\n if (count < 0)\n read += count;\n }\n\n yield return (buffer, (int)read);\n\n } while (true);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T16:08:14.990",
"Id": "442620",
"Score": "1",
"body": "Thanks, @t3chb0t for your solution. However, I won't apply it because of the disorder of returning tuples (I'm not scared of unsafety)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T16:10:24.187",
"Id": "442621",
"Score": "1",
"body": "@DavideCannizzo sure, there is no _must apply_ ;-] I just thought it's good to know there is one more overload that makes it more convenient in certain situations - might be useful someone else. But could you expand what kind of _disorder_ you mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T16:12:39.313",
"Id": "442622",
"Score": "0",
"body": "@DavideCannizzo I now noticed your edit. _disorder of returning tuples_? I might still need help understanding this one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T16:13:16.717",
"Id": "442623",
"Score": "0",
"body": "I'm happy to know about the overload you were pointing out (indeed, I upvoted your answer the same). However, I feel your code a bit messy. EnumerateSubstring, as per its name, should enumerate some substrings (each one per buffer), so it'll be strange if it returned tuples. Moreover, I made it to make things simple, and if it gave the responsibility to cut the buffers, it would be uncomfortable to use it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T16:15:35.330",
"Id": "442625",
"Score": "0",
"body": "@DavideCannizzo haha, now I see what you mean. It's just for demonstration purposes. It doesn't mean it _has to be_ implemented exactly like that. The point was the overload ;-) but... the other iterators _consume_ performance too, so in a perfomrance critical parts there is no or very little clean-code :P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T16:21:10.097",
"Id": "442628",
"Score": "1",
"body": "@DavideCannizzo as a matter of fact I started this with the pointers and only later noticed there was the second overload. The reason it looks the way it is, is because enumerators didn't like unsafe code :-P Had I started with the _safe_ one, it'd probably turned out differently hehe."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T16:24:34.153",
"Id": "442631",
"Score": "0",
"body": "Right, @t3chb0t. I didn't know about pointers not being able to be used in enumerator contexts as well. The second thing I learned with your answer. Thank you very much!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T12:25:24.767",
"Id": "442806",
"Score": "0",
"body": "Why in the past few weeks have tuples started appearing everywhere?!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T13:43:57.397",
"Id": "442828",
"Score": "0",
"body": "@VisualMelon tuples for president! :-P"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T16:00:25.877",
"Id": "227414",
"ParentId": "227278",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227329",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T17:22:47.313",
"Id": "227278",
"Score": "9",
"Tags": [
"c#",
"strings",
"search",
"stream"
],
"Title": "Stream text scanning"
}
|
227278
|
<p>This came out on the spur of the moment, as a quick and dirty tool to have the job done.</p>
<p>This is a simple image scraper for immensely popular and legendary comic website inspired by a Python Easter Egg.</p>
<p><em>For those who don't know it, run your Python interpreter and type <code>import antigravity</code> and hit Enter.</em> :)</p>
<p>As for the code below, I'd appreciate any feedback, particularly in regards to threading, as I'm new to this.</p>
<pre><code>#!/usr/bin/python3
import os
import sys
import time
import threading
from pathlib import Path
from shutil import copyfileobj
import requests
from lxml import html
BASE_URL = "https://www.xkcd.com/"
ARCHIVE = "https://www.xkcd.com/archive"
SAVE_DIRECTORY = Path('xkcd_comics')
LOGO = """
_ _
tiny | | image | | downloader for
__ _| | _____ __| | ___ ___ _ __ ___
\ \/ / |/ / __/ _` | / __/ _ \| '_ ` _ \
> <| < (_| (_| || (_| (_) | | | | | |
/_/\_\_|\_\___\__,_(_)___\___/|_| |_| |_|
version 0.1
"""
def show_logo():
print(LOGO)
def fetch_url(url: str) -> requests.Response:
return requests.get(url)
def head_option(values: list) -> str:
return next(iter(values), None)
def get_penultimate(url: str) -> int:
page = fetch_url(url)
tree = html.fromstring(page.content)
newest_comic = head_option(
tree.xpath('//*[@id="middleContainer"]/a[1]/@href'))
return int(newest_comic.replace("/", ""))
def get_images_from_page(url: str) -> str:
page = fetch_url(url)
tree = html.fromstring(page.content)
return head_option(tree.xpath('//*[@id="comic"]//img/@src'))
def get_number_of_pages(latest_comic: int) -> int:
print(f"There are {latest_comic} comics.")
print(f"How many do you want to download? Type 0 to exit.")
while True:
try:
number_of_comics = int(input(">> "))
except ValueError:
print("Error: Expected a number. Try again.")
continue
if number_of_comics > latest_comic or number_of_comics < 0:
print("Error: Incorrect number of comics. Try again.")
continue
elif number_of_comics == 0:
sys.exit()
return number_of_comics
def clip_url(img: str) -> str:
return img.rpartition("/")[-1]
def make_dir():
return os.makedirs(SAVE_DIRECTORY, exist_ok=True)
def save_image(img: str):
comic_name = clip_url(img)
print(f"Downloading: {comic_name}")
f_name = SAVE_DIRECTORY / comic_name
with requests.get("https:" + img, stream=True) as img, open(f_name, "wb") \
as output:
copyfileobj(img.raw, output)
def show_time(seconds: int) -> int:
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
time_elapsed = f"{hours:02d}:{minutes:02d}:{seconds:02d}"
return time_elapsed
def get_xkcd():
show_logo()
make_dir()
collect_garbage = []
latest_comic = get_penultimate(ARCHIVE)
pages = get_number_of_pages(latest_comic)
start = time.time()
for page in reversed(range(latest_comic - pages + 1, latest_comic + 1)):
print(f"Fetching page {page} out of {latest_comic}")
try:
url = get_images_from_page(f"{BASE_URL}{page}/")
thread = threading.Thread(target=save_image, args=(url, ))
thread.start()
except (ValueError, AttributeError, requests.exceptions.MissingSchema):
print(f"WARNING: Invalid comic image source url.")
collect_garbage.append(f"{BASE_URL}{page}")
continue
thread.join()
end = time.time()
print(f"Downloaded {pages} comic(s) in {show_time(int(end - start))}.")
if len(collect_garbage) > 0:
print("However, was unable to download images for these pages:")
print("\n".join(page for page in collect_garbage))
def main():
get_xkcd()
if __name__ == '__main__':
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T08:57:49.770",
"Id": "442342",
"Score": "17",
"body": "I have rolled back your last edit. 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)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T08:58:00.933",
"Id": "442343",
"Score": "2",
"body": "While your intentions by removing part of the code are good, it does invalidate existing answers. We can't have that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T09:35:17.590",
"Id": "442350",
"Score": "0",
"body": "I also suggest recording statistics, the number of requests made, the bandwidth used by the scraper, ...etc"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T09:45:28.560",
"Id": "442352",
"Score": "1",
"body": "Why isn't the api provided used?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T09:51:43.883",
"Id": "442353",
"Score": "5",
"body": "@Thomas there's an API there? If so, that's a game changer!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T10:05:43.357",
"Id": "442355",
"Score": "25",
"body": "https://xkcd.com/json.html"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T21:05:27.400",
"Id": "442468",
"Score": "3",
"body": "[Relevant xkcd](https://xkcd.com/353/)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T22:56:50.093",
"Id": "442475",
"Score": "0",
"body": "By the way, the DoS problems with this code would not have been an issue if it didn't have so many wheels it needed to reinvent. Robot exclusion, interval between requests, restricting bandwidth during download, skipping already downloaded files, selecting only images newer than _x_ days: These are all built into tools like `wget`. I don't know the Python equivalent, but hopefully someone who does can post the answer here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T00:47:32.853",
"Id": "442482",
"Score": "1",
"body": "A comment about the xkcd scraping part rather than the code: xkcd has title text on every image, and you may wish to save that if you're scraping. (Some of that title text is also non-ASCII, so that'll possibly add an additional challenge.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T10:07:05.270",
"Id": "442778",
"Score": "1",
"body": "Minor bug, you've over-counted the number of comics. latest_comic (and thus the reported total number of comics) returns the id of the, well, latest comic. Since comics are indexed from 1 to 2198 (as of today), there would seem to be 2198 comics. HOWEVER, that assumes every index corresponds to a comic. https://xkcd.com/404/"
}
] |
[
{
"body": "<h2>Globals</h2>\n\n<p>As it is, there would be an advantage to <code>LOGO</code> being a local instead of a global - it's only used by <code>show_logo</code>, and moving it there would clean up the global namespace.</p>\n\n<p>That said (and as others have pointed out), it's fairly common to see stuff like this at the top of Python files in global scope. However, the larger issue is that if you move it to local scope, you have to get clever with indentation. There are no great solutions to this - either you have to de-indent all but the first line, which is ugly; or you have to post-process the string to remove all whitespace at the beginning of each line. So this one is kind of a wash.</p>\n\n<h2>Base URLs</h2>\n\n<p>You correctly saved a base URL, but then didn't use it in the correct contexts. Particularly problematic:</p>\n\n<pre><code>ARCHIVE = \"https://www.xkcd.com/archive\"\n</code></pre>\n\n<p>This ignores the <code>BASE_URL</code> entirely, when it shouldn't.</p>\n\n<p><code>fetch_url</code> is currently useless - it doesn't add anything to <code>requests.get</code>. You could make it useful by making the argument a path relative to the base path.</p>\n\n<pre><code>with requests.get(\"https:\" + img\n# ...\nurl = get_images_from_page(f\"{BASE_URL}{page}/\")\n</code></pre>\n\n<p>Naive string concatenation is not the right thing to do, here. Python has a full-featured <code>urllib</code> to deal with URL parsing and construction.</p>\n\n<h2>show_time</h2>\n\n<p><code>divmod</code> on a numeric time interval is not the right thing to do. Use <code>datetime.timedelta</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T08:15:59.273",
"Id": "442330",
"Score": "8",
"body": "What's wrong with listing hard-coded values as constants at the beginning of a module? It looks like common practice to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T13:08:19.677",
"Id": "442384",
"Score": "0",
"body": "@Vincent Sure; though the larger problem is indentation. I've added some commentary to what's a more nuanced issue than I first indicated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T14:03:06.320",
"Id": "442394",
"Score": "0",
"body": "@Vincent That's common, it doesn't mean it's best. From my point of view, when I see a whole bunch of constants declared at the beginning of the module, and those constants' names imply that they might change depending on the situation (base url might change in the future), I think they belong to a config file instead. Yes, in this case it might be overkill, but that's the idea."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T08:27:53.727",
"Id": "442528",
"Score": "1",
"body": "@ChatterOne While config file is fine too, using it makes you import configparser and handle paths just for the sake of having a config file. It makes no sense to do such a thing unless the constants are meant to be pluggable instead of just having one place in file so that I don't need to rewrite strings everywhere if the script suddenly stops working."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T02:16:54.700",
"Id": "227292",
"ParentId": "227280",
"Score": "15"
}
},
{
"body": "<pre><code>for page in reversed(range(latest_comic - pages + 1, latest_comic + 1)):\n print(f\"Fetching page {page} out of {latest_comic}\")\n try:\n url = get_images_from_page(f\"{BASE_URL}{page}/\")\n thread = threading.Thread(target=save_image, args=(url, ))\n thread.start()\n except (ValueError, AttributeError, requests.exceptions.MissingSchema):\n print(f\"WARNING: Invalid comic image source url.\")\n collect_garbage.append(f\"{BASE_URL}{page}\")\n continue\nthread.join()\n</code></pre>\n\n<p>Here you create several threads that download the pages. There are at least two problems with this code:</p>\n\n<ol>\n<li>You create a number of threads, but only join() the last one you created. There is no guarantee that all threads have finished before the last one does. Maintain a list of your threads.</li>\n<li>No rate limit. If you try to download 100 pages, it will try to do all 100 simultaneously. That is not a good idea. Only create a limited amount of threads at a time.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T10:21:18.107",
"Id": "442784",
"Score": "0",
"body": "As far as threading is concerned and in what OP is most interested in, I wonder that they decided to accept the other answer where this one is much more valuable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T11:06:07.867",
"Id": "442789",
"Score": "1",
"body": "@t3chb0t To be fair, the accepted answer explained the issue with #2 better than me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T14:58:21.340",
"Id": "442854",
"Score": "0",
"body": "@t3chb0t: You're right, this answer (and every other here) contains valuable information for OP. It's hard to pick an accepted answer in this case, and the choice must have been somewhat arbitrary."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T08:03:21.973",
"Id": "227301",
"ParentId": "227280",
"Score": "11"
}
},
{
"body": "<blockquote>\n <p>As for the code below, I'd appreciate any feedback, particularly in regards to threading</p>\n</blockquote>\n\n<p>You might want to use a <a href=\"https://docs.python.org/3/library/concurrent.futures.html#threadpoolexecutor\" rel=\"noreferrer\">ThreadPoolExecutor</a> to manage your threads. This approach has two advantages:</p>\n\n<ul>\n<li>The executor can be used as a context manager to make sure all the threads are joined.</li>\n<li>It lets you limit the number of threads in the thread pool.</li>\n</ul>\n\n<p>Example:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> with ThreadPoolExecutor(max_workers=8) as executor:\n for page in reversed(range(latest_comic - pages + 1, latest_comic + 1)):\n print(f\"Fetching page {page} out of {latest_comic}\")\n try:\n url = get_images_from_page(f\"{BASE_URL}{page}/\")\n executor.submit(save_image, url)\n except (ValueError, AttributeError, requests.exceptions.MissingSchema):\n print(f\"WARNING: Invalid comic image source url.\")\n collect_garbage.append(f\"{BASE_URL}{page}\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T08:07:37.127",
"Id": "227303",
"ParentId": "227280",
"Score": "8"
}
},
{
"body": "<h1>Stop hammering XKCD server</h1>\n\n<ul>\n<li><p>You basically wrote a <a href=\"https://en.wikipedia.org/wiki/Denial-of-service_attack\" rel=\"noreferrer\">denial-of-service attack</a>, since you try to connect as fast and as often as possible to the server.</p></li>\n<li><p>By sharing this code on CodeReview, it becomes a <a href=\"https://en.wikipedia.org/wiki/Denial-of-service_attack#Distributed_DoS\" rel=\"noreferrer\">distributed denial-of-service</a>.</p></li>\n</ul>\n\n<p>Just in case it wasn't clear : don't do that.</p>\n\n<p>I suppose the load of XKCD servers is high enough that your code won't make any noticeable difference. Still, the primary goal of your code should be to stay under the radar. Seen from outside, there shouldn't be any difference between launching your script and casually browsing <a href=\"https://xkcd.com/\" rel=\"noreferrer\">https://xkcd.com/</a>.</p>\n\n<p>It isn't just as a courtesy to fellow developers : you might be banned by the remote servers if you send too many requests too fast.</p>\n\n<h1>Solutions</h1>\n\n<ul>\n<li>Wait at least one second before downloading any picture. The desired pause might be defined as <a href=\"https://en.wikipedia.org/wiki/Robots_exclusion_standard#Crawl-delay_directive\" rel=\"noreferrer\"><code>Crawl-delay</code></a> in <a href=\"https://en.wikipedia.org/wiki/Robots_exclusion_standard\" rel=\"noreferrer\"><code>robots.txt</code></a>.</li>\n<li>Remove multi-threading or at least limit the number of threads.</li>\n<li>Don't download a file again if it is already in <code>SAVE_DIRECTORY</code>. You can check if it's here, if its size is larger than <code>0</code> or if it is indeed a PNG file.</li>\n</ul>\n\n<h1>Unrelated note</h1>\n\n<p>You know the id for each comic. You should probably write it in the filename : <code>geologic_time.png</code> could be called <code>2187_geologic_time.png</code> or <code>02187_geologic_time.png</code>.</p>\n\n<p>This way, comics are sorted chronologically inside <code>SAVE_DIRECTORY</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T08:56:19.307",
"Id": "442341",
"Score": "9",
"body": "I was completely unaware of this and had no intention whatsoever to cause or invite others to perform DoS and/or DDoS. I'll remove the threading part from the code. Actually, once I've accidentally written it, I now fully understand what and how dangerous DoS can be. O.o"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T09:19:25.623",
"Id": "442346",
"Score": "27",
"body": "@baduker: It shouldn't be a problem because XKCD is so popular. Calling your code a DDOS is a bit of a stretch but I wanted to make my point very clear. When scraping information, the goal should be to stay under the radar."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T09:24:01.040",
"Id": "442347",
"Score": "3",
"body": "I appreciate your feedback since I'm still rather new to the scraping realm. However, that's a valuable lesson for the future."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T09:26:53.793",
"Id": "442348",
"Score": "11",
"body": "@baduker This is even for the benefits of your crawler, the first defense line against crawlers/bots is the requests speed, I ban bots on my website if they made more than 5 requests in 10 seconds, and I told them that in my `robots.txt` file `Crawl-delay: 2000`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T14:04:55.437",
"Id": "442395",
"Score": "3",
"body": "@Accountantم that sounds like another answer. I'd love to see the code for pinging the robots.txt and querying relevant parts (such as respecting no-robots, crawl delay, etc)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T14:10:50.560",
"Id": "442397",
"Score": "0",
"body": "@Draco18s I'm sorry I don't write Python"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T20:11:15.293",
"Id": "442462",
"Score": "0",
"body": "@Draco18s Well, perhaps while not exactly *respecting* no-robots, it is certainly possible to be nice and slow about it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T21:21:56.000",
"Id": "442470",
"Score": "0",
"body": "@BaardKopperud Oh, definitely. I was just thinking that querying the robots.txt file *for the crawl delay value* would be a good answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T20:34:41.063",
"Id": "442695",
"Score": "0",
"body": "This answer would be improved if it mentions `robots.txt`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T20:59:03.713",
"Id": "442696",
"Score": "0",
"body": "@Yakk: Thanks for the comment. Answer has been edited."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T12:02:17.540",
"Id": "442803",
"Score": "0",
"body": "@Accountantم Do most crawlers comply with `robots.txt`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T12:45:22.223",
"Id": "442813",
"Score": "0",
"body": "@Mast The famous bots like (google, yandex, bing) sure respect the `robots.txt` except the `Crawl-delay` is not supported by GoogleBot and has to be set by google webmasters tools. Most of The unknown bots ignore `robots.txt` and just crawl every URL they find, but there are many unknown bots still do respect `robots.txt`. It is just easier to program a bot without the extra work of complying with the `robots.txt.`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T14:41:49.333",
"Id": "442849",
"Score": "2",
"body": "@Accountantم: TBF, abuse of `robots.txt` to prevent all non-browser-based access to a site makes it so that ignoring `robots.txt` entirely is a fairly decent approximation of most-correct behavior. I don't know if current `wget` is better, but I used to patch `robots.txt` support out of it back in the day just to be able to use it even for *single file* downloads."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T14:45:09.667",
"Id": "442851",
"Score": "2",
"body": "@Accountantم And some malevolent bots only crawl the pages they're not supposed to access (e.g. `Disallow` in `robots.txt`), hoping they'll find a vulnerability or sensitive information."
}
],
"meta_data": {
"CommentCount": "14",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T08:44:50.087",
"Id": "227307",
"ParentId": "227280",
"Score": "89"
}
},
{
"body": "<p>As mentioned in a comment by Thomas, another option is to use XKCD's <a href=\"https://xkcd.com/json.html\" rel=\"noreferrer\">JSON interface</a> rather than scraping HTML:</p>\n\n<pre><code>import requests, time, tempfile, os.path\nfrom shutil import copyfileobj\n\npath = tempfile.mkdtemp()\nprint(path)\nf_name = \"{num:04d}-{safe_title}.{ext}\"\ncurrent_comic = requests.get(\"https://xkcd.com/info.0.json\").json()\n\n# Iterates over numbers from comic 1 to the comic before current\nfor n in range(1,current_comic[\"num\"]):\n comic_req = requests.get(\"https://xkcd.com/{}/info.0.json\".format(n))\n # if status code is 2**\n if comic_req.status_code <= 299:\n comic = comic_req.json()\n comic[\"ext\"] = comic[\"img\"][-3:]\n fn = f_name.format(**comic)\n\n img = requests.get(comic_req.json()[\"img\"], stream=True)\n with open(os.path.join(path, fn), \"wb\") as output:\n copyfileobj(img.raw, output)\n img.close()\n\n print(\"Saved {}\".format(os.path.join(path, fn)))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T01:50:30.773",
"Id": "227367",
"ParentId": "227280",
"Score": "11"
}
},
{
"body": "<p>Not a problem in terms of functionality (seems to have been covered pretty well already) but in terms of clarity/readability:</p>\n\n<h3>Misleading name <code>get_penultimate</code></h3>\n\n<p>It appears to functionally be <code>get_last</code> (<code>get_ultimate</code>, if you will), so there is a clear mismatch between this name and the implemented functionality. The functionality makes sense, so the name appears to be wrong.<br>\nTo explicitly point out the mismatch: <em>penultimate</em> means <em>second to last</em>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T16:42:23.040",
"Id": "227417",
"ParentId": "227280",
"Score": "8"
}
},
{
"body": "<p>Why have <code>main()</code> be a single line calling a single function? Either rename <code>main()</code> to <code>get_xkcd()</code> or just call <code>get_xkcd()</code>.</p>\n\n<p>Also, maybe use <code>BeautifulSoup</code> instead of <code>lxml</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T16:41:13.470",
"Id": "442871",
"Score": "1",
"body": "Without the main() function, the code would get executed even if the script was imported as a module. Also, the function makes it possible to run that code with: import module; module.main(). If the code was just in the if block, it couldn't be run from elsewhere."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T19:51:55.813",
"Id": "442897",
"Score": "4",
"body": "@baduker Tbf, I don't think that Kurt is suggesting that any code should be moved out of a function. To my understanding, their suggestion is rather to either rename `get_xkcd` to `main` or to call `get_xkcd` directly in the `if __name__ == '__main__'` block."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T22:25:45.990",
"Id": "442911",
"Score": "0",
"body": "@HåkanLindqvist That's exactly what I was suggesting. Thanks for the downvote baduker..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-24T21:46:19.687",
"Id": "446693",
"Score": "0",
"body": "Lxml VS beautiful soup, could you elaborate on that on your answer?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T16:17:03.807",
"Id": "227473",
"ParentId": "227280",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "227307",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T18:42:39.497",
"Id": "227280",
"Score": "33",
"Tags": [
"python",
"python-3.x",
"web-scraping"
],
"Title": "Tiny image scraper for xkcd.com"
}
|
227280
|
<p>For simplicity, I have omitted the SubProcedure class which has an execute function, and returns Progress when done, for the real code I simply iterate over these sub procedures and insert the progress into the queue instead of iterating over the progress list.</p>
<p>This code is in logic.py:</p>
<pre class="lang-py prettyprint-override"><code>import random
from collections import namedtuple
import asyncio
Progress = namedtuple('Progress', ('stage', 'progress'))
class JobManager:
_selected_job = None
_latest_stage = None
def __init__(self, loop):
self._message_queue = asyncio.Queue(loop=loop)
def current_job(self):
return self._selected_job
async def start_processing(self, selected_job):
self._selected_job = selected_job
progress_stages = (
Progress('Start processing', 0.1), Progress('Processing...', 0.3),
Progress('Processing some more...', 0.5), Progress("Done", 1)
)
for stage in progress_stages:
await asyncio.sleep(random.randrange(1, 10))
await self._message_queue.put(stage)
await self._message_queue.put(None)
async def get_progress(self):
progress = await self._message_queue.get()
if progress is None:
self._selected_job = None
self._latest_stage = progress
return progress
def latest_stage(self):
return self._latest_stage
</code></pre>
<p>As for the server, I'm using Sanic - a framework similar to flask, but asyncio based. Let's get the uninteresting boilerplate code out of the way first:</p>
<pre class="lang-py prettyprint-override"><code>import logic
from sanic import Sanic
from sanic.response import stream, html, text
from jinja2 import Environment, PackageLoader
import json
import asyncio
env = Environment(loader=PackageLoader('app', 'templates'))
app = Sanic(__name__)
app.static('/static', 'app/static')
def render_template(html_file, **kwargs):
template = env.get_template(html_file)
html_content = template.render(url_for=app.url_for, **kwargs)
return html(html_content)
</code></pre>
<p>Now that we got this out of the way - to the meat:</p>
<p>Currently, the web app supports a single manager, so it's initialized as a singleton, using sanic's event loop </p>
<pre class="lang-py prettyprint-override"><code>
@app.listener('after_server_start')
def create_jobManager(app, loop):
asyncio.set_event_loop(loop)
app.job_manager = logic.JobManager(loop)
</code></pre>
<p>For the GET method, it renders the job selection screen if no job has been selected, and the job monitoring screen if a job is under processing.</p>
<p>In the case that a job had been selected, the POST method had been used, and in this case the job_manager is told to start the long process with</p>
<pre class="lang-py prettyprint-override"><code>asyncio.gather(app.job_manager.start_processing(selected_job))
</code></pre>
<p>Here's the complete code:</p>
<pre class="lang-py prettyprint-override"><code>@app.route("/", methods=('GET', 'POST'))
def home(request):
if request.method == 'GET':
if app.job_manager.current_job():
return render_template('process_and_monitor.html', selection=app.job_manager.current_job())
else:
return render_template('select_job.html', names=logic.get_names())
elif not app.job_manager.current_job():
selected_job = request.form.get('selection', None)
if selected_job:
asyncio.gather(app.job_manager.start_processing(selected_job))
return render_template('process_and_monitor.html', selection=selected_job)
else:
return render_template('process_and_monitor.html', selection=app.job_manager.current_job())
</code></pre>
<p>Now the only thing left is reporting the progress:</p>
<pre class="lang-py prettyprint-override"><code>@app.route("/get_progress", stream=True)
async def get_progress(request):
async def jsonify(response):
if app.job_manager.latest_stage():
await response.write(f"data: {json.dumps(app.job_manager.latest_stage()._asdict())}\n\n")
while True:
progress = await app.job_manager.get_progress()
if progress is None:
return
await response.write(f"data: {json.dumps(progress._asdict())}\n\n")
return stream(jsonify, content_type='text/event-stream')
</code></pre>
<p>On the client side, the update looks like this:</p>
<pre><code>window.onload = function (e) {
var source = new EventSource("get_progress");
source.onmessage = function(event) {
try {
const response = JSON.parse(event.data);
document.getElementById("progress").innerHTML = response.stage;
document.getElementById("progress_bar").style.width = (response.progress * 100) + "%";
if (response.progress == 1) {
document.getElementById("back_button").style.display = "block";
source.close();
}
} catch (error) {
document.getElementById("progress").innerHTML = "<h1 class=\"error\">Failed parsing progress</h1>";
console.log(error);
}
}
}
</code></pre>
<p>I have omitted a status poll which is triggered by the client every second, to make sure the server is ok (since if it stopped working, the page would never get updated, and there would be no way to know something went wrong), but that code is uninteresting.</p>
<p>This is my first web app, my fist use of asyncio, sanic, jinja, and javascript - any suggestion regarding best practices, readability, pointing out stupid things I did, or things that could be done better using other modules or approaches is welcome.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T19:12:12.850",
"Id": "227281",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"asynchronous",
"web-services"
],
"Title": "Web App Starts a long, many staged procedure and gets informed by server side events of progress until completion"
}
|
227281
|
<p>I've written this shell script to place Ant build.xml and build.properties into my project directory. It takes two options, one which ensures the project is set up for JUnit test compilation/running. The other modifies java compile/execution targets for JavaFX. A name for the project node in build.xml can also be given.</p>
<p>It's a glorified copy/paste from starter Ant files into the project directory because I only have options to support two libraries. I want it for future use when I'm creating a wider variety of projects.</p>
<p>It's my first shell script apart from its previous version which used entirely <code>sed</code> commands rather than <code>xmlstarlet</code>.</p>
<h2>createantbuild.sh</h2>
<pre><code>#!/bin/bash
# Creates Ant build.xml and build.properties files for a new project in the
# current directory.
helpText="Creates Ant build.xml and build.properties files for a new project in
the current directory.
Usage: createantbuild.sh [<options>] [<project-name>]
where <options> are
-f, --javafx - include JavaFX modules in compilation and execution tasks
-u, --junit - provide JUnit-related Ant targets: compile-tests and test
--help - print help
If no options are given, the basic Ant targets are provided. They are:
usage (default), init, compile, execute, clean, and generate-javadoc.
If no project name is given, the Ant project will be the same name as the
current directory."
# Process arguments
for ARG in "$@"; do
case $ARG in
"--help")
echo "$helpText"
exit 0
;;
"-f" | "--javafx")
provideJavaFX="set"
echo "Debug: Processed JavaFX option \"$ARG\"."
;;
"-u" | "--junit")
provideJUnit="set"
echo "Debug: Processed JUnit option \"$ARG\"."
;;
"-" | "--")
echo "Error: Expected option, but none given after \"$ARG\"."
exit 1
;;
*)
if [ "${ARG:0:2}" = "--" ]; then
# A long option that's not recognized
echo "Error: Unexpected option \"$ARG\"."
exit 1
elif [ "${ARG:0:1}" = "-" ]; then
# Iterate single character options
for ((a = 1; a < ${#ARG}; a++)); do
singleCharOption=${ARG:a:1}
case $singleCharOption in
"f")
provideJavaFX="set"
echo "Debug: Processed JavaFX option \"-$singleCharOption\"."
;;
"u")
provideJUnit="set"
echo "Debug: Processed JUnit option \"-$singleCharOption\"."
;;
*)
echo "Error: Unexpected option \"-$singleCharOption\"."
exit 1
;;
esac
done
elif [ -z "$projectName" ]; then
# This argument must be the project name
projectName=$ARG
echo "Debug: Set project name to \"$ARG\"."
else
# Any other non-option arguments are in error
echo "Error: Unexpected option \"$ARG\"."
exit 1
fi
;;
esac
done
# Delete existing Ant files
[ -e build.xml ] && rm build.xml
[ -e build.properties ] && rm build.properties
# Copy in starter Ant files
cp ~/bin/build.xml ./build.xml
cp ~/bin/build.properties ./build.properties
# Set project name to same as directory if necessary
if [ ${#projectName} = 0 ] ; then
directoryName=`pwd`
directoryName=${directoryName##*/}
projectName=$directoryName
echo "Debug: Set project name to the current directory, \"${projectName}\"."
fi
# Update value of name attribute in project node
xmlstarlet ed -L -u '/project[@name="unset"]/@name' \
-v "$projectName" build.xml
# Delete JavaFX-related content
if [ "$provideJavaFX" != "set" ]; then
# Delete elements in build.xml
xmlstarlet ed -L -d \
'/project/target[@name="compile"]/javac/compilerarg' build.xml
xmlstarlet ed -L -d '/project/target[@name="execute"]/java/jvmarg' \
build.xml
# Delete lines in build.properties
sed -i 18,21d ./build.properties
fi
# Delete JUnit-related content
if [ "$provideJUnit" != "set" ]; then
# Delete elements in build.xml
xmlstarlet ed -L -d '/project/path[@id="classpath.test"]' build.xml
xmlstarlet ed -L -d \
'/project/target[@name="usage"]/echo[@id="compile-tests"]' \
build.xml
xmlstarlet ed -L -d '/project/target[@name="usage"]/echo[@id="test"]' \
build.xml
xmlstarlet ed -L -d '/project/target[@name="usage"]/echo[@id="blank"]' \
build.xml
# shellcheck disable=SC2016
xmlstarlet ed -L -d \
'/project/target[@name="init"]/mkdir[@dir="${test.src.dir}"]' \
build.xml
xmlstarlet ed -L -d '/project/target[@name="compile-tests"]' build.xml
xmlstarlet ed -L -d '/project/target[@name="test"]' build.xml
# shellcheck disable=SC2016
xmlstarlet ed -L -d \
'/project/target[@name="clean"]/delete[@dir="${test.build.dir}"]' \
build.xml
# Delete lines in build.properties
sed -i 10,17d ./build.properties
fi
exit 0
</code></pre>
<p>These are the the starting Ant files the script acts on after it copies them into the project directory</p>
<h2>build.xml</h2>
<pre><code><?xml version = "1.0"?>
<project name="unset" xmlns:if="ant:if" xmlns:unless="ant:unless"
default="usage">
<property environment="env"/>
<property file="build.properties"/>
<path id="classpath.execute">
<pathelement location="${main.build.dir}"/>
</path>
<path id="classpath.test">
<pathelement location="${lib.dir}/junit4.jar"/>
<pathelement location="${main.build.dir}"/>
</path>
<target name="usage">
<!-- List available targets -->
<echo message="${ant.project.name} targets:"/>
<echo message=""/>
<echo message="usage –> Display this target listing"/>
<echo message="init –> Create project directory structure"/>
<echo message=""/>
<echo message="compile –> Compile application sources"/>
<echo message='execute -Dmain="package.subpackage.ClassName"'/>
<echo message=" –> Execute program at a provided main"/>
<echo message=""/>
<echo id="compile-tests"
message="compile-tests –> Compile unit test sources"/>
<echo id="test"
message="test –> Execute unit tests"/>
<echo id="blank" message=""/>
<echo message="clean –> Clean output directories"/>
<echo message="generate-javadoc –> Generate javadocs"/>
</target>
<target name="init">
<!-- Create project directory structure -->
<mkdir dir="${main.src.dir}"/>
<mkdir dir="${test.src.dir}"/>
</target>
<target name="compile">
<!-- Compile application sources -->
<mkdir dir="${main.build.dir}"/>
<javac srcdir="${main.src.dir}" destdir="${main.build.dir}"
includeantruntime="false" debug="true">
<compilerarg line="--module-path ${path.to.fx}"/>
<compilerarg line="--add-modules javafx.controls"/>
</javac>
</target>
<target name="execute">
<!-- Execute program at a provided main -->
<java if:set="main" fork="true" classname="${main}">
<jvmarg line="--module-path ${path.to.fx}"/>
<jvmarg line="--add-modules javafx.controls"/>
</java>
<echo unless:set="main" message='Error: Execute requires the program entry point as a parameter.'/>
<echo unless:set="main" message='E.g. ant execute -Dmain="package.subpackage.ClassName"'/>
</target>
<target name="compile-tests" depends="compile">
<!-- Compile unit test sources -->
<mkdir dir="${test.build.dir}"/>
<javac srcdir="${test.src.dir}" destdir="${test.build.dir}"
includeantruntime="false" debug="true">
<classpath refid="classpath.test"/>
</javac>
</target>
<target name="test" depends="compile-tests">
<!-- Execute unit tests -->
<junit printsummary="yes" haltonfailure="yes" haltonerror="yes">
<classpath>
<path refid="classpath.test"/>
<pathelement location="${test.build.dir}"/>
</classpath>
<formatter type="plain" usefile="false"/>
<batchtest>
<fileset dir="${test.src.dir}" includes="**/*Test.java"/>
</batchtest>
</junit>
</target>
<target name="clean">
<!-- Clean output directories -->
<delete dir="${main.build.dir}"/>
<delete dir="${test.build.dir}"/>
</target>
<!--Generate documentation-->
<target name="generate-javadoc">
<javadoc packagenames="*" sourcepath="${main.src.dir}"
destdir="doc" version="true">
</javadoc>
</target>
</project>
</code></pre>
<h2>build.properties</h2>
<pre><code>### Common ###
# Directory for main program sources
main.src.dir = src
# Root output directory for built class files
build.dir = build
# Output directory for built application classes
main.build.dir = ${build.dir}/classes
# Directory for generated documentation
doc.dir = doc
### JUnit ###
# Directory for test java sources
test.src.dir = test
# Output directory for built test classes
test.build.dir = ${build.dir}/test-classes
# Directory where JUnit library is located
lib.dir = /usr/share/java
### JavaFX ###
# Path to JavaFX library
path.to.fx = ${env.PATH_TO_FX}
</code></pre>
<h1>Output</h1>
<p>The bulk of the shell script works with arguments so I included test runs to confirm they are processed and bad arguments are acknowledged.</p>
<pre><code>~/test$ cab
Debug: Set project name to the current directory, "test".
~/test$ cab ""
Debug: Set project name to "".
Debug: Set project name to the current directory, "test".
~/test$ cab myproject
Debug: Set project name to "myproject".
~/test$ cab myproject --
Debug: Set project name to "myproject".
Error: Expected option, but none given after "--".
~/test$ cab --javafx --junit myproject
Debug: Processed JavaFX option "--javafx".
Debug: Processed JUnit option "--junit".
Debug: Set project name to "myproject".
~/test$ cab -f myproject
Debug: Processed JavaFX option "-f".
Debug: Set project name to "myproject".
~/test$ cab -f -u
Debug: Processed JavaFX option "-f".
Debug: Processed JUnit option "-u".
Debug: Set project name to the current directory, "test".
~/test$ cab -fu
Debug: Processed JavaFX option "-f".
Debug: Processed JUnit option "-u".
Debug: Set project name to the current directory, "test".
~/test$ cab myproject whoops
Debug: Set project name to "myproject".
Error: Unexpected option "whoops".
~/test$ cab -b
Error: Unexpected option "-b".
~/test$ cab --what
Error: Unexpected option "--what".
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T22:30:27.247",
"Id": "442299",
"Score": "1",
"body": "I'm honestly not quite sure why you're creating ant builds for new projects... As it stands, maven and gradle are more widespread (and IMO easier to use) alternatives that should support all your usecases"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T07:03:58.887",
"Id": "442323",
"Score": "0",
"body": "I'm only using/learning Java at the moment. I figured it would be easier to find info relating to my immediate issues if I focused on a Java-centric tool. It has been successful as I have been able to rapidly find solutions to issues with the documentation alone. I will use a more general tool surely as I move to C++ and when I begin working with a variety of open source projects."
}
] |
[
{
"body": "<h2>Commandline Syntax</h2>\n\n<p>You seem to be using the POSIX and <a href=\"https://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html\" rel=\"nofollow noreferrer\">GNU</a> command line syntax, allowing both short as long options:</p>\n\n<blockquote>\n<pre><code>\"-f\" | \"--javafx\"\n</code></pre>\n</blockquote>\n\n<p>But the most important one \"help\" is only accessible through:</p>\n\n<blockquote>\n<pre><code> \"--help\"\n</code></pre>\n</blockquote>\n\n<p>I would be consistent and use:</p>\n\n<pre><code> \"-h\" | \"--help\" | \"-?\"\n</code></pre>\n\n<p>Also note that the question mark is a universal identifier for the <em>help</em> command.</p>\n\n<p>You may also want to add a disclaimer or about info:</p>\n\n<pre><code> \"--about\" | \"-!\" \n</code></pre>\n\n<p>And maybe some version info:</p>\n\n<pre><code> \"--version\" | \"-v\" \n</code></pre>\n\n<p>Keep in mind that your empty option check treats the operand delimiter <code>--</code> as an invalid option. While in many systems, this means all remaining arguments are to be treated as operands, even if prefixed with <code>-</code> or <code>--</code>.</p>\n\n<blockquote>\n<pre><code>\"-\" | \"--\"\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T00:50:19.260",
"Id": "442483",
"Score": "1",
"body": "I appreciate that manual resource. I wasn't familiar with it nor some of these common option short forms. I was mimicking the options of `rm` on my system which only lists the long forms of --help and --version, but I now know secretly implements -h. The empty -- is good to know. I can see why it exists, and I'll keep it in mind."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T19:44:25.797",
"Id": "227284",
"ParentId": "227282",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "227284",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T19:34:14.717",
"Id": "227282",
"Score": "3",
"Tags": [
"beginner",
"shell",
"ant"
],
"Title": "Shell script to set up Ant targets and properties for a new project"
}
|
227282
|
<p>I'm writing a bash script to that picks up a user password from an environment variable, hashes this, and inserts the results into a postgres database.</p>
<p>What I have works and looks <em>fairly</em> readable to me but I'm no expert on bash. Are there better conventions I could be following for what I'm doing?</p>
<pre><code>#!/bin/bash
HASHED=$(echo -n $GUAC_PASSWORD | sha256sum | head -c 64)
PGPASSWORD=$POSTGRES_PASSWORD psql -U postgres << EOF
INSERT INTO guacamole_entity (name, type) VALUES ('guacadmin', 'USER');
INSERT INTO guacamole_user (entity_id, password_hash, password_salt, password_date)
SELECT
entity_id,
decode('${HASHED}', 'hex'),
null,
CURRENT_TIMESTAMP
FROM guacamole_entity WHERE name = 'guacadmin' AND guacamole_entity.type = 'USER';
EOF
</code></pre>
<p>Edit: I thought up a way to do it without sed feels neater to me.</p>
<hr>
<p>Update: Thanks @OhMyGoodness and @TobySpeight! The conversations about passwords being in the clear got me twitchy enough to use <a href="https://docs.docker.com/v17.12/engine/swarm/secrets/" rel="nofollow noreferrer">docker secrets</a>. So now I have the passwords in a file, not environment variables. <code>PGPASSWORD</code> isn't actually needed as</p>
<blockquote>
<p>The PostgreSQL image sets up trust authentication locally so you may notice a password is not required when connecting from localhost</p>
</blockquote>
<p>The finalized script looks like this now:</p>
<pre><code>#!/bin/bash
hashed=$(tr -d '\n' < /run/secrets/guac_password | sha256sum | tr -dc a-f0-9)
psql -U postgres << EOF
INSERT INTO guacamole_entity (name, type) VALUES ('guacadmin', 'USER');
INSERT INTO guacamole_user (entity_id, password_hash, password_salt, password_date)
SELECT
entity_id,
decode('${hashed}', 'hex'),
null,
CURRENT_TIMESTAMP
FROM guacamole_entity WHERE name = 'guacadmin' AND guacamole_entity.type = 'USER';
EOF
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T21:45:40.440",
"Id": "443181",
"Score": "0",
"body": "I'm not sure what the protocol is - should I be accepting an answer? Multiple people can help with code review so does an accepted answer make sense?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T06:32:49.820",
"Id": "443209",
"Score": "1",
"body": "There is impedance mismatch between the SE platform's workings and the process of reviewing code, as you've observed. It's customary to accept an answer when one is clearly best. It's fine to not when multiple people made contributions, like here. Knowing that my answer was helpful is more important to me than the points."
}
] |
[
{
"body": "<p>If <code>GUAC_PASSWORD</code> is a string like <code>-e foo</code> or <code>/etc/*</code>, that's going to create problems. </p>\n\n<p>Quote the input and avoid <code>echo</code> altogether. While you're at it, whitelist the checksum output, making <code>head</code> redundant:</p>\n\n<pre><code>HASHED=$( tr -d '\\n' <<<\"$GUAC_PASSWORD\" | sha256sum | tr -dc a-f0-9 )\n</code></pre>\n\n<p><em>edit: suppress newline added by <code><<<</code></em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T01:07:51.787",
"Id": "442302",
"Score": "0",
"body": "Is this to avoid an injection attack?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T06:01:51.777",
"Id": "442320",
"Score": "0",
"body": "it avoids any number of surprises. We're not worried about a future version of `sha256sum` having `'` in its output or error messages. And we're not quoting the assignment: the whitelist makes that unnecessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T09:37:46.053",
"Id": "442351",
"Score": "0",
"body": "You'll want to deal with the newline that `<<<` adds to the string. Otherwise, this is great advice - it avoids exposing the plaintext password in command arguments, for one thing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T13:44:35.870",
"Id": "442386",
"Score": "0",
"body": "@TobySpeight good catch, I'll copy your `tr` approach there"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T00:46:10.843",
"Id": "227289",
"ParentId": "227285",
"Score": "6"
}
},
{
"body": "<p>Try to avoid using <code>echo</code> in your bash script; use <code>printf</code> instead (why? <a href=\"//unix.stackexchange.com/q/65803\">look here</a>):</p>\n\n<pre><code>hashed=$(printf \"%s\" \"$GUAC_PASSWORD\" | sha256sum | cut -f1 -d\\ )\n</code></pre>\n\n<p>Note also the uppercase variable in bash script are for environment variables; use lowercase ones (<a href=\"//unix.stackexchange.com/q/42847\">ref</a>).</p>\n\n<p>At last, do <strong>not</strong> use <code><<<</code> in your case because it adds a newline and won't output the same hash as <code>echo -n</code>!</p>\n\n<p>Try this:</p>\n\n<pre><code>echo -n \"Hello World\" | sha256sum \na591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e -\nsha256sum <<< \"Hello World\"\nd2a84f4b8b650937ec8f73cd8be2c74add5a911ba64df27458ed8229da804a26 -\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T07:28:41.657",
"Id": "227298",
"ParentId": "227285",
"Score": "3"
}
},
{
"body": "<p>There's nothing here that requires Bash rather than standard (POSIX) shell, so we can use</p>\n\n<pre><code>#!/bin/sh\n</code></pre>\n\n<p>However, don't do that, because we can use a Bash feature to avoid exposing the plaintext password to other users (see below).</p>\n\n<p>I recommend making the shell exit if we attempt to expand any unset variables, or if any of the programs we run exits with an error status:</p>\n\n<pre><code>set -eu -o pipefail\n</code></pre>\n\n<p>Let's look at this line:</p>\n\n<blockquote>\n<pre><code>HASHED=$(echo -n $GUAC_PASSWORD | sha256sum | head -c 64)\n</code></pre>\n</blockquote>\n\n<p>Firstly, use uppercase names only for well-known environment variables to be shared between processes; we should prefer lower-case for our own variables.</p>\n\n<p>Avoid non-standard <code>echo -n</code> and quote variable expansions used as command arguments.</p>\n\n<p>Don't include private information as a command argument. Any process can see command arguments (e.g. using <code>ps</code> or <code>top</code>), so that is a privacy violation right there. We can avoid that by using a Bash here-string, using <code><<<</code> redirection, but we need to be aware that this will add a newline to the stream. We could use <code>tr</code> to remove that:</p>\n\n<pre><code>hashed=$(tr -d '\\n' <<<\"$GUAC_PASSWORD\" | sha256sum | cut -d' ' -f1)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T09:49:38.113",
"Id": "227310",
"ParentId": "227285",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T20:56:20.967",
"Id": "227285",
"Score": "7",
"Tags": [
"bash",
"shell"
],
"Title": "Inserting command output into multiline string"
}
|
227285
|
<p>I am new to JavaScript. The below code works on array y from tree values of 1 to 5, but I want to extend it to check trees value of 100. </p>
<p>array y is of the type [{key:value, key:value}, {key:value, key:value}]</p>
<p>I was wondering if I can I implement a loop within the repeating portion of the body of the code?</p>
<p>Thanks in advance for anyone who may know how to do this.</p>
<p>Thank you</p>
<pre><code>z = y.length
for (let i = 0; i < z; i++)
y[i].coupons = 0;
for (let i = 49; i < (z - 1); i++) {
cval = y[i].trees
if (y[i].trees > 0 && y[i].coconuts > 0 && (i + cval) < (z-1)) {
if (y[i].trees === 1 ) {
if (y[i].lentils > y[i].coconuts
&& y[i + 1].apples > y[i].coconuts && y[i + 1].onions < y[i].coconuts && y[i+1].horses < y[i+1].maple) {
y[i].coupons = y[i].coconuts
}
} else if (y[i].trees === 2) {
if (y[i].lentils > y[i].coconuts
&& y[i + 1].apples > y[i].coconuts && y[i + 1].onions < y[i].coconuts && y[i + 1].horses < y[i + 1].maple
&& y[i + 2].horses < y[i].coconuts) {
y[i].coupons = y[i].coconuts
} else if (Math.min(y[i].lentils, y[i + 1].lentils) > y[i].coconuts
&& y[i + 2].apples > y[i].coconuts && y[i + 2].onions < y[i].coconuts && y[i + 2].horses < y[i + 2].maple) {
y[i].coupons = y[i].coconuts
}
} else if (y[i].trees === 3) {
if (y[i].lentils > y[i].coconuts
&& y[i + 1].apples > y[i].coconuts && y[i + 1].onions < y[i].coconuts && y[i + 1].horses < y[i + 1].maple
&& Math.max(y[i + 2].horses, y[i + 3].horses) < y[i].coconuts) {
y[i].coupons = y[i].coconuts
} else if (Math.min(y[i].lentils, y[i + 1].lentils) > y[i].coconuts
&& y[i + 2].apples > y[i].coconuts && y[i + 2].onions < y[i].coconuts && y[i + 2].horses < y[i + 2].maple
&& y[i + 3].horses < y[i].coconuts) {
y[i].coupons = y[i].coconuts
} else if (Math.min(y[i].lentils, y[i + 1].lentils, y[i + 2].lentils) > y[i].coconuts
&& y[i + 3].apples > y[i].coconuts && y[i + 3].onions < y[i].coconuts && y[i + 3].horses < y[i + 3].maple) {
y[i].coupons = y[i].coconuts
}
} else if (y[i].trees === 4) {
if (y[i].lentils > y[i].coconuts
&& y[i + 1].apples > y[i].coconuts && y[i + 1].onions < y[i].coconuts && y[i + 1].horses < y[i + 1].maple
&& Math.max(y[i + 2].horses, y[i + 3].horses, y[i + 4].horses) < y[i].coconuts) {
y[i].coupons = y[i].coconuts
} else if (Math.min(y[i].lentils, y[i + 1].lentils) > y[i].coconuts
&& y[i + 2].apples > y[i].coconuts && y[i + 2].onions < y[i].coconuts && y[i + 2].horses < y[i + 2].maple
&& Math.max(y[i + 3].horses, y[i + 4].horses) < y[i].coconuts) {
y[i].coupons = y[i].coconuts
} else if (Math.min(y[i].lentils, y[i + 1].lentils, y[i + 2].lentils) > y[i].coconuts
&& y[i + 3].apples > y[i].coconuts && y[i + 3].onions < y[i].coconuts && y[i + 3].horses < y[i + 3].maple
&& y[i + 4].horses < y[i].coconuts) {
y[i].coupons = y[i].coconuts
} else if (Math.min(y[i].lentils, y[i + 1].lentils, y[i + 2].lentils, y[i + 3].lentils) > y[i].coconuts
&& y[i + 4].apples > y[i].coconuts && y[i + 4].onions < y[i].coconuts && y[i + 4].horses < y[i + 4].maple) {
y[i].coupons = y[i].coconuts
}
} else if (y[i].trees === 5) {
if (y[i].lentils > y[i].coconuts
&& y[i + 1].apples > y[i].coconuts && y[i + 1].onions < y[i].coconuts && y[i + 1].horses < y[i + 1].maple
&& Math.max(y[i + 2].horses, y[i + 3].horses, [i + 4].horses, y[i + 5].horses) < y[i].coconuts) {
y[i].coupons = y[i].coconuts
} else if (Math.min(y[i].lentils, y[i + 1].lentils) > y[i].coconuts
&& y[i + 2].apples > y[i].coconuts && y[i + 2].onions < y[i].coconuts && y[i + 2].horses < y[i + 2].maple
&& Math.max(y[i + 3].horses, y[i + 4].horses, y[i + 5].horses) < y[i].coconuts) {
y[i].coupons = y[i].coconuts
} else if (Math.min(y[i].lentils, y[i + 1].lentils, y[i + 2].lentils) > y[i].coconuts
&& y[i + 3].apples > y[i].coconuts && y[i + 3].onions < y[i].coconuts && y[i + 3].horses < y[i + 3].maple
&& Math.max(y[i + 4].horses, y[i + 5].horses) < y[i].coconuts) {
y[i].coupons = y[i].coconuts
} else if (Math.min(y[i].lentils, y[i + 1].lentils, y[i + 2].lentils, y[i + 3].lentils) > y[i].coconuts
&& y[i + 4].apples > y[i].coconuts && y[i + 4].onions < y[i].coconuts && y[i + 4].horses < y[i + 4].maple
&& y[i + 4].horses < y[i].coconuts) {
y[i].coupons = y[i].coconuts
} else if (Math.min(y[i].lentils, y[i + 1].lentils, y[i + 2].lentils, y[i + 3].lentils, y[i + 4].lentils) > y[i].coconuts
&& y[i + 5].apples > y[i].coconuts && y[i + 5].onions < y[i].coconuts && y[i + 5].horses < y[i + 5].maple) {
y[i].coupons = y[i].coconuts
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T01:12:57.180",
"Id": "442303",
"Score": "0",
"body": "*The below code works on array y from tree values of 1 to 5, but I want to extend it to check trees value of 100*, so is this working as intended or not?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T01:18:36.063",
"Id": "442304",
"Score": "0",
"body": "Hi, it works fine yes. But I can't write it out to trees === 100 because it would take a long time and I may introduce errors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T01:31:49.133",
"Id": "442305",
"Score": "0",
"body": "Hi, what problem is the code solving? It's not clear to me what the meaning is of `y[i + 1]`, `y[i + 2]`, etc…"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T01:33:39.530",
"Id": "442306",
"Score": "0",
"body": "It might also help to provide an example of `y` when it has 5 trees."
}
] |
[
{
"body": "<p>A few suggestions to improve the readability and maintenance of your code:</p>\n\n<ul>\n<li>Use meaningful variable names. <code>i</code> is well understood, but for all the others give them longer names that describe what they are.</li>\n<li>Indent your code consistently. Everything inside that second <code>for</code> loop needs another level of indentation. You'll know it's right when the braces at the end of the code look elegant.</li>\n<li>Use braces around the body of loops and conditionals, even when it's not required.</li>\n<li>Put a semicolon after each statement, even when it's not required.</li>\n<li>Add line comments to describe what sections of code do.</li>\n</ul>\n\n<p>For example if <code>y</code> is a couponBook (I'm totally guessing) then start by renaming <code>y</code> to <code>couponBook</code> wherever it's declared and then after applying these suggestions the first few lines could be be:</p>\n\n<pre><code>const couponCount = couponBook.length;\n\n// reset coupons\nfor (let i = 0; i < couponCount; i++) {\n couponBook[i].coupons = 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T02:10:49.893",
"Id": "227291",
"ParentId": "227290",
"Score": "2"
}
},
{
"body": "<h2>DRY code with functions</h2>\n\n<p>Oh dear your code is completely un-maintainable, a bug waiting to happen.</p>\n\n<p>When ever you find yourself writing code that is the same repeated over and over, with only some minor differences, create a function and pass it the differences as arguments. It will make the code easier to read, and maintain, and save you a lot of work.</p>\n\n<h2>The reduction</h2>\n\n<p>The following is how I took your code and reduced it by small steps. Some are only to help clarify the patterns in my head.</p>\n\n<h3>Reduce the noise</h3>\n\n<p>So first lets create some alias names as its a sea text to me</p>\n\n<pre><code>const L = \"lentils\";\nconst C = \"coconuts\";\nconst O = \"onions\";\nconst H = \"horses\";\nconst M = \"maple\";\nconst A = \"apples\";\n</code></pre>\n\n<p>We can then use bracket notation to locate each item</p>\n\n<pre><code>y[i][L] \n// is the same as\ny[i].lentils\n</code></pre>\n\n<h3>Align the logic</h3>\n\n<p>Now looking at the if statements you are switching between < and > a lot.</p>\n\n<pre><code>if (y[i].trees === 1 ) {\n if (y[i].lentils > y[i].coconuts && \n y[i + 1].apples > y[i].coconuts && \n y[i + 1].onions < y[i].coconuts && \n y[i+1].horses < y[i+1].maple) {\n y[i].coupons = y[i].coconuts\n }\n} else //... and so on\n</code></pre>\n\n<p>In this case to help design better source code use only > and swap the references if there is a <. Thus the above becomes</p>\n\n<pre><code>if (y[i].trees === 1 ) {\n if (y[i].lentils > y[i].coconuts && \n y[i+1].apples > y[i].coconuts && \n y[i].coconuts > y[i+1].onions && \n y[i+1].maple > y[i+1].horses ) {\n y[i].coupons = y[i].coconuts;\n }\n} else //... and so on\n</code></pre>\n\n<h3>Start from the smallest logic unit</h3>\n\n<p>and work up.</p>\n\n<p>This is how to start building the functions that will help reduce overall source code size. First a function called <code>greater</code> that will do a single left side greater that right side</p>\n\n<pre><code>const greater = (name1, name2, i1 = 0, i2 = 0) => y[i + i1][name1] > y[i +i2][name2];\n</code></pre>\n\n<p>How we apply that function in a statement</p>\n\n<pre><code>if (y[i].lentils > y[i].coconuts && \n y[i+1].apples > y[i].coconuts && \n y[i].coconuts > y[i+1].onions && \n y[i+1].maple > y[i+1].horses )\n\n// becomes \nif (\n greater(L,C) && \n greater(A, C, 1) && \n greater(C, O, 0, 1) && \n greater(M, H, 1, 1) ) {\n</code></pre>\n\n<h3>Special cases to separate functions</h3>\n\n<p>A function to handle min lentils via a loop so you need not have to do <code>y[i] ... y[i + 1]</code> and so on. Also the min is not really needed, rather if min lentils greater than coconuts.</p>\n\n<pre><code>const minLentils = (count, min = Infinity) => {\n while (count--) { Math.min(y[i + count].lentils, min) }\n return min > y[i].coconuts;\n}\n\n// Thus \nMath.min(y[i].lentils, y[i + 1].lentils, y[i + 2].lentils) > y[i].coconuts;\n\n// becomes \nminLentils(3);\n</code></pre>\n\n<p>And same for <code>maxHorses</code> but include start offset </p>\n\n<pre><code>const maxHorses = (count, offset, max = -Infinity) => {\n if (count > 1) {\n while (count--) { Math.max(y[i + offset + count].horses, max) }\n return max < y[i].coconuts;\n }\n return true; \n}\n\n// thus \nMath.max(y[i + 2].horses, y[i + 3].horses, y[i + 4].horses) < y[i].coconuts\n\n// becomes\nmaxHorses(3, 2);\n</code></pre>\n\n<h3>What action to perform</h3>\n\n<p>If any of the statements are true, assign coconuts to coupons within the if statements. For now create a flag (semaphore) that if true will, on the last line inside the loop, move coconuts to coupons</p>\n\n<pre><code>let getCoupons = false;\n\n ... if statements ...\n\nif (getCoupons) { y[i].coupons = y[i].coconuts } \n</code></pre>\n\n<h3>Find a pattern</h3>\n\n<p>We need to find a pattern to the logic so we can further reduce to functions</p>\n\n<p>For a more complex statement, align the greater side to the left</p>\n\n<pre><code>if( Math.min(y[i].lentils, y[i + 1].lentils, y[i + 2].lentils) > y[i].coconuts && \n y[i + 3].apples > y[i].coconuts && \n y[i].coconuts > y[i + 3].onions && \n y[i + 3].maple > y[i + 3].horses && \n Math.max(y[i + 4].horses, y[i + 5].horses) < y[i].coconuts) { \n\n// replace Math.min and Math.max functions with the new min max functions\n// and add the greater function for the rest\n\n\nif( minLentils(3) && \n greater(A, C, 3) && \n greater(C, O, 0, 3) && \n greater(M, H, 3, 3) && \n maxHorses(2, 4) { \n</code></pre>\n\n<p>Still not seeing the pattern but almost there. </p>\n\n<h3>Look for similarities</h3>\n\n<p>Calling the function <code>greater(L, C)</code> is the same as calling <code>minLentils(1)</code> and <code>greater(H, C, 3)</code> is the same as <code>maxHorses(1, 3)</code></p>\n\n<p>So rather than manually call each function we can create an array of arrays, each sub array contains the arguments for each call to <code>greater</code>, <code>minLentils</code>, and <code>maxHorses</code></p>\n\n<pre><code>// the line\nif (minLentils(3) && greater(A, C, 3) && greater(C, O, 0, 3) && greater(M, H, 3, 3) && maxHorses(2, 4)) { \n\n// has the set of arguments as an array\n[[3], [A, C, 3], [C, O, 0, 3], [M, H, 3, 3], [2, 4]];\n</code></pre>\n\n<p>Create a function that takes the above array that uses the first sub array to call<code>minLentils</code>, last sub array calls <code>maxHorses</code> and the rest call <code>greater</code></p>\n\n<pre><code>const pass = (...args) => {\n if (! maxHorses(...args.pop()) && minLentils(...args[0])) { return false }\n while (args.length > 1) { \n if (! greater(...args.pop()) ) { return false }\n }\n return true;\n}\n\n// the line\nif (minLentils(3) && greater(A, C, 3) && greater(C, O, 0, 3) && greater(M, H, 3, 3) && maxHorses(2, 4)) { \n\n// now becomes \nif (pass([[3], [A, C, 3], [C, O, 0, 3], [M, H, 3, 3], [2, 4]]) { getCoupons = true }\n</code></pre>\n\n<h3>Finding the logic pattern</h3>\n\n<p>Now we have a shorter way of writing the statements using the arrays and functions, lets convert a set of statements into the new declarative code</p>\n\n<pre><code>} else if (y[i].trees === 5) {\n if (y[i].lentils > y[i].coconuts &&\n y[i + 1].apples > y[i].coconuts && \n y[i + 1].onions < y[i].coconuts && \n y[i + 1].horses < y[i + 1].maple &&\n Math.max(y[i + 2].horses, y[i + 3].horses, [i + 4].horses, y[i + 5].horses) < y[i].coconuts) {\n y[i].coupons = y[i].coconuts\n } else if (\n Math.min(y[i].lentils, y[i + 1].lentils) > y[i].coconuts &&\n y[i + 2].apples > y[i].coconuts && \n y[i + 2].onions < y[i].coconuts && \n y[i + 2].horses < y[i + 2].maple &&\n Math.max(y[i + 3].horses, y[i + 4].horses, y[i + 5].horses) < y[i].coconuts) {\n y[i].coupons = y[i].coconuts\n } else if (\n Math.min(y[i].lentils, y[i + 1].lentils, y[i + 2].lentils) > y[i].coconuts && \n y[i + 3].apples > y[i].coconuts && \n y[i + 3].onions < y[i].coconuts && \n y[i + 3].horses < y[i + 3].maple && \n Math.max(y[i + 4].horses, y[i + 5].horses) < y[i].coconuts) {\n y[i].coupons = y[i].coconuts\n } else if (\n Math.min(y[i].lentils, y[i + 1].lentils, y[i + 2].lentils, y[i + 3].lentils) > y[i].coconuts &&\n y[i + 4].apples > y[i].coconuts && \n y[i + 4].onions < y[i].coconuts && \n y[i + 4].horses < y[i + 4].maple && \n y[i + 4].horses < y[i].coconuts) {\n y[i].coupons = y[i].coconuts \n } else if (Math.min(y[i].lentils, y[i + 1].lentils, y[i + 2].lentils, y[i + 3].lentils, y[i + 4].lentils) > y[i].coconuts && \n y[i + 5].apples > y[i].coconuts && \n y[i + 5].onions < y[i].coconuts && \n y[i + 5].horses < y[i + 5].maple) {\n y[i].coupons = y[i].coconuts\n }\n</code></pre>\n\n<p>becomes </p>\n\n<pre><code> if(pass([[1], [A, C, 1], [C, O, 0, 1], [M, H, 1, 1], [4, 2]]) ||\n pass([[2], [A, C, 2], [C, O, 0, 2], [M, H, 2, 2], [3, 3]]) ||\n pass([[3], [A, C, 3], [C, O, 0, 3], [M, H, 3, 3], [2, 4]]) || \n pass([[4], [A, C, 4], [C, O, 0, 4], [M, H, 4, 4], [1, 4]]) ||\n pass([[5], [A, C, 5], [C, O, 0, 5], [M, H, 5, 5], [0]]) ) { getCoupons = true }\n</code></pre>\n\n<p>We finally can see the pattern (That's me, you likely know the pattern very well)</p>\n\n<h3>Implement the common pattern</h3>\n\n<p>A loop can be used to create the arrays to test. That loop uses the value in y[i].trees as the count. If a function pass return true then we are done and can assign coconuts coupons</p>\n\n<pre><code>const testTree = (count) => {\n var j = 0;\n while(i < count) {\n if (pass([[j], [A, C, j], [C, O, 0, j], [M, H, j, j], [count - 1 - j, j + 1]])) {\n y[i].coupons = y[i].coconuts;\n break;\n }\n }\n}\n</code></pre>\n\n<h2>The DRY result</h2>\n\n<p>Gather all the functions. Wrap them in closure, add some extra args to the function <code>testTree</code> to the to allow the functions to see the index <code>i</code>, and the array <code>y</code></p>\n\n<p>Remove the aliases and use the names as strings.</p>\n\n<p>The following snippet is a full replacement of your code and able to handle any value of <code>y[i].tree</code> if the pattern found continues.</p>\n\n<pre><code>const testTree = (()=> {\n var y, idx;\n const greater = (name1, name2, i1 = 0, i2 = 0) => y[idx + i1][name1] > y[idx +i2][name2];\n const minLentils = (count, min = Infinity) => {\n while (count--) { Math.min(y[idx + count].lentils, min) }\n return min > y[idx].coconuts;\n }\n const maxHorses = (count, offset, max = -Infinity) => {\n if (count > 1) {\n while (count--) { Math.max(y[idx + offset + count].horses, max) }\n return max < y[idx].coconuts;\n }\n return true;\n }\n const pass = (...args) => {\n if (! maxHorses(...args.pop()) && minLentils(...args[0])) { return false }\n while (args.length > 1) { \n if (! greater(...args.pop()) ) { return false }\n }\n return true;\n } \n return (yy, i) => {\n var j = 0; \n const count = yy[i].tree;\n y = yy; \n idx = i;\n while (j < count) {\n if (pass(...[\n [j], [\"apples\", \"coconuts\", j], [\"coconuts\", \"onions\", 0, j], [\"maple\", \"horses\", j, j], \n [count - 1 - j, j + 1]\n ])) {\n y[i].coupons = y[i].coconuts;\n break;\n }\n }\n };\n})();\n\nfor (const item of y) { item.coupon = 0 }\nfor (let i = 49; i < y.length - 1; i++) {\n const trees = y[i].trees;\n if (trees > 0 && y[i].coconuts > 0 && (i + trees) < y.length - 1) { testTree(y, i) }\n}\n</code></pre>\n\n<h2>NOTE</h2>\n\n<ul>\n<li><p>As there was no data to test on the is likely many typos in the code. It is aas an example only</p></li>\n<li><p>There where some odd values in your example that I assumed where typos on your part. If they were not typos or the pattern I found not the pattern at higher counts you will have to continue the process of reduction via functions.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T00:10:09.340",
"Id": "227365",
"ParentId": "227290",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T01:09:37.010",
"Id": "227290",
"Score": "2",
"Tags": [
"javascript",
"beginner"
],
"Title": "This code searches for an object which meets mathematical Max, Min, or less than/greater than criteria at certain counter i points"
}
|
227290
|
<p>I'm feeling uneasy with this service method that I wrote:</p>
<pre><code> @Override
public Optional<Set<TenantDTO>> getAllTenantsOfUsers(Set<Long> usersIds) {
return Optional.ofNullable(usersIds)
.map((ids) -> tenantRepository.findAll(QTenant.tenant.users.any().id.in(usersIds)))
.map((it) -> StreamSupport.stream(it.spliterator(), false))
.map((strm) -> strm.map((tenant) -> tenantMapper.toDto(tenant)).collect(Collectors.toSet()));
}
</code></pre>
<p>My <code>tenantRepository.findAll</code> returns an <code>iterable</code> of <code>Tenant</code> entity</p>
<p>Is this the better approach to get all performance, with good code?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T03:36:21.857",
"Id": "442310",
"Score": "3",
"body": "Why is `userIds` nullable? Passing in an empty set, instead of `null`, would be equivalent, and cleaner, and remove the `Optional.ofNullable()`."
}
] |
[
{
"body": "<p>Both optional collection and a collection of optionals are anti-patterns. There is no scenario where returning <code>Optional<Set<X>></code> or <code>Set<Optional<X>></code> is preferable to returning a <code>Set<X></code> that can be empty.</p>\n\n<p>As @AJNeufeld mentions, a guard condition is a good way to start. In your case. If incoming <code>usersIds</code> are null then return an empty set.</p>\n\n<pre><code>public Set<TenantDTO> getAllTenantsOfUsers(Set<Long> usersIds) {\n if (usersIds == null) {\n return Collections.emptySet();\n }\n // ...\n}\n</code></pre>\n\n<p>Its really confusing when you mix Optional.map and Stream.map in a single call chain. But since the <code>usersIds == null</code> case is handled, you don't need <code>Optional.ofNullable</code> anymore. You can simplify this to just operations over your ids and Tenants.</p>\n\n<p>Something like this:</p>\n\n<pre><code>public Set<TenantDTO> getAllTenantsOfUsers(Set<Long> usersIds) {\n if (usersIds == null) {\n return Collections.emptySet();\n }\n return tenantRepository\n .findAll(QTenant.tenant.users.any().id.in(usersIds))\n .stream()\n .map((tenant) -> tenantMapper.toDto(tenant))\n .collect(Collectors.toSet());\n}\n</code></pre>\n\n<p>Now that <code>getAllTenantsOfUsers</code> returns Set(possibly empty Set), all clients of this code can use it directly instead of caring about handling and unwrapping optional.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T16:22:15.357",
"Id": "442629",
"Score": "0",
"body": "the findAll return an iterable so there is no stream, I m ok with the anti-patern you r right and I would remove it,"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T14:41:18.567",
"Id": "227403",
"ParentId": "227293",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T02:53:14.590",
"Id": "227293",
"Score": "1",
"Tags": [
"java",
"performance",
"stream",
"optional"
],
"Title": "Is there better alternative to making an optional set of elements from iterable in java?"
}
|
227293
|
<p>Earlier I did post with full code about <a href="https://codereview.stackexchange.com/questions/227220/prepare-and-export-data-to-ms-word-file/">Prepare and export data to MS Word file</a>. The user <a href="https://codereview.stackexchange.com/users/59161/t3chb0t">t3chb0t</a> recommended me to separate some part of full code to this post.</p>
<h2>Context</h2>
<p>The task of code for review is convert my types (<code>Contracts</code>, <code>ActCompletion</code>) to <code>Dictionary<></code>.</p>
<p>I will describe the context of this task. I have a template of MS Word. I need to insert some text to it. For doing it, I use <code>MergeField</code>. <code>MergeField</code> has name. The key of dictionary is name for it. The value of dictionary is some text. I take all MergeFields and replace to text.</p>
<p>The name of MergeField can change. Therefore I need to use additional dictionary. For it, the key is const name for code and the value is MergeField's name. If don't do it, the program has to recompile every time when MergeField's name change.</p>
<p>In order to store the dictionary with MergeFiled's names I use Settings of program.</p>
<pre><code>Properties.Settings.Default.MergeFieldDictionaryAsString
</code></pre>
<p>This is string with value like this </p>
<pre><code>{"NUM_CONTRACT":"НОМЕР_ДОГОВОРА","FULL_NAME":"ПОЛНОЕ_ФИО", and so on }
</code></pre>
<p>For translate such string into the dictionary I use <code>Newtonsoft.Json</code> like this</p>
<pre><code>// parse
Dictionary<string, string> fields = JsonConvert.DeserializeObject<Dictionary<string, string>>
(Properties.Settings.Default.MergeFieldDictionaryAsString);
// add new value
Properties.Settings.Default.MergeFieldDictionaryAsString = JsonConvert.SerializeObject(dict);
</code></pre>
<p>And another clarification. From my previous post:</p>
<blockquote>
<p>There are two documents. <code>Contracts</code> is the main document. <code>ActCompletion</code>
is derived from <code>Contracts</code>. It contains some already known data from
<code>Contracts</code> and adds its own. <code>Contracts</code> describes a table in the
database. <code>ActCompletion</code> takes existing <code>Contracts</code> and runtime receives
their individual data from the user. They are not stored anywhere in
the database.</p>
</blockquote>
<p>That's why I need the method <code>AddGeneralField()</code></p>
<h2>Elements</h2>
<ul>
<li><code>ShaperField</code> is auxiliary static class. Contains methods for formatting data into string.</li>
<li><code>ConverterBase</code> the class to be inherited. It is common for <code>Contracts</code> and <code>ActCompletion</code></li>
<li><code>ConverterContract</code> and <code>ConverterActCompletion</code> it is a shell to hide the inner implemented. Both have <code>private class Converter : ConverterBase</code> with <code>override Convert()</code>. If I do not make such a shell, will have access to public fields and <code>ConverterBase</code> methods from the outside.</li>
</ul>
<p>I mean that will be like this</p>
<p><a href="https://i.stack.imgur.com/wym8V.png" rel="noreferrer"><img src="https://i.stack.imgur.com/wym8V.png" alt="enter image description here"></a></p>
<p>But now with "shell" is</p>
<p><a href="https://i.stack.imgur.com/2zQyl.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2zQyl.png" alt="enter image description here"></a></p>
<h2>Code</h2>
<p><strong>Contracts</strong> and <strong>ActCompletion</strong></p>
<pre><code>// Generated by provider database
// add from me:
// "int id = 0" and "this.Id = id"
public partial class Contracts
{
public Contracts(int id = 0)
{
this.Id = id;
ListKindWorks = new HashSet<ListKindWorks>();
ListSubjects = new HashSet<ListSubjects>();
}
public int Id { get; set; }
public string Num { get; set; }
public DateTime DateConclusion { get; set; }
public int Worker { get; set; }
public DateTime DateStartWork { get; set; }
public DateTime DateEndWork { get; set; }
public double Salary { get; set; }
public virtual Workers WorkerNavigation { get; set; }
public virtual ICollection<ListKindWorks> ListKindWorks { get; set; }
public virtual ICollection<ListSubjects> ListSubjects { get; set; }
}
// Not applicable to database, set values in runtime and not stored
public class ActCompletion
{
public Contracts Contract { get; set; }
public double Salary { get; set; }
public Dates Dates { get; private set; }
public ActCompletion()
{
Dates = new Dates();
}
}
public class Dates
{
public DateTime DateConclusion { get; set; }
public DateTime DateStart { get; set; }
public DateTime DateEnd { get; set; }
}
</code></pre>
<p><strong>ConverterContract</strong></p>
<pre><code>class ConverterContract
{
private readonly Converter converter;
public ConverterContract()
{
converter = new Converter();
}
public Dictionary<string, string> Convert(Contracts contract)
{
return converter.Convert(contract);
}
private class Converter : ConverterBase
{
public override Dictionary<string, string> Convert(object obj)
{
Contracts c = obj as Contracts;
InitializeDict(c, c.Salary);
AddKindWork(c.ListKindWorks);
AddSubject(c.ListSubjects);
AddDates(c.DateStartWork, c.DateEndWork);
AddPassport(c.WorkerNavigation);
AddBank(c.WorkerNavigation);
return Dict;
}
private void AddKindWork(ICollection<ListKindWorks> list)
{
Dict.Add(Fields["KIND_WORK"], ShaperField.ShapeKindWork(list));
}
private void AddSubject(ICollection<ListSubjects> list)
{
Dict.Add(Fields["SUBJECT"], ShaperField.ShapeSubject(list));
}
private void AddDates(DateTime start, DateTime end)
{
Dict.Add(Fields["DATE_START_CONTRACT"], ShaperField.ShapeDate(start));
Dict.Add(Fields["DATE_END_CONTRACT"], ShaperField.ShapeDate(end));
}
private void AddPassport(Workers w)
{
Dict.Add(Fields["ADDRESS"], ShaperField.ShapeAddress(w.Address));
Dict.Add(Fields["PASSPORT"], ShaperField.ShapePassport(w));
Dict.Add(Fields["PASSPORT_NUMBER"], ShaperField.ShapePassportNumber(w.PassportNumber));
}
private void AddBank(Workers w)
{
Dict.Add(Fields["BANK"], ShaperField.ShapeBank(w));
}
}
}
</code></pre>
<p><strong>ConverterActCompletion</strong></p>
<pre><code>class ConverterActCompletion
{
private readonly Converter converter;
public ConverterActCompletion()
{
converter = new Converter();
}
public Dictionary<string, string> Convert(ActCompletion act)
{
return converter.Convert(act);
}
private class Converter : ConverterBase
{
public override Dictionary<string, string> Convert(object obj)
{
ActCompletion act = obj as ActCompletion;
InitializeDict(act.Contract, act.Salary);
AddDates(act.Dates);
return Dict;
}
private void AddDates(Dates dates)
{
Dict.Add(Fields["DATE_FILL_ACT_COMPLETION"], ShaperField.ShapeDate(dates.DateConclusion));
Dict.Add(Fields["DATE_START_ACT_COMPLETION"], ShaperField.ShapeDate(dates.DateStart));
Dict.Add(Fields["DATE_END_ACT_COMPLETION"], ShaperField.ShapeDate(dates.DateEnd));
}
}
}
</code></pre>
<p><strong>ConverterBase</strong></p>
<pre><code>using Newtonsoft.Json;
abstract class ConverterBase
{
public Dictionary<string, string> Fields { get; private set; }
public Dictionary<string, string> Dict { get; private set; }
public ConverterBase()
{
Dict = new Dictionary<string, string>();
Fields = JsonConvert.DeserializeObject<Dictionary<string, string>>
(Properties.Settings.Default.MergeFieldDictionaryAsString);
}
public void InitializeDict(Contracts c, double salary)
{
Dict.Clear();
AddGeneralField(c);
AddSalary(salary);
}
public abstract Dictionary<string, string> Convert(object obj);
private void AddGeneralField(Contracts c)
{
Dict.Add(Fields["NUM_CONTRACT"], ShaperField.ShapeNum(c.Num));
Dict.Add(Fields["DATE_FILL_CONTRACT"], ShaperField.ShapeDate(c.DateConclusion));
Dict.Add(Fields["FULL_NAME"], ShaperField.ShapeFullName(c.WorkerNavigation.FullName));
Dict.Add(Fields["SHORT_NAME"], ShaperField.ShapeShortName(c.WorkerNavigation.FullName));
}
private void AddSalary(double salary)
{
ConvertSalary cs = new ConvertSalary();
cs.setSalaryWithTax(salary);
Dict.Add(Fields["SALARY_GROSS"], cs.GetSalaryWithTax());
Dict.Add(Fields["INCOME_TAX_PROCENT"], Properties.Settings.Default.ConvertSalary_IncomeTaxProcent.ToString());
Dict.Add(Fields["INCOME_TAX_SUM"], cs.GetIncomeTaxValue());
Dict.Add(Fields["INSURANCE_TAX_PROCENT"], Properties.Settings.Default.ConvertSalary_InsuranceTaxProcent.ToString());
Dict.Add(Fields["INSURANCE_TAX_SUM"], cs.GetInsuranceTaxValue());
}
}
</code></pre>
<p><strong>ShaperField</strong></p>
<pre><code>static class ShaperField
{
public static string ShapeNum(string value)
{
return value;
}
public static string ShapeDate(DateTime value)
{
return value.ToLongDateString();
}
public static string ShapeFullName(string value)
{
return value;
}
// TODO: зачем в KindWork и Subject - ToArray()
public static string ShapeKindWork(ICollection<ListKindWorks> list)
{
return string.Join(", ", list.Select(x => "«" + x.IdKindWorkNavigation.Title + "»").ToArray());
}
public static string ShapeSubject(ICollection<ListSubjects> list)
{
return string.Join(", ", list.Select(x => "«" + x.IdSubjectNavigation.Title + "»").ToArray());
}
public static string ShapeAddress(string value)
{
return value;
}
public static string ShapePassport(Workers w)
{
return string.Format("{0} выдан {1} {2} г.", w.PassportSeries, w.IssuedNavigation.Title, w.DateIssued.ToString("dd.MM.yyyy"));
}
public static string ShapePassportNumber(string value)
{
return value;
}
public static string ShapeBank(Workers w)
{
return string.Format("{0}\nв {1}", w.BankAccount, w.BankNavigation.Title);
}
public static string ShapeShortName(string fullName)
{
string[] name = fullName.Split(' ');
if (TryFormatShortName(name))
{
return FormatShortName(name);
}
else
{
ShowMessage.Error(string.Format("Во время получения инициалов от полного ФИО произошла ошибка. " +
"Возможно ФИО не содержит трех слов.\nВ случае продолжения, сокращенное имя получит значение \"{0}\"",
fullName));
return fullName;
}
}
private static bool TryFormatShortName(string[] name)
{
try
{
string shortName = FormatShortName(name);
}
catch (Exception ex)
{
return false;
}
return true;
}
private static string FormatShortName(string[] name, string pattern = "{0}.{1}. {2}")
{
return string.Format(pattern, name[1][0], name[2][0], name[0]);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T07:07:50.520",
"Id": "442326",
"Score": "2",
"body": "I find this is a very good question and it looks like everything is there ;-]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T06:36:12.483",
"Id": "442517",
"Score": "0",
"body": "@t3chb0t so many pluses and viewed, but no answers. It's strange)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T06:47:03.493",
"Id": "442518",
"Score": "1",
"body": "This is a long question so it requires time to study. It's good and complete, maybe a little bit confusing but time-consuming. Be patient, it's been here only for 24 hours :-]"
}
] |
[
{
"body": "<p>Here're are my suggestions:</p>\n\n<hr>\n\n<p><strong>Remove <code>ConverterContract</code> and <code>ConverterActCompletion</code></strong> These two classes are unnecessary wrappers to hide the inner converter. You're saying that you're doing this to hide <code>Fields</code> and <code>Dict</code> so here's the next suggestion:</p>\n\n<p><strong>Make <code>Fields</code> and <code>Dict</code> <code>protected</code></strong> You don't want the outside world see them? Use proper access modifiers like <code>protected</code> or <code>internal</code> where applicable.</p>\n\n<p><strong>Make <code>ConverterBase</code> generic</strong> The current <code>Convert(object obj)</code> overload is too general and can and should be more specific because you always cast <code>obj</code> to a concrete type:</p>\n\n<pre><code>abstract class ConverterBase<T>\n{\n public abstract Dictionary<string, string> Convert(T obj);\n\n // ..\n}\n</code></pre>\n\n<p>Then implement the other two converters with concrete types and concrete names. This is one of them:</p>\n\n<pre><code>public class ActCompletionConverter : ConverterBase<ActCompletion>\n{\n public override Dictionary<string, string> Convert(ActCompletion obj)\n {\n // casting not necessary as 'obj' already has the desired type\n // ..\n }\n\n // .. \n}\n</code></pre>\n\n<p><strong>Favor pure methods</strong> Pure methods do not change any class state so they are easier to debug and to test and they can safely be used in parallel. Your current implemention doesn't allow that because <code>Convert</code> requries the caller to change the state, this is the <code>Dict</code>. In order to improve that, let <code>InitializeDict(c, c.Salary);</code> return the initialized dictionary instead of using a field. Then make all of the <code>AddX</code> methods like <code>AddKindWork</code> accept the dictionary as a parameter. When you do this, you'll notice that all of them can now be made static. In order to make the signature shorter and not use the <code>Dictionary<string, string></code> all the time, I suggest a helper class:</p>\n\n<pre><code>internal FormattedFieldDictionary : Dictionary<string, string> \n{ \n public Dictionary<string, string> Mappings { get; set; }\n}\n</code></pre>\n\n<p>You can then implement all the <code>AddX</code> methods as extensions like:</p>\n\n<pre><code>public static FormattedFieldDictionary AddSubject(this FormattedFieldDictionary fields, ICollection<ListSubjects> list)\n{\n fields.Add(fields.Mappings[\"SUBJECT\"], ShaperField.ShapeSubject(list));\n return fields;\n}\n</code></pre>\n\n<p>so the final implementation of <code>Convert</code> would become a chain of extensions:</p>\n\n<pre><code>public override Dictionary<string, string> Convert(Contracts obj)\n{\n return\n InitializeFormattings(c, c.Salary)\n .AddKindWork(c.ListKindWorks)\n .AddSubject(c.ListSubjects)\n ..;\n}\n</code></pre>\n\n<p><strong><code>ShaperField</code> is a <em>Formatter</em></strong> We usually call utilities like this one <em>Formatters</em> so I think it'd be easier to understand your code if you named this one <code>FieldFormatter</code> and each of the methods <em>FormatX</em> like <code>FormatSubject</code>. This naming convention would be consistent with other framework API like <code>string.Format</code> etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T17:32:01.013",
"Id": "442644",
"Score": "1",
"body": "I am kind of surprised you did not recommend returning `IDictionary` instead of `Dictionary`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T17:35:01.473",
"Id": "442648",
"Score": "1",
"body": "@RickDavin mhmm, me either ;-) myself I would most probably use the `IImmutableDictionary` for that but since OP is a beginner I thought I might be too much for one _session_."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T09:48:54.957",
"Id": "442945",
"Score": "0",
"body": "I did static `AddSalary()` and `AddGeneralField()`, but in class `ConverterActCompletion : ConverterBase<ActCompletion>` I got error `Extension methods must be defined in a non generic static class`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T09:51:11.923",
"Id": "442947",
"Score": "0",
"body": "If I delete `this` into method `AddDates()`, error is gone"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T09:51:46.080",
"Id": "442948",
"Score": "0",
"body": "@Viewed indeed. Just do what the compiler says ;-] put them inside a non-generic `static class`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T09:53:07.067",
"Id": "442949",
"Score": "0",
"body": "Both case I can't do chain `InitializeFormattings(c, c.Salary).AddKindWork(c.ListKindWorks). so on`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T09:58:17.340",
"Id": "442951",
"Score": "0",
"body": "Must I add `AddDates()` and related into `FormattedFieldDictionary`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T10:00:05.903",
"Id": "442952",
"Score": "0",
"body": "@Viewed I wouldn't, they're better off as extensions. I suggest reading [this](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods) _short_ article about extensions on msdn."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T10:08:56.957",
"Id": "442954",
"Score": "0",
"body": "In this chain it attempts to look up methods inside `FormattedFieldDictionary` because `InitializeFormattings` return it. So I don't understand how you made this chain."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T15:06:44.273",
"Id": "227408",
"ParentId": "227296",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "227408",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T07:00:49.187",
"Id": "227296",
"Score": "9",
"Tags": [
"c#",
"beginner",
"object-oriented",
"hash-map",
"converting"
],
"Title": "Convert to dictionary"
}
|
227296
|
<p>Jojo is browsing the internet while suddenly he sees an ad about the new cafe. The promotion is if the price
of an item is N dollars, then you can buy the second item for half the price, the third item for a quarter of the
original price, and so on, but if it becomes less than M dollars, then you have to pay M dollars. He wonders
how much he has to pay if he buys K item.</p>
<hr>
<p>Format Input</p>
<p>The first line will contain an integer <code>T</code>, the number of test cases.
Each test case will have 3 integers <code>N</code>, <code>M</code>, and <code>K</code>, each denoting the original price, the minimum price, and the
amount Jojo is going to buy.</p>
<p>Format Output</p>
<p>For each test case, print “Case #X: “ (X starts with 1), then followed by the price Jojo has to pay rounded to 3
decimal digits.</p>
<p>Constraints</p>
<p>1 <= <code>T</code> <= 10</p>
<p>1 <= <code>M</code> <= <code>N</code> <= 1,000,000,000</p>
<p>1 <= <code>K</code> <= 1,000,000,000 </p>
<pre><code>#include <stdio.h>
int main()
{
int T;
scanf("%d", &T);
for (int i = 1; i <= T; i++) {
int M, K, N;
scanf("%d %d %d", &N, &M, &K);
float halfPrice = N;
float sum = halfPrice;
for (int j = 0; j < K-1; j++) {
halfPrice /= 2;
halfPrice = (halfPrice < M) ? M : halfPrice;
sum += halfPrice;
}
printf("Case #%d: %.3f\n", i, sum);
}
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>Formatting</strong><br>\nThis may be a copy and paste error, but generally <code>int main()</code> will start in the first column like the #include does. Other the rest of the indentation needs to be based on that. This was correctly done in your earlier question.</p>\n\n<pre><code>#include <stdio.h>\n\nint main()\n{\n int T;\n scanf(\"%d\", &T);\n\n ...\n\n}\n</code></pre>\n\n<p><strong>Functions</strong><br>\nYou may not have run into difficult problems yet, but as the programs get more complex the best way to solve them will be to break it up into smaller pieces where each particular task is easy to solve. In this case the outer for loop would make a good function. Perhaps the inner loop would make a second good function.</p>\n\n<p><strong>Variable Names</strong><br>\nVariable names should be meaningful to make the code more readable, easier to understand and maintainable.</p>\n\n<p>The problem statement gives you the variable names <code>T</code>, <code>N</code>, <code>M</code> and <code>K</code> which are currently being used in the code, however, it also gives you what the variables are used for. It might be better to use names such as <code>testCount</code> for <code>T</code>, <code>maxPrice</code> for <code>N</code>, <code>minPrice</code> for <code>M</code> and <code>itemCount</code> for <code>K</code>.</p>\n\n<p>The variable name <code>halfPrice</code> could be misleading be it won't always be half of the maximum price.</p>\n\n<p><strong>Mixing Types in Comparisons</strong><br>\nThere is the possibility of <a href=\"https://en.wikipedia.org/wiki/Floating_point_error_mitigation\" rel=\"nofollow noreferrer\">Floating Point Error</a> in the code because of this comparison: </p>\n\n<pre><code> halfPrice = (halfPrice < M) ? M : halfPrice;\n</code></pre>\n\n<p>While the minimum price is input as an <code>integer</code> it might be better to convert it to a <code>float</code> and use that in the comparison. This conversion should only be done once per test case.</p>\n\n<p>In many cases banks work around this by keeping amounts in 2 integer values, one for dollars and one for cents (units are USA, units may differ based on location).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T17:32:50.620",
"Id": "442441",
"Score": "0",
"body": "In the comparison, `M` is promoted to float automagically."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T14:28:03.963",
"Id": "227332",
"ParentId": "227306",
"Score": "3"
}
},
{
"body": "<ul>\n<li><p>Your approach is working too hard. The inner loop does <code>K</code> iterations (with could be as large as <code>1,000,000,000</code>), and most of them are redundant: as soon as <code>halfPrice</code> goes beyond <code>M</code> it will stay beyond <code>M</code> for the rest of the loop. Notice that in the worst case (<code>N = 1,000,000,000</code>, and <code>M = 1</code>) you'll need just 30 iteration to reach <code>M</code>. So, something along the lines of</p>\n\n<pre><code> int halvings = 0;\n while ((halfPrice > M) && (halvings < K)) {\n sum += halfPrice;\n halfPrice /= 2;\n halvings++;\n }\n sum += (K - halvings) * M;\n</code></pre>\n\n<p>will run up to 30,000,000 times faster.</p>\n\n<p>Now, the entire loop is in fact unnecessary. As Jojo applies the promotions (say, <code>P</code> times), the amounts he pays form a geometrical progression: <span class=\"math-container\">\\$N + \\frac{N}{2} + \\frac{N}{4} + ... + \\frac{N}{2^P}\\$</span>.</p>\n\n<p>It is easy to sum. The accumulated price he pays here is <span class=\"math-container\">\\$(1 - \\frac{1}{2^{P+1}})*N\\$</span>. The only thing left is to determine <code>P</code>. Recall that it is such that <span class=\"math-container\">\\$\\dfrac{N}{2^P} \\ge M\\$</span> and <span class=\"math-container\">\\$\\dfrac{N}{2^{P+1}} \\lt M\\$</span>. An accurate application of <code>log</code> computes it immediately.</p></li>\n<li><p>Beware of the accuracy. During long summation the unavoidable floating point errors do accumulate. They accumulate even more when you add a very small number to a very large one. This phenomenon manifests quite surprisingly: floating point addition is not associative.</p>\n\n<p>This is why it is recommended to do summation other way around: start from small values and work towards the large ones. I don't know if this particular problem is subject to such kind of numerical instability or not. You may want to experiment. In any case, this is necessary to know when tackling floating point.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T07:37:46.350",
"Id": "442521",
"Score": "0",
"body": "Good performance ideas."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T17:31:32.413",
"Id": "227349",
"ParentId": "227306",
"Score": "3"
}
},
{
"body": "<p><strong>Precision</strong></p>\n\n<p><code>1 <= M <= N <= 1,000,000,000</code> implies a need for 30 bit of precision. (log<sub>2</sub>1,000,000,000 --> 29.897...)</p>\n\n<p><code>float</code> <a href=\"https://en.wikipedia.org/wiki/Single-precision_floating-point_format#IEEE_754_single-precision_binary_floating-point_format:_binary32\" rel=\"nofollow noreferrer\">usually</a> has 24 bits of precision (23 explicitly encoded, 1 implied).</p>\n\n<p>Code as below can readily lose precision when converting from <code>int</code> to <code>float</code> for values of <code>N</code> > 2<sup>24</sup>.</p>\n\n<pre><code>float halfPrice = N;\nfloat sum = halfPrice;\n</code></pre>\n\n<p><code>double</code> <a href=\"https://en.wikipedia.org/wiki/Double-precision_floating-point_format\" rel=\"nofollow noreferrer\">typically</a> affords sufficient precision.</p>\n\n<hr>\n\n<p>C <a href=\"https://stackoverflow.com/a/32214586/2410359\">lacks a great type</a> to use for financial code. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T22:46:15.493",
"Id": "227361",
"ParentId": "227306",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227349",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T08:40:19.007",
"Id": "227306",
"Score": "2",
"Tags": [
"beginner",
"algorithm",
"c"
],
"Title": "Getting the Sum of Discounted Price"
}
|
227306
|
<p>I would appreciate som feedback on my fictional survey form. I am doing the freeCodeCamp curriculum and a <a href="https://learn.freecodecamp.org/responsive-web-design/responsive-web-design-projects/build-a-survey-form" rel="nofollow noreferrer">Survey Form</a> is one of the Responsive Web Design Projects using only HTML/CSS.</p>
<p>I am especially interested in feedback regarding best practice, naming conventions and efficient code.</p>
<hr>
<p>The code is also <a href="https://oyvind-solberg.github.io/fcc-survey-form/" rel="nofollow noreferrer">on GitHub</a>.</p>
<p>HTML file:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="css/style.css" />
<title>Healthy Eating</title>
</head>
<body>
<main>
<form id="survey-form" action="#" method="GET">
<header>
<h1 id="title">Survey Form</h1>
<div class="grid-columns">
<p id="description">
Our job at <strong>Healthy Eating</strong> is to map
the eating habbits of the population.
<span class="new-line">Please
fill in the form below to help us with our work.</span>
</p>
<div class="col">
<img src="img/carrot-solid.svg" alt="Icon" />
</div>
</div>
</header>
<div class="row">
<section id="p-info">
<h2>
Personal information
</h2>
<label class="main-label" id="name-label" for="name"
>Name</label
>
<input
type="text"
name="name"
id="name"
placeholder="Enter your name"
required
/>
<label class="main-label" id="email-label" for="email"
>Email</label
>
<input
type="email"
name="email"
id="email"
placeholder="Enter your e-mail"
required
/>
<div class="row">
<div class="col">
<label
class="main-label"
id="number-label"
for="number"
>Age</label
>
<input
type="number"
name="age"
id="number"
min="1"
max="100"
placeholder="Age"
/>
</div>
<div class="col">
<label class="main-label" for="dropdown"
>Sex</label
>
<select name="sex" id="dropdown">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
</div>
</section>
<section id="eating-habits">
<h2>Eating habits</h2>
<div class="row">
<fieldset class="fset-sub">
<legend class="main-label legend-sub">
Meals per day
</legend>
<div class="option">
<input
id="meals-per-day-1"
type="radio"
name="meals-per-day"
value="1"
/>
<label for="meals-per-day-1">One</label>
</div>
<div class="option">
<input
id="meals-per-day-2"
type="radio"
name="meals-per-day"
value="2"
/>
<label for="meals-per-day-2">Two</label>
</div>
<div class="option">
<input
id="meals-per-day-3"
type="radio"
name="meals-per-day"
value="3"
/>
<label for="meals-per-day-3">Tree</label>
</div>
<div class="option">
<input
id="meals-per-day-4"
type="radio"
name="meals-per-day"
value="4"
/>
<label for="meals-per-day-4">Four</label>
</div>
<div class="option">
<input
id="meals-per-day-5"
type="radio"
name="meals-per-day"
value="5"
/>
<label for="meals-per-day-5">Five</label>
</div>
<div class="option">
<input
id="meals-per-day-6"
type="radio"
name="meals-per-day"
value="6-or-more"
/>
<label for="meals-per-day-6"
>Six or more</label
>
</div>
</fieldset>
<fieldset class="fset-sub">
<legend class="main-label legend-sub">
Meal composition
</legend>
<div class="option">
<input
id="meal-comp-1"
type="checkbox"
name="meal-content"
value="fruit-and-vegetables"
/>
<label for="meal-comp-1"
>Fruit and vegetables</label
>
</div>
<div class="option">
<input
id="meal-comp-2"
type="checkbox"
name="meal-content"
value="meat"
/>
<label for="meal-comp-2">Meat</label>
</div>
<div class="option">
<input
id="meal-comp-3"
type="checkbox"
name="meal-content"
value="tubers"
/>
<label for="meal-comp-3">Tubers</label>
</div>
<div class="option">
<input
id="meal-comp-4"
type="checkbox"
name="meal-content"
value="dairy"
/>
<label for="meal-comp-4"
>Dairy products</label
>
</div>
<div class="option">
<input
id="meal-comp-5"
type="checkbox"
name="meal-content"
value="grains"
/>
<label for="meal-comp-5">Grains</label>
</div>
<div class="option">
<input
id="meal-comp-6"
type="checkbox"
name="meal-content"
value="sugar"
/>
<label for="meal-comp-6">Sugar</label>
</div>
</fieldset>
</div>
</section>
</div>
<section id="add-info">
<h2>
Additional information
</h2>
<label class="main-label" for="comments">Comments</label>
<textarea
name="comments"
id="comments"
cols="30"
rows="10"
placeholder="Enter your comment here..."
></textarea>
<div class="row">
<fieldset class="fset-sub">
<legend class="main-label legend-sub">
Newsletter
</legend>
<div class="option">
<input
id="newsletter"
type="checkbox"
name="newsletter"
value="subscribe"
/>
<label for="newsletter"
>Keep in touch with our newsletter</label
>
</div>
</fieldset>
<div class="col">
<button id="submit" class="btn">Submit</button>
</div>
</div>
</section>
</form>
</main>
</body>
</html>
</code></pre>
<p>CSS file:</p>
<pre><code>/* Color scheme */
:root {
--background: #efefef;
--form-bg-standard: #fff;
--form-bg-alt: #eee;
--form-bg-dark: #444;
--text-standard: #666;
--text-title: #333;
--focus: #7bc94e;
--focus-alt: #4394d6;
}
/* Basic Reset */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
/* Standard setup */
body {
background-color: var(--background);
/* background: linear-gradient(45deg, #759b61, #619b85); */
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
line-height: 1.5;
color: var(--text-standard);
}
main {
margin: auto;
}
#survey-form {
max-width: 900px;
margin: auto;
padding: 2rem 2rem;
}
img {
width: 100%;
height: auto;
}
h1 {
font-size: 2.5rem;
color: #fff;
text-align: center;
}
h2 {
font-size: 1.25rem;
margin-bottom: 1rem;
color: var(--focus-alt);
}
/* Utility classes */
.row {
display: flex;
width: 100%;
}
.col {
display: flex;
flex-direction: column;
width: 100%;
}
.grid-columns {
display: grid;
grid-template-columns: 1fr 1fr;
}
.new-line {
display: block;
margin-top: 0.5rem;
}
/* Buttons */
.btn {
border: none;
padding: 1rem 1rem;
width: 20rem;
background-color: var(--focus);
color: #fff;
font-size: 1.1rem;
border-radius: 5px;
}
.btn:hover {
cursor: pointer;
}
/* Form */
section {
background-color: var(--form-bg-standard);
display: flex;
flex-direction: column;
width: 100%;
padding: 1.5rem 1.5rem 1.5rem 1.5rem;
margin: 0.5rem 0;
border: none;
box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.05);
}
.row section:first-of-type {
margin-right: 0.5rem;
}
.row section:last-of-type {
margin-left: 0.5rem;
}
.fset-sub {
display: block;
width: 100%;
border: none;
}
input[type="text"],
input[type="email"],
input[type="number"],
select,
#comments {
display: inline-block;
width: 100%;
padding: 0.5rem;
border-color: var(--form-bg-alt);
border-style: solid;
margin-bottom: 1rem;
font-size: 16px;
}
select {
background-color: var(--form-bg-alt);
}
label {
font-size: 1rem;
}
.main-label {
font-size: 1.1rem;
margin-bottom: 0.5rem;
color: var(--text-title);
}
legend.main-label {
display: block;
float: left;
width: 100%;
margin-top: 0rem;
}
/* Header */
header {
/* background-color: var(--focus-alt); */
background: linear-gradient(45deg, #4394d6, #43c5d6);
padding: 2rem 1rem 1rem 1rem;
box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.05);
margin-bottom: 0.5rem;
color: #fff;
}
header div {
padding: 2rem 5rem;
justify-content: center;
align-items: center;
}
#description {
margin-right: 1rem;
font-size: 1rem;
font-weight: 500;
width: 100%;
}
header img {
height: 100px;
width: auto;
margin-left: 1rem;
}
/* P-info */
#p-info .col:first-of-type {
margin-right: 1rem;
}
/* Eating habits */
#eating-habits .option {
margin-bottom: 0.5rem;
}
/* Additional-info */
#add-info .col {
justify-content: center;
align-items: flex-end;
}
/* Media queries desktop first */
/* Tablet 840px */
@media only screen and (max-width: 840px) {
form > .row {
flex-direction: column;
}
form .row section {
margin: 0.5rem 0;
}
#eating-habits {
margin: 0.5rem 0;
}
.btn {
width: 100%;
}
#survey-form {
padding: 1rem 1rem;
}
header {
padding: 1rem 0.5rem 0.5rem 0.5rem;
}
header div {
padding: 1.5rem 3rem;
}
}
/* Phone 568px */
@media only screen and (max-width: 568px) {
.row {
flex-direction: column;
}
.grid-columns {
grid-template-columns: 1fr;
}
#survey-form {
padding: 0.5rem 0.5rem;
}
header div {
padding: 1rem 1.5rem 0 1.5rem;
}
header img,
header #description {
margin: 0.5rem 0 0 0;
}
h1 {
font-size: 2rem;
}
.option:last-of-type {
padding-bottom: 1rem;
}
#p-info .col:first-of-type {
margin-right: 01rem;
}
header img {
margin: 1rem;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>It looks ok to me. What you could improve is the order of your CSS statements. For example</p>\n\n<p><strong>This:</strong></p>\n\n<pre><code>header {\n /* background-color: var(--focus-alt); */\n background: linear-gradient(45deg, #4394d6, #43c5d6);\n padding: 2rem 1rem 1rem 1rem;\n box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.05);\n margin-bottom: 0.5rem;\n color: #fff;\n}\n</code></pre>\n\n<p>Would look a little bit cleaner <strong>this way</strong>(alphabetical order):</p>\n\n<pre><code>header {\n /* background-color: var(--focus-alt); */\n background: linear-gradient(45deg, #4394d6, #43c5d6);\n box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.05);\n color: #fff;\n margin-bottom: 0.5rem;\n padding: 2rem 1rem 1rem 1rem;\n}\n</code></pre>\n\n<p>There are a few different ways to order CSS statements. For example you could write out all statements that change the appearance first (background, color, font-size) and then all statements that change the box model (width, height, padding, margin).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T09:26:46.403",
"Id": "444978",
"Score": "0",
"body": "Thanks for the advice. I installed CSScomb in VS code now, an it seems to do just that"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T14:54:13.777",
"Id": "227725",
"ParentId": "227309",
"Score": "2"
}
},
{
"body": "<p>There's really not much you can improve. My follow up question would be where and how did you decide on your breakpoints?</p>\n\n<p>I suggest using a bit more standardized sizes; the ones I pasted below are directly from the Bootstrap 4 Template <a href=\"https://getbootstrap.com/docs/4.3/layout/overview/\" rel=\"nofollow noreferrer\">https://getbootstrap.com/docs/4.3/layout/overview/</a></p>\n\n<p>You <strong>do not</strong> need all 4 sizes, but these are a bit more <em>standard</em> (even though there's a bajillion different sizes, these are most common)</p>\n\n<pre><code>// Small devices (landscape phones, 576px and up)\n@media (min-width: 576px) { ... }\n\n// Medium devices (tablets, 768px and up)\n@media (min-width: 768px) { ... }\n\n// Large devices (desktops, 992px and up)\n@media (min-width: 992px) { ... }\n\n// Extra large devices (large desktops, 1200px and up)\n@media (min-width: 1200px) { ... }\n</code></pre>\n\n<p>And maybe some general clean up. For example right now you have:</p>\n\n<h2>Current</h2>\n\n<pre><code> form .row section {\n margin: 0.5rem 0;\n }\n #eating-habits {\n margin: 0.5rem 0;\n }\n</code></pre>\n\n<h2>Revised</h2>\n\n<pre><code>#eating-habits, form .row section{\n margin: 0.5rem 0;\n}\n</code></pre>\n\n<p>Keep all the same style in one block. So if there are a bunch of things that have the exact same property and value, put them in a single block. I usually do ID's then class (alphabetical). And same with the properties themselves as mentioned by Dennis.</p>\n\n<h2>Reason</h2>\n\n<p>Lets say you have 50 elements, and they all need to <code>display:block</code> . Its much quicker to write that out once, and attach all the classes and ID's to that property, than the inverse. If you look at most CSS frameworks you'll find them written in this fashion.</p>\n\n<p>Otherwise great work! :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T09:36:27.173",
"Id": "444980",
"Score": "0",
"body": "Thanks. I will try to get all the same styles in one block.\n\nThe reason for my nonstandard breakpoints is just that text started wraping or overflow on those points."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T22:05:40.867",
"Id": "227743",
"ParentId": "227309",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227725",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T09:32:21.670",
"Id": "227309",
"Score": "2",
"Tags": [
"html",
"css"
],
"Title": "Survey form (freeCodeCamp Responsive Web Design project)"
}
|
227309
|
<p>I have to calculate costs based on country code and city(optional). There is also a condition that countries in Asia have separate pricing logic depending on both country and city and they are stored in a different table (for segregating regional price variances). For the rest, it's only dependent on country code. Let's assume we must have separate tables Asia & the rest.</p>
<p>Please suggest some improvements in the below code.</p>
<pre class="lang-py prettyprint-override"><code>def get_cost_by_location(country_code: str, city=None) -> Optional[models.OperatorCost]:
cost = None
# check if the country is in Asia
if models.OperatorCostAsia.objects.filter(country=country_code).exists():
cost = models.OperatorCostAsia.objects.filter(country=country_code, city__icontains=city).first()
if cost is None:
cost = models.OperatorCostAsia.objects.filter(country=country_code).first()
else:
cost = models.OperatorCost.objects.filter(country=country_code).first()
return cost
</code></pre>
<p>I have two different tables to calculate the prices. The pricing table for Asia has three columns: Country code, city name and the price itself. The pricing table for rest of the countries just has country code and price columns.<br>
I get a mandatory country code and an optional city name as parameters from the frontend. First I check these params against the Asia pricing table. if the selected country happens to be Asian, I query against country code and city name (if there is one). If the city param is empty, i just pick the first match against the country. </p>
<p>If the country is not an Asian country, I simply query the second (Rest of the world) table to find the pricing against the country code. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T11:11:10.317",
"Id": "442369",
"Score": "0",
"body": "@Linny I came here for help. Whether it's my code or not, I have been given the responsibility to clean up my project written by 10 other developers in past few years. What's the point of having this forum if I someone can't review a piece of code just because he/she is too busy finding the original author of the code. \nAlso, how are you so sure that all the post in this forum are 100% verified that they are written by the author? It's pointless and impractical."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T12:48:30.030",
"Id": "442381",
"Score": "1",
"body": "I don't completely get the Asian country and city thing… Per your description, each country in Asia (found by its country code) is split into several city. But your code seems to imply that a country could have no city attached to it. Either that, or you pick the first city out of the given country any time an invalid city is provided. Can you explain a bit more what's going on here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T16:04:34.597",
"Id": "442416",
"Score": "0",
"body": "@mathias added more info in the post. Please check now."
}
] |
[
{
"body": "<p>The first thing that would benefit this code, beside removing the useless initialization for <code>cost</code>, is to save the <code>models.OperatorCostAsia.objects.filter(country=country_code)</code> queryset for reuse instead of rebuilding it each time. It feels easier to understand and filtering twice is identical to using two parameters in a single filter anyway:</p>\n\n<pre><code>def get_cost_by_location(country_code: str, city=None) -> Optional[models.OperatorCost]:\n asian_country = models.OperatorCostAsia.objects.filter(country=country_code)\n if asian_country.exists():\n cost = asian_country.filter(city__icontains=city).first()\n if cost is None:\n cost = asian_country.first()\n else:\n cost = models.OperatorCost.objects.filter(country=country_code).first()\n\n return cost\n</code></pre>\n\n<hr>\n\n<p>Now there are a few other changes that I would perform but these may change the behavior of the function so it's a bit of guessing territory on how you use this function.</p>\n\n<p>For starter I would use <code>iexact</code> instead of <code>icontains</code> when searching for the city name, it feels less error prone.</p>\n\n<p>Second, I would use <code>.get(...)</code> instead of <code>.filter(...).first()</code> when applicable to check for wrongly constructed inputs that would return more than the one result they are expected to return:</p>\n\n<pre><code>def get_cost_by_location(country_code: str, city=None) -> Optional[models.OperatorCost]:\n asian_country = models.OperatorCostAsia.objects.filter(country=country_code)\n if asian_country.exists():\n try:\n return asian_country.get(city__iexact=city)\n except models.OperatorCostAsia.DoesNotExist:\n return asian_country.first()\n else:\n return models.OperatorCost.objects.get(country=country_code)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T18:23:14.633",
"Id": "442443",
"Score": "0",
"body": "Great. just what i was looking for. I was just wondering is there any performance difference between `iexact` and `icontains`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T18:33:50.050",
"Id": "442447",
"Score": "1",
"body": "@saran3h `iexact` is a `WHERE city ILIKE 'city'` while `icontains` is a `WHERE city ILIKE '%city%'` clause. Now I'm no SQL expert but I'd say the second preforms more work and is thus slower."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T17:30:24.613",
"Id": "227348",
"ParentId": "227311",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227348",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T09:55:12.330",
"Id": "227311",
"Score": "1",
"Tags": [
"python",
"performance",
"mysql",
"django"
],
"Title": "Code improvement suggestions for cost calculation"
}
|
227311
|
<p>For past few months I was trying to understand genetic algorithms (GA) and most of the materials availble in the web was not always easy for me. Then I came across this article written by Ahmed Gad <a href="https://towardsdatascience.com/genetic-algorithm-implementation-in-python-5ab67bb124a6" rel="nofollow noreferrer">Genetic Algorithm Implementation in Python</a> which implemented GA with numpy. Using this as a guiding tool I wrote my first GA in python with numpy. All of the codes were written by me except <code>cal_pop_fitness</code>.</p>
<p>The problem GA need to solve was to find parameters <code>(a,b)</code> in an equation of the format <code>y = a*x1+b*x2</code> where <code>x1</code>,<code>x2</code> and <code>y</code> are give as a numpy array. The equation I chose to solve is <code>y = 2*x1+3*x2</code>. Because we have two parameters to solve I chose two genes per chromosome. In all GA's we have to choose a fitness function and I chose <code>mean squared error</code> (MSE) as the fitness function for selecting best parents. MSE was chosen because we already have the real output <code>y</code>. The lesser the MSE better the parents we selected. This also the main difference between mine and Ahmed's GA where he used a maximisation fitness function I used a minimisation function. From the selected parents we generate offsprings by crossover and mutations. All offsprings go through crossovers but only a few offsprings have mutations.</p>
<pre><code>import numpy as np
np.set_printoptions(formatter={'float': '{: 0.3f}'.format})
np.random.seed(1)
def generate_data(x_range):
# Formula='2*x1+3*x2'
x_range = range(-x_range,x_range)
x = np.vstack((np.array(x_range),np.array(x_range)*2)).T
y = [2*i[0]+3*i[1] for i in x]
return x,np.array(y)
def cal_pop_fitness(equation_inputs, pop):
fitness = np.sum(pop*equation_inputs, axis=1)
return fitness
def select_best_parents(total_population,top_parents):
arr = []
for i in total_population:
pred_y = cal_pop_fitness(i,X)
mse = (np.square(y-pred_y)).mean(axis=None) # Mean squared error
# Append the mse with chromose values
row = np.append(i,mse).tolist()
arr.append(row)
arr = np.array(arr)
# Sorting the chromosomes respect to mse
# Lower the mse better the individuals
arr = arr[arr[:,2].argsort()]
error = arr[:,2]
arr = arr[:,0:2] # removing mse column
return arr[0:top_parents,:],error[0:top_parents]
def crossover(sub_population):
children = []
for i in range(population_size):
# Selecting random two parents
parent1 = np.random.randint(0,sub_population.shape[0])
parent2 = np.random.randint(0,sub_population.shape[0])
# A child is created from parent1's first gene and parent2's second gene
child = [sub_population[parent1][0],sub_population[parent2][1]]
children.append(child)
return np.array(children)
def mutation(population):
for i,row in enumerate(population):
if np.random.rand() < mutation_rate:
# Random mutations
population[i][np.random.randint(genes)] = np.random.uniform(low = -4.0, high = 4.0)
return population
if __name__ == "__main__":
# Generate input ouptut data
X,y = generate_data(150)
genes = X.shape[1] # Total genes in a chromosome
population_size = 50 # Number of populations
top_parents = int(0.25*population_size) # Select top parents from the total populations for mating
mutation_rate = 0.1 # Mutation rate
generations = 1000 # number of generations
# Step1 : Population
# Total population
total_population = np.random.uniform(low = -4.0, high = 4.0, size = (population_size,genes))
for i in range(generations):
# Step2 : Fitness calculation
# Step3 : Mating pool
# Step4 : Parents selection
# Choosing best parents with their corresponding mse
sub_population,mse = select_best_parents(total_population,top_parents)
# Step5 : Mating
# Crossover
new_population = crossover(sub_population)
# Mutation
new_population = mutation(new_population)
print("Best Parameters: ",np.round(sub_population[0],3),"Best MSE: ", round(mse[0],3))
# Next population
total_population = new_population
# Real
x_range=range(-10,10)
x1 = np.array(x_range)
x2 = np.array(x_range)*2
formula='2*x1+3*x2'
y1=eval(formula)
# Predicted by Genetic algorithm
a = 1.943
b = 3.029
formula = 'a*x1+b*x2'
y2=eval(formula)
print("\nMSE between Real and predicted Forumulas : ",(np.square(y1-y2)).mean(axis=None))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T11:25:24.577",
"Id": "442373",
"Score": "0",
"body": "What is it that you expect to get from the community? General feedback on the code? Style? Clarity? Performance?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T11:28:21.577",
"Id": "442374",
"Score": "0",
"body": "Code review. eventhough I took the ideas from the mentioned article I wrote the code myself except for `cal_pop_fitness`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T11:34:11.470",
"Id": "442376",
"Score": "0",
"body": "My question was more on which aspects of the code should be in the focus of the review. If you don't care which aspects get attention it's okay to say so."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T11:37:39.480",
"Id": "442377",
"Score": "0",
"body": "Actuall the implementation of GA itself. Especially the creation of offspring using crossover and mutation. Whether my implementation is correct or not?. The second reason for posting the code here is to share my implementation for the newbie's in GA."
}
] |
[
{
"body": "<p>From my understanding of the subject your implementation seem correct but there are numerous things you could fix or improve there.</p>\n\n<h2>Specific remarks</h2>\n\n<ol>\n<li>Use actually predicted values for printing i.e.</li>\n</ol>\n\n<pre><code> # Predicted by Genetic algorithm\n a, b = sub_population[0]\n</code></pre>\n\n<ol start=\"2\">\n<li><p>Your initialisation of <code>X</code> is dangerous and prevents the algorithm to converge on some values since <code>X[0] = 2*X[1]</code>, while they are supposed to be independant variables. Use random values instead.</p></li>\n<li><p>Don't use <code>X</code> and <code>y</code> from global context in <code>select_best_parents</code> you could have ugly surprises if these are used elsewhere in the program. Add them to function parameters.</p></li>\n<li><p>Your mutation function uses magic numbers, you could make <code>[-4, 4]</code> interval a parameter of your GA to make it more generic.</p></li>\n<li><p>You could make a function of the main's <code>for</code> to segregate well what is part of algorithm and what is parameters. </p></li>\n<li><p>You could extract your sorting key (MSE) as a separate function so it's easier to replace.</p></li>\n</ol>\n\n<h2>General remarks</h2>\n\n<ol>\n<li><p>If you want to validate your approach you need more than a single test value. So for example after you make a and b (3 and 2) parameters, you can use a loop or a variety of examples to prove it converges toward these values.</p></li>\n<li><p>I find odd and damaging scientific programmers often pass on object oriented design. Using classes could be handy to pass the variables from core function to core function using object context rather than extending parameters of every function as needed, so it would to propose a catalog of different implementations of GA mutation, for instance. Consider migrating to an object oriented design if these are later goals</p></li>\n<li><p>It could be beneficial to separate the usage example from the core GA functions in two distinct modules and files. They are independent parts that can be improved and extended separatedly.</p></li>\n<li><p>I believe you can support more than two dimensions using a bit of tidying and genericizing in generate_data, crossover, and select_best_parents.</p></li>\n<li><p>Improve style and formatting a bit, trying to follow PEP8. Keyword don't need spaces, two spaces between function definitions, use docstrings rather than comments etc. </p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T01:52:34.393",
"Id": "227368",
"ParentId": "227313",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227368",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T10:59:09.130",
"Id": "227313",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"numpy",
"machine-learning",
"genetic-algorithm"
],
"Title": "Simple Genetic Algorithm in Python"
}
|
227313
|
<p>I was asked to move the code here.</p>
<p>I have different <a href="https://shapely.readthedocs.io/en/stable/manual.html#linestrings" rel="nofollow noreferrer"><code>shapely.LineStrings</code></a> like so:
<a href="https://i.stack.imgur.com/ffKXa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ffKXa.png" alt="enter image description here"></a></p>
<p>which I then <a href="https://shapely.readthedocs.io/en/stable/manual.html#object.buffer" rel="nofollow noreferrer"><code>buffer</code></a> to create a polygon like so:
<a href="https://i.stack.imgur.com/64O9t.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/64O9t.png" alt="enter image description here"></a></p>
<p>I've played around a bit and found that buffering each line segment is <strong>slightly</strong> faster than <a href="https://shapely.readthedocs.io/en/stable/manual.html#shapely.ops.cascaded_union" rel="nofollow noreferrer"><code>unary_union</code></a>-ing all the linestrings and then buffering the whole thing together. However I do need the total area of the buffered lines as a shapely polygon as I am using it for intersection detection later. So I end up having to <a href="https://shapely.readthedocs.io/en/stable/manual.html#shapely.ops.cascaded_union" rel="nofollow noreferrer"><code>unary_union</code></a> the buffered polygons to get the overall polygon and this is taking some time (not for this particular example but for other examples with more green lines).</p>
<p>So is there a faster way to get the buffered polygon that I am unaware of?</p>
<p>Here is a reproducible example:</p>
<pre><code>import numpy as np
from shapely.geometry import MultiLineString, LineString, Polygon
from shapely import ops, affinity
import matplotlib.pyplot as plt
from math import atan2, degrees
from descartes.patch import PolygonPatch
if __name__ == '__main__':
Coords = np.array([
[0, 0, 0, 0, 'N', 0, 0],
[0, 1, 0, 'BRANCH', 'N', 0, 0],
[0, 0, 0, 'BRANCH', 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[-0.85, -0.51, 0, 'BRANCH', 'Y', 45, 0],
[-0.85, -0.51, 0, 'NODE', 'Y', 45, 0],
[-1.71, -1.03, 0, 0, 'Y', 45, 0],
[-1.66, -2.02, 0, 'BRANCH', 'Y', 45, 0],
[-1.66, -2.02, 0, 'NODE', 'Y', 45, 0],
[-1.60, -3.02, 0, 'BRANCH', 'Y', 45, 0],
[0, 0, 0, 0, 0, 0, 0],
[0.90, -0.42, 0, 'BRANCH', 'Y', 45, 0],
[0.90, -0.42, 0, 'NODE', 'Y', 45, 0],
[1.81, -0.84, 0, 'BRANCH', 'Y', 45, 0],
[0, 0, 0, 'BRANCH', 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0.10, -0.99, 0, 0, 'Y', 45, 0],
[-0.69, -1.59, 0, 0, 'Y', 45, 0],
[-0.53, -2.58, 0, 'BRANCH', 'Y', 45, 0],
[-0.53, -2.58, 0, 'NODE', 'Y', 45, 0],
], dtype=object)
for ind, coord in enumerate(Coords):
if coord[3] == 'BRANCH':
if (coord[0:3] == Coords[ind + 1, 0:3]).all():
np.delete(Coords, ind, 0)
lines = []
j = 0
for i in range(len(Coords)):
if (Coords[i, 3] == 'BRANCH') or (i == (len(Coords) - 1)):
lines.append(Coords[j:i+1].tolist())
j = i+1
if not lines:
Lines = [Coords[:]]
else:
Lines = [line for line in lines if len(line) > 1]
fig, ax = plt.subplots()
patches = []
lines = []
Vs = []
all_r_lines = []
texts = []
for num, line in enumerate(Lines):
line = np.asarray(line, dtype=object)
num_coords = line[:, 0:2]
cumm = 0
indi_coords = []
for i, joint in enumerate(line):
if joint[4] == 'Y' and joint[3] != 'BRANCH':
""" --------------- BODY -------------------------------- """
indi_coords.append((joint[0], joint[1]))
new_coords = ((line[i+1][0]), (line[i+1][1]))
angle = degrees(atan2(
(new_coords[1] - joint[1]),
(new_coords[0] - joint[0])
))
if cumm > 0:
Lines[num][i][6] = cumm
cumm += 1
else:
indi_coords.append((joint[0], joint[1]))
cumm = 0
lines.append(np.asarray(indi_coords))
linestring = MultiLineString(lines)
for num, line_coords in reversed(list(enumerate(Lines))):
for i, joint in reversed(list(enumerate(line_coords))):
if joint[4] == 'Y' and i < (len(Coords)-1) and joint[3] != 'BRANCH':
if joint[6] > 0:
""" --------------- PATCH -------------------------------- """
lineA = LineString([(joint[0], joint[1]),
((line_coords[i+1][0]), (line_coords[i+1][1]))])
left_line = affinity.rotate(
lineA, joint[5]/2, (joint[0], joint[1]))
rigt_line = affinity.rotate(
lineA, -joint[5]/2, (joint[0], joint[1]))
try:
Vs[-1] = ops.unary_union([MultiLineString(
[lineA, left_line, rigt_line])] + all_r_lines[-1])
except:
Vs.append(MultiLineString([lineA, left_line, rigt_line]))
""" --------------- ANGLE LINES -------------------------------- """
rotate_angle = line_coords[i-1][5]/2
r_lines = [affinity.rotate(
Vs[-1],
j,
(line_coords[i-1][0], line_coords[i-1][1])
) for j in np.linspace(-rotate_angle, rotate_angle, num=3)
]
all_r_lines += [r_lines]
Vs[-1] = ops.unary_union([Vs[-1]] + r_lines)
else:
""" --------------- PATCH -------------------------------- """
lineA = LineString([(joint[0], joint[1]),
((line_coords[i+1][0]), (line_coords[i+1][1]))])
left_line = affinity.rotate(
lineA, joint[5]/2, (joint[0], joint[1]))
rigt_line = affinity.rotate(
lineA, -joint[5]/2, (joint[0], joint[1]))
Vs.append(MultiLineString([lineA, left_line, rigt_line]))
all_r_lines = []
all_lines = Vs
a = ops.unary_union(all_lines)
creature = (Vs + [a] + [linestring])
polies = []
for l in creature:
polies.append(Polygon(l.buffer(0.5)))
creature_poly = ops.unary_union(polies)
creature_patch = PolygonPatch(creature_poly, fc='BLUE', alpha=0.1)
absorbA = creature_poly
moves = Vs
for c_l in linestring:
x, y = c_l.xy
ax.plot(x, y)
for m in all_lines:
for line in m:
x, y = line.xy
ax.plot(x, y, 'g--', alpha=0.25)
ax.axis('equal')
ax.add_patch(creature_patch)
ax.axis('equal')
plt.show()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T13:53:08.800",
"Id": "442391",
"Score": "0",
"body": "Cross-posted: https://stackoverflow.com/questions/57753813/speed-up-shapely-buffer"
}
] |
[
{
"body": "<p>Welcome to CodeReview! I'm not familiar enough with your stack to suggest performance improvements, but one other thing I will suggest: use a fixed-width format for your table, like this:</p>\n\n<pre><code> Coords = np.array([\n [ 0.00, 0.00, 0.00, 0.00, 'N', 0, 0],\n [ 0.00, 1.00, 0.00, 'BRANCH', 'N', 0, 0],\n [ 0.00, 0.00, 0.00, 'BRANCH', 0.00, 0, 0],\n [ 0.00, 0.00, 0.00, 0.00, 0.00, 0, 0],\n [-0.85, -0.51, 0.00, 'BRANCH', 'Y', 45, 0],\n [-0.85, -0.51, 0.00, 'NODE', 'Y', 45, 0],\n [-1.71, -1.03, 0.00, 0.00, 'Y', 45, 0],\n [-1.66, -2.02, 0.00, 'BRANCH', 'Y', 45, 0],\n [-1.66, -2.02, 0.00, 'NODE', 'Y', 45, 0],\n [-1.60, -3.02, 0.00, 'BRANCH', 'Y', 45, 0],\n [ 0.00, 0.00, 0.00, 0.00, 0.00, 0, 0],\n [ 0.90, -0.42, 0.00, 'BRANCH', 'Y', 45, 0],\n [ 0.90, -0.42, 0.00, 'NODE', 'Y', 45, 0],\n [ 1.81, -0.84, 0.00, 'BRANCH', 'Y', 45, 0],\n [ 0.00, 0.00, 0.00, 'BRANCH', 0.00, 0, 0],\n [ 0.00, 0.00, 0.00, 0.00, 0.00, 0, 0],\n [ 0.10, -0.99, 0.00, 0.00, 'Y', 45, 0],\n [-0.69, -1.59, 0.00, 0.00, 'Y', 45, 0],\n [-0.53, -2.58, 0.00, 'BRANCH', 'Y', 45, 0],\n [-0.53, -2.58, 0.00, 'NODE', 'Y', 45, 0],\n ], dtype=object)\n</code></pre>\n\n<p>It's more legible. In this case it actually violates PEP8, but this violation is actually worth it for the increase in legibility.</p>\n\n<p>Otherwise, you really need to make subroutines. If you care enough about performance, subroutines will help you understand the output of a profiler.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T07:15:07.247",
"Id": "442519",
"Score": "1",
"body": "You're right about readability, but I think a better approach would be to move this data to an external text file (maybe CSV to use `numpy.loadtxt`? I don't think JSON would be a good choice here)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T15:21:47.827",
"Id": "227338",
"ParentId": "227314",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T11:00:05.200",
"Id": "227314",
"Score": "2",
"Tags": [
"python",
"performance",
"graphics"
],
"Title": "Speed up shapely buffer"
}
|
227314
|
<p>Here is my take on Minesweeper in Java. Any feedback is welcome regarding readability, design or anything really.</p>
<p><strong>Cell.java</strong></p>
<pre class="lang-java prettyprint-override"><code>public class Cell {
public static final int BOMB = -1;
boolean revealed = false;
int row, col, val;
public Cell(int... coordinates) {
this.row = coordinates[0];
this.col = coordinates[1];
}
boolean isBomb() {
return val == BOMB;
}
boolean isEmpty() {
return val == 0;
}
}
</code></pre>
<p><strong>Board.java</strong></p>
<pre class="lang-java prettyprint-override"><code>class Board {
enum BoardResponse {
OK, BOMB, ALL_CELLS_REVEALED
}
Cell[][] rows;
// Returns a new Board with a few bombs and the values around the bombs.
public static Board newBoard() {
Board board = new Board();
board.rows = new Cell[7][7]; // todo: Accept parameters instead of 7,7
for (int i = 0; i < board.rows.length; i++)
for (int j = 0; j < board.rows[i].length; j++)
board.rows[i][j] = new Cell(i, j);
board.rows[1][1].val = Cell.BOMB; // todo: randomise bomb placement
board.rows[3][3].val = Cell.BOMB; // make sure bombs not adjacent
board.rows[5][5].val = Cell.BOMB;
// Fill bombs surroundings with values.
for (Cell[] row : board.rows)
for (Cell cell : row)
if (cell.isBomb())
board.surroundingCells(cell).forEach(c -> c.val = c.val + 1);
return board;
}
// Accepts a row and a column, modifies the state as needed and returns
// whether game is finished, a bomb has been clicked or game continues.
BoardResponse flipCell(int... coordinates) {
Cell clicked = rows[coordinates[0]][coordinates[1]];
clicked.revealed = true;
// Player lost
if (clicked.isBomb())
return BoardResponse.BOMB;
// Check if game finished, i.e. player won..
// For the game to finish all cells
// (except the ones holding bombs) must be revealed.
boolean allCellsRevealed = true;
isAllCellsRevealed:
for (Cell[] row : rows)
for (Cell cell : row)
if (!cell.revealed && !cell.isBomb()) {
allCellsRevealed = false;
break isAllCellsRevealed;
}
if (allCellsRevealed)
return BoardResponse.ALL_CELLS_REVEALED;
// If the cell clicked on is an empty cell,
// reveal all surrounding cells recursively until valued cells.
if (clicked.isEmpty()) {
Queue<Cell> queue = new LinkedList<>();
surroundingCells(clicked)
.stream().filter(c -> !c.revealed).forEach(queue::add);
while (!queue.isEmpty()) {
Cell cell = queue.remove();
cell.revealed = true;
if (cell.isEmpty()) {
Set<Cell> cells = surroundingCells(cell);
cells.stream().filter(c -> !c.revealed).forEach(queue::add);
}
}
}
return BoardResponse.OK;
}
// Given a single cell in the board, returns all surrounding cells in a Set.
private Set<Cell> surroundingCells(Cell cell) {
Set<Cell> surroundingCells = new HashSet<>();
// Cells in upper row
for (int i = cell.col - 1; i < cell.col + 2; i++)
if (inBounds(cell.row - 1, i))
surroundingCells.add(rows[cell.row - 1][i]);
// Cells in lower row
for (int i = cell.col - 1; i < cell.col + 2; i++)
if (inBounds(cell.row + 1, i))
surroundingCells.add(rows[cell.row + 1][i]);
// Cell to left
if (inBounds(cell.row, cell.col - 1))
surroundingCells.add(rows[cell.row][cell.col - 1]);
// Cell to right
if (inBounds(cell.row, cell.col + 1))
surroundingCells.add(rows[cell.row][cell.col + 1]);
return surroundingCells;
}
// Helper method to surroundingCells.
// Tries to access the cell in given coordinates handling OutOfBoundException.
private boolean inBounds(int... coordinates) {
try {
Cell cell = rows[coordinates[0]][coordinates[1]];
return true;
} catch (ArrayIndexOutOfBoundsException e) {
return false;
}
}
}
</code></pre>
<p>And here is a command line client I have:</p>
<pre class="lang-java prettyprint-override"><code>public class MinesweeperCli {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Board board = Board.newBoard();
Board.BoardResponse boardResponse;
do {
int row = in.nextInt();
int col = in.nextInt();
boardResponse = board.flipCell(row, col);
printBoard(board);
if (boardResponse == Board.BoardResponse.BOMB) {
System.out.println("Bomb!");
break;
}
} while (boardResponse != Board.BoardResponse.ALL_CELLS_REVEALED);
in.close();
}
public static void printBoard(Board board) {
StringBuilder sb = new StringBuilder();
for (Cell[] row : board.rows) {
for (Cell cell : row)
sb.append(cellRep(cell)).append(" ");
sb.append("\n");
}
System.out.println(sb.toString());
}
public static String cellRep(Cell cell) {
if (!cell.revealed)
return "-";
if (cell.isBomb())
return "*";
if (cell.isEmpty())
return ".";
return valueOf(cell.val);
}
}
</code></pre>
<p><strong>A Sample Run</strong></p>
<pre><code>0
0
1 - - - - - -
- - - - - - -
- - - - - - -
- - - - - - -
- - - - - - -
- - - - - - -
- - - - - - -
6
0
1 - - - - - -
- - - - - - -
1 1 2 - - - -
. . 1 - - - -
. . 1 1 2 - -
. . . . 1 - -
. . . . 1 - -
1
1
1 - - - - - -
- * - - - - -
1 1 2 - - - -
. . 1 - - - -
. . 1 1 2 - -
. . . . 1 - -
. . . . 1 - -
Bomb!
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>Unabbreviated names would be nicer.</li>\n<li>Immutable properties (row, column) should be made final.</li>\n<li>Package private <em>directly accessible</em> - especially mutable - fields are not liked.</li>\n<li><code>...</code> have their uses, but not here.</li>\n<li><code>{}</code> in generally also are Always used.</li>\n</ul>\n\n<p>So:</p>\n\n<pre><code>public class Cell {\n\n public static final int BOMB = -1;\n\n final int row;\n final col;\n\n boolean revealed;\n int value;\n\n public Cell(int row, int col) {\n this.row = row;\n this.col = col;\n }\n</code></pre>\n\n<p>Critics:</p>\n\n<ul>\n<li><code>cellRep</code> belongs more to class <code>Cell</code>. You could make it a <code>char</code> method, in order\nto have just one char, for the board representation.</li>\n<li><code>printBoard</code> belongs more to <code>Board</code>.</li>\n<li>You might consider the board size as constructor Parameters too.</li>\n</ul>\n\n<p>Design criticism:</p>\n\n<p><code>row</code> and <code>col</code> are redundant.</p>\n\n<p>There are also a couple of pitfalls you avoided, so in general the code is not bad.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T13:44:12.583",
"Id": "442385",
"Score": "0",
"body": "Thanks, I am planning on creating a UI with Swing so I am not sure if `printBoard` belongs to `Board`. Same for `cellRep`. Thank you for your valuable response."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T13:46:41.213",
"Id": "442387",
"Score": "0",
"body": "A `String toString()` would be nice for logging though. But okay."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T15:09:11.117",
"Id": "442402",
"Score": "0",
"body": "What “pitfalls” were avoided?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T15:32:20.970",
"Id": "442406",
"Score": "2",
"body": "@Peter using StringBuilder, using inBounds. Shows some insights. Despite not keeping to main-stream coding conventions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T11:20:55.873",
"Id": "442546",
"Score": "0",
"body": "@JoopEggen I see and makes sense. A `toString` ignoring `isRevealed` and only printing the values would be nice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T17:22:20.887",
"Id": "443279",
"Score": "0",
"body": "`row and col are redundant.` -> It is quite difficult to replace the `Set<Cell> cells = surroundingCells(row, col);` in depth-first search I have if I remove `row` and `col` from `Cell`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T06:45:19.010",
"Id": "443411",
"Score": "0",
"body": "@KorayTugay I agree that \"redundant\" is more a gray category. One could have `board.getSurroundingCells(row, col)` but that might require again other changes. I also often have redundantly a Map of X. key to X."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T13:37:16.647",
"Id": "227327",
"ParentId": "227315",
"Score": "5"
}
},
{
"body": "<p>It seems unclear what responsibilities the Cell class is supposed to have. You obtain a Cell from the Board and then query the cell for information about whether it is flipped or not but to flip a cell or get the surrounding cells you have to make a request to Board.</p>\n\n<p>To me it would make sense that the operations that are done on a Cell would be done through the Cell in question. The cell would provide information about whether it is flipped or not. Whether it has been flagged or not. It's status after flipping (empty, number of surrounding mines, bomb).</p>\n\n<p>The board would provide information about the state of the game and access to cells.</p>\n\n<p>Even though the model is internal to your CLI/Swing UI, you should still maintain separation of concerns. Access to object's fields should be done through accessor methods, not directly, and the fields should be private. Once you start modifying object's internal state from other objects you introduce yourself to a food fight in an Italian restaurant. That spaghetti gets really messy.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T10:59:58.303",
"Id": "442787",
"Score": "0",
"body": "Thank you for your valuable time and review. `Access to object's fields should be done through accessor methods` I really do not care much about this when just playing with code myself. \n\nRegarding `You obtain a Cell from the Board and then query the cell for information about whether it is flipped or not but to flip a cell or get the surrounding cells you have to make a request to Board.`, how would you do it? How can a single cell know about its surroundings?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T15:55:32.820",
"Id": "442864",
"Score": "0",
"body": "Please don't post if you're not interested in feedback. We're doing this for free and it just wastes our time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T16:02:17.510",
"Id": "442865",
"Score": "0",
"body": "I am not telling I am not interested in feedback. I actually asked you a specific question on your feedback, if you realised. I do not have to accept all the feedback, do I?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T07:45:58.190",
"Id": "227452",
"ParentId": "227315",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227327",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T11:31:19.037",
"Id": "227315",
"Score": "2",
"Tags": [
"java",
"game",
"minesweeper"
],
"Title": "Yet another Minesweeper implementation (in Java)"
}
|
227315
|
<p>As a guy who started coding a month ago, I would like an honest review of my version of breakout that I created using pygame.</p>
<pre><code>import pygame
import random
import sys
#level1
global level1
level1 =[
[0,0,0,0,1,1,1,0,0,0,0],
[0,0,0,0,1,1,0,0,0,0,0],
[0,0,1,1,1,1,1,1,0,0,0],
[0,0,0,1,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,1,0,0,1,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,1,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0]
]
def reset_array(array):
for line in array:
for i,num in enumerate(line):
if num == 2:
line[i] = 1
#colour
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
blue = (0,0,255)
#paddle
class paddle:
def __init__(self,x,y,width,height,vel):
self.x = x
self.y = y
self.width = width
self.height = height
self. vel = vel
Paddle = paddle(350,550,80,20,5)
def draw_paddle():
pygame.draw.rect(screen,red,(Paddle.x,Paddle.y,Paddle.width,Paddle.height))
#ball
class ball:
def __init__(self,x,y,rad,velx,vely):
self.x = x
self.y = y
self.rad = rad
self.velx = velx
self.vely = vely
Ball = ball(30,30,10,2,5)
def ball_move():
Ball.x -= Ball.velx
Ball.y -= Ball.vely
#block
class block:
def __init__(self,x,y,width,height):
self.x = x
self.y = y
self.width = width
self.height = height
Block = block(0,0,75,35)
def draw_block(self,array):
x = self.x
y = self.y
for line in array:
for character in line:
if character == 1:
pygame.draw.rect(screen,white,(x,y,self.width,self.height))
pygame.draw.rect(screen,red,(x,y,self.width,self.height),1)
x += self.width
y += self.height
x = 0
def draw_ball():
pygame.draw.circle(screen,white,(Ball.x,Ball.y), Ball.rad)
#init
pygame.init()
#window
swidth = 800
sheight = 600
screen = pygame.display.set_mode((swidth,sheight))
def main():
#gamestart bool
global gamestart
gamestart = False
#player lives
global player_lives
player_lives = 3
#main loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if player_lives <= 0:
reset_array(level1)
player_lives = 3
#paddlemove
key = pygame.key.get_pressed()
if key[pygame.K_a]:
Paddle.x -= Paddle.vel
if key[pygame.K_d]:
Paddle.x += Paddle.vel
if Paddle.x + 80 < 0:
Paddle.x += swidth
if Paddle.x >= swidth:
Paddle.x -= swidth
#ballmove
posx = Ball.y
posy = Ball.x
row = posx // 35
column = posy // 75
if level1[row][column] == 1:
level1[row][column] = 2
Ball.vely = -Ball.vely
if gamestart == False:
Paddle.x = 350
Ball.x = Paddle.x + 40
Ball.y = Paddle.y - 10
Ball.velx = 2
Ball.vely = 5
if key[pygame.K_SPACE]:
gamestart = True
if gamestart == True:
ball_move()
if Ball.y <= 0:
Ball.vely = - Ball.vely
if Ball.y >= 600:
gamestart = False
player_lives -= 1
print(player_lives)
if Ball.x <= 0:
Ball.velx = - Ball.velx
if Ball.x >= 800:
Ball.velx = - Ball.velx
#collision
if Paddle.x <= Ball.x <= Paddle.x +44 and Paddle.y == Ball.y:
Ball.vely = - Ball.vely
if Ball.x > Paddle.x:
Ball.velx = Ball.velx
if Ball.x < Paddle.x:
Ball.velx = -Ball.velx
if Paddle.x +45 <= Ball.x <= Paddle.x +80 and Paddle.y == Ball.y:
Ball.vely = - Ball.vely
if Ball.x < Paddle.x:
Ball.velx = - Ball.velx
if Ball.x > Paddle.x:
Ball.velx = Ball.velx
#game end
victory = False
for line in level1:
for col in line:
if all(all(item != 1 for item in item)for item in level1):
victory = True
if victory == True:
print("you win")
break
screen.fill(blue)
draw_paddle()
draw_ball()
draw_block(Block,level1)
pygame.display.flip()
main()
</code></pre>
|
[] |
[
{
"body": "<p>Welcome to CodeReview!</p>\n\n<h2>Formatting</h2>\n\n<p>Get an IDE such as PyCharm or VSCode that's capable of linting. It will give you several \"PEP8\" suggestions, such as newlines around functions, that will make your code more legible. Some particulars that will be suggested:</p>\n\n<ul>\n<li><code>paddle</code> = <code>Paddle</code> (classes)</li>\n<li><code>black</code> = <code>BLACK</code> (global constants)</li>\n<li><code>Ball</code> = <code>ball</code> and vice versa - instance variables should be lowercase, classes uppercase</li>\n</ul>\n\n<h2>Avoid globals</h2>\n\n<p>They're a messy way of tracking information. In particular, <code>ball</code> and <code>block</code> instances, and the <code>screen</code> instance should be moved to local variables, maybe class members.</p>\n\n<h2>Simplify logic</h2>\n\n<pre><code>if Paddle.x + 80 < 0:\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>if Paddle.x < -80:\n</code></pre>\n\n<h2>Global code</h2>\n\n<pre><code>pygame.init()\n#window\nswidth = 800\nsheight = 600\nscreen = pygame.display.set_mode((swidth,sheight))\n</code></pre>\n\n<p>Stuff like this should move into your <code>main</code> function.</p>\n\n<h2>Long methods</h2>\n\n<p><code>main</code> should be subdivided into several subroutines for legibility and maintainability.</p>\n\n<h2>Magic numbers</h2>\n\n<p>\"44\" doesn't mean much to us, and in six months it probably won't mean much to you either. It's best to put this and similar quantities into named constants.</p>\n\n<h2>Nested <code>all</code></h2>\n\n<pre><code>if all(all(item != 1 for item in item)for item in level1):\n</code></pre>\n\n<p>You don't need an inner <code>all</code>. One level of <code>all</code> and two inner comprehension loops will work.</p>\n\n<h2>Level data</h2>\n\n<p>Your <code>level1</code> array is a reasonable representation of the level during program runtime. However, it's verbose to construct manually. You'd probably be better off representing this with a more compact string-based format and parsing it out on program load.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T13:28:11.207",
"Id": "227324",
"ParentId": "227318",
"Score": "4"
}
},
{
"body": "<pre><code>#level1\nglobal level1\n</code></pre>\n\n<p>The comment here is not useful, if you have a variable <code>level1</code>, well... that's <code>level1</code>, right?</p>\n\n<p>The same goes for all your other comments in the code. You should think of comments as a way to describe why you did things that specific way or the meaning of something. If you need them to describe what is happening, most likely you need to refactor something.</p>\n\n<p>Also, as already pointed out in the other answers, this is a global variable, which in this case would not be terrible except that if it's <code>level1</code>, you probably also expect to have <code>level2</code> and maybe <code>level3</code>, which would make it quite ugly, especially if you hardcode your levels in the module.</p>\n\n<p>You might want to look into loading a text file into a variable. You might have different text files named <code>level1.txt</code>, <code>level2.txt</code> and so on, depending on the level.</p>\n\n<pre><code>class paddle:\n def __init__(self,x,y,width,height,vel):\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n self. vel = vel\nPaddle = paddle(350,550,80,20,5)\ndef draw_paddle():\n pygame.draw.rect(screen,red,(Paddle.x,Paddle.y,Paddle.width,Paddle.height))\n</code></pre>\n\n<p>You have a class paddle (as already noted it should be <code>Paddle</code>), so why not having the <code>draw</code> inside the class?</p>\n\n<p>That way you'd have something like:</p>\n\n<pre><code>class Paddle:\n def __init__(self,x,y,width,height,vel):\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n self. vel = vel\n\n def draw(self):\n pygame.draw.rect(screen,red,(self.x, self.y, self.width, self.height))\n\npaddle = Paddle(350,550,80,20,5)\n...\npaddle.draw()\n</code></pre>\n\n<p>The same goes for <code>block</code> and <code>ball</code>.</p>\n\n<p>Actually, you could go the extra mile and have a list of objects on which you loop to call the <code>draw</code> and maybe a possible <code>update</code> function.</p>\n\n<p>Something like:</p>\n\n<pre><code>game_objects = [Paddle(350,550,80,20,5), Block(0,0,75,35), Ball(30,30,10,2,5)]\nfor game_object in game_objects:\n game_object.update()\n game_object.draw()\n</code></pre>\n\n<p>As already noted, these magic numbers (e.g. <code>row = posx // 35</code>) are better written as constants, even if you use them only once, to explain their meaning.</p>\n\n<pre><code>if Paddle.x <= Ball.x <= Paddle.x +44 and Paddle.y == Ball.y:\n Ball.vely = - Ball.vely\n if Ball.x > Paddle.x:\n Ball.velx = Ball.velx\n if Ball.x < Paddle.x:\n Ball.velx = -Ball.velx\nif Paddle.x +45 <= Ball.x <= Paddle.x +80 and Paddle.y == Ball.y:\n Ball.vely = - Ball.vely\n if Ball.x < Paddle.x:\n Ball.velx = - Ball.velx\n if Ball.x > Paddle.x:\n Ball.velx = Ball.velx\n</code></pre>\n\n<p>This is a block of code that is prone to errors, because of the multiple conditions check and the multiple nested <code>if</code>s.</p>\n\n<p>You don't need the <code>Ball.velx = Ball.velx</code> line, that doesn't do anything, which mean that you can remove that check.</p>\n\n<p>There's also an issue with checking a strict <code>Paddle.y == Ball.y</code> because if you increase the speed of the ball, there's the chance that it will go past the paddle's <code>y</code> and not be detected, so you should check if the ball's <code>y</code> plus the ball's height is within the paddle's <code>y</code> plus the paddle's height.</p>\n\n<p>The outer <code>if</code> would also be more readable if you put that in a function and called it with the specific parameters, something like:</p>\n\n<pre><code>if paddle_and_ball_collided(paddle, ball):\n Ball.vely = - Ball.vely\n if Ball.x < Paddle.x:\n Ball.velx = -Ball.velx\n</code></pre>\n\n<p>You should also look into the integrated collision detection functions from pygame, they can save you a bit of trouble (see e.g. <a href=\"https://stackoverflow.com/questions/29640685/how-do-i-detect-collision-in-pygame\">https://stackoverflow.com/questions/29640685/how-do-i-detect-collision-in-pygame</a> )</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T14:41:09.377",
"Id": "227335",
"ParentId": "227318",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T11:58:26.057",
"Id": "227318",
"Score": "4",
"Tags": [
"python",
"beginner",
"array",
"pygame"
],
"Title": "Breakout clone in pygame"
}
|
227318
|
<p>I am pulling some financial data from the <a href="https://iexcloud.io/docs/api/" rel="nofollow noreferrer">IEX Cloud API</a>. Since it is a paid API w/ <a href="https://iexcloud.io/docs/api/#streaming" rel="nofollow noreferrer">rate limits</a>, I would like to do this as efficiently as possible (i.e., as few calls as possible). Given that the <code>tickers</code> list is likely to have thousands of indexes (oftentimes with duplicates), is there a better/more efficient way than what I'm currently doing? </p>
<p>(Feel free to use the token in the code, as there is no limit to the number of API calls that you can make to sandboxed data.)</p>
<pre><code>import os
from iexfinance.stocks import Stock
import iexfinance
import pandas as pd
# Set IEX Finance API Token (Test)
os.environ['IEX_API_VERSION'] = 'iexcloud-sandbox'
os.environ['IEX_TOKEN'] = 'Tsk_5798c0ab124d49639bb1575b322841c4'
# List of ticker symbols
tickers = ['MSFT', 'V', 'ERROR', 'INVALID', 'BRK.B', 'MSFT']
# Create output Dataframe
output_df = pd.DataFrame(columns=['Net Income', 'Book Value'])
# Loop through companies in tickers list
for ticker in tickers:
# Call IEX Cloud API, and output to Dataframe
try:
company = Stock(ticker, output_format='pandas')
try:
# Get income from last 4 quarters, sum it, and store to temp Dataframe
df_income = company.get_income_statement(period="quarter", last='4')
df_income['TTM'] = df_income.sum(axis=1)
income_ttm = int(df_income.loc['netIncome', 'TTM'])
# Get book value from most recent quarter, and store to temp Dataframe
df_book = company.get_balance_sheet(period="quarter")
book_value = int(df_book.loc['shareholderEquity'])
# If IEX Cloud errors, make stats = 0
except (iexfinance.utils.exceptions.IEXQueryError, TypeError, KeyError) as e:
book_value = 0
income_ttm = 0
# Store stats to output Dataframe
output_df.loc[ticker] = [income_ttm, book_value]
except ValueError:
pass
print(output_df)
</code></pre>
|
[] |
[
{
"body": "<p>This seems mostly to be an API question? Assuming all that data for\neach of the companies is required and there's no combined API endpoint\nthat can be fed with, say, 10s or 100s of symbols, this would seem to\nbe the best way. If so, there'd still be possible concurrent execution\noptions to make multiple API requests at the same time and possible get\nmore throughput with it, though the number of API calls would still be\nthe same.</p>\n\n<p>The <a href=\"https://iexcloud.io/docs/api/#streaming\" rel=\"nofollow noreferrer\">streaming endpoints</a> looking interesting at first, but they don't support the data here; any other endpoints all look like they only accept single symbols.</p>\n\n<hr>\n\n<p>What you should definitely do is create a (few) function(s) and ideally\nget rid of the <code>try</code> blocks. From a first look I've zero idea where\nstuff gets thrown. But I'm guessing mostly keys not being present.\nPreferably this could be handled directly (with default values or\nsimilar features) that do not require lots of exception handling. Yes,\nPython might encourage this, but simply catching <code>ValueError</code> around a\nhuge block will eventually catch unintended exceptions too.</p>\n\n<p>So at least something like this would be a good start:</p>\n\n<pre><code>def fetch_company_info(ticker):\n company = Stock(ticker, output_format='pandas')\n\n book_value = 0\n income_ttm = 0\n\n try:\n # Get income from last 4 quarters, sum it, and store to temp Dataframe\n df_income = company.get_income_statement(period=\"quarter\", last=4)\n df_income['TTM'] = df_income.sum(axis=1)\n income_ttm = int(df_income.loc['netIncome', 'TTM'])\n\n # Get book value from most recent quarter, and store to temp Dataframe\n df_book = company.get_balance_sheet(period=\"quarter\")\n book_value = int(df_book.loc['shareholderEquity'])\n\n # Ignore IEX Cloud errors\n except iexfinance.utils.exceptions.IEXQueryError:\n pass\n\n return income_ttm, book_value\n</code></pre>\n\n<p>I also shuffled the variables a bit around - with the right order this\ncould even be type checked ...</p>\n\n<p>In any case, I can't see anything wrong here and I've removed the other\ntwo exceptions as they look more like hiding problems than actual proper\nhandling of the exact problem that was encountered. With the example\nnames I also couldn't trigger them at all.</p>\n\n<p>The main body of the script is now rather small:</p>\n\n<pre><code># Loop through companies in tickers list\nfor ticker in tickers:\n # Call IEX Cloud API, and store stats to Dataframe\n output_df.loc[ticker] = fetch_company_info(ticker)\n\nprint(output_df)\n</code></pre>\n\n<p>If there's no need for reusability then that's it, otherwise I'd suggest\na <code>main</code> function and moving all currently global definitions into it,\nthen have some argument parser or configuration file handling, etc. to\nmake it a more fully grown solution.</p>\n\n<hr>\n\n<p>After some discussion in the comments it turns out that splitting the\nreturn values from the assignment can lead to easy mistakes like the\norder of the values being wrong. With that in mind, either the <code>output_df</code>\nglobal should be kept in the function, or (better) be passed in as\na variable instead:</p>\n\n<pre><code>for ticker in tickers:\n fetch_company_info(ticker, output_df)\n</code></pre>\n\n<p>and</p>\n\n<pre><code>def fetch_company_info(ticker, output_df):\n ...\n output_df[ticker] = [income_ttm, book_value]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T23:23:35.573",
"Id": "442476",
"Score": "1",
"body": "I did come across this [recent post](https://intercom.help/iexcloud/en/articles/2852094-how-do-i-query-multiple-symbols-or-data-types-in-one-api-call) from the API provider, and it sounds like you can batch calls up to 100 at a time. Not sure if that changes any of the approach or not though?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T09:38:52.680",
"Id": "442536",
"Score": "1",
"body": "Ah yes, go for that. The general approach would be largely the same, you'll just have to split the ticker symbols into (arbitrary-sized) batches and then detangle the output into separate rows again. Plus the error handling might be a bit more complicated if only some of the symbols aren't available etc., but that's the price for more efficient calls I'd say."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T19:12:49.807",
"Id": "442684",
"Score": "1",
"body": "Okay cool, thanks for the help. So I should store all the symbols to one global list, then loop through that list 100 indexes at a time—each time writing to the ```output_df```?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T00:02:38.337",
"Id": "442703",
"Score": "0",
"body": "Shouldn't ```output_df.loc[ticker] = [income_ttm, book_value]``` be inside the function; otherwise the totals for ```income_ttm``` and ```book_value``` are wrong.? I think what's happening is it's looping through ```tickers``` and then adding ```netIncome``` _n_ # of indexes that are in ```tickers```. So if I move ```output_df.loc[ticker] = [income_ttm, book_value]``` inside the function, and then simply do: ```for ticker in tickers:\n fetch_company_info(ticker)``` then it looks correct."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T11:16:33.430",
"Id": "442792",
"Score": "0",
"body": "Looping through the list, by chunks of 100, then write to `output_df`, yes, sounds like it.\n\nThe assignment to `output_df` you could do in the function, sure, but global variables are really something avoid in general. And I don't see actually why you can't simply return the values from the function, that's much cleaner. What totals? In the original function there's no adding up of any values at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T15:18:53.693",
"Id": "442856",
"Score": "0",
"body": "Not sure if it's the way the Dataframes are setup or something, but if you run the code in the original post vs your proposed changes, the values for ```income_ttm``` and ```book_value``` are way different. I can fix this if I move ```output_df.loc[ticker] = [income_ttm, book_value]``` into the function and out of the loop. Note that the numbers returned by the API are randomized within +/-5%. But when running your proposed changes, the returned numbers are far outside this range."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T15:28:56.500",
"Id": "442859",
"Score": "1",
"body": "Never mind, looks it's just returning ```income_ttm``` and ```book_value``` in the opposite order from what I was expecting. My mistake."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T19:17:31.960",
"Id": "442893",
"Score": "1",
"body": "Oops. Fixed. To be fair that's a good confirmation that it should be moved into the function :)"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T21:19:03.973",
"Id": "227360",
"ParentId": "227322",
"Score": "2"
}
},
{
"body": "<p>The most suspicious thing to me is this:</p>\n\n<pre><code>except ValueError:\n pass\n</code></pre>\n\n<p>It's on a very broad <code>try</code> block, which leads me to believe that it was thrown in to attempt a pseudo fail-safe loop. Fail-safe loops are not a bad thing, but this isn't a great way to go about it. Contrary to most circumstances, it's actually a good idea here to broaden your caught exception class to <code>Exception</code>, so long as you output the error before continuing with the loop.</p>\n\n<p>I'll also say: if <code>ValueError</code> is produced by a condition that you know and understand, try to check for that condition before it raises an exception, print a message and continue. And/or - if you understand the source line of this common exception but aren't able to check for failure conditions beforehand, apply a narrower try/catch to only that line, again emitting a sane message and continuing on with your loop.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T02:40:46.837",
"Id": "227370",
"ParentId": "227322",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227360",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T13:15:34.323",
"Id": "227322",
"Score": "4",
"Tags": [
"python",
"performance",
"api",
"pandas",
"finance"
],
"Title": "Pulling financial data via IEX Cloud API"
}
|
227322
|
<p>I am trying to do certain operations in dataframe as shown in my code below. Though this works fine.However I am repeating the same statements twice or following a dirty approach to perform the operations twice. Can you help me to make it efficient and elegant?</p>
<p>I have a dataframe <code>df</code> in which I have to apply certain rules (see at the bottom <code>PEEP_con</code> and <code>Fio2_con</code>). <code>PEEP_con</code> has to be applied only to records with <code>item_name</code> == <code>PEEP</code> (<code>df_P</code>) and <code>FiO2_con</code> to <code>item_name</code> == <code>Fio2</code> (<code>df_F</code>)</p>
<p>Before I apply the final conditions, I do certain preprocessing tasks which is 100 pc same for both the conditions but has to be done once for <code>df_P</code> and <code>df_F</code> . Hope this helps</p>
<p>Please find my code below (credit to SO users for help)</p>
<pre><code>df = pd.read_csv('sample_data.csv')
df['charttime'] = pd.to_datetime(df['charttime'])
df = df.loc[df.value.mod(1).eq(0)] # removes records with values like 5.4,6.1 etc
# I am creating two dataframes here. Is it possible to do this on the fly without creating two dataframes
df_P = df[df['item_name'] == 'PEEP']
df_P['value'] = np.where(df_P['value'] < 5, 5, df_P['value'])
df_F = df[df['item_name'] == 'Fi02/100']
# for the first time, I manually keep it to df_P and later I change it to df_F manually
dfa = df_F
# below operations is same for both the dataframes
m = dfa.assign(date=dfa.charttime.dt.date).groupby(['date',dfa.value.ne(dfa.value.shift()).cumsum()]).first().reset_index(drop=True)
c = pd.to_timedelta(24,unit='h')-(m.charttime-m.charttime.dt.normalize())
m['total_hr'] = m.groupby(['subject_id'])['charttime'].diff().shift(-1).fillna(c).dt.total_seconds()/3600
final_df = m.assign(date = m.charttime.dt.date)
gone_hr = final_df[final_df['total_hr'] > 1]
lone_hr = final_df[final_df['total_hr'] < 1]
min_gone_hr_data = gone_hr.groupby(['subject_id','date'])['value'].min().reset_index()
min_lone_hr_data = lone_hr.groupby(['subject_id','date'])['value'].min().reset_index()
op1 = gone_hr.merge(min_gone_hr_data, on = ['subject_id','date','value'],how = 'inner')
op2 = lone_hr.merge(min_lone_hr_data, on = ['subject_id','date','value'],how = 'inner')
op = (op1.set_index(['subject_id','date']).combine_first(op2.set_index(['subject_id','date'])).reset_index())
# This condition is only for `df_P`
PEEP_con = lambda x: (x.shift(2).ge(x.shift(1))) & (x.ge(x.shift(2).add(3))) & (x.shift(-1).ge(x.shift(2).add(3)))
# This condition is only for `df_F`
Fi02_con = lambda x: (x.shift(2).ge(x.shift(1))) & (x.ge(x.shift(2).add(20))) & (x.shift(-1).ge(x.shift(2).add(20)))
# this field should only be applied for df_P
op['fake_VAC'] = op.groupby('subject_id')['value'].transform(PEEP_con).map({True:'fake VAC',False:''})
# this field should only be applied for df_F
op['Fi02_flag'] = op.groupby('subject_id')['value'].transform(Fi02_con).map({True:'VAC',False:''})
</code></pre>
<p>I request your inputs in making this more elegant and efficient. Though suggestions w.r.t to logic are welcome, I am mostly looking for ways to optimize the code structure</p>
<p>Currently I generate two csv file output (one for PEEP and other for Fi02). Instead I would like to have both the columns <code>Fi02_flag</code> and <code>fake_VAC</code> in the same csv file (one final dataframe)</p>
|
[] |
[
{
"body": "<p>You're indeed doing a lot of stuff twice. The first step is recognizing that you have a problem :D</p>\n\n<p>The following collection of functions could be used to decrease the repetition:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def load_df(item_name):\n return df[df['item_name'] == item_name]\n\ndef get_hr_op(predicate):\n \"\"\" Predicate is a lambda \"\"\"\n hr = final_df[predicate(final_df['total_hr'])]\n min_hr = hr.groupby(['subject_id','date'])['value'].min().reset_index()\n op = hr.merge(min_hr, on = ['subject_id','date','value'],how = 'inner')\n return op.set_index(['subject_id','date'])\n\ndef make_con(add_qty):\n def con(x):\n return (\n x.shift(2).ge(x.shift(1))\n ) & (\n x.ge(x.shift(2).add(3))\n ) & (\n x.shift(-1).ge(\n x.shift(2).add(add_qty)\n )\n )\n return con\n\ndef apply_field(name, title, add_qty):\n con = make_con(add_qty)\n op[name] = op.groupby('subject_id')['value'].transform(con).map({True:title,False:''})\n\n</code></pre>\n\n<p>You get the idea. Basically, functions are your friend. There may be some fancier way of cleaning this up using Pandas-specific stuff, but this is the Python way.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T14:11:46.947",
"Id": "442398",
"Score": "0",
"body": "Will try now. Thanks. Upvoted"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T13:43:36.453",
"Id": "227328",
"ParentId": "227323",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "227328",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T13:18:31.277",
"Id": "227323",
"Score": "1",
"Tags": [
"python",
"pandas"
],
"Title": "Elegant way to do the dataframe operations twice"
}
|
227323
|
<p>I have a settings file, which is loaded in once and takes the values from the settings json file and uses them as the attribute values. I was thinking of using the <code>@property</code> instead of overriding <code>__getattribute__</code> but I feel as if there is a better, more elegant solution. Note that the application it is used in is multi-threaded.</p>
<p><strong>settings.py</strong></p>
<pre><code>class SettingsMeta(type, JsonFileWrapperBase):
_file_path = os.path.join(os.getcwd(), "..", "data", "settings.json")
# Declarations to avoid PyCharm highlighting
manga_save_dir, database_path, total_scrapper_threads, log_file = None, None, None, None
_default_data = {
"manga_save_dir": r"D:\dir",
"database_path": r"D:\db.sqlite3",
"log_file": os.path.join(os.getcwd(), "..", "data", "log.log"),
"total_scrapper_threads": 1
}
@classmethod
def __getattribute__(mcs, item):
data = mcs._get_data()
if item in data:
return data[item]
elif hasattr(mcs, item):
return getattr(mcs, item)
raise AttributeError(f"Settings has no attribute {item}")
class Settings(metaclass=SettingsMeta):
pass
</code></pre>
<p><strong>json_file_wrapper_base.py</strong></p>
<pre><code>class JsonFileWrapperBase:
_loaded_data = None
_file_path = ""
_default_data = ""
@classmethod
def _write_default(cls):
cls._write_data(cls._default_data)
@classmethod
def _write_data(cls, d):
os.makedirs(os.path.dirname(os.path.abspath(cls._file_path)), exist_ok=True)
try:
with open(cls._file_path, "w") as f:
json.dump(d, f)
except FileNotFoundError as e:
print(e)
@classmethod
def _get_data(cls):
"""
Reads and caches the JSON file, if the file has already been cached then return the cached file, I cache
the file to avoid users editing the file during execution and causing errors
"""
# File has not been cached yet
if cls._loaded_data is None:
cls._read_file()
return cls._loaded_data
@classmethod
def _read_file(cls) -> bool:
assert cls._loaded_data is None, "_read_file should only be called once per object"
# File doesn't exist or is not valid
if not os.path.isfile(cls._file_path):
cls._write_default()
try:
with open(cls._file_path, "r") as f:
data = json.load(f)
print(f"Log: Loaded {cls._file_path}")
cls._loaded_data = data
except FileNotFoundError as e:
print(e)
return False
return True
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T15:46:03.993",
"Id": "442408",
"Score": "1",
"body": "Please add your imports. This is especially important since you use `JsonFileWrapperBase._get_data`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T15:49:51.610",
"Id": "442409",
"Score": "1",
"body": "I don't think the base class is relevant to my question about best practises forwarding values from JSON but I added it to my question neverthless."
}
] |
[
{
"body": "<h2>Pathlib</h2>\n\n<p>Use it. It makes stuff like this:</p>\n\n<pre><code>os.path.join(os.getcwd(), \"..\", \"data\", \"log.log\"),\n</code></pre>\n\n<p>much nicer. It can also avoid this kind of thing:</p>\n\n<pre><code>\"D:\\dir\"\n</code></pre>\n\n<p>namely, OS-specific directory separators. If you ever hope to have this be cross-platform, you'll want to remove your backslashes and use the libraries for path manipulation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T16:32:46.163",
"Id": "442424",
"Score": "0",
"body": "OK. First thing is that the base class is in a different file. i only added due to a comment (I'll make it clearer in my question). Second, the assert is a very last resort I used for debugging, It will never be called. Thirdly, as you can see I use a metaclass as solely overriding ```__getattribute__``` doesn't work for which ```mcs``` is standard."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T16:40:01.277",
"Id": "442427",
"Score": "0",
"body": "It was an formatting error regarding your ```assert``` comment. You haven't actually answered my question regarding forwarding values from JSON."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T16:43:45.570",
"Id": "442430",
"Score": "0",
"body": "That's true! And it doesn't matter - refer to https://codereview.meta.stackexchange.com/questions/5773/is-it-okay-to-give-a-review-without-actually-answering-some-of-the-ops-requests"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T16:45:30.127",
"Id": "442431",
"Score": "0",
"body": "Ok, thats fair enough."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T16:26:52.313",
"Id": "227346",
"ParentId": "227340",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T15:38:28.840",
"Id": "227340",
"Score": "7",
"Tags": [
"python",
"json"
],
"Title": "Forward values from JSON file as class attributes"
}
|
227340
|
<p>In part one (<a href="https://codereview.stackexchange.com/questions/225537/tkinter-program-to-teach-arabic">Tkinter program to teach Arabic</a>) I was asking for help to review the part of the program responsible for managing the main screens and links to all of the different lessons. From the responses I got, I was able to reduce a lot of redundancies in my code thru the use of classes (a new skill for me) and was able to clean my code up to comply with PEP 8 and hopefully improve the readability of the code. </p>
<p>In this post, I am looking at the second part of my program. This part is stored in a separate .py file and is responsible for loading the actual content of a lesson selected from the main program. </p>
<p>I'm hoping to get some pointers on the use of global variables. Almost everything I can read on the internet talks about how bad they are but for me I can't quite see how I could do what I'm doing without them. I have five different variables declared as global. Any commentary on why they might be good or bad for my program would be very helpful. If they do need to go, then suggestions on "how to" would be helpful. </p>
<pre><code>"""
Module Docstring:
This is the lesson template for almost all of the lesson plans Liblib Aribi.
It includes different types of quesitons such as: multiple choice, entry box, matching, and sentance re-ordering questions.
"""
import os
import random
import winsound
import tkinter
##from tkinter import *
from tkinter import Label, Button, IntVar, Radiobutton, PhotoImage, Entry, Toplevel, ttk
import json
SCORE = None #Defining Global Variables
LIVES = None
VAR = None
WORD_POSITION = None
USER_ANSWER = None
STANDARD_CONFIGS = {
"active":
{"rel": tkinter.SUNKEN, "color": "gold"},
"inactive":
{"rel": tkinter.RAISED, "color": "gray95"},
"width": "100",
"height": "100",
"bg": "gray",
"font": {
"bodytext": ("Helvetica", 15),
"title": ("Helvetica", 35),
"title2": ("Helvetica", 25),
"secondaryhedding": ("Helvetica", 20)
},
"borderwidth": "2",
"disabled": tkinter.DISABLED
}
class CheckAnswers:
"""
This class checkes the given answer against the stated correct answer
and adjusts the scoring and live counter accordinly.
"""
def __init__(self, sf, cho, noa):
self.specialframes = sf
self.choices = cho
self.no_of_answers = noa
def wrong_answer(self):
global LIVES
global SCORE
self.specialframes[1].grid_remove() #Right answer frame
self.specialframes[0].grid(column=1, row=0, rowspan=2) #Wrong answer frame
LIVES -= 1
incorrect_button = Label(
self.specialframes[0],
text=f"That's incorrect!\n Lives: {str(LIVES)}\n Score: {str(SCORE)}",
font=STANDARD_CONFIGS["font"]["title"])
incorrect_button.grid(row=0, rowspan=2, column=0, columnspan=3)
def right_answer(self):
global LIVES
global SCORE
self.specialframes[0].grid_remove() #Wrong answer frame
self.specialframes[1].grid(column=1, row=0, rowspan=2) #Right answer frame
correct_button = Label(
self.specialframes[1],
text=f" That's right! \n Lives: {str(LIVES)}\n Score: {str(SCORE)}",
font=STANDARD_CONFIGS["font"]["title"])
correct_button.grid(row=0, rowspan=2, column=0, columnspan=5)
if self.no_of_answers is not None:
for i in range(self.no_of_answers):
self.choices[i].config(state=STANDARD_CONFIGS["disabled"])
def lesson_template(lesson_name, jfn, lesson_type):
"""
This function loads a pre-determined json file to quiz the user.
"""
root_file_name = "C:\\LearningArabic\\LiblibArriby\\"
lesson_file_path = f"{root_file_name}Lessons\\{lesson_name}\\"
with open(
f"{lesson_file_path}{jfn}.json",
"r",
encoding="utf-8-sig") as question_file:
data = json.load(question_file)
no_of_questions = (len(data["lesson"])) #Counts the number of questions in the .json file
if lesson_type == "quiz":
no_of_quiz_questions = 8
if lesson_type == "short":
no_of_quiz_questions = 4
if lesson_type == "conversation":
no_of_quiz_questions = 1
if lesson_type == "long":
no_of_quiz_questions = 8
global WORD_POSITION
WORD_POSITION = 0
def question_frame_populator(frame_number, data, current_frame, question_number):
question_directory = data["lesson"][question_number]
question = question_directory.get("question")
questiontype = question_directory.get("questiontype")
correctanswer = question_directory.get("answer")
arabic = question_directory.get("arabic")
english_transliteration = question_directory.get("transliteration")
if english_transliteration is None:
english_transliteration = "N/A"
sound = question_directory.get("pronounciation")
image = question_directory.get("image")
image_location = os.path.join(image_path, f"{image}")
if questiontype == "mc":
if os.path.isfile(image_location):
arabic_image = PhotoImage(file=image_location)
image_label = Label(current_frame, image=arabic_image)
image_label.image = arabic_image
image_label.grid(row=1, rowspan=4, column=0, columnspan=2)
maine_question = Label(
current_frame,
text=question,
font=STANDARD_CONFIGS["font"]["title"],
wraplength=500)
transliteration_button = Button(
current_frame,
text="Show Transliteration",
font=STANDARD_CONFIGS["font"]["bodytext"],
command=lambda: transliteration(
current_frame,
arabic,
english_transliteration))
next_button(frame_number) # Creates the "next" button and displays it.
quit_program_button(current_frame) # Creates the "quit" button and displays it.
pronounciation_button = Button(
current_frame,
text="Listen",
font=STANDARD_CONFIGS["font"]["bodytext"],
command=lambda: pronounciation(sound))
maine_question.grid(columnspan=4, row=0)
if english_transliteration != "N/A":
transliteration_button.grid(column=0, row=5, columnspan=2)
pronounciation_button.grid(column=2, row=5, columnspan=1)
wronganswer = question_directory["wronganswer"]
global VAR
VAR = IntVar()
VAR.set(0) #Sets the initial radiobutton selection to nothing
answers = generate_answers(wronganswer, correctanswer)
no_of_answers = len(answers)
choices = []
for i in range(4):
choice = Radiobutton(
current_frame,
text=answers[i],
variable=VAR,
value=i+1,
font=STANDARD_CONFIGS["font"]["bodytext"],
command=lambda: check_mc_answer(choices, no_of_answers)
)
#choice.image = answers[i]
choices.append(choice)
random.shuffle(choices) #Randomizes the order of the radiobuttons.
if os.path.isfile(image_location):
choices[0].grid(row=1, column=2, columnspan=2)
choices[1].grid(row=2, column=2, columnspan=2)
choices[2].grid(row=3, column=2, columnspan=2)
choices[3].grid(row=4, column=2, columnspan=2)
if not os.path.isfile(image_location):
choices[0].grid(row=1, column=1, columnspan=2)
choices[1].grid(row=2, column=1, columnspan=2)
choices[2].grid(row=3, column=1, columnspan=2)
choices[3].grid(row=3, column=1, columnspan=2)
if questiontype == "eb":
if os.path.isfile(image_location):
arabic_image = PhotoImage(file=image_location)
image_label = Label(current_frame, image=arabic_image)
image_label.image = arabic_image
image_label.grid(row=1, rowspan=3, column=0, columnspan=2)
main_question = Label(
current_frame,
text=question,
font=STANDARD_CONFIGS["font"]["title"],
wraplength=500)
transliteration_button = Button(
current_frame,
text="Show Transliteration",
font=STANDARD_CONFIGS["font"]["bodytext"],
command=lambda: transliteration(
current_frame,
arabic,
english_transliteration))
next_button(frame_number) # Creates the "next" button and displays it
quit_program_button(current_frame) # Creates the "quit" button
pronounciation_button = Button(
current_frame,
text="Listen",
font=STANDARD_CONFIGS["font"]["bodytext"],
command=lambda: pronounciation(sound))
entry_box = Entry(
current_frame,
width=20,
font=STANDARD_CONFIGS["font"]["secondaryhedding"])
entry_box.focus()
check_answer_button = Button(
current_frame,
text="Check Answer",
font=STANDARD_CONFIGS["font"]["secondaryhedding"],
command=lambda: check_entry_box(entry_box, correctanswer))
main_question.grid(column=0, row=0, columnspan=4)
entry_box.grid(column=1, row=1, columnspan=2)
check_answer_button.grid(column=1, row=3, columnspan=2)
if english_transliteration != "N/A":
transliteration_button.grid(column=0, row=5, columnspan=2)
pronounciation_button.grid(column=2, row=5, columnspan=1)
if questiontype == "matching":
no_of_statements = (len(data["lesson"]))
list_of_sentances = []
list_of_answers = []
list_of_sounds = []
for i in range(no_of_statements):
directory = data["lesson"][f"question{str(i)}"]
sentance = directory.get("question")
list_of_sentances.append(sentance)
answer = directory.get("answer")
list_of_answers.append(answer)
sound = directory.get("pronounciation")
list_of_sounds.append(sound)
paired = []
for i in range(no_of_statements):
pair = (list_of_sentances[i],
list_of_answers[i],
list_of_sounds[i])
paired.append(pair)
random.shuffle(paired)
for i in range(no_of_statements):
sound_button = Button(
current_frame,
text="Listen",
font=STANDARD_CONFIGS["font"]["bodytext"],
command=lambda i=i: pronounciation(paired[i][2]))
sound_button.grid(column=0, row=i+1)
for i in range(no_of_statements):
label_1 = Label(
current_frame,
text=paired[i][0],
font=STANDARD_CONFIGS["font"]["bodytext"])
label_1.grid(column=1, row=1+i)
list_of_entry_boxes = []
for i in range(no_of_statements):
entry_box_1 = Entry(
current_frame,
width=10,
font=STANDARD_CONFIGS["font"]["bodytext"])
entry_box_1.grid(column=2, columnspan=1, row=i+1)
list_of_entry_boxes.append(entry_box_1)
main_quesion = Label(
current_frame,
text="Use the entry boxes on the right to correctly order the conversation",
font=STANDARD_CONFIGS["font"]["secondaryhedding"],
wraplength=500)
main_quesion.grid(columnspan=4, row=0)
check_answer_button = Button(
current_frame,
text="Check Answer",
font=STANDARD_CONFIGS["font"]["bodytext"],
command=lambda: check_multiple_entry_boxes(
list_of_entry_boxes,
paired,
current_frame,
no_of_statements))
check_answer_button.grid(column=0, columnspan=4, row=8)
if questiontype == "wordbank":
current_frame.grid_rowconfigure(1, weight=1)
current_frame.grid_rowconfigure(2, weight=1)
if os.path.isfile(image_location):
arabic_image = PhotoImage(file=image_location)
image_label = Label(current_frame, image=arabic_image)
image_label.image = arabic_image
image_label.grid(row=1, rowspan=4, column=0, columnspan=2)
question_title = Label(
current_frame,
text=question,
font=STANDARD_CONFIGS["font"]["title"],
wraplength=500)
transliteration_button = Button(
current_frame,
text="Show Transliteration",
font=STANDARD_CONFIGS["font"]["bodytext"],
command=lambda: transliteration(
current_frame,
arabic,
english_transliteration))
check_answer_button = Button(
current_frame,
text="Check Answer",
font=STANDARD_CONFIGS["font"]["bodytext"],
command=lambda: check_sentance_order(solution, USER_ANSWER))
clear_selection_button = Button(
current_frame,
text="Clear Selection",
font=STANDARD_CONFIGS["font"]["bodytext"],
command=lambda: clear_selected_words(
word_bank,
size_of_word_bank,
word_chosen))
pronounciation_button = Button(
current_frame,
text="Listen",
font=STANDARD_CONFIGS["font"]["bodytext"],
command=lambda: pronounciation(sound))
sentance_label = Label(
current_frame,
text="Sentence:",
font=STANDARD_CONFIGS["font"]["bodytext"])
word_bank_label = Label(
current_frame,
text="Word Bank:",
font=STANDARD_CONFIGS["font"]["bodytext"])
size_of_solution = len(question_directory["solution"])
size_of_word_bank = len(question_directory["answers"])
sentance_components = []
solution = []
for i in range(size_of_solution):
word = question_directory["solution"][i]
solution.append(word)
word_chosen = []
for i in range(size_of_word_bank):
word = question_directory["answers"][i]
sentance_components.append(word)
label = Label(current_frame,
text=sentance_components[i],
font=STANDARD_CONFIGS["font"]["bodytext"])
word_chosen.append(label)
global USER_ANSWER
USER_ANSWER = []
word_bank = []
for i in range(size_of_word_bank):
word = Button(
current_frame,
text=sentance_components[i],
font=STANDARD_CONFIGS["font"]["bodytext"],
command=lambda i=i: sentancebuilder(
question_directory,
word_bank,
i,
sentance_components,
size_of_word_bank,
word_chosen))
word_bank.append(word)
random.shuffle(word_bank)
next_button(frame_number) # Creates the "next" button and displays it.
question_title.grid(column=0, row=0, columnspan=6)
sentance_label.grid(column=0, row=1, columnspan=1)
word_bank_label.grid(column=0, row=2, columnspan=1)
for i in range(size_of_word_bank):
word_bank[i].grid(column=i+1, row=2, columnspan=1)
pronounciation_button.grid(column=0, row=3, columnspan=1)
clear_selection_button.grid(column=1, row=3, columnspan=2)
check_answer_button.grid(column=3, row=3, columnspan=2)
transliteration_button.grid(column=0, row=5, columnspan=2)
def sentancebuilder(question_directory, word_bank, i, sentance_components, size_of_word_bank, word_chosen):
for index in range(size_of_word_bank):
if word_bank[index]["text"] == sentance_components[i]:
word_bank[index].grid_forget()
global WORD_POSITION
if question_directory["translationdirection"] == "EtoA":
word_chosen[i].grid(column=size_of_word_bank-WORD_POSITION, row=1, columnspan=1)
if question_directory["translationdirection"] == "AtoE":
word_chosen[i].grid(column=WORD_POSITION+1, row=1, columnspan=1)
WORD_POSITION += 1
global USER_ANSWER
USER_ANSWER.append(sentance_components[i])
def clear_selected_words(word_bank, size_of_word_bank, word_chosen):
for i in range(size_of_word_bank):
word_chosen[i].grid_forget()
global WORD_POSITION
WORD_POSITION = 0
global USER_ANSWER
USER_ANSWER = []
for i in range(size_of_word_bank):
word_bank[i].grid(column=i+1, row=2)
def check_multiple_entry_boxes(list_of_entry_boxes, paired, current_frame, no_of_statements):
entered_values = []
for i in range(no_of_statements):
value = list_of_entry_boxes[i].get()
entered_values.append(value)
for i in range(no_of_statements):
if entered_values[i] == paired[i][1]:
label_1 = Label(
current_frame,
text="Correct ",
font=STANDARD_CONFIGS["font"]["bodytext"])
label_1.grid(column=3, row=i+1)
for i in range(no_of_statements):
if entered_values[i] != paired[i][1]:
label_1 = Label(
current_frame,
text="Incorrect",
font=STANDARD_CONFIGS["font"]["bodytext"])
label_1.grid(column=3, row=i+1)
def check_sentance_order(solution, USER_ANSWER):
if solution == USER_ANSWER:
CheckAnswers(special_frames, None, None).right_answer()
if solution != USER_ANSWER:
CheckAnswers(special_frames, None, None).wrong_answer()
def check_entry_box(entry_box, correctanswer):
entered_value = entry_box.get()
if entered_value == correctanswer:
CheckAnswers(special_frames, None, None).right_answer()
if entered_value != correctanswer:
CheckAnswers(special_frames, None, None).wrong_answer()
def check_mc_answer(choices, no_of_answers):
if str(VAR.get()) != "4":
CheckAnswers(special_frames, choices, no_of_answers).wrong_answer()
if str(VAR.get()) == "4":
CheckAnswers(special_frames, choices, no_of_answers).right_answer()
def transliteration(current_frame, arabic, english_transliteration):
transliteration_button = Label(
current_frame,
text=f"'{arabic}' is pronounced '{english_transliteration}'",
font=STANDARD_CONFIGS["font"]["secondaryhedding"])
transliteration_button.grid(row=5, column=0, columnspan=6)
def pronounciation(sound):
winsound.PlaySound(f"{sound_path}{sound}", winsound.SND_FILENAME)
def generate_answers(wronganswer, correctanswer):
wans = random.sample(wronganswer, 3)
answers = wans
answers.append(correctanswer)
return answers
def check_remaining_lives(create_widgets_in_current_frame, current_frame):
if LIVES <= 0:
zero_lives()
else:
current_frame.grid(column=0, row=0)
create_widgets_in_current_frame
def zero_lives():
all_frames_forget()
for i in range(1): #This is for the progress bar frame
progress_bar_frame[i].grid_forget()
special_frames[2].grid(column=0, row=0, sticky=(tkinter.W, tkinter.E))
label_5 = Label(
special_frames[2],
text="You have no remaining lives. \nPlease quit the lesson and try again.",
font=STANDARD_CONFIGS["font"]["title"])
label_5.grid(columnspan=4, row=0)
quit_button = Button(
special_frames[2],
text="Quit",
command=root_window.destroy)
quit_button.grid(column=1, columnspan=2, row=2)
def quit_program_button(current_frame):
quit_button = Button(
current_frame,
text="Quit",
font=STANDARD_CONFIGS["font"]["bodytext"],
command=quit_program)
quit_button.grid(column=3, row=5)
def quit_program():
root_window.destroy()
def next_button(frame_number):
next_button = Button(
special_frames[1],
text="Next Question",
command=lambda: next_question(frame_number))
next_button.grid(column=0, columnspan=5, row=3)
def next_question(frame_number):
frame_number += 1
progress_bar.step(1)
call_frame(frame_number)
def all_frames_forget():
for i in range(0, no_of_quiz_questions): #This is for question frames
frames[i].grid_remove()
for i in range(0, 3): #This is for special frames: (correct and incorrect answer frames)
special_frames[i].grid_remove()
def create_widgets_function(frame_number):
current_frame = frames[frame_number]
question_number = random_list_of_questions[frame_number]
question_frame_populator(frame_number, data, current_frame, question_number)
def call_frame(frame_number):
all_frames_forget()
if frame_number == no_of_quiz_questions:
print("Lesson complete")
root_window.destroy()
if frame_number != no_of_quiz_questions:
create_widgets_in_current_frame = create_widgets_function(frame_number)
current_frame = frames[frame_number]
check_remaining_lives(create_widgets_in_current_frame, current_frame)
##### Program starts here #####
image_path = f"{lesson_file_path}Images\\"
sound_path = f"{lesson_file_path}Sounds\\"
root_window = Toplevel() # Create the root GUI window.
root_window.title(full_lesson_name) #This variable is passed from the main program
random_list_of_questions = []
for i in range(0, no_of_questions):
random_question = f"question{str(i)}"
random_list_of_questions.append(random_question)
random.shuffle(random_list_of_questions) #This section randomizes the question order
global SCORE
SCORE = 0 #Setting the initial score to zero.
global LIVES
LIVES = 3 #Setting the initial number of lives.
frame_number = 0
frames = [] # This includes frames for all questions
for i in range(0, no_of_quiz_questions):
frame = tkinter.Frame(
root_window,
borderwidth=STANDARD_CONFIGS["borderwidth"],
relief=STANDARD_CONFIGS["active"]["rel"])
frame.grid(column=0, row=0, sticky=(tkinter.W, tkinter.N, tkinter.E))
frames.append(frame)
special_frames = [] #Includes the frames: wrong ans, right ans, zero lives, and progress bar
for i in range(0, 4):
special = tkinter.Frame(
root_window,
borderwidth=STANDARD_CONFIGS["borderwidth"],
relief=STANDARD_CONFIGS["active"]["rel"])
special.grid(column=1, row=0, sticky=(tkinter.W, tkinter.E))
special.grid_forget()
special_frames.append(special)
progress_bar_frame = []
for i in range(0, 1):
test = tkinter.Frame(
root_window,
borderwidth=STANDARD_CONFIGS["borderwidth"],
relief=STANDARD_CONFIGS["active"]["rel"])
test.grid(column=0, row=1)#, sticky=(tkinter.W, tkinter.E))
progress_bar_frame.append(test)
progress_bar = ttk.Progressbar(
progress_bar_frame[0],
orient='horizontal',
mode='determinate',
maximum=no_of_quiz_questions)
progress_bar.grid(column=0, row=1, columnspan=3)
random.shuffle(frames)
call_frame(frame_number) #Calls the first function which creates the firist frame
root_window.mainloop()
</code></pre>
<p>If other problems become apparent during the review of my code please feel free to comment on them as well. I'm hoping to learn more about the use of global variables specifically but I open to any and all feedback that is offered. There are some images below of examples of the different types of questions being asked.</p>
<p>Multiple Choice Question:</p>
<p><a href="https://i.stack.imgur.com/LKk9T.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LKk9T.png" alt="enter image description here"></a></p>
<p>Entry Box Question: </p>
<p><a href="https://i.stack.imgur.com/Y6yJY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y6yJY.png" alt="enter image description here"></a></p>
<p>Sentence Re-Ordering Question:
<a href="https://i.stack.imgur.com/NT2y2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NT2y2.png" alt="enter image description here"></a></p>
<p>Matching Question:</p>
<p><a href="https://i.stack.imgur.com/vvU8N.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vvU8N.png" alt="enter image description here"></a></p>
<p>Example of a question answered incorrectly:
<a href="https://i.stack.imgur.com/AiAyX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AiAyX.png" alt="enter image description here"></a></p>
<p>Example of a question answered correctly:
<a href="https://i.stack.imgur.com/c4H9k.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c4H9k.png" alt="enter image description here"></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T16:03:09.670",
"Id": "442415",
"Score": "0",
"body": "As far as I know the general rule is \"avoid global variables\". Only used them for constants. If parts of your code require accessing common variables, then all those functions and variables should belong to a class."
}
] |
[
{
"body": "<p>It's clear that you're starting to pick up some good habits, but this code still has a way to go.</p>\n\n<h2>This is a comment</h2>\n\n<pre><code>Module Docstring:\n</code></pre>\n\n<p>No need to write this - it's obvious from context.</p>\n\n<h2>Type hints</h2>\n\n<pre><code>def __init__(self, sf, cho, noa):\n</code></pre>\n\n<p>Those parameters have no documentation, and it isn't clear what type they are. Do a Google for type hinting in Python - that will help, even if you don't end up adding a docstring for this function.</p>\n\n<h2>Class purpose</h2>\n\n<pre><code>class CheckAnswers:\n</code></pre>\n\n<p>The name of this class on its own suggests that it isn't really being used correctly. \"Check answers\", as an action phrase, means that this would be better-suited to a method. At the least, this should be called <code>AnswerCheck</code> or <code>AnswerChecker</code>, nouns that imply objects instead of actions.</p>\n\n<h2>Dictionaries</h2>\n\n<p>This block:</p>\n\n<pre><code>if lesson_type == \"quiz\":\n no_of_quiz_questions = 8\nif lesson_type == \"short\":\n no_of_quiz_questions = 4\nif lesson_type == \"conversation\":\n no_of_quiz_questions = 1\nif lesson_type == \"long\":\n no_of_quiz_questions = 8\n</code></pre>\n\n<p>is better-represented as a dictionary with a single lookup call.</p>\n\n<h2>Globals and state management</h2>\n\n<p>This boils down to object-oriented programming theory and how to manage program state. You're correct to identify that your usage of globals is not ideal. Taking a look at this code:</p>\n\n<pre><code> global WORD_POSITION\n if question_directory[\"translationdirection\"] == \"EtoA\":\n word_chosen[i].grid(column=size_of_word_bank-WORD_POSITION, row=1, columnspan=1)\n if question_directory[\"translationdirection\"] == \"AtoE\":\n word_chosen[i].grid(column=WORD_POSITION+1, row=1, columnspan=1)\n WORD_POSITION += 1\n\n global USER_ANSWER\n USER_ANSWER.append(sentance_components[i])\n</code></pre>\n\n<p>You're modifying two globals. That means that this method is not written in the right context. It should probably be written as a method on a top-level <code>Game</code> class, and those two variables should be properties. Most of the time, class methods should only modify the state of their own class instance.</p>\n\n<h2>Nested functions</h2>\n\n<p>You've written a long series of nested functions in <code>lesson_template</code>. There's no clear need for this. They should be moved to global scope, or to class methods.</p>\n\n<h2>Loooooooong methods</h2>\n\n<p><code>question_frame_populator</code> is way too long. Try to divide it up into logical sub-routintes.</p>\n\n<h2>Method names</h2>\n\n<p><code>sentancebuilder</code> should be <code>sentence_builder</code>, or more appropriately <code>build_sentence</code>.</p>\n\n<h2>else</h2>\n\n<pre><code> if solution == USER_ANSWER:\n CheckAnswers(special_frames, None, None).right_answer()\n\n if solution != USER_ANSWER:\n CheckAnswers(special_frames, None, None).wrong_answer()\n</code></pre>\n\n<p>You can replace the second <code>if</code> with an <code>else</code>. This pattern is seen elsewhere.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T16:13:30.287",
"Id": "227343",
"ParentId": "227342",
"Score": "3"
}
},
{
"body": "<p>Your global variable naming violates PEP 8. <a href=\"https://www.python.org/dev/peps/pep-0008/#constants\" rel=\"nofollow noreferrer\">Names in all upper-case are <em>constants</em></a>; variables that never change in value. Your globals aren't constant though. Lines like</p>\n\n<pre><code>LIVES -= 1\n</code></pre>\n\n<p>change the value that <code>LIVES</code> holds.</p>\n\n<p>Yes, global names should be in uppercase, but only because globals should also ideally only be constants. Global mutable state is a pain to deal with and complicates testing and debugging.</p>\n\n<hr>\n\n<p>The simplest way to get rid of the global variables is to package them into a state that gets passed around to any function that needs it. While simple and not ideal, this solves the major problem with using globals: You can't just pass in data that you want to be used when testing. When using globals, you must modify the global state just to test how a function reacts to some data. This is less-straightforward than just passing the data, and has the potential to lead to situations where another function reads from the global that you set, causing it to change in behavior along with the function that you're testing.</p>\n\n<p>So, how can you do this?</p>\n\n<p>Represent the state of the game as a class (something like a <code>dataclass</code> would work well here, but I'm just going to use a plain class for simplicity).</p>\n\n<pre><code>class GameState:\n def __init__(self):\n self.lives = 3\n self.score = 0\n self.var = None # Bad name. Doesn't describe its purpose\n self.word_position = None\n self.user_answer = None\n</code></pre>\n\n<p>Then pass an instance of this object (and alter this object) to change the \"globals\". This at the very least allows you to easily pass in exactly the data that you want to test.</p>\n\n<hr>\n\n<hr>\n\n<p>I'd review further, but I started feeling sick about half way through writing this. I'm going to go lay down :/</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T09:01:07.570",
"Id": "442532",
"Score": "0",
"body": "Thanks, this was a really helpful review and I've been working on fixing my use of global variables as a result! I'm marking the other answer as \"correct\" simply because it is more comprehensive but this was truly helpful. Hope you're feeling better now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T13:04:05.937",
"Id": "442567",
"Score": "0",
"body": "@JackDuane No problem. Glad to help. And it ended up being food poisoning. Seems to have resolved itself now."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T16:22:56.307",
"Id": "227345",
"ParentId": "227342",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "227343",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T15:51:45.327",
"Id": "227342",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"game",
"comparative-review",
"tkinter"
],
"Title": "Tkinter Program to teach Arabic Part 2 - Proper use of Global Variables"
}
|
227342
|
<p>I wrote a page with Laravel to manage projects with Scrumpoker through blade syntax with controllers, models and Vue.js.</p>
<p>My problem is that I wrote the actual Scrumpoker in a single file.php file and it is loading by using a method through an onclick event of a form.</p>
<p>Now I want to split it up, make some refactoring and implement in my clean written .php Laravel files. I am doing this because it does not fetch every picture of my /storage folder correctly and to create a clean project.</p>
<p>My helper at need receives a little reward for helping me out of this messy structure.</p>
<p>Here is the code (only index.php + images folder with /themes/decksize/13plus1 or /themes/decksize/6plus1 with a.png/b.png/std.png sliced up in single pictures)</p>
<pre><code><?php error_reporting(0); ?>
<?php
session_start();
if (isset($_GET['name']) && ($_GET['name'] == "UserDebug" ||
substr($_GET['name'], 0, 4) == "tata")) {
exit;
}
if (isset($_GET['name']) && $_GET['name'] == '') {
// user is observer
unset($_GET['name']);
}
if (isset($_GET['name'])) {
$_GET['name'] = strip_tags($_GET['name']);
}
define('IDLE_TIMEOUT_SECONDS', 5);
define('IDLE_TIMEOUT_DELETE_SECONDS', 25);
define('PATH_TO_DATA_FILE', './storage/rooms');
define('LOCKFILE', './scrumlock');
define('DEBUG', false);
if (!isset($_GET['decksize'])) {
$decksize = '13plus1';
} else {
$decksize = $_GET['decksize'];
$_SESSION['decksize'] = $decksize;
}
if (!isset($_SESSION['decksize'])) {
$_SESSION['decksize'] = $decksize;
}
// valid cards - order is the same for the theme png-files
$validOptions = array(
'13plus1' => array(
"1" => "[ 0 ]",
"2" => "[ 1/2 ]",
"3" => "[ 1 ]",
"4" => "[ 2 ]",
"5" => "[ 3 ]",
"6" => "[ 5 ]",
"7" => "[ 8 ]",
"8" => "[ 13 ]",
"9" => "[ 20 ]",
"10" => "[ 40 ]",
"11" => "[ 100 ]",
"12" => "[ ? ]",
"13" => "[ C ]",
// 14 => backside of card
),
'6plus1' => array(
"1" => "[ 1 ] Piece of cake",
"2" => "[ 3 ] Hexenwerk",
"3" => "[ 8 ] Raketenwissenschaft",
"4" => "[ 100 ] O M G !",
"5" => "[ ? ] Ich brauche mehr details",
"6" => "[ C ] Kaffeepause",
// 7 => backside of card
),
);
// will be used to slice the theme.png image into x slices - one per card
define('CARDS_IN_THEME', sizeof($validOptions[$_SESSION['decksize']]) + 1);
function dbg($str)
{
if (DEBUG) {
echo $str;
}
}
// set standard theme if no theme is set
if (!isset($_GET['theme'])) {
$_GET['theme'] = 'A';
}
// players name matches tablename? == admin
$admin = false;
if (isset($_GET['name']) && isset($_GET['table']) && $_GET['name'] == $_GET['table']) {
$admin = true;
}
// calculate card width, height and check if theme is available on disk
$offsets = getCardOffset("1", $validOptions[$_SESSION['decksize']], $_GET['theme']);
if (is_array($offsets)) {
$cardWidth = $offsets[1];
$placeWidth = 20 + $offsets[1];
$cardHeight = $offsets[2];
$placeHeight = 20 + $offsets[2];
} else {
$cardWidth = 50;
$placeWidth = 100;
$cardHeight = 75;
$placeHeight = 95;
}
// Handle AJAX requests
// new players come here, their cards or ajax-commands to reset the table
if (isset($_GET['table']) && isset($_GET['ajax'])) {
// tabledata is stored in a file named same as table within /tmp
// for security - prevent writing to other directories than /tmp by stripping all dots and slashes
$table = str_replace(array('.', '/'), '', $_GET['table']);
// create a new game if the player is admin and no game exists
if (!file_exists(PATH_TO_DATA_FILE . $table) && $admin) {
touch(PATH_TO_DATA_FILE . $table);
}
// stop all players on playing on non existing tables
// ajax requests to non existing tables stop here
if (!file_exists(PATH_TO_DATA_FILE . $table)) {
echo 'Table does not exist.';
exit;
}
// making sure just ONE player fiddles arround with the array on the disk at the same time
while (!@mkdir(LOCKFILE)) {
sleep(2);
}
// read the tabledata from file
$filedata = unserialize(file_get_contents(PATH_TO_DATA_FILE . $table));
if (!is_array($filedata)) {
$filedata = array();
}
// kill the game if requested
if (isset($_GET['kill']) && $admin) {
$filedata = array();
unlink(PATH_TO_DATA_FILE . $table);
echo "table killed.";
rmdir(LOCKFILE);
exit;
}
// initiate new game when not done yet
if (!isset($filedata['table'])) {
$filedata['table'] = array();
}
if (!isset($filedata['history'])) {
$filedata['history'] = array();
}
if (!isset($filedata['message'])) {
$filedata['message'] = 'Welcome to Scrummy:';
}
// split game array in sub parts
$tabledata = $filedata['table']; // array of the current game (on the red blanket)
$tabledatahistory = $filedata['history']; // array holding previous game arrays (below the red blanket)
$players = $filedata['players']; // array holding last seen timestamps for players
$message = $filedata['message']; // message of the table
if (isset($_GET['options']) && $_GET['options']) {
// override message for the table
if (strpos($_GET['options'], 'https://it.ly/2NDNWF8') !== false) {
$_GET['options']
=
'<A href="' . $_GET['options'] . '" target="_blank">' . str_replace(
'https://it.ly/2NDNWF8',
'',
$_GET['options']
) . '</A>';
}
$filedata['message'] = $_GET['options'];
$message = $filedata['message'];
file_put_contents(PATH_TO_DATA_FILE . $table, serialize($filedata));
}
// check for user manipulation
$userIsSpoofingArround = false;
if (isset($_GET['name']) && isset($_GET['ID']) && $tabledata[$_GET['name']]['ID'] != $_GET['ID']) {
$userIsSpoofingArround = true;
}
if (isset($_GET['name']) && isset($tabledata[$_GET['name']]) && $userIsSpoofingArround) {
if ((time() - $players[$_GET['name']]) < IDLE_TIMEOUT_DELETE_SECONDS) {
dbg("[" . $tabledata[$_GET['name']]['ID'] . "] == [" . $_GET['ID'] . "]<br>");
echo 'AUTHENTICATION PROBLEM - FRAUD DETECTED!';
rmdir(LOCKFILE);
exit;
} else {
// user is spoofing another user who idled out. user can take the session
if ($_GET['ID']) {
$tabledata[$_GET['name']]['ID'] = $_GET['ID'];
dbg("updating ID<br>");
}
}
} else {
// echo "[".$tabledata[$_GET['name']]['ID']."] == [".$_GET['ID']."]<br>";
}
// put the current game into the history
if (isset($_GET['add']) && $admin) {
$tabledatahistory[] = $tabledata;
$tabledata = array();
$filedata['table'] = $tabledata;
$filedata['history'] = $tabledatahistory;
file_put_contents(PATH_TO_DATA_FILE . $table, serialize($filedata));
rmdir(LOCKFILE);
exit;
}
// set a card for a player if all _GET data is valid
if (
isset($_GET['guess']) && $_GET['guess'] != '' && isset($_GET['name']) && $_GET['name']
&& isset($tabledata[$_GET['name']])
&& $tabledata[$_GET['name']]['ID'] == $_GET['ID']
) {
if (in_array($_GET['guess'], array_keys($validOptions[$_SESSION['decksize']]))) {
dbg("saving guess and updating time<br>");
$tabledata[$_GET['name']] = array('name' => $_GET['name'], 'guess' => $_GET['guess'], 'ID' => $_GET['ID']);
$players[$_GET['name']] = time();
}
}
// recognition of new player without a card - prepare slot
if (isset($_GET['name']) && !isset($tabledata[$_GET['name']]) && isset($_GET['name']) && $_GET['name']) {
$tabledata[$_GET['name']] = array('name' => $_GET['name'], 'guess' => '...', 'ID' => $_GET['ID']);
dbg("adding new player with guess ...<br>");
}
// drop ideling players after IDLE_TIMEOUT_SECONDS
if (isset($_GET['name']) && isset($tabledata[$_GET['name']]) && $_GET['name'] && !$userIsSpoofingArround) {
$players[$_GET['name']] = time();
dbg("updating time<br>");
}
// combine history and current game into one array
$filedata['table'] = $tabledata;
$filedata['history'] = $tabledatahistory;
$filedata['players'] = $players;
$filedata['message'] = $message;
// write table data to disk
if (isset($_GET['name']) && $_GET['name']) {
file_put_contents(PATH_TO_DATA_FILE . $table, serialize($filedata));
dbg("writing data to disk<br>");
}
// prepare layout of the webpage
// show all cards
$showAllCards = true;
// echo table header with names
ksort($players);
$playernames = array();
if (is_array($players)) {
$playernames = array_keys($players);
}
$totalPlayers = 0;
$activePlayers = 0;
$playersOnTable = 0;
// check if some players did not choose yet
if (is_array($playernames)) {
foreach ($playernames as $eachPlayername) {
$totalPlayers++;
if ((time() - $players[$eachPlayername]) < IDLE_TIMEOUT_SECONDS) {
$activePlayers++;
}
if ((time() - $players[$eachPlayername]) < IDLE_TIMEOUT_DELETE_SECONDS) {
$playersOnTable++;
}
if (
$tabledata[$eachPlayername]['guess'] == '...'
&& (time() - $players[$eachPlayername]) < IDLE_TIMEOUT_SECONDS
) {
$showAllCards = false;
}
}
}
// automatic new row
if ($showAllCards && $activePlayers > 1) {
$tabledatahistory[] = $tabledata;
//$tabledata = array(); <-- will not work - enables session hijacking
foreach ($tabledata as $username => $userarray) {
$tabledata[$username]['guess'] = '...';
}
$filedata['table'] = $tabledata;
$filedata['history'] = $tabledatahistory;
file_put_contents(PATH_TO_DATA_FILE . $table, serialize($filedata));
}
rmdir(LOCKFILE);
echo '<A href="javascript:clearTimeout(TIMEOUT)">Take A Break(STOP REFRESH)</A><br><br>';
echo '<h2>' . $message . '</h2>';
echo '<style>
.striped-border {
border: 1px dashed #000;
width: 50%;
margin: auto;
margin-top: 5%;
margin-bottom: 5%;
}
hr {
height: 1px;
color: #123455;
background-color: #123455;
border: none;
}
.center {
margin: auto;
width: 60%;
border: 15px solid #000000;
padding: 10px;
text-align: center
}
</style>
<div class=center>Players On Table: ' . $playersOnTable . "<br>";
echo 'Total Player:' . $totalPlayers . "<br>";
echo 'Active Players: ' . $activePlayers . "<br>";
echo '<div class="header">';
if (is_array($playernames)) {
foreach ($playernames as $eachPlayerName) {
$id = '(' . $tabledata[$eachPlayerName]['ID'] . '/' . $_GET['ID'] . ')';
$id = '';
if (time() - $players[$eachPlayerName] < IDLE_TIMEOUT_SECONDS) {
echo '<div class="place" style="text-align:left"' . $placeWidth . 'px;overflow:hidden">' . '<strong>' . 'Player:' . '</strong>' . ' ' . $eachPlayerName . '<br>' ./*'<b>'.hash('sha512',session_id($eachPlayerName)).'</b>'.*/ $id
. '</div>';
} elseif (time() - $players[$eachPlayerName] < IDLE_TIMEOUT_DELETE_SECONDS) {
echo '<div class="place" style="width:' . $placeWidth . 'px;overflow:hidden">' . $eachPlayerName . $id
. '<br><i>INACTIVE</i></div>';
}
}
echo '</div>';
// CURRENT TABLE
echo '<div class="currentTable" style="width:' . ($playersOnTable * $placeWidth) . '"><nobr>';
foreach ($playernames as $eachPlayerName) {
$styleaddon = '';
$ownPlace = (isset($_GET['name']) && $tabledata[$eachPlayerName]['name'] == $_GET['name']);
$playerPlayedACard = ($tabledata[$eachPlayerName]['guess'] != '...');
if (time() - $players[$eachPlayerName] < IDLE_TIMEOUT_DELETE_SECONDS) {
echo '<div class="place"><center>';
$offsets = getCardOffset($tabledata[$eachPlayerName]['guess'], $validOptions[$_SESSION['decksize']], $_GET['theme']);
if (is_array($offsets)) {
// show nifty cards
echo '' . (($showAllCards || ($ownPlace && $playerPlayedACard))
?
// show card face up
'<div style="width:' . $cardWidth . ';height:' . $cardHeight . ';background-image:url(\'/storage/'
. $offsets[3] . '\');background-position:' . $offsets[0] . ' 0px;">&nbsp;</div>'
: ($playerPlayedACard
?
// show card face down
'<div style="width:' . $cardWidth . ';height:' . $cardHeight
. ';background-image:url(\'' . $offsets[3] . '\');background-position:'
. (-(CARDS_IN_THEME - 1) * $cardWidth) . 'px 0px;">&nbsp;</div>'
:
// show empty place
'<div style="' . $styleaddon . 'width:' . $cardWidth . ';height:' . $cardHeight
. ';overflow:hidden;">&nbsp;</div>')) . '';
} else {
// theme not found or erroneous - show text cards
echo '' . (($showAllCards || ($ownPlace && $playerPlayedACard))
?
// show card face up
'<div class="card"><span style="height:' . $cardHeight
. 'px; width:1px; vertical-align:middle"></span>'
. $validOptions[$_SESSION['decksize']][$tabledata[$eachPlayerName]['guess']] . '</div>'
: ($playerPlayedACard
?
// show card face down
'<img src="/storage/images/back.jpg?t=' . filemtime('images/back.jpg') . '>'
:
// show empty place
'<div style="' . $styleaddon . 'width:' . $cardWidth . ';height:' . $cardHeight
. ';overflow:hidden;">&nbsp;</div>')) . '';
// '<img src="./images/blank2.jpg">'));
}
echo '</center></div>';
}
}
echo '</nobr></div>';
$tabledatahistory = array_reverse($tabledatahistory);
// HISTORY
foreach ($tabledatahistory as $eachHistory) {
echo '<div class="historyTable" style="width:' . ($playersOnTable * $placeWidth) . '">';
foreach ($playernames as $eachPlayerName) {
if (time() - $players[$eachPlayerName] < IDLE_TIMEOUT_DELETE_SECONDS) {
echo '<div class="place"><p><i>' . $eachPlayerName . '<hr>' . '</i><center>';
$offsets = getCardOffset($eachHistory[$eachPlayerName]['guess'], $validOptions[$_SESSION['decksize']], $_GET['theme']);
if (is_array($offsets)) {
// show nifty cards
echo '<div style="width:' . $cardWidth . ';height:' . $offsets[2] . ';background-image:url(\'themes/13plus1/std.png?1435657352'\');background-position:' . $offsets[0] . ' 0px;">&nbsp;</div>';
} else {
// theme not found or erroneous - show text cards
echo '<div class="card"><span style="height:' . $cardHeight
. 'px; width:1px; vertical-align:middle"></span>'
. $validOptions[$_SESSION['decksize']][$eachHistory[$eachPlayerName]['guess']] . '</div>';
}
echo '</center></div>';
}
}
echo '</div>';
}
}
// echo '<pre>';
exit;
}
$ID = session_id();
/**
* @param $guess
* @param $validOptions
* @param $theme
* @return string
*/
function getCardOffset($guess, $validOptions, $theme)
{
$return = 0;
$found = false;
$imageName = 'storage/themes/' . $_SESSION['decksize'] . '/' . str_replace(array('/', '.'), '', $theme) . '.png';
if (file_exists($imageName)) {
$img = imagecreatefrompng($imageName);
if ($img) {
$width = imagesx($img);
$cardWidth = $width / CARDS_IN_THEME;
foreach ($validOptions as $key => $val) {
if ($guess != $key) {
$return -= $cardWidth;
} else {
$found = true;
break;
}
}
} else {
return false;
}
} else {
return false;
}
if (!$found) {
return false;
}
return array($return . "px", $cardWidth, imagesy($img), $imageName . '?' . filemtime($imageName));
}
if (!isset($_GET['table'])) {
$folder = 'themes/' . $_SESSION['decksize'] . '/';
$otherfolder = 'themes/6plus1' . $_SESSION['secdecksize'] . '/';
exit;
} else {
// handle HTML page for the client
?>
<html>
<head>
<title>Scrummy</title>
<link href="//cdn.muicss.com/mui-0.9.43/css/mui.min.css" rel="stylesheet" type="text/css" />
<script src="//cdn.muicss.com/mui-0.9.43/js/mui.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.min.css">
<script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>
<style>
body {
background-color: coral ;
}
.card {
width: <?php echo $cardWidth; ?>px;
height: <?php echo $cardHeight; ?>px;
overflow: hidden;
background-image: url('/storage/images/blank.jpg');
background-size: <?php echo $cardWidth; ?>px auto;
border: 0px solid red;
}
* {
font-family: Verdana;
font-size: 8pt;
}
.currentTable {
border: 0px solid black;
background-image: url('storage/images/rw.png');
height: <?php echo $placeHeight; ?>px;
}
.historyTable {
border: 0px solid dotted;
height: <?php echo $placeHeight; ?>px;
}
.place {
border: 0px solid black;
overflow: hidden;
float: left;
text-align: center;
width: <?php echo $placeWidth; ?>px;
}
.currentTable .place {
margin-top: 10px;
}
.historyTable .place {
margin-top: 10px;
}
.header {
border: 0px solid black;
height: 25px;
clear: both;
}
</style>
<script>
var TIMEOUT;
var VALUE = "...";
function statusCommand(cmd, user, table, options) {
if (options == undefined) {
options = '';
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
}
}
xmlhttp.open("GET", "?ID=<?php echo session_id(); ?>&ajax&name=" + user + "&table=" + table + "&" + cmd + "&options=" + options, true);
xmlhttp.send();
}
function showUser(str, name, table) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
if (str != "..." && str != "AUTO") {
VALUE = str;
document.getElementById("guess").value = "...";
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
if (str == "AUTO") {
xmlhttp.open("GET", "?theme=<?php echo $_GET['theme']; ?>&ID=<?php echo session_id(); ?>&ajax&table=" + table + "&name=" + name, true);
} else {
xmlhttp.open("GET", "?theme=<?php echo $_GET['theme']; ?>&ID=<?php echo session_id(); ?>&ajax&table=" + table + "&guess=" + str + "&name=" + name, true);
}
xmlhttp.send();
if (document.getElementById("txtHint").innerHTML != "Table does not exist.") {} else {
VALUE = "...";
}
timeout_init();
}
function timeout_init() {
clearTimeout(TIMEOUT);
TIMEOUT = setTimeout('showUser("AUTO","<?php echo $_GET['name']; ?>","<?php echo $_GET['table']; ?>")', 2000);
}
function initCards() {
showUser("AUTO", "<?php echo $_GET['name']; ?>", "<?php echo $_GET['table']; ?>");
timeout_init();
}
</script>
</head>
<body onLoad="initCards()">
<?php
for ($i = 8; $i > 0; $i--) {
//echo '<img src="cards/E'.$i.'.png" width="50">';
}
//echo '<br>';
?>
<form method="GET" onsubmit="javascript:return false;" class="mui-form">
<?php
if (isset($_GET['name'])) {
?>
<div class="mui-select">
<select id="guess" name="guess" onchange="showUser(this.value,'<?php echo $_GET['name']; ?>','<?php echo $_GET['table']; ?>')">
<option value="...">Select Your Card:</option>
<?php
foreach ($validOptions[$_SESSION['decksize']] as $key => $val) {
echo "<option value=\"" . $key . "\">" . $val . "</option>\n";
}
?>
</select></div>
<?php
foreach ($validOptions[$_SESSION['decksize']] as $key => $val) {
$offsets = getCardOffset($key, $validOptions[$_SESSION['decksize']], $_GET['theme']);
echo '<div class="place"><center><A href="javascript:showUser(\'' . $key . '\',\'' . $_GET['name']
. '\',\'' . $_GET['table'] . '\')">';
if (is_array($offsets)) {
// show nifty cards
echo '' .
'<div style="width:' . $cardWidth . ';height:' . $cardHeight . ';background-image:url(\''.
$offsets[3] . '\');background-position:' . $offsets[0] . ' 0px;">&nbsp;</div>';
} else {
// theme not found or erroneous - show text cards
echo '' .
// show card face up
'<div class="card"><span style="height:' . $cardHeight
. 'px; width:1px; vertical-align:middle"></span>'
. $validOptions[$_SESSION['decksize']][$tabledata[$eachPlayerName]['guess']] . '</div>';
}
echo '</A></center></div>';
}
echo '<br style="clear:both">';
// echo '<A href="javascript:clearTimeout(TIMEOUT)">STOP REFRESH</A>';
?>
<?php
} else {
?>
<input name="message" size="100" onkeypress="statusCommand('message', '<?php echo $_GET['name']; ?>', '<?php echo $_GET['table']; ?>', this.value)" onkeyup="statusCommand('message', '<?php echo $_GET['name']; ?>', '<?php echo $_GET['table']; ?>', this.value)" onchange="statusCommand('message', '<?php echo $_GET['name']; ?>', '<?php echo $_GET['table']; ?>', this.value)" onblur="statusCommand('message', '<?php echo $_GET['name']; ?>', '<?php echo $_GET['table']; ?>', this.value)">
<?php
}
?>
</form>
<br>
<?php
if ($admin) {
echo '<mark>' . 'You`re the Scrumleader' . '</mark>' . '<br>';
?>
<A href="javaScript:statusCommand('kill','<?php echo $_GET['name']; ?>','<?php echo $_GET['table']; ?>')">Reset</A> the current game
<br>
<A href="javaScript:statusCommand('add','<?php echo $_GET['name']; ?>','<?php echo $_GET['table']; ?>')">New</A> Round? (Adds new game row)
<br>
<?php
}
?>
<div id="txtHint"><b>Cards are shown here</b></div>
</body>
</html>
<?php
}
?>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T16:28:53.167",
"Id": "227347",
"Score": "3",
"Tags": [
"php",
"laravel"
],
"Title": "Divide / Split single file .php into clean code parts"
}
|
227347
|
<p>I am making session store which will store some data and read some, This
session store can store multiple data( SessionInfo) to the map.</p>
<p>Data Structure</p>
<pre><code>#include <map>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <memory>
#include <iostream>
template <typename T>
class IBasicStream;
namespace
{
constexpr int kClassVersion = 1;
}
/*
ToSerial and FromSerial are for backward support
*/
struct Calendar
{
int day;
int month;
int year;
Calendar() : day(0), month(0), year(0)
{
}
Calendar &operator=(const Calendar &other)
{
day = other.day;
month = other.month;
year = other.year;
return *this;
}
template <typename streamType>
void ToSerial(IBasicStream<streamType> &stream)
{
stream << kClassVersion;
stream << day;
stream << month;
stream << year;
}
//class version Going to use for future change;
template <typename streamType>
void FromSerial(IBasicStream<streamType> &stream)
{
int classVersion = 0;
stream >> classVersion;
stream >> day;
stream >> month;
stream >> year;
}
template <typename streamType>
friend IBasicStream<streamType> &operator<<(IBasicStream<streamType> &stream, Calendar &Calendar)
{
Calendar.ToSerial(stream);
return stream;
}
template <typename streamType>
friend IBasicStream<streamType> &operator>>(IBasicStream<streamType> &stream, Calendar &Calendar)
{
Calendar.FromSerial(stream);
return stream;
}
};
struct Timings
{
Calendar startDate;
int numberOfDays;
int duration;
std::vector<Calendar> customDate;
Timings() : startDate{}, numberOfDays(0), duration(0)
{
}
Timings &operator=(const Timings &other)
{
startDate = other.startDate;
numberOfDays = other.numberOfDays;
duration = other.duration ;
customDate = other.customDate;
return *this;
}
template <typename streamType>
void ToSerial(IBasicStream<streamType> &stream)
{
stream << kClassVersion;
stream << startDate;
stream << numberOfDays;
stream << duration;
int size = int(customDate.size());
stream << size;
for (auto item : customDate)
{
stream << item;
}
}
template <typename streamType>
void FromSerial(IBasicStream<streamType> &stream)
{
int size = -1;
int classVersion = 0;
stream >> classVersion;
stream >> startDate;
stream >> numberOfDays;
stream >> duration;
stream >> size;
customDate.clear();
for (int i = 0; i < size; i++)
{
Calendar item;
stream >> item;
customDate.push_back(item);
}
}
template <typename streamType>
friend IBasicStream<streamType> &operator<<(IBasicStream<streamType> &stream, Timings &timings)
{
timings.ToSerial(stream);
return stream;
}
template <typename streamType>
friend IBasicStream<streamType> &operator>>(IBasicStream<streamType> &stream, Timings &timings)
{
timings.FromSerial(stream);
return stream;
}
};
// It should have title
// Reminder Title
// TODO: priority
struct Description
{
std::string title;
std::string reminderTitle;
Description() : title(""), reminderTitle("")
{
}
Description &operator=(const Description &other)
{
title = other.title;
reminderTitle = other.reminderTitle;
return *this;
}
template <typename streamType>
void ToSerial(IBasicStream<streamType> &stream)
{
stream << kClassVersion;
stream << title;
stream << reminderTitle;
}
template <typename streamType>
void FromSerial(IBasicStream<streamType> &stream)
{
int classVersion = 0;
stream >> classVersion;
stream >> title;
stream >> reminderTitle;
}
template <typename streamType>
friend IBasicStream<streamType> &operator<<(IBasicStream<streamType> &stream, Description &description)
{
description.ToSerial(stream);
return stream;
}
template <typename streamType>
friend IBasicStream<streamType> &operator>>(IBasicStream<streamType> &stream, Description &description)
{
description.FromSerial(stream);
return stream;
}
};
enum State
{
Started,
Ended,
Suspended,
InProgress,
Invalid,
};
class SessionInfo
{
public:
//ToDo : Way to make ctor private as only
//so that Session Class can only access
//but std::map is currently accessing It so not
//possible write now.
SessionInfo() noexcept : mDescription(), mTimings(), mState(State::Started)
{
}
SessionInfo(const SessionInfo &other) : mDescription(other.mDescription),
mTimings(other.mTimings),
mState(other.mState)
{
}
SessionInfo &operator=(const SessionInfo &other)
{
mDescription = other.mDescription;
mTimings = other.mTimings;
mState = other.mState;
return *this;
}
SessionInfo(SessionInfo &&other) : mDescription(std::move(other.mDescription)),
mTimings(std::move(other.mTimings)),
mState(std::move(other.mState))
{
}
SessionInfo &operator=(SessionInfo &&other)
{
mDescription = std::move(other.mDescription);
mTimings = std::move(other.mTimings);
mState = std::move(other.mState);
return *this;
}
SessionInfo &SetTitle(const std::string &title)
{
mDescription.title = title;
return *this;
}
~SessionInfo()
{
}
std::string GetTitle() const
{
return mDescription.title;
}
SessionInfo &SetState(const State &other)
{
mState = other;
return *this;
}
State GetState()
{
return mState;
}
SessionInfo &SetReminderTitle(const std::string &reminderTitle)
{
mDescription.reminderTitle = reminderTitle;
return *this;
}
std::string GetReminderTitle() const
{
return mDescription.reminderTitle;
}
SessionInfo &SetDescription(const Description &other)
{
mDescription.reminderTitle = other.reminderTitle;
mDescription.title = other.title;
return *this;
}
Description &GetDescription()
{
return mDescription;
}
template <typename streamType>
void ToSerial(IBasicStream<streamType> &stream)
{
stream << kClassVersion;
stream << mDescription;
stream << mTimings;
int state = mState;
stream << state;
}
template <typename streamType>
void FromSerial(IBasicStream<streamType> &stream)
{
stream >> kClassVersion;
stream >> mDescription;
stream >> mTimings;
int state = 0;
stream >> state;
mState = (State)state;
}
template <typename streamType>
friend IBasicStream<streamType> &operator>>(IBasicStream<streamType> &stream, SessionInfo &obj)
{
obj.FromSerial(stream);
return stream;
}
template <typename streamType>
friend IBasicStream<streamType> &operator<<(IBasicStream<streamType> &stream, SessionInfo &obj)
{
obj.ToSerial(stream);
return stream;
}
SessionInfo &SetTimings(const Timings &other)
{
mTimings = other;
return *this;
}
private:
//template<typename T> friend class ISessionDataBaseFactory;
//friend class Session;
Description mDescription;
Timings mTimings;
State mState;
};
</code></pre>
<p>This is the class which is responsible for storing session information with its interface.</p>
<pre><code>template <typename childClass>
class ISessionDataBaseFactory
{
public:
ISessionDataBaseFactory() noexcept
{
}
template <typename streamType>
bool LoadSession(IBasicStream<streamType> &stream)
{
auto childObj = static_cast<childClass *>(this);
return childObj->LoadSessionImpl(stream);
}
template <typename streamType>
void SaveAllSession(IBasicStream<streamType> &stream)
{
auto childObj = static_cast<childClass *>(this);
childObj->SaveAllSessionImpl(stream);
}
void SetSessionInfo(std::string &sessionId, SessionInfo &info)
{
auto childObj = static_cast<childClass *>(this);
childObj->SetSessionInfoImpl(sessionId, info);
}
SessionInfo &GetSessionInfo(const std::string &sessionId)
{
auto childObj = static_cast<childClass *>(this);
return childObj->GetSessionInfoImpl(sessionId);
}
/* will be making SessionInfo as private */
SessionInfo &BuildSessionInfo()
{
auto childObj = static_cast<childClass *>(this);
return childObj->BuildSessionInfoImpl();
}
};
//
class Session : public ISessionDataBaseFactory<Session>
{
public:
Session() noexcept : mSessionStore{}, invalidStateObj{}, session{}
{
invalidStateObj.SetState(State::Invalid);
session.SetState(State::Started);
mSessionStore.clear();
}
/*
The members of the map are internally stored in a tree structure.
There is no way to build the tree until you know the keys and values
that are to be stored.
*/
template <typename streamType>
bool LoadSessionImpl(IBasicStream<streamType> &stream)
{
int size = -1;
stream >> size;
if (stream.IsValid() && size > 0)
{
for (int i = 0; i < size; i++)
{
std::string key;
SessionInfo value;
stream >> key;
stream >> value;
mSessionStore.insert(std::make_pair(key, value));
}
return true;
}
return false;
}
//TODO : in future invalid mState object is going to use more
SessionInfo &GetSessionInfoImpl(const std::string &sessionId)
{
int size = mSessionStore.size();
if (size > 0 && mSessionStore.find(sessionId) != mSessionStore.end())
{
return mSessionStore[sessionId];
}
else
{
return invalidStateObj;
}
}
template <typename streamType>
void SaveAllSessionImpl(IBasicStream<streamType> &stream)
{
if (mSessionStore.size() > 0)
{
int size = int(mSessionStore.size());
stream << size;
for (auto &item : mSessionStore)
{
stream << item.first;
stream << item.second;
}
stream.Flush();
}
}
//TODO: Add logic to genrate session ID's
void SetSessionInfoImpl(std::string &sessionId, SessionInfo &info)
{
if (mSessionStore.size() > 0 && mSessionStore.find(sessionId) != mSessionStore.end())
{
mSessionStore[sessionId] = info;
}
else
{
mSessionStore.insert(std::make_pair(sessionId, info));
}
}
SessionInfo &BuildSessionInfoImpl()
{
return session;
}
~Session() noexcept
{
}
//Timing Methods
private:
std::map<std::string, SessionInfo> mSessionStore;
SessionInfo invalidStateObj;
SessionInfo session;
};
/*
*/
</code></pre>
<p>These classes responsible for proving stream classes.</p>
<pre><code>template <typename childClass>
class IBasicStream
{
public:
IBasicStream() noexcept
{
}
IBasicStream(const std::string filename) noexcept
{
}
IBasicStream(IBasicStream<childClass> &&other)
{
//Nothing needed ...
}
~IBasicStream()
{
}
IBasicStream<childClass> &operator=(IBasicStream<childClass> &&other)
{
// Nothing n
}
void Open(const std::string &filePath)
{
auto child = static_cast<childClass *>(this);
child->OpenImpl(filePath);
}
bool IsValid()
{
auto child = static_cast<childClass *>(this);
return child->IsValidImpl();
}
/***Issue here is that
i need operator ">>" and "<<" for all
the implicit types but i don't want
for class so can't make genric.
may be need to create for double and other class Too
other are using friend function to do that
***/
void operator<<(int data)
{
auto child = static_cast<childClass *>(this);
child->FromSerial(data);
}
void operator<<(char data)
{
auto child = static_cast<childClass *>(this);
child->FromSerial(data);
}
/* void operator<<(std::string & data) {
auto child = static_cast< childClass * >(this);
child->FromSerial(data);
}*/
void operator<<(float data)
{
auto child = static_cast<childClass *>(this);
child->FromSerial(data);
}
void operator<<(std::basic_string<char> data)
{
auto child = static_cast<childClass *>(this);
child->FromSerial(data);
}
void operator>>(std::basic_string<char> data)
{
auto child = static_cast<childClass *>(this);
child->FromSerial(data);
}
void operator>>(char data)
{
auto child = static_cast<childClass *>(this);
child->FromSerial(data);
}
/*void operator>>(std::string & data) {
auto child = static_cast< childClass * >(this);
child->FromSerial(data);
}*/
void operator>>(float data)
{
auto child = static_cast<childClass *>(this);
child->FromSerial(data);
}
void operator>>(int data)
{
auto child = static_cast<childClass *>(this);
child->FromSerial(data);
}
bool IsEmpty()
{
auto child = static_cast<childClass *>(this);
return child->IsEmptyImpl();
}
void Clear()
{
auto child = static_cast<childClass *>(this);
child->ClearImpl();
}
void Flush()
{
auto child = static_cast<childClass *>(this);
child->FlushImpl();
}
};
class BinaryStream : public IBasicStream<BinaryStream>
{
public:
BinaryStream() : Parent()
{
}
BinaryStream(const std::string filename) noexcept
{
mBinaryStream.open(filename, std::fstream::in | std::fstream::out | std::fstream::trunc);
}
void OpenImpl(const std::string filename)
{
if (!IsValidImpl())
{
mBinaryStream.open(filename, std::fstream::in | std::fstream::out | std::fstream::trunc);
}
}
BinaryStream(BinaryStream &&other) : Parent(std::move(other))
{
*this = std::move(other);
}
BinaryStream &operator=(BinaryStream &&other)
{
mBinaryStream = std::move(other.mBinaryStream);
return *this;
}
template <typename T>
void ToSerial(T &data)
{
if (mBinaryStream.is_open())
{
mBinaryStream << data;
}
}
template <typename T>
void FromSerial(T &data)
{
if (mBinaryStream.is_open())
{
mBinaryStream >> data;
}
}
bool IsValidImpl()
{
return mBinaryStream.is_open();
}
bool IsEmptyImpl()
{
return mBinaryStream.peek() == std::fstream::traits_type::eof();
}
void ClearImpl()
{
if (mBinaryStream.is_open())
{
mBinaryStream.clear();
}
}
void FlushImpl()
{
if (mBinaryStream.is_open())
{
mBinaryStream.flush();
mBinaryStream.sync();
}
}
friend std::fstream &operator<<(std::fstream &stream, std::string &str)
{
int length = 0;
length = str.size();
stream << length;
stream.write(str.c_str(), length);
return stream;
}
friend std::fstream &operator>>(std::fstream &stream, std::string &str)
{
int length = 0;
stream >> length;
char cstr[length];
stream.read(cstr, length);
str = std::string(cstr);
return stream;
}
private:
typedef IBasicStream<BinaryStream> Parent;
std::fstream mBinaryStream;
};
// Save Session Class
</code></pre>
<p>Test case :</p>
<pre><code>int main()
{
std::shared_ptr<IBasicStream<BinaryStream>> mystream(new BinaryStream("ABC"));
std::cout << "mystream is valid: " << mystream->IsValid() <<std::endl;
std::shared_ptr<ISessionDataBaseFactory< Session >> sess(new Session());
auto sessinfo(sess->BuildSessionInfo());
sessinfo.SetState(State::Invalid);
sessinfo.SetReminderTitle("This is awful");
std::string as ="Anb";
sess->SetSessionInfo(as,sessinfo);
sess->SaveAllSession(*mystream);
//bool status = sess->LoadSession(*mystream);
//TODO Flushing Issue needs to resolve
std::cout << "mystream is valid: " << mystream->IsValid() << std::endl;
auto sesinfo_other = sess->GetSessionInfo(as);
if(sesinfo.GetReminderTitle() == sessinfo_other.GetReminderTitle())
{
std::cout <<"Both sessions are equal as expected " << std::endl;
}
else
{
std::cout <<"TODO Flushing Issue needs to resolve " << std::endl;
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T18:02:27.710",
"Id": "442442",
"Score": "2",
"body": "You can improve the question by adding main and some test cases that will demonstrate how the classes are used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T18:31:47.263",
"Id": "442446",
"Score": "1",
"body": "Sure, Thanks doing it right now :) ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T10:19:37.853",
"Id": "442537",
"Score": "0",
"body": "What is `<io.h>`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T12:48:46.147",
"Id": "442563",
"Score": "0",
"body": "No use for that now I should be removing"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T18:55:17.670",
"Id": "442677",
"Score": "1",
"body": "`#include <memory>` is missing, `std::end` is unknown, at least to my compiler and me. You may also receive a lot improvement suggestions by compiling with warnings enabled ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T04:09:30.180",
"Id": "442723",
"Score": "0",
"body": "Thanks a lot man :). Took your advice now i have updated the code by compiling with warnings.It was very useful thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T10:54:38.510",
"Id": "442785",
"Score": "0",
"body": "You could fix the dodgy spellings (`Calander`, `straemType`, `ISessionDataBaseFectory`, etc), which would make the code easier to read."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T11:29:39.707",
"Id": "442798",
"Score": "0",
"body": "Fixed ! thanks :)"
}
] |
[
{
"body": "<p>I accidentally deleted my first review, so this will only cover the main points:</p>\n\n<hr>\n\n<ul>\n<li><p><strong>bug</strong>: I think this is the main reason your code doesn't work. Flushing isn't the issue.</p>\n\n<pre><code>void operator<<(int data)\n{\n auto child = static_cast<childClass *>(this);\n child->FromSerial(data);\n}\n\nvoid operator>>(int data)\n{\n auto child = static_cast<childClass *>(this);\n child->FromSerial(data);\n}\n</code></pre></li>\n<li><p><strong>bug</strong>: <code>std::fstream::in | std::fstream::out | std::fstream::trunc</code>. This truncates the input file, so we won't be able to read its content.</p></li>\n<li><p><strong>bug</strong>: Conforming C++ compilers do not allow variable length arrays. You will need to use a <code>std::string</code> or <code>std::vector</code> instead.</p>\n\n<pre><code>int length = 0;\nstream >> length;\nchar cstr[length];\n</code></pre></li>\n<li><p><code>operator<<</code> and <code>operator>></code> do <em>formatted</em> input and output (i.e. they read and write text), so <code>BinaryStream</code> is a very misleading name.</p></li>\n<li><p><strong>bug</strong>: they also don't insert whitespace when writing (so your file will look like: <code>1Anb11This is awful110000004</code>. However, they <em>do</em> depend on whitespace when reading. So your current input system simply won't work.</p></li>\n<li><p>Note that for text input, many reliable XML and JSON libraries already exist.</p></li>\n<li><p><code>int</code> does not cover the correct range of values for storing an index into, or the size of, a standard container. Use <code>std::size_t</code> instead.</p></li>\n</ul>\n\n<hr>\n\n<p>C++ uses run-time polymorphism (inheritance and virtual functions) so that classes of different types can implement the same interface, and be referred to through a common base class:</p>\n\n<pre><code>class ISession\n{\npublic:\n\n virtual void Load(Stream& stream) = 0; // abstract fucntion\n virtual void Save(Stream& stream) const = 0;\n};\n\nclass SessionA : public ISession\n{\n virtual void Load(Stream& stream) override\n {\n // ... implementation specific to SessionA\n }\n virtual void Save(Stream& stream) const override\n {\n // ... implementation specific to SessionA\n }\n};\n\nclass SessionB : public ISession\n{\n virtual void Load(Stream& stream) override\n {\n // ... implementation specific to SessionB\n }\n virtual void Save(Stream& stream) const override\n {\n // ... implementation specific to SessionB\n }\n};\n\nstd::vector<std::unique_ptr<ISession>> sessions;\n// ...\n\nfor (auto const& s : sessions)\n s->Save(stream);\n</code></pre>\n\n<p>However, your current implementation does not allow this, since (e.g.) <code>ISessionBaseFactory<SessionA></code> and <code>ISessionBaseFactory<SessionB></code> are not a common base class, but entirely different types.</p>\n\n<p>If we need only static (compile-time) polymorphism, we can use templates instead, and avoid the common base class entirely.</p>\n\n<pre><code>class SessionA\n{\n void Load(Stream& stream);\n void Save(Stream& stream) const;\n};\n\nclass SessionB\n{\n void Load(Stream& stream);\n void Save(Stream& stream) const;\n};\n\ntemplate<class SessionT>\nvoid DoSomething(SessionT const& session)\n{\n Stream stream;\n session.Save(stream); // works with SessionA and SessionB\n}\n</code></pre>\n\n<p>It appears, however, that you don't actually need either kind of polymorphism, since there is only one session type.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T11:22:35.020",
"Id": "442962",
"Score": "0",
"body": "1) I am intentionally using Compile time polymorphism as it can be faster and we can achieve almost same behavior(no static used). 2) Thanks for pointing out stream bug nd int/size bug i am working on that i will update the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T13:48:30.000",
"Id": "442981",
"Score": "0",
"body": "Great. (Also, just to note that when you update the code it's best to create a new question instead of editing the existing one - that way the answers still make sense)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T14:19:40.747",
"Id": "442984",
"Score": "0",
"body": "Sure man thanks"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T10:03:26.507",
"Id": "227504",
"ParentId": "227350",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227504",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T17:41:24.913",
"Id": "227350",
"Score": "3",
"Tags": [
"c++",
"c++11",
"design-patterns"
],
"Title": "Consistent and extendable way to store data for session"
}
|
227350
|
<p>I made this javascript code for a simple slider that can be controlled by arrows up/down.</p>
<p>I'm wondering what I could have done better..</p>
<pre><code>document.addEventListener('keydown', changeSlide);
var wrap = document.querySelector('#wrap');
var slides = wrap.getElementsByTagName('div');
var slidesCount = wrap.children.length-1;
var i = 0;
slides[i].classList.add('active');
document.querySelector('#current').innerHTML += i+1;
document.querySelector('#total').innerHTML += slidesCount+1;
function changeSlide(e) {
if (e.keyCode == 38) {
if(i >= slidesCount) {
i = 0;
} else(
i++
)
} else if (e.keyCode == 40) {
if(i <= 0) {
i = slidesCount;
} else (
i--
)
}
for (let index = 0; index < slidesCount+1; index++) {
slides[index].classList.remove('active');
}
slides[i].classList.add('active');
document.querySelector('#current').innerHTML = (i+1);
}
</code></pre>
<p>Here is event html:</p>
<pre><code><body>
<link rel = "stylesheet" href = "style.css"/>
<div id = "wrap">
<div>
<h3>Title</h3>
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/19/Ryan_ten_Doeschate_ODI_batting_graph.svg/1216px-Ryan_ten_Doeschate_ODI_batting_graph.svg.png" alt="">
</div>
<div>
<h3>Title</h3>
<img src="https://pmpaspeakingofprecision.files.wordpress.com/2013/06/ismmay2013.jpg" alt="">
</div>
<div >
<h3>Title</h3>
<img src="https://www.rba.gov.au/speeches/2016/images/sp-so-2016-07-12-graph3.gif" alt="">
</div>
<div >
<h3>Title</h3>
<img src="https://www.rbnz.govt.nz/-/media/ReserveBank/Images/Key%20graphs/key-graph-mortgage-rates-since-1990.jpg?la=en&hash=B224DD2C76E0B0C2DDC85D3A7D3E9A60B7A73ACC" alt="">
</div>
<div >
<h3>Title</h3>
<img src="https://realtechwater.com/w_p/wp-content/uploads/2018/09/BOD-Graph-Website.jpg" alt="">
</div>
</div>
<div id = counter>
<span id="current"></span>
<span>of</span>
<span id="total"></span>
</div>
<script src="slider.js"></script>
</body>
</code></pre>
<p>And a little bit of css:</p>
<pre><code>img {
display: block;
width: 100%;
}
#wrap > div {
display: none;
}
#counter {
position: absolute;
bottom: 5px;
right: 5px;
}
.active {
display: block!important;
}
</code></pre>
<p>For those who like codepen, <a href="https://codepen.io/pantata/pen/BaBWege" rel="nofollow noreferrer">here is the link</a>.</p>
|
[] |
[
{
"body": "<p>The main part of code I would focus on is this part with high branch complexity:</p>\n\n<blockquote>\n<pre><code>if (e.keyCode == 38) {\n\n if(i >= slidesCount) {\n i = 0;\n } else(\n i++\n )\n\n} else if (e.keyCode == 40) {\n\n if(i <= 0) {\n i = slidesCount;\n } else (\n i--\n )\n}\n</code></pre>\n</blockquote>\n\n<p>When you realise a carousel has circular navigation, you could take advantage of <em>modular arithmetic</em>. Note that you could then just use the actual count, without the <code>-1</code> 'hack'.</p>\n\n<pre><code>const slidesCount = wrap.children.length;\n</code></pre>\n\n<p>Refactored using modular arithmetic:</p>\n\n<pre><code>if (e.keyCode == 38) {\n i = (i + 1) % slidesCount;\n} else if (e.keyCode == 40) {\n i = (i - 1 + slidesCount) % slidesCount;\n}\n</code></pre>\n\n<p>This could further be refactored using a bi-directional formula:</p>\n\n<pre><code>const phase = e.keyCode == 38 ? 1 : e.keyCode == 40 ? -1 : 0;\ni = ((i + phase) % slidesCount + slidesCount) % slidesCount;\n</code></pre>\n\n<hr>\n\n<p>When initialising the carousel, you activate the first slide. This exact code is repeated in <code>changeSlide</code>. </p>\n\n<blockquote>\n<pre><code>slides[i].classList.add('active');\ndocument.querySelector('#current').innerHTML += i+1;\n</code></pre>\n</blockquote>\n\n<p>Consider providing a method <code>activate(index)</code>, which should also include the code for deactivating the other sliders.</p>\n\n<hr>\n\n<p>Prefer the use of <code>let</code> and <code>const</code> over <code>var</code>. The scope and intention of these keywords are better than the ol' var.</p>\n\n<blockquote>\n<pre><code>var wrap = document.querySelector('#wrap');\nvar slides = wrap.getElementsByTagName('div');\nvar slidesCount = wrap.children.length-1;\nvar i = 0;\n</code></pre>\n</blockquote>\n\n<pre><code>const wrap = document.querySelector('#wrap');\nconst slides = wrap.getElementsByTagName('div');\nconst slidesCount = wrap.children.length;\nlet index = 0;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T18:34:11.797",
"Id": "442661",
"Score": "0",
"body": "You use _modular arithmic_ twice but did you perhaps mean _arithmetic_?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T18:37:13.393",
"Id": "442663",
"Score": "0",
"body": "Of course, I put that one in for you to find... why else ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T18:37:22.113",
"Id": "442664",
"Score": "0",
"body": "I guess it's a side-effect of that kotlin app about music notes some times ago :-]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T00:04:14.160",
"Id": "442704",
"Score": "0",
"body": "nesting ternaries "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T09:12:36.320",
"Id": "442769",
"Score": "0",
"body": "@LukeRobertson some like it, some don't :) I find this one to be readable."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T19:34:08.457",
"Id": "227354",
"ParentId": "227353",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T19:08:02.387",
"Id": "227353",
"Score": "2",
"Tags": [
"javascript",
"html",
"dom"
],
"Title": "javascript carousel"
}
|
227353
|
<p>I have these scripts</p>
<pre><code>@section('custom-scripts')
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript">
let steps = ['device', 'agent', 'ssid', 'tunnel', 'captivePortal', 'traffic'];
let stepColors = ['#4BB7E8', '#769BD0', '#9B83BC', '#82C341', '#53BD6D', '#30B795'];
var selections = [];
var correctIndex = 0;
var selectedIndex = 0;
var agentUuid = '';
var agentInterfaces = '';
var selectedText = 'device';
var fadeColor = '#4BB7E8';
var selectedInterface = '';
var sessionName = '';
$('div.col-sm-2').hide();
$('div.col-sm-2').fadeIn(5000);
$('div.options').hide();
$('div.selected').hide();
$('div.line').hide();
function showOptions(selector) {
var nextCircle = '';
/*======================================
= Circle Clicked =
======================================*/
$('.' + selector).on("click", function() {
selectedIndex = steps.indexOf(selector);
if (steps.indexOf(selector) != -1) {
nextCircle = steps[steps.indexOf(selector) + 1];
nextIndex = steps.indexOf(nextCircle);
console.log('currentCircle = ', selector);
// console.log('selectedIndex = ',steps.indexOf(selector));
// console.log('correctIndex =', correctIndex);
// console.log('nextCircle =', nextCircle);
// console.log('nextIndex =', nextIndex);
console.log('%c ---------------------------', "color: green;");
if(selectedIndex > correctIndex){
alert("Please start by selecting your device.");
return false;
}else{
$('.' + selector).off();
}
}
if(selector == 'agent'){
$('.fa.fa-plus').hide();
}else {
$('.fa.fa-plus').show();
}
let circle = $(this);
$('div.options').fadeOut('fast');
let currentOptions = circle.next().next('.options');
circle.animate({backgroundColor: fadeColor }, 100);
var data = {};
data.object = selector;
$.ajax({
method: 'POST',
url: `/profiles/${selector}`,
crossDomain: true,
contentType: false,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('value'),
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"Cache-Control": "no-cache"
},
data: data,
success: function(response) {
console.log(JSON.parse(JSON.stringify(response)));
for (var i = 0; i < response.length; i++) {
var id = response[i].replace('.','-').split(' ').join('-')
if(selector == 'agent'){
var agentName = response[i];
}
var htmlDivOption = `
<p id="${id}">
<span class="option">${id}</span>
<i id="${id}" class="btn btn-sm btn-info fa fa-info-circle float-right" data-toggle="popover" data-content="" title="" data-placement="right" data-html="true" role="button" ></i>
</p>
`;
currentOptions.append(htmlDivOption);
}
if(selector == 'tunnel'){
var htmlExtraOptions = `
<p id="vlan">
<span class="option">VLAN Tunnel</span>
<i class="btn btn-sm btn-info fa fa-info-circle float-right" data-toggle="popover" data-content="" title="" data-placement="right" data-html="true" role="button" ></i>
</p>
<p id="none">
<span class="option">No Tunnel</span>
<i class="btn btn-sm btn-info fa fa-info-circle float-right" data-toggle="popover" data-content="" title="" data-placement="right" data-html="true" role="button" ></i>
</p>
`;
currentOptions.append(htmlExtraOptions);
}
if(selector == 'agent'){
$.ajax({
method: 'POST',
url: `/profiles/${selector}/${agentName}`,
crossDomain: true,
contentType: false,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('value'),
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"Cache-Control": "no-cache"
},
data: data,
success: function(agentDetails) {
agentUuid = agentDetails.agent_uuid;
agentInterfaces = agentDetails.agent_interfaces;
console.log(JSON.parse(JSON.stringify(agentDetails)));
console.log('%c agentUuid :' + agentUuid , "color: green;");
}
});
}
currentOptions.slideDown(100);
$('.popover').remove();
let currentPlusSign = currentOptions.find('.fa-plus');
currentPlusSign.on("click", function(event) {
$('#'+selector+'Modal').modal('show');
});
/*======================================
= Option Clicked =
======================================*/
circle.siblings('.options').find('span.option').one("click", function(event) {
selectedText = $(this).closest("p").prop("id");
selections[selector] = selectedText;
if(selectedText == 'none' || selectedText == 'vlan'){
// alert(agentInterfaces);
//show interface options
if(selectedText == 'vlan'){
$(`p#none span`).unbind();
$(`p#${selectedText} span`).animate({"color": '#82C341'}, 100);
}else{
$(`p#vlan span`).unbind();
$(`p#${selectedText} span`).animate({"color": '#82C341'}, 100);
}
var htmlInterfaceSelect = `
<hr>
<div class="form-group row">
<label for="tunnelType" class="col-sm-6 col-form-label">Interface</label>
<div class="col-sm-6">
<select id="interface-${selectedText}">
<option value="default">Select your interface</option>
</select>
</div>
</div>`;
currentOptions.append(htmlInterfaceSelect);
var htmlInterfaceOptions = '';
for (i = 0; i < agentInterfaces.length; i++) {
console.log(agentInterfaces[i]);
var interfaceName = agentInterfaces[i];
htmlInterfaceOptions = htmlInterfaceOptions.concat(
`<option value="${interfaceName}">${interfaceName}</option>`);
}
// console.log('htmlInterfaceOptions = ',htmlInterfaceOptions);
// console.log(`#interface-${selectedText}`);
// htmlInterfaceOptions = htmlInterfaceOptions.concat('<button class="btn btn-sm btn-info "role="button"> Next </button>');
$(`#interface-${selectedText}`).prepend(htmlInterfaceOptions);
$(`#interface-${selectedText}`).slideDown(100);
currentOptions.slideDown(100);
$(`#interface-${selectedText}`).on('change', function(){
selectedInterface = $(this).val();
console.log('selectedInterface = ',selectedInterface);
$(this).slideUp();
hideOptions(circle.siblings('.options').find('span.option'), selector);
});
} else {
hideOptions($(this), selector);
}
});
$('.fa-info-circle').on("click", function(event) {
$('.popover').remove();
// $('.fa-info-circle').not(this).popover('hide');
let object = $(this).parent().parent().parent().find('span').attr("circle-name");
let objectName = $(this).closest("p").prop("id");
var data = {};
data.object = object;
data.objectName = objectName;
$.ajax({
method: 'POST',
url: `/profiles/${object}/${objectName}`,
crossDomain: true,
contentType: false,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('value'),
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"Cache-Control": "no-cache"
},
data: data,
success: function(response) {
console.log(JSON.parse(JSON.stringify(response)));
if (response.http_code >= 200 && response.http_code <= 207) {
var dataContent = '';
console.log("object = ", object);
console.log("objectName = ", objectName);
$('.fa-info-circle#'+objectName).attr("data-original-title", response.name);
if(object == 'device'){
dataContent = `
<p><strong>flow_type</strong> : ${response.flow_type} </p>
<p><strong>subscriber_type</strong> : ${response.subscriber_type} </p>`;
}else if(object == 'agent'){
dataContent = `
<p><strong>uuid</strong> : ${response.agent_uuid} </p>
<p><strong>hostname</strong> : ${response.hostname} </p>`;
}else if(object == 'ssid'){
dataContent = `
<p><strong>uuid</strong> : ${response.name} </p>
<p><strong>ssid</strong> : ${response.ssid} </p>
<p><strong>vlan</strong> : ${response.vlan} </p>`;
}else if(object == 'tunnel'){
dataContent = `
<p><strong>uuid</strong> : ${response.name} </p>
<p><strong>encap_type</strong> : ${response.encap_type} </p>
<p><strong>tunnel_mac</strong> : ${response.tunnel_mac} </p>`;
}else if(object == 'captiveportal'){
dataContent = `
<p><strong>login_success_msg</strong> : ${response.login_success_msg} </p>
<p><strong>logout_url</strong> : ${response.logout_url} </p>
<p><strong>submit_button_value</strong> : ${response.submit_button_value} </p>`;
}else if(object == 'traffic'){
dataContent = `
<p><strong>name</strong> : ${response.name} </p>
<p><strong>enable_speedtest</strong> : ${response.enable_speedtest}</p>`;
}else{}
objectName = objectName.replace('.','-').split(' ').join('-');
console.log('objectName = ',objectName);
$('.fa-info-circle#'+objectName).attr('data-content',dataContent);
$('.fa-info-circle#'+objectName+'[data-toggle="popover"]').popover('show');
} else {
//console.log('%c -------->> Error <<--------', "color: red;");
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
});
}
});
});
}
for (i = 0; i < steps.length; i++) {
showOptions(steps[i], stepColors[i]);
}
$('#sessionName').keyup(function() {
this.value = this.value.replace(/\s/g, '');
});
</script>
@include('layouts.admin.sessions.create.scripts.addGlow')
@include('layouts.admin.sessions.create.scripts.hideOptions')
@include('layouts.admin.sessions.create.scripts.launch')
@include('layouts.admin.sessions.create.scripts.save')
@stop
</code></pre>
<hr />
<h1>addGlow.blade.php</h1>
<pre><code><script type="text/javascript">
/*===============================
= addGlow =
===============================*/
function addGlow(selector) {
fadeColor = stepColors[selectedIndex];
// console.log('selectedIndex = ', selectedIndex);
// console.log('fadeColor = ', fadeColor);
selector.css("-webkit-box-shadow", "0 0 5px " + fadeColor, 100);
selector.css("-moz-box-shadow", "0 0 5px " + fadeColor, 100);
selector.css("box-shadow", "0 0 5px " + fadeColor, 100);
}
</script>
</code></pre>
<hr />
<h1>hideOptions.blade.php</h1>
<pre><code><script type="text/javascript">
// console.log($(window).width());
// console.log(window.devicePixelRatio);
/*====================================
= Hide Options =
====================================*/
function hideOptions(currentObject, selector) {
$(currentObject).parent().parent().slideUp("slow", function() {
fadeColor = stepColors[steps.indexOf(selector)];
//console.log('fadeColor = ', fadeColor);
$(this).next('.selected').text(selectedText).fadeIn(100);
$(this).next('.selected').css({"color": fadeColor }, 100);
$(this).next('.selected').css("border", "3px solid " + fadeColor, 100);
addGlow($(this).next('.selected'));
if (selector != 'traffic') {
correctIndex++;
$(this).prev('.line').fadeIn('fast');
if(window.devicePixelRatio < 1.2){
if ($(window).width() < 2500 && $(window).width() >= 2400 ) {
var width = '375px';
} else if ($(window).width() < 2400 && $(window).width() >= 2133 ) {
var width = '300px';
} else if ($(window).width() < 2133 && $(window).width() >= 1920 ) {
var width = '300px';
} else if ($(window).width() < 1920 && $(window).width() >= 1745) {
var width = '250px';
} else if ($(window).width() < 1745 && $(window).width() >= 1536) {
var width = '200px';
} else{}
} else {
if ($(window).width() < 2000 && $(window).width() >= 1800 ) {
var width = '300px';
} else if ($(window).width() < 1800 && $(window).width() >= 1600 ) {
var width = '200px';
} else if ($(window).width() < 1600 && $(window).width() >= 1440 ) {
var width = '200px';
} else if ($(window).width() < 1440 && $(window).width() >= 1309) {
var width = '150px';
} else if ($(window).width() < 1309 && $(window).width() >= 1152) {
var width = '100px';
} else{}
}
console.log('lineWidth = ', width);
$(this).prev('.line').animate({"width": width}, 1100);
addGlow($(this).prev('.line'));
$('span.'+selector).animate({backgroundColor: fadeColor }, 100);
}
$('.popover').remove();
// console.log(selections);
// console.log(typeof JSON.parse(JSON.stringify(selections)))
// console.log(Object.keys(selections).length);
if (Object.keys(selections).length == $('.circle-icon').length) {
// console.log(selections);
$('#sessionNameModal').modal('show');
$('#launch').on('click', function() {
sessionName = $('#sessionName').val();
launch(selections);
});
}
});
}
</script>
</code></pre>
<hr />
<h1>launch.blade.php</h1>
<pre><code><script type="text/javascript">
/*==============================
= launch =
==============================*/
function launch(selections) {
console.log('selections = ', selections);
var data = {};
data.clientProfile = selections.device;
data.agent = selections.agent;
data.ssidProfile = selections.ssid;
data.tunnelProfile = selections.tunnel;
data.trafficProfile = selections.traffic;
data.sessionName = sessionName;
data.agentUuid = agentUuid;
data.selectedInterface = selectedInterface;
console.log("data", data);
$.ajax({
method: 'POST',
url: '/sessions/store',
crossDomain: true,
contentType: false,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('value'),
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"Cache-Control": "no-cache"
},
data: data,
success: function(response) {
console.log('response = ', response);
if (response.http_code >= 200 && response.http_code <= 207) {
toastr.options = {
"debug": false,
"newestOnTop": true,
"positionClass": "toast-top-right",
"closeButton": true,
"progressBar": false
};
console.log('%c -------->> Success <<--------', "color: green;");
toastr.success(sessionName + ' launched !');
window.location.replace("/sessions");
} else {
toastr.options = {
"debug": false,
"newestOnTop": true,
"positionClass": "toast-top-right",
"closeButton": true,
"progressBar": false
};
toastr.error('can not launch.');
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
</script>
</code></pre>
<hr />
<h1>save.blade.php</h1>
<pre><code><script type="text/javascript">
/*============================
= save =
============================*/
function save(objectName,formId) {
var inputs = [];
$("form#" + formId + " :input").each(function(){
console.log($(this).val()); // This is the jquery object of the input, do what you will
var name = $(this).attr('name');
var value = $(this).val();
inputs[name] = value;
});
var object = $.extend({}, inputs);
// console.log("object", object);
$.ajax({
method: 'POST',
url: '/profiles/' + objectName + '/store',
crossDomain: true,
contentType: false,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('value'),
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"Cache-Control": "no-cache"
},
data: object,
success: function(response) {
console.log('response = ', response);
if (response.http_code >= 200 && response.http_code <= 207) {
toastr.options = {
"debug": false,
"newestOnTop": true,
"positionClass": "toast-top-right",
"closeButton": true,
"progressBar": false
};
console.log('%c -------->> Success <<--------', "color: green;");
toastr.success('created');
//window.location.replace("/sessions");
//hide modal;
$('#'+objectName+'Modal').modal('hide');
//rendering the list
var data = {};
data.object = objectName;
$.ajax({
method: 'POST',
url: `/profiles/${objectName}`,
crossDomain: true,
contentType: false,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('value'),
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"Cache-Control": "no-cache"
},
data: data,
success: function(response) {
console.log(JSON.parse(JSON.stringify(response)));
var options = JSON.parse(JSON.stringify(response));
var lastItem = options[options.length-1];
console.log(lastItem);
var htmlDivOption = `
<p id="${lastItem}">
<span class="option">${lastItem}</span>
<i id="${lastItem}" class="btn btn-sm btn-info fa fa-info-circle float-right" data-toggle="popover" data-content="" title="" data-placement="right" data-html="true" role="button" ></i>
</p>
`;
console.log('objectName =',objectName);
console.log($('#'+objectName).next().next('.options'));
$('.'+objectName).next().next('.options').append(htmlDivOption);
$('.'+objectName).next().next('.options').last().hide().fadeIn(200);
//return false;
}
});
} else {
toastr.options = {
"debug": false,
"newestOnTop": true,
"positionClass": "toast-top-right",
"closeButton": true,
"progressBar": false
};
toastr.error('can not create.');
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
</script>
</code></pre>
<p>I need some good suggestions on how can I do to refactor this a bit more.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T14:54:48.770",
"Id": "442986",
"Score": "2",
"body": "Out of interest, why are these blade files files that only contain JavaScript?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T13:17:05.603",
"Id": "451473",
"Score": "0",
"body": "Also, you'll need to add a little bit more context to your post if you want quality answers. What exactly is your code supposed to do?"
}
] |
[
{
"body": "<p>The question here is, as I see it, what are you trying to accomplish?\nDo you want to make the JavaScript more readable; focus on the JavaScript, do you want to organize these files better; focus on organizing the JavaScript and how it's passed to the frontend.</p>\n\n<p>Looking to myself, I would move the JavaScript scripts to a JavaScript file and reference them in your scripts stack. That way you can organize the JavaScript on the JavaScript side and keep your blade views clean</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-29T08:43:22.593",
"Id": "231447",
"ParentId": "227355",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T19:38:43.543",
"Id": "227355",
"Score": "1",
"Tags": [
"javascript",
"php",
"jquery",
"laravel"
],
"Title": "How to splits blade files that contain javascript?"
}
|
227355
|
<p>This Python code generates mazes with color and size customization. I intend to add several new maze generating algorithms(Sidewinder, Kruskal, Prim ...) to the Maze class but for now, there is only one (Binary tree algorithm). I need feedback for the overall code and there are a few specific points that I need suggestions on how to refactor/improve without affecting the features, main concern is feedback for accuracy of pixel calculations.</p>
<hr>
<ul>
<li>In <code>_make_grid_image()</code>: How to improve the drawing technique to be more accurate without leaving traces that need to be fixed (I fixed them by x_end and y_end coordinates for closing the maze)</li>
<li>In <code>make_binary_tree_maze_image()</code> and
<code>make_binary_tree_maze_visualization()</code>: both
functions share the same logic (one creates a single image and one
generates a GIF of the maze being created) however, because of the
inaccuracy of the drawing, I added some constants to adjust the
painting and the over painting for each frame in the case of GIF
generation and at the end in the case of the generation of a single
maze image. In order not to confuse you, try changing the <code>line_width</code>
default parameter in the Maze constructor and generate a single image
using <code>make_binary_tree_maze_image()</code>. The result most
probably will contain traces of the painting and overpainting of
lines. I need suggestions on how to improve this without affecting
the functionalities given that I will be using the same code for
future methods of the Maze class (that will include other maze
generating algorithms).</li>
</ul>
<p>The code works perfectly fine, have fun generating mazes and awaiting
your suggestions for improvements.</p>
<p><strong>Note:</strong> generation of 500 x 500 gif frames might take a while (30-60 secs) however generating a single full maze image takes less than a second, more for really large images (1000+ x 1000+)</p>
<p>Here are GIF examples for mazes created by binary tree algorithm:</p>
<p><a href="https://i.stack.imgur.com/ZKmcs.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZKmcs.gif" alt="50 x 50 Dark Blue x Red"></a>
<a href="https://i.stack.imgur.com/dcA3u.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dcA3u.gif" alt="50 x 50 Black x White"></a></p>
<p><a href="https://i.stack.imgur.com/hPFIc.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hPFIc.gif" alt="50 x 50 Purple x Light Green"></a>
<a href="https://i.stack.imgur.com/hxBhH.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hxBhH.gif" alt="50 x 50 Yellow x Dark Orange"></a></p>
<hr>
<pre><code>#!/usr/bin/env python
from PIL import Image, ImageDraw
import random
import os
import glob
import imageio
import shutil
class Cell:
"""Create grid cell."""
def __init__(self, row_index, column_index, rows, columns):
"""
Initialize grid cell.
row_index: cell row index.
column_index: cell column index.
rows: number of rows in grid.
columns: number of columns in grid.
"""
if row_index >= rows or row_index < 0:
raise ValueError(f'Expected a row index in range(0, {rows}) exclusive, got {row_index}')
if column_index >= columns or column_index < 0:
raise ValueError(f'Expected a column index in range(0, {columns} exclusive, got {column_index}')
self.row = row_index
self.column = column_index
self.rows = rows
self.columns = columns
self.linked_cells = []
def neighbors(self, grid):
"""Return North, South, East, West neighbor cells."""
neighbors = []
north = self.row - 1, self.column
if north[0] < 0:
north = 0
neighbors.append(0)
if north:
neighbors.append(grid[north[0]][north[1]])
south = self.row + 1, self.column
if south[0] >= self.rows:
south = 0
neighbors.append(0)
if south:
neighbors.append(grid[south[0]][south[1]])
east = self.row, self.column + 1
if east[1] >= self.columns:
east = 0
neighbors.append(0)
if east:
neighbors.append(grid[east[0]][east[1]])
west = self.row, self.column - 1
if west[1] < 0:
west = 0
neighbors.append(0)
if west:
neighbors.append(grid[west[0]][west[1]])
return neighbors
def link(self, other, grid):
"""Link 2 unconnected cells."""
if self in other.linked_cells or other in self.linked_cells:
raise ValueError(f'{self} and {other} are already connected.')
if self.columns != other.columns or self.rows != other.rows:
raise ValueError('Cannot connect cells in different grids.')
if self not in other.neighbors(grid) or other not in self.neighbors(grid):
raise ValueError(f'{self} and {other} are not neighbors and cannot be connected.')
if not isinstance(other, Cell):
raise TypeError(f'Cannot link Cell to {type(other)}.')
self.linked_cells.append(other)
other.linked_cells.append(self)
def unlink(self, other):
"""Unlink 2 connected cells."""
if self not in other.linked_cells or other not in self.linked_cells:
raise ValueError(f'{self} and {other} are not connected.')
self.linked_cells.remove(other)
other.linked_cells.remove(self)
def coordinates(self):
"""Return cell (row, column)."""
return self.row, self.column
def __str__(self):
"""Cell display."""
return f'Cell{self.coordinates()}'
class Maze:
"""
Generate a maze using different algorithms:
- Binary Tree algorithm.
"""
def __init__(self, rows, columns, width, height, line_width=5, line_color='black', background_color='white'):
"""
Initialize maze variables:
rows: number of rows in initial grid.
columns: number of columns in initial grid.
width: width of the frame(s).
height: height of the frame(s).
line_width: width of grid/maze lines.
line_color: color of grid/maze lines.
background_color: color of the grid/maze background (cells/path)
"""
if width % columns != 0:
raise ValueError(f'Width: {width} not divisible by number of columns: {columns}.')
if height % rows != 0:
raise ValueError(f'Height: {height} not divisible by number of {rows}.')
self.rows = rows
self.columns = columns
self.width = width
self.height = height
self.line_width = line_width
self.line_color = line_color
self.background_color = background_color
self.cell_width = width // columns
self.cell_height = height // rows
self.drawing_constant = line_width // 2
self.path = input('Enter path to folder to save maze creation GIF: ').rstrip()
def _make_grid_image(self):
"""Initiate maze initial grid image."""
grid = Image.new('RGB', (self.width, self.height), self.background_color)
for x in range(0, self.width, self.cell_width):
x0, y0, x1, y1 = x, 0, x, self.height
column = (x0, y0), (x1, y1)
ImageDraw.Draw(grid).line(column, self.line_color, self.line_width)
for y in range(0, self.width, self.cell_height):
x0, y0, x1, y1 = 0, y, self.width, y
row = (x0, y0), (x1, y1)
ImageDraw.Draw(grid).line(row, self.line_color, self.line_width)
x_end = (0, self.height - self.drawing_constant),\
(self.width - self.drawing_constant, self.height - self.drawing_constant)
y_end = (self.width - self.drawing_constant, 0), (self.width - self.drawing_constant, self.height)
ImageDraw.Draw(grid).line(x_end, self.line_color, self.line_width)
ImageDraw.Draw(grid).line(y_end, self.line_color, self.line_width)
return grid
def _create_maze_cells(self):
"""Return maze cells."""
return [[Cell(row, column, self.rows, self.columns) for column in range(self.columns)]
for row in range(self.rows)]
def _binary_tree_configuration(self):
"""Return binary tree maze configuration."""
cells = self._create_maze_cells()
for row in range(self.rows):
for column in range(self.columns):
current_cell = cells[row][column]
north, south, east, west = current_cell.neighbors(cells)
to_link = random.choice('nw')
if not north and not west:
continue
if to_link == 'n' and north:
current_cell.link(north, cells)
if to_link == 'w' and west:
current_cell.link(west, cells)
if to_link == 'n' and not north:
current_cell.link(west, cells)
if to_link == 'w' and not west:
current_cell.link(north, cells)
return cells
def make_binary_tree_maze_image(self):
"""Produce a maze image using binary tree algorithm."""
maze = self._make_grid_image()
cells = self._binary_tree_configuration()
linked_cells = {cell.coordinates(): [linked.coordinates() for linked in cell.linked_cells]
for row in cells for cell in row}
for row in range(self.rows):
for column in range(self.columns):
current_cell_coordinates = (row, column)
if (row, column + 1) in linked_cells[current_cell_coordinates]:
x0 = (column + 1) * self.cell_width
y0 = (row * self.cell_height) + (self.line_width - 2)
x1 = x0
y1 = y0 + self.cell_height - (self.line_width + 1)
wall = (x0, y0), (x1, y1)
ImageDraw.Draw(maze).line(wall, self.background_color, self.line_width)
if (row + 1, column) in linked_cells[current_cell_coordinates]:
x0 = column * self.cell_width + self.line_width - 2
y0 = (row + 1) * self.cell_height
x1 = x0 + self.cell_width - (self.line_width + 1)
y1 = y0
wall = (x0, y0), (x1, y1)
ImageDraw.Draw(maze).line(wall, self.background_color, self.line_width)
x_end = (0, self.height - self.drawing_constant),\
(self.width - self.drawing_constant, self.height - self.drawing_constant)
y_end = (self.width - self.drawing_constant, 0), (self.width - self.drawing_constant, self.height)
ImageDraw.Draw(maze).line(x_end, self.line_color, self.line_width)
ImageDraw.Draw(maze).line(y_end, self.line_color, self.line_width)
return maze
def make_binary_tree_maze_visualization(self, frame_speed):
"""
** NOTE: Works on Unix systems only.
Create a GIF for maze being created by a binary tree algorithm.
frame_speed: speed in ms.
"""
print('GIF creation started ...')
os.chdir(self.path)
maze = self._make_grid_image()
cells = self._binary_tree_configuration()
linked_cells = {cell.coordinates(): [linked.coordinates() for linked in cell.linked_cells]
for row in cells for cell in row}
count = 0
for row in range(self.rows):
for column in range(self.columns):
current_cell_coordinates = (row, column)
# Remove vertical walls
if (row, column + 1) in linked_cells[current_cell_coordinates]:
x0 = (column + 1) * self.cell_width
y0 = (row * self.cell_height) + (self.line_width - 2)
x1 = x0
y1 = y0 + self.cell_height - (self.line_width + 1)
wall = (x0, y0), (x1, y1)
ImageDraw.Draw(maze).line(wall, self.background_color, self.line_width)
y_end = (self.width - self.drawing_constant, 0), (self.width - self.drawing_constant, self.height)
ImageDraw.Draw(maze).line(y_end, self.line_color, self.line_width)
maze.save(self.path + str(count) + '.png', 'png')
count += 1
# Remove horizontal walls
if (row + 1, column) in linked_cells[current_cell_coordinates]:
x0 = column * self.cell_width + self.line_width - 2
y0 = (row + 1) * self.cell_height
x1 = x0 + self.cell_width - (self.line_width + 1)
y1 = y0
wall = (x0, y0), (x1, y1)
ImageDraw.Draw(maze).line(wall, self.background_color, self.line_width)
x_end = (0, self.height - self.drawing_constant), \
(self.width - self.drawing_constant, self.height - self.drawing_constant)
ImageDraw.Draw(maze).line(x_end, self.line_color, self.line_width)
maze.save(self.path + str(count) + '.png', 'png')
count += 1
rand_name = 'maze' + str(random.randint(10 ** 6, 10 ** 8))
os.mkdir(rand_name)
for file in os.listdir(self.path):
if file.endswith('.png'):
shutil.move(file, rand_name)
os.chdir(rand_name)
frames = glob.glob('*.png')
frames.sort(key=lambda x: int(x.split('.')[0]))
frames = [imageio.imread(frame) for frame in frames]
imageio.mimsave(self.path + str(rand_name) + '.gif', frames, 'GIF', duration=frame_speed)
print(f'Creation of {count} frames GIF successful.')
if __name__ == '__main__':
maze_test = Maze(50, 50, 500, 500)
maze_test.make_binary_tree_maze_image().show()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T11:04:23.177",
"Id": "442788",
"Score": "2",
"body": "I have rolled back the edits again to the point where the code is the same as the code reviewed in the answer. I have also locked the post for a short while to prevent alterations. Please do not update the code in your question after it has been answered (even if you believe it does not invalidate the answers). 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)*. Feel free to post a follow-up question linking back to this one instead."
}
] |
[
{
"body": "<h2>Type hints</h2>\n\n<pre><code>row_index, column_index, rows, columns\n</code></pre>\n\n<p>I can guess that these are all <code>int</code> based on the docs. But adding <code>:int</code> (etc) will help, here.</p>\n\n<h2>Variable reuse</h2>\n\n<pre><code> north = self.row - 1, self.column\n if north[0] < 0:\n north = 0\n neighbors.append(0)\n if north:\n neighbors.append(grid[north[0]][north[1]])\n</code></pre>\n\n<p>This is confusing. <code>north</code> starts off as a tuple, and then <em>maybe</em> becomes an int. First - it shouldn't be an int, it should be a <code>bool</code> based on your usage. Second - it shouldn't really change type. Variables should do one thing. Here you're using it for two things - coordinates, and a flag. Third - you don't even need the flag. Just replace <code>if north</code> with <code>else</code>.</p>\n\n<h2>Don't repeat yourself</h2>\n\n<p>The block I paste above is repeated four times with only minor variations. Think about what's common (references to <code>self.row</code> and <code>self.column</code>, bounds checking, appending to neighbours) and what changes (the deltas added to the coordinates, and the comparison value for bounds checking). Use this information to create a function that's called four times.</p>\n\n<p>The same applies to this block:</p>\n\n<pre><code> if (row, column + 1) in linked_cells[current_cell_coordinates]:\n x0 = (column + 1) * self.cell_width\n y0 = (row * self.cell_height) + (self.line_width - 2)\n x1 = x0\n y1 = y0 + self.cell_height - (self.line_width + 1)\n wall = (x0, y0), (x1, y1)\n ImageDraw.Draw(maze).line(wall, self.background_color, self.line_width)\n if (row + 1, column) in linked_cells[current_cell_coordinates]:\n x0 = column * self.cell_width + self.line_width - 2\n y0 = (row + 1) * self.cell_height\n x1 = x0 + self.cell_width - (self.line_width + 1)\n y1 = y0\n wall = (x0, y0), (x1, y1)\n ImageDraw.Draw(maze).line(wall, self.background_color, self.line_width)\n x_end = (0, self.height - self.drawing_constant),\\\n (self.width - self.drawing_constant, self.height - self.drawing_constant)\n y_end = (self.width - self.drawing_constant, 0), (self.width - self.drawing_constant, self.height)\n ImageDraw.Draw(maze).line(x_end, self.line_color, self.line_width)\n ImageDraw.Draw(maze).line(y_end, self.line_color, self.line_width)\n</code></pre>\n\n<p>Most of that is doubled up and shouldn't be.</p>\n\n<h2>Factor out logic</h2>\n\n<pre><code>if to_link == 'n':\n target = north or west\nelse:\n target = west or north\ncurrent_cell.link(target, cells)\n</code></pre>\n\n<p>This takes advantage of the fact that</p>\n\n<ul>\n<li><code>to_link</code> will only ever be <code>n</code> or <code>w</code>, so you can use an <code>else</code></li>\n<li><code>or</code> semantics in Python will take the first thing that's truthy, which is effectively what you were doing</li>\n<li>Only one call to <code>current_cell.link</code> is needed</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T03:35:02.570",
"Id": "442497",
"Score": "0",
"body": "any suggestions regarding the paint re-paint mechanism? I want to eliminate magic numbers and draw everything accurately, one of the reasons of repetition is that I'm not an expert when it comes to image processing so this might be the best I could do but of course there must be a better way that won't leave any traces and I won't have to repaint borders for each frame and tweak numbers manually inside the functions to get accurate frames."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T03:47:27.513",
"Id": "442502",
"Score": "1",
"body": "Paint re-paint? Do you mean the four calls to `ImageDraw.Draw`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T03:55:43.620",
"Id": "442504",
"Score": "0",
"body": "yeah, try changing the line width parameter in the Maze constructor and see what happens, the higher the change, the higher you will get a pixelated image unless you change self.line_width - 2 and self.line_width + 1 and play with them a little bit until the image adjusts, I need another technique that calculates which pixels (x, y) coordinates more accurately and maybe put it in a new function or so that automatically adjusts according to size and line width changes"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T03:07:38.043",
"Id": "227375",
"ParentId": "227363",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T00:08:31.503",
"Id": "227363",
"Score": "9",
"Tags": [
"python",
"python-3.x",
"image",
"animation"
],
"Title": "Maze generator in Python- Gif animator-Custom colors/sizes"
}
|
227363
|
<p><strong>Problem</strong> </p>
<p>I need to read custom text input of a sample document object model (DOM) represented in a <code>json</code> format from a file and store it in a struct I've defined as <code>DomNode</code>. I need help on properly navigating these DOM elements from the input file and keeping track of the child node pointers at each level of the dom tree. </p>
<p>The <code>read_dom_hierarchy</code> has a block comment that shows the contents of <code>dom.txt</code>.</p>
<p>I can not use any 3rd party libraries for this problem. Assume <code>dom.txt</code> will always have exactly 18 lines and it's content will not change.</p>
<p><strong>Source</strong></p>
<pre><code>#include <fstream>
#include <iostream>
#include <stack>
#include <string>
#include <sstream>
#include <vector>
struct DomNode
{
int level;
std::string tag;
std::string id;
std::vector<DomNode*>child;
};
static void read_dom_hierarchy(std::string* dom)
{
// reading custom input on my local machine, that follows this structure
/*
{
"tag": "div",
"id": "first",
"children":
[
{
"tag": "span",
"id": "second",
"children":
[
{
"tag": "span",
"id": "third"
}
]
}
]
}
*/
std::ifstream file_stream("dom.txt");
std::string line;
int i = 0;
while (getline(file_stream, line))
{
dom[i] = line;
i++;
}
}
static void parse_element_data(std::string& s)
{
s = s.substr(s.find(":") + 2);
s.erase(s.find(","));
s.erase(s.find("\""));
}
static void construct_dom_from_text(std::string* dom, DomNode* node, std::stack<std::string> token)
{
DomNode* current = node;
int level = 1;
for (int i = 0; i < 18; i++)
{
std::string line = dom[i];
if (line.find("{") != std::string::npos)
{
token.push(line);
}
else if(line.find("}") != std::string::npos)
{
if (token.top() == "{") {
token.pop();
return;
}
else {
token.push(line);
}
}
if (line.find("[") != std::string::npos)
{
token.push(line);
++level;
}
else if (line.find("]") != std::string::npos)
{
if (token.top() == "[") {
token.pop();
--level;
}
else {
token.push(line);
}
}
if (level == 0) { return; }
// store dom current data
if (line.find("tag") != std::string::npos) {
parse_element_data(line);
current->tag = line;
}
else if (line.find("id") != std::string::npos) {
parse_element_data(line);
current->id = line;
}
else if (line.find("children") != std::string::npos) {
current->level = level;
DomNode* c = new DomNode();
current->child.push_back(c);
}
}
}
int main()
{
std::string dom[18];
read_dom_hierarchy(dom);
DomNode* root = new DomNode();
std::stack<std::string> token;
construct_dom_from_text(dom, root, token);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T16:06:30.373",
"Id": "442618",
"Score": "0",
"body": "A fair number of JSON parsers have been posted here in the past (e.g., https://codereview.stackexchange.com/questions/7567/yet-another-c-json-parser-recursive), that might provide some inspiration for ways to consider approaching this task."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T11:21:57.413",
"Id": "442795",
"Score": "3",
"body": "The answer is removed now. Feel free to edit your current question into shape instead of asking a new one. We'll open it up once it has been sufficiently edited."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T16:49:09.147",
"Id": "443006",
"Score": "0",
"body": "Does it only have one node? `{tag, id, children}`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T16:53:44.570",
"Id": "443009",
"Score": "0",
"body": "If so using [ThorsSerializer](https://github.com/Loki-Astari/ThorsSerializer) you can read that like this: https://gist.github.com/Loki-Astari/078a223c6a4a815d44527a46d408da03"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T00:09:55.200",
"Id": "227364",
"Score": "2",
"Tags": [
"c++",
"json",
"dom",
"pointers"
],
"Title": "Parse DOM Tree in C++"
}
|
227364
|
<p>I'm working on a server and need a complete list of plugins that are installed for all wp installations. I only need to know whether a plugin exists or not, it doesn't matter where it exists.</p>
<p><strong>For example, given:</strong></p>
<pre><code>/siteA/wp-content/plugins/someplugin
/siteA/wp-content/plugins/anotherplugin
/siteB/wp-content/plugins/someplugin
</code></pre>
<p><strong>I need the following result:</strong></p>
<pre><code>someplugin
anotherplugin
</code></pre>
<p><strong>Here is the working command:</strong></p>
<pre><code>for i in $(find . -type d -name 'plugins' | grep 'wp-content/plugins$'); do find ${i} -maxdepth 1 -type d -exec sh -c 'for f do basename -- "$f"; done' sh {} + ; done | sort -u
</code></pre>
<p>Can this command be shortened?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T09:22:01.910",
"Id": "442534",
"Score": "0",
"body": "Doesn't work as expected for me. Output from\n`for i in $(find . -type d -name 'plugins' | grep 'wp-content/plugins$'); do find ${i} -maxdepth 1 -type d -exec sh -c 'for f do basename -- \"$f\"; done' sh {} + ; done | sort -u`\n is *anotherplugin **plugins** someplugin*. *Plugins* isn't requisite, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T20:57:27.847",
"Id": "443173",
"Score": "0",
"body": "No plugins isn't a requisite, it could be considered an error in the code as it's not actually a plugin but for my use case I didn't mind it being listed"
}
] |
[
{
"body": "<p>If <code>plugins</code> only contain directories, list every unique entry in <code>plugins</code>:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>shopt -s globstar\n\\ls -- **/wp-content/plugins |sort -u\n</code></pre>\n\n<p>Otherwise, include the final targets in the glob, plus a trailing slash to limit globbing to directories. </p>\n\n<p>That will yield paths relative to <code>.</code>, with trailing slash like <code>siteA/wp-content/plugins/anotherplugin/</code>. We clean it up with <code>basename</code> (shorter, easier) or <code>awk</code> (<s>faster if there are very many results</s> <em>EDIT: nope, awk is slower in spite of the algorithmic efficiency</em>).</p>\n\n<p>The backslash ignores aliases, just in case an aliased <code>ls</code> would mess up the output.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>shopt -s globstar\n\n# probably easier to remember\n\\ls -d -- **/wp-content/plugins/*/ |xargs -n1 basename -- |sort -u\n\n# slower, fancier\n\\ls -d -- **/wp-content/plugins/*/ |awk -F/ '!u[$(NF-1)]++ { print $(NF-1) }'\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T02:43:34.557",
"Id": "227371",
"ParentId": "227366",
"Score": "3"
}
},
{
"body": "<p><strong>Note:</strong> a module is actually a directory located in some \"wp-content/plugins\" directories.</p>\n\n<p>The main issue with your algorithm is the <code>-exec</code> primary. Contrary to what you think, the primary executes its argument for each corresponding file.</p>\n\n<pre><code>for i in $(find . -type d -name 'plugins' | grep 'wp-content/plugins$'); do\n find $i -maxdepth 1 -type d -exec basename -- '{}' \\;\ndone | sort -u\n</code></pre>\n\n<p>Otherwise, the algorithm is correct but we have an issue about the performance. A good knowledge of utilities makes the difference.</p>\n\n<p>For instance, your shell command operation looks like this:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>> find <dir>\n >> find <dir A> <sub_dirs>\n >>> basename <dir 1> \n >>> basename <dir 2>\n ...\n >> find <dir B> <sub_dirs>\n >>> basename <dir 1>\n >>> basename <dir 2>\n ...\n >> find ...\n >>> basename ...\n ...\n> sort the output\n</code></pre>\n\n<p>Your may use <code>find</code> using the \"AND\" operator <code>-a</code> to filter the directory names.</p>\n\n<pre><code>find . -type d -path \"*/wp-contents/plugins/*\" -a \\\n ! -path \"*/wp-contents/plugins/*/*\" -exec basename '{}' \\; |\n sort -u\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T20:54:05.980",
"Id": "443170",
"Score": "2",
"body": "I like the use of path but there would still be work to do after your command has run. Wouldn't the output contain duplicates and display the absolute path to each plugin?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T20:16:57.010",
"Id": "227603",
"ParentId": "227366",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T01:21:29.893",
"Id": "227366",
"Score": "2",
"Tags": [
"bash",
"shell",
"sh"
],
"Title": "Shell command to output all plugins that exist across multiple wordpress installations"
}
|
227366
|
<p>I have the following table in a PostgreSQL database:</p>
<pre><code> creator uuid not null,
post uuid not null,
type text not null,
content text not null,
constraint check_type check
(type = 'comment' or
(type = 'vote' and
(content = 'up' or
content = 'down')))
</code></pre>
<p>In order to enforce the constraint that there is no duplicate pair of (creator, post, type) where <code>type = 'vote'</code> (ie. a specific user can only vote on a specific post once) I can either create a unique index like so:</p>
<pre><code>create unique index interactions_index on posts.interactions
(creator, post, type, content) where type = 'vote';
</code></pre>
<p><strong>Or</strong> I can query the table on in the server code and do a check there.</p>
<p>My questions: </p>
<ol>
<li><p>which one is more efficient, or should I include both for safeguards? How much will having a unique index impact performance (say 100,000 posts @ 1000 likes/post = 100,000,000 database lines)?</p></li>
<li><p>I am using this to store "interactions" with a post (ie. likes, comments), is this a good/sustainable way to approach this, or should I be doing something different?</p></li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T05:04:47.783",
"Id": "443077",
"Score": "0",
"body": "What is the difference between `type='like'` and `type='vote'`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T22:35:20.507",
"Id": "443182",
"Score": "0",
"body": "none. it's a typo :)"
}
] |
[
{
"body": "<blockquote>\n <p>which one is more efficient</p>\n</blockquote>\n\n<p>Almost surely the unique index will be. Querying back and forth between the server and database is very expensive, and the query that you would have to write to check the table beforehand would do the same thing as the unique constraint - just far less efficiently. The <em>best case</em> is that you'd have to still add an index to the database to get vaguely similar performance, and the connection round-trip expense between the server and database would then be the limiting factor.</p>\n\n<p>All of that said: you aren't asking the more important question, which is</p>\n\n<p><em>which method gives me a better guarantee of correctness?</em></p>\n\n<p>Under most circumstances, it's useless to do performance tuning when your data are wrong. The database can guarantee that the data remain valid if you give it a constraint to enforce. If the server is responsible for enforcing the constraint, and it has a race condition or other nasty concurrency edge case, you're setting yourself up for a very difficult debugging session trying to find why duplicates are getting into your database.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T03:42:01.250",
"Id": "442500",
"Score": "0",
"body": "a followup, in the case where you try to insert a duplicate, is it better/more efficient to query the database and block it if it exists, or try to insert right away and let the unique index throw an error?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T03:45:08.800",
"Id": "442501",
"Score": "0",
"body": "Let the database index return a unique constraint violation. Think about the number of trips to the database and back. In the first case, there's one request and one response. In the second case, there are two requests and two responses."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T03:25:22.280",
"Id": "227377",
"ParentId": "227372",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "227377",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T03:01:34.540",
"Id": "227372",
"Score": "3",
"Tags": [
"performance",
"sql",
"postgresql"
],
"Title": "Enforcing a constraint that a user may vote on each post at most once"
}
|
227372
|
<p>The code below parses a tracklist (sample input below) and generates a six-member tuple, including cumulative timestamps in <code>mm:ss</code>. (sample output at bottom).</p>
<ul>
<li>couldn't easily see how to rewrite it from a for-loop to a generator <code>get_track_with_cumulative_timestamp(itt)</code></li>
<li>I think we don't need a custom object, i.e. avoid <a href="https://codereview.stackexchange.com/questions/166158/split-mp3-of-album-into-individual-tracks">this approach</a></li>
<li>generator will need to internally store state <code>(tmm, tss)</code> being the end-time of each song. So we yield each result with the start-time of each song; incrementing the time-arithmetic comes after that.</li>
<li>are there better idioms for the (mm,ss) modulo-60 counters? <code>decimal.Decimal</code> seems overkill. I suppose we could always pull a trick internally using one float to represent both (mm,ss)</li>
</ul>
<p>Current not-so-great procedural code:</p>
<pre><code>tracklist = """
1. Waiting For A Miracle 5:02
2. Bedroom Eyes 5:01
3. In Over My Head 4:31
4. Higher Ground / Written-By – S. Wonder* 3:38
5. Hot Blood 4:15
6. Running Away 4:28
7. I've Had Enough 3:47
8. Blacklisted / Guitar [Other] – Jonny Fean* 4:11
9. Last Thing At Night 2:49"""
tracklist = [t for t in tracklist.split('\n') if t]
import re
pat = re.compile(r'(?P<no>[0-9]+)\. (?P<name>.*) (?P<mm>[0-9]+):(?P<ss>[0-9]+)')
(tmm,tss) = (0,0)
result = []
for t in tracklist:
m = pat.match(t)
#print(m.groups())
lmm, lss = int(m['mm']), int(m['ss'])
result.append((int(m['no']), tmm, tss, lmm, lss, m['name']))
#yield (int(m['no']), tmm, tss, lmm, lss, m['name']))
tss += lss
tmm += lmm
if tss >= 60:
tmm += 1
tss -= 60
# Output looks like this:
for _ in result: print('{} | {:02d}:{:02d} | {}:{:02d} | {}'.format(*_))
</code></pre>
<pre class="lang-none prettyprint-override"><code>1 | 00:00 | 5:02 | Waiting For A Miracle
2 | 05:02 | 5:01 | Bedroom Eyes
3 | 10:03 | 4:31 | In Over My Head
4 | 14:34 | 3:38 | Higher Ground / Written-By – S. Wonder*
5 | 18:12 | 4:15 | Hot Blood
6 | 22:27 | 4:28 | Running Away
7 | 26:55 | 3:47 | I've Had Enough
8 | 30:42 | 4:11 | Blacklisted / Guitar [Other] – Jonny Fean*
9 | 34:53 | 2:49 | Last Thing At Night
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T03:31:39.643",
"Id": "442493",
"Score": "1",
"body": "Please do not edit your question with modified code. Once you've gathered sufficient feedback from this question, CRSE policy is that you open a new question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T03:34:30.413",
"Id": "442496",
"Score": "0",
"body": "@Reinderien: I didn't gather 'sufficient feedback'; your answer did not actually address how to do better idiom for the (mm,ss) modulo-60 counter for this use-case. We're not talking about generalized timedeltas of anything from milliseconds to years."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T03:36:01.333",
"Id": "442498",
"Score": "1",
"body": "I'm not suggesting that my answer was conclusive... I'm suggesting that you leave this open until you're satisfied with my (or someone else's) feedback. Patience."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T04:15:09.660",
"Id": "442505",
"Score": "1",
"body": "I've rolled this back per https://codereview.meta.stackexchange.com/questions/1763/for-an-iterative-review-is-it-okay-to-edit-my-own-question-to-include-revised-c"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T05:15:06.107",
"Id": "442509",
"Score": "0",
"body": "@Reinderien: ok I wasn't aware of the no-code-revisions policy. And yes you're right about `datetime.timedelta`"
}
] |
[
{
"body": "<h2>Implicit tuples</h2>\n\n<pre><code>(tmm,tss) = (0,0)\n</code></pre>\n\n<p>This shouldn't need any parens.</p>\n\n<h2>Generator</h2>\n\n<blockquote>\n <p>couldn't easily see how to rewrite it from a for-loop to a generator </p>\n</blockquote>\n\n<p>It actually is quite easy. Make your code into a function, delete <code>result</code>, and replace <code>result.append</code> with <code>yield</code>.</p>\n\n<h2>Time spans</h2>\n\n<blockquote>\n <p>are there better idioms for the (mm,ss) modulo-60 counters? </p>\n</blockquote>\n\n<p><a href=\"https://docs.python.org/3/library/datetime.html#timedelta-objects\" rel=\"noreferrer\">Yes</a>!</p>\n\n<h2>Custom objects</h2>\n\n<blockquote>\n <p>I think we don't need a custom object</p>\n</blockquote>\n\n<p>Named tuples take one line to declare, and suck less than unstructured data. So do that, at least.</p>\n\n<h2>Underscores</h2>\n\n<p>I just noticed that you're looping with an underscore as your loop variable. By convention this means \"I'm not going to use this value\"... but then you used it anyway. Give this variable a meaningful name.</p>\n\n<h2>Example</h2>\n\n<pre><code>import re\nfrom collections import namedtuple\nfrom datetime import timedelta\n\nTRACK_PAT = re.compile(r'(?P<no>[0-9]+)\\. (?P<name>.*) (?P<mm>[0-9]+):(?P<ss>[0-9]+)$', re.M)\nTrack = namedtuple('Track', ('number', 'time', 'length', 'name'))\n\n\ndef parse_track(body):\n t_total = timedelta()\n for match in TRACK_PAT.finditer(body):\n length = timedelta(minutes=int(match['mm']), seconds=int(match['ss']))\n yield Track(int(match['no']), t_total, length, match['name'])\n t_total += length\n\n\nfor track in parse_track(\n\"\"\"\n1. Waiting For A Miracle 5:02\n2. Bedroom Eyes 5:01\n3. In Over My Head 4:31\n4. Higher Ground / Written-By – S. Wonder* 3:38\n5. Hot Blood 4:15\n6. Running Away 4:28\n7. I've Had Enough 3:47\n8. Blacklisted / Guitar [Other] – Jonny Fean* 4:11\n9. Last Thing At Night 2:49\"\"\"\n):\n print(f'{track.number} | {track.time} | {track.length} | {track.name}')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T03:23:57.507",
"Id": "442491",
"Score": "0",
"body": "1) Yes I know parens are not needed around implicit tuples, I wanted to be explicit that it's an mm:ss counter 2) Done 3) Time spans with `datetime.timedelta` seem to be overkill *for this use-case* like I said: can you show equivalent code that is <=8 lines long? I doubt it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T03:30:29.913",
"Id": "442492",
"Score": "0",
"body": "Given that your code is currently about 33 lines long, 8 lines seems like an unrealistic request. Regardless, I'll post example code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T03:32:01.323",
"Id": "442494",
"Score": "0",
"body": "You're missing my point that `datetime.timedelta` is not good for this particular use-case and will be lomger, more clunky and less readable than the current."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T03:34:15.407",
"Id": "442495",
"Score": "0",
"body": "You asked for a better idiom. Doing one's own time math is a foul code smell. If you don't like it, don't listen to me ¯\\_(ツ)_/¯"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T03:39:11.147",
"Id": "442499",
"Score": "0",
"body": "I'm aware that doing one's own time math is generally a bad code smell, that's precisely one of the two reasons I posted this question in the first place. However I did listen to your comments and you haven't shown any better code idiom for this use-case. `datetime.timedelta` is terrible overkill."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T03:49:23.520",
"Id": "442503",
"Score": "0",
"body": "Btw my code clearly isn't 33 lines long. The generator body is only 10 lines long. That's my point to you: it's hard to see how anyone can show shorter code than the (admittedly distasteful) manual modulo-60 mm,ss counter tuple. (Without hacking into a single float, which is even more distasteful)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T05:02:29.417",
"Id": "442506",
"Score": "2",
"body": "Ok thanks you were right and I was wrong, that is much more compact and elegant. Mind you the `datetime.timedelta` doc doesn't showcase that. As to the need for an object/ namedtuple Track, really we just want some sort of object or tuple which can take a custom `__str__()` method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T00:07:57.840",
"Id": "443506",
"Score": "0",
"body": "Accepted. Any thoughts on how to improve the `datetime.timedelta` doc? It is all syntax and no examples. I've used it for 10 years and never realized it could do that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T02:13:14.683",
"Id": "443512",
"Score": "0",
"body": "Improve the documentation? How? It seems quite clear to me. It spells out which kwargs are accepted by the constructor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T06:53:15.150",
"Id": "443517",
"Score": "0",
"body": "Reinderien: there's zero documentation to say that `'{}'.format(timedelta(month=6, minutes=4, seconds=32))` magically works **without any strftime format string and gives a smart format, dropping unneeded leading zero fields week, day**. Thus: `'0:04:32'`. Yet `'{}'.format(timedelta(weeks=6, minutes=4, seconds=32))` gives `'42 days, 0:04:32'`. No documentation of that smart-formatting behavior in the [doc](https://docs.python.org/3/library/datetime.html) or `help(datetime)`. I would have expected unwanted leading and trailing junk like `(0 days, ..., 0 milliseconds)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T13:16:23.553",
"Id": "443562",
"Score": "0",
"body": "That's also documented quite clearly. `Returns a string in the form [D day[s], ][H]H:MM:SS[.UUUUUU], where D is negative for negative t.` Those square brackets are Backus-Naur format, and mean that the days, leading hour digits and microseconds are optional."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T17:53:28.630",
"Id": "443641",
"Score": "0",
"body": "No it's not and I just stated why, and I've been using it for 10+ years. The doc implies that `'{}'.format(timedelta(month=6, minutes=4, seconds=32))` would render as `(0 days, ..., 0 milliseconds)` and nowhere does it say that unused leading or trailing zero fields get dropped. Yes we know what Backus-Naur format is, but the dropping is not being communicated. Look, the doc is deficient for both the constructor, `__str__` and other formatting methods in not explicitly saying \"if a timedelta only has min and sec, that is all that will get shown, with one single leading zero hour digit\"...."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T17:55:40.887",
"Id": "443643",
"Score": "0",
"body": "...and here's a [blatant counterexample from the 2.6 doc showing that you can and do get unwanted junk 'days' values](https://docs.python.org/2.6/library/datetime.html) : Note that normalization of negative values may be surprising at first. For example: `timedelta(microseconds=-1)` gives `(d.days, d.seconds, d.microseconds)` = `(-1, 86399, 999999)`"
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T03:16:46.877",
"Id": "227376",
"ParentId": "227374",
"Score": "5"
}
},
{
"body": "<p>This part is not that compact in terms of code lines, which you seek to decrease:</p>\n\n<blockquote>\n<pre><code>tss += lss\ntmm += lmm\nif tss >= 60:\n tmm += 1\n tss -= 60\n</code></pre>\n</blockquote>\n\n<p>One solution is to keep track of <code>t</code> (total seconds) instead of <code>tss</code> and <code>tmm</code>.</p>\n\n<pre><code>t = 0\nresult = []\n\nfor t in tracklist:\n m = pat.match(t)\n lmm, lss = int(m['mm']), int(m['ss'])\n\n result.append((int(m['no']), t // 60, t % 60, lmm, lss, m['name']))\n\n t += 60 * lmm + lss\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T05:03:37.593",
"Id": "442507",
"Score": "1",
"body": "Also a good approach (to the arithmetic). Yes I get that it can equally be done in a generator."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T05:06:01.437",
"Id": "442508",
"Score": "0",
"body": "it can easily be transformed using a generator if you want. My point was only about that modulo logic :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T04:59:34.270",
"Id": "227379",
"ParentId": "227374",
"Score": "3"
}
},
{
"body": "<p>Here was my updated v0.02 written as a generator. (Can combine with either Reinderien's <code>datetime.timedelta</code> aproach or dfhwze's modulo code)</p>\n\n<pre><code>import re\n\n#tracklist = \"\"\"... as defined above ...\"\"\"\ntracklist = iter(t for t in tracklist.split('\\n') if t)\n\npat = re.compile(r'(?P<no>[0-9]+)\\. (?P<name>.*) (?P<mm>[0-9]+):(?P<ss>[0-9]+)')\n\ndef gen_cumulative_timestamp(itracklist):\n tmm, tss = 0, 0\n\n for t in itracklist:\n m = pat.match(t)\n lmm, lss = int(m['mm']), int(m['ss'])\n\n yield ( int(m['no']), tmm, tss, lmm, lss, m['name'] )\n\n tss += lss\n tmm += lmm\n if tss >= 60:\n tmm += 1\n tss -= 60\n\nfor t in gen_cumulative_timestamp(tracklist):\n # Ideally should have a custom object/NamedTuple which has a custom __str__() method\n print('{} | {:02d}:{:02d} | {}:{:02d} | {}'.format(*t))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T05:11:37.453",
"Id": "227380",
"ParentId": "227374",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227376",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T03:03:26.857",
"Id": "227374",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"parsing",
"datetime",
"formatting"
],
"Title": "Python process tracklist, get cumulative timestamp of each track"
}
|
227374
|
<p>I'm a beginner in python so I decided to take a simple challenge and wrote tictactoe</p>
<p>How to write it better in future?
What's wrong with my code?</p>
<pre><code>from random import choice
again = ''
board = '[1][2][3]\n[4][5][6]\n[7][8][9]'
win_combination = [(1,2,3),(4,5,6),(7,8,9),(1,4,7),(2,5,8),(3,6,9),(1,5,9),
(3,5,7)]
pleyer_numbers = []
computer_numbers = []
numbers = [x for x in range(1,10)
def replece_board(board):
board = board.replace(str(pleyer_number),'X')
board = board.replace(str(computer_number),'O')
return board
def change_number():
pleyer_numbers.append(int(pleyer_number))
computer_numbers.append(int(computer_number))
def check_win(who):
check = 0
for win in win_combination:
for number in win:
if number in who:
check += 1
if check == 3:
return True
else:
continue
check = 0
return False
print('Welcome in simple tic-tac-toe!\nYour enemy is computer.')
while True:
board = '[1][2][3]\n[4][5][6]\n[7][8][9]'
pleyer_numbers = []
computer_numbers = []
numbers = [x for x in range(1,10)]
while True:
print(board)
pleyer_number = input('Enter the field number: ')
if int(pleyer_number) not in range(1,10):
print('There is no filed with this number.')
continue
elif int(pleyer_number) not in numbers:
print('This field is occupied.')
continue
numbers.remove(int(pleyer_number))
if numbers:
computer_number = choice(numbers)
numbers.remove(computer_number)
print('Computer chose field: ' + str(computer_number))
change_number()
board = replece_board(board)
if check_win(pleyer_numbers):
print(board.replace(str(pleyer_number),'X'))
print('----------YOU WON!----------')
break
if check_win(computer_numbers):
print(board)
print('----------YOU LOST!----------')
break
if not numbers:
print('\n----------TIE!----------')
break
again = input('Do you want to play again? y/n ')
while True:
if again != 'y' and again != 'n':
again = input('Only y/n ')
else:
break
if again == 'n':
break
else:
print('----------------------------\nYou started new game!')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T12:02:49.747",
"Id": "442555",
"Score": "1",
"body": "Welcome to Code Review! Please make sure that the code in your question is actually working. It seems like there is at least a missing bracket at `numbers = [x for x in range(1,10)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T12:08:26.320",
"Id": "442558",
"Score": "1",
"body": "Also, `pleyer` should be spelled `player`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T13:04:35.323",
"Id": "442568",
"Score": "1",
"body": "I have rolled back your last edit. 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)*."
}
] |
[
{
"body": "<p>Welcome to code review.</p>\n\n<h1>Bug:</h1>\n\n<p>unmatched parenthesis at line 9:</p>\n\n<pre><code>numbers = [x for x in range(1,10)\n</code></pre>\n\n<h1>Style:</h1>\n\n<p>I suggest you check PEP0008 <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">https://www.python.org/dev/peps/pep-0008/</a> the official Python style guide and here are a few comments:</p>\n\n<pre><code>win_combination = [(1,2,3),(4,5,6),(7,8,9),(1,4,7),(2,5,8),(3,6,9),(1,5,9),(3,5,7)]\n</code></pre>\n\n<p>a space should be left after commas for readability like this:</p>\n\n<pre><code>win_combination = [(1, 2, 3), (4, 5, 6), (7, 8, 9), (1, 4, 7), (2, 5, 8), (3, 6, 9), (1, 5, 9)] \n</code></pre>\n\n<h1>Spelling</h1>\n\n<pre><code>pleyer_numbers = []\ndef replece_board(board):\nprint('There is no filed with this number.')\n</code></pre>\n\n<p>A code is also designed for human beings to read regardless of whether the machine does or does not care if names are not significant we would be using barcodes as variable names instead.)</p>\n\n<h1>Code</h1>\n\n<p>General remarks: your code is a bit longer than it should and disorganized and you might want to consider breaking down your code into functions with separate roles.</p>\n\n<pre><code>def replece_board(board):\n</code></pre>\n\n<p>replace what board? what is board? </p>\n\n<pre><code>def change_number():\n</code></pre>\n\n<p>what number?</p>\n\n<pre><code>def check_win(who):\n</code></pre>\n\n<p>what is who? a number? a string? a list? something else?</p>\n\n<p>for each public function you make now and in the future you should include a docstring answering such obvious questions.</p>\n\n<p><strong>Docstrings:</strong> Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. It's specified in source code that is used, like a comment, to document a specific segment of code.</p>\n\n<pre><code>if __name__ == '__main__': \n</code></pre>\n\n<p>guard to be used at the end of script to test your functions and this allows your module to be imported by other modules without running the whole script.</p>\n\n<pre><code>again = ''\nboard = '[1][2][3]\\n[4][5][6]\\n[7][8][9]'\nwin_combination = [(1,2,3),(4,5,6),(7,8,9),(1,4,7),(2,5,8),(3,6,9),(1,5,9), \n(3,5,7)]\npleyer_numbers = []\ncomputer_numbers = []\nnumbers = [x for x in range(1,10)\n</code></pre>\n\n<p><strong>Global variables:</strong> Are to be avoided as much as possible, a better approach is to enclose your variables inside their corresponding functions that use them</p>\n\n<p><strong>Catching invalid inputs</strong> since you're dealing with user input, it is very likely that someone enters a wrong value example:</p>\n\n<pre><code>Enter the field number: w\n</code></pre>\n\n<p>results in an error, you should control errors that would terminate your program</p>\n\n<pre><code>confirm_number = input('Enter field number: ')\nwhile not confirm_number.isdecimal():\n print('You should enter integer numbers only!')\n confirm_number = input('Enter field number: ')\n</code></pre>\n\n<p><strong>f-strings</strong> since you're using Python 3 I suppose from the print statements, f-strings are a new string formatting mechanism known as Literal String Interpolation or more commonly as F-strings (because of the leading f character preceding the string literal). ... In Python source code, an f-string is a literal string, prefixed with 'f', which contains expressions inside braces providing a way to embed expressions inside string literals, using a minimal syntax. </p>\n\n<p>a statement like</p>\n\n<pre><code>print('Computer chose field: ' + str(computer_number))\n</code></pre>\n\n<p>can be written:</p>\n\n<pre><code>print(f'Computer chose: {computer_number}.')\n</code></pre>\n\n<p>which improves readability.</p>\n\n<pre><code>print('----------YOU WON!----------')\nprint('----------YOU LOST!----------')\nprint('----------------------------\\nYou started new game!')\n</code></pre>\n\n<p><strong>String multiplication:</strong> the statements above can be replaced with:</p>\n\n<pre><code> print(f\"{10 * '-'}YOU WON!{10 * '-'}\")\n print(f\"{10 * '-'}YOU LOST!{10 * '-'}\")\n print(f\"{30 * '-'}\\nYou started a new game!\")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T13:51:23.770",
"Id": "442573",
"Score": "0",
"body": "Poor advice. `\"\"\"docstrings\"\"\"` are for the generation of automatic documentation for the **use** of **public** functions. You should not write docstrings for each and every function / class / module you write; only the ones intended to be reusable by other coders. `# comments` should be used to document private functions and implementation details not required for the use of the function. `replace_board`, `change_number` and `check_win` all look like private methods, which should be commented and named with a leading underscore; they do not need docstrings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T17:11:05.700",
"Id": "442639",
"Score": "0",
"body": "@HelloBT As AJNeufeld pointed out i made a mistake, the isinstance check i indicated is falsy, to be replaced by while not number.isdigit() and same goes for the comments, The general conclusion: if functions are public, docstrings should be included."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T07:43:25.447",
"Id": "227384",
"ParentId": "227381",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "227384",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T06:05:18.263",
"Id": "227381",
"Score": "-2",
"Tags": [
"python",
"game",
"tic-tac-toe"
],
"Title": "Simple Python tic tac toe"
}
|
227381
|
<p>Here is my problem, I receive these kind of json data and I don't know in advance the keys (unknownProperty#) but the different objects in this data array have the same keys. What I need to do is to calculate the number of each level of alert (these levels are fixed).
Here is what my end result should look like</p>
<pre><code>var result = { unknownProperty1: { unknown: 0, ok: 2, warning: 0, ko: 1 },
unknownProperty2: { unknown: 0, ok: 0, warning: 2, ko: 1 },
unknownProperty3: { unknown: 3, ok: 0, warning: 0, ko: 0 },
unknownProperty4: { unknown: 0, ok: 0, warning: 3, ko: 0 },
unknownProperty5: { unknown: 0, ok: 0, warning: 2, ko: 1 } }
</code></pre>
<p>My script is working but I would like to know if there is any way to optimize/clean it with map/reduce/filter javascript function</p>
<pre><code>const data = [
{
unknownProperty1: { alert: "ok", unusedItem1: "something" },
unknownProperty2: { alert: "warning", unusedItem1: "something" },
unknownProperty3: { alert: "unknown", unusedItem1: "something" },
unknownProperty4: { alert: "warning", unusedItem1: "something" },
unknownProperty5: { alert: "ko", unusedItem1: "something" }
},
{
unknownProperty1: { alert: "ok", unusedItem1: "something" },
unknownProperty2: { alert: "warning", unusedItem1: "something" },
unknownProperty3: { alert: "unknown", unusedItem1: "something" },
unknownProperty4: { alert: "warning", unusedItem1: "something" },
unknownProperty5: { alert: "warning", unusedItem1: "something" }
},
{
unknownProperty1: { alert: "ko", unusedItem1: "something" },
unknownProperty2: { alert: "ko", unusedItem1: "something" },
unknownProperty3: { alert: "unknown", unusedItem1: "something" },
unknownProperty4: { alert: "warning", unusedItem1: "something" },
unknownProperty5: { alert: "warning", unusedItem1: "something" }
}
];
var result = new Object();
var dataKeys = data.map(function(element) {
return Object.keys(element);
});
dataKeys[0].map(function(element) {
result[element] = { unknown: 0, ok: 0, warning: 0, ko: 0 };
});
//At this point the result is like what we expect but no calculation has been made yet
//We then increment the right values
data.map(function(element) {
for (var prop in element) {
if (Object.prototype.hasOwnProperty.call(element, prop)) {
// element correspond to the current object
// prop corresponds to the name of the key, for example 'unknownProperty1'
switch (element[prop].alert) {
case "ok":
result[prop].ok++;
break;
case "warning":
result[prop].warning++;
break;
case "unknown":
result[prop].unknown++;
break;
case "ko":
result[prop].ko++;
break;
default:
break;
}
}
}
});
console.log(result);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T08:43:30.200",
"Id": "442529",
"Score": "0",
"body": "Is there a reason to redact the unknown properties?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T08:45:38.513",
"Id": "442530",
"Score": "0",
"body": "This is just to illustrate I don't know them when I receive them"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T08:45:59.560",
"Id": "442531",
"Score": "1",
"body": "I first posted my question here https://stackoverflow.com/questions/57767830/javascript-script-optimization-with-map-reduce-filter"
}
] |
[
{
"body": "<h2>Compact Code</h2>\n\n<p>If you're looking for more compact code, you can start by avoiding redundant function declarations:</p>\n\n<blockquote>\n<pre><code>var dataKeys = data.map(function(element) {\n return Object.keys(element);\n});\n</code></pre>\n</blockquote>\n\n<pre><code>var dataKeys = data.map(Object.keys);\n</code></pre>\n\n<p>And a compact notation for an empty object.</p>\n\n<blockquote>\n<pre><code>var result = new Object();\n</code></pre>\n</blockquote>\n\n<pre><code>var result = {};\n</code></pre>\n\n<h2>Pivot Table</h2>\n\n<p>What you're doing is pivotting data from rows to columns. You are correct to mention <code>reduce</code> as this method could help us out here. It's possible to leave out the switch case if we just loop through the entries and aggregate the results.</p>\n\n<pre><code>var pivotTable = data.reduce((result, item) => {\n Object.entries(item).forEach(([key, val]) => {\n if (result[key] === undefined) {\n result[key] = { unknown: 0, ok: 0, warning: 0, ko: 0 };\n }\n result[key][val.alert]++;\n });\n return result;\n}, {});\n\nconsole.log(pivotTable);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T15:26:24.170",
"Id": "227411",
"ParentId": "227386",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227411",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T08:35:39.847",
"Id": "227386",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Counting the number of alerts by type and partition from a JSON object"
}
|
227386
|
<p>I have just written this code for toggling between two possible states of an object.</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>// This can't change, and only ever has two states
const MODES = {
ON: 'ON',
OFF: 'OFF'
}
// this is my method
const toggleMode = currentMode => {
const modes = Object.values(MODES);
const newMode = modes.find(mode => mode !== currentMode);
return newMode
};
// toggle state
const firstState = MODES.ON;
console.log(firstState);
const secondState = toggleMode(firstState);
console.log(secondState);
const thirdState = toggleMode(secondState)
console.log(thirdState)</code></pre>
</div>
</div>
</p>
<p>Is this a good way of toggling between the two states? I'm concerned it's less readable than the verbose <code>if one state, then pick the other, else pick the current state</code>. But this way also means that so long as we know there's only two states, then nothing needs to be hardcoded in the function doing the toggling.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T11:38:59.947",
"Id": "442550",
"Score": "0",
"body": "Related: https://codereview.stackexchange.com/questions/101995/function-to-toggle-between-two-values-of-an-enum, https://codereview.stackexchange.com/questions/186774/toggle-between-two-states-in-react"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T12:06:15.660",
"Id": "442556",
"Score": "1",
"body": "Could you show us how you'd use that code in action?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T12:07:02.980",
"Id": "442557",
"Score": "0",
"body": "@dfhwze how much context do you need? The way it's used in the snippet isn't far off."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T12:08:58.837",
"Id": "442559",
"Score": "0",
"body": "I can see it toggles, but how would you end up using 'ON' and 'OFF' on an object?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T12:13:35.323",
"Id": "442561",
"Score": "0",
"body": "@dfhwze thats not really relevant to the code. Just that it has two states. I could have had `const HAT_POLICY = {INDOORS: 'INDOORS', OUTDOORS:'OUTDOORS'}` but that is less obvious. That state is used in a lot of other places in the code base so not relevant to the actual toggling."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T13:03:06.243",
"Id": "442566",
"Score": "0",
"body": "_so long as we know there's only two states_ would you also care about more than 2 states to toggle between, or just 2?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T15:24:33.807",
"Id": "442594",
"Score": "0",
"body": "@dfhwze we only care about two states. We're toggling, not cycling."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T15:27:35.210",
"Id": "442597",
"Score": "1",
"body": "I have no further questions, your honor."
}
] |
[
{
"body": "<p>You currently only print the currently selected mode to the console, but you probably will use this mode for other purposes, such as the business logic of your application. To that end, I suggest splitting the <em>toggling logic</em> from the <em>presentation</em> and <strong>use booleans to store the value</strong> which you can easily use for branching depending on the currently selected mode.</p>\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>// Logic: Define the two modes and toggling logic\nconst MODES = { ON: true, OFF: false }\nconst toggleMode = currentMode => !currentMode;\n\n// Presentation: Display a selected mode\nconst displayMode = currentMode => currentMode ? 'ON' : 'OFF';\n\n// Demo\nconst firstState = MODES.ON\nconsole.log(displayMode(firstState));\nconst secondState = toggleMode(firstState);\nconsole.log(displayMode(secondState));\nconst thirdState = toggleMode(secondState);\nconsole.log(displayMode(thirdState));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T08:11:56.353",
"Id": "442757",
"Score": "0",
"body": "This is a clever distinction, but I don't' think it applies in my case as I'm not going to be displaying the state (the console logs were just to show the function working). I'm also not keen on(sort of) handling two lots of state/processes to get to state."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T08:33:51.543",
"Id": "442760",
"Score": "0",
"body": "All the better, if you don't need to display it. The toggling function can be used stand-alone and you can alway check either against truthiness (`if(firstState){ … }`) or against the \"Enum\" (`if(firststate == MODES.ON){ … }`) so not to depend on the inner value."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T21:19:05.320",
"Id": "227433",
"ParentId": "227393",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "227433",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T11:38:31.830",
"Id": "227393",
"Score": "1",
"Tags": [
"javascript",
"state"
],
"Title": "Toggle between two options in an object?"
}
|
227393
|
<p>I have a working code and it works fine for small amounts of data</p>
<pre><code>Option Explicit
Sub Test()
Dim ws As Worksheet
Dim myAreas As Areas
Dim c As Range
Dim sTemp As String
Dim lr As Long
Dim i As Long
Application.ScreenUpdating = False
Application.Calculation = xlManual
'Refers to the worksheet using ws as variable to refer to it
Set ws = ThisWorkbook.Worksheets(1)
'Determine the last row based on column 9 (Column I)
lr = ws.Cells(Rows.Count, 9).End(xlUp).Row
'Determine the areas separated by empty row so as to deal with each block of data
'And this will be based on column I
Set myAreas = ws.Range("I2:I" & lr).SpecialCells(2).Areas
'Change the format of column I to be as Text
ws.Columns(9).NumberFormat = "@"
ws.Columns("AN:AO").NumberFormat = "@"
'Loop through the areas (blocks of data)
For i = 1 To myAreas.Count
'Empty the variable because we will use it again
sTemp = Empty
'Extend the block to include 38 columns after column I
With myAreas(i).Resize(, 38)
'Debug.Print .Address 'Gives you the address of the range
'Sort data by column I which is the first column in that range
.Sort Key1:=.Columns(1), Order1:=xlAscending, Header:=xlNo
'loop through cells in column I
For Each c In .Columns(1).Cells
'Adjust the format of the cell
c.Value = AddZeros(c.Value, 2)
'if the cell value="01 or "11" then the inside lines will be executed
If c.Value = "01" Or c.Value = "11" Then
'Put asterisk in the column AM and AP
c.Offset(, 30).Value = "*": c.Offset(, 33).Value = "*"
'Cell in AO column equals to cell in AN
c.Offset(, 32).Value = c.Offset(, 31).Value
'Foramt number to be equal to 9 length
c.Offset(, 31).Value = AddZeros(c.Offset(, 31).Value, 9)
c.Offset(, 32).Value = AddZeros(c.Offset(, 32).Value, 9)
End If
Next c
End With
'Deal with the block again
With myAreas(i).Resize(, 38)
'Loop through column S cells
For Each c In .Columns(11).Cells
'if cell value not empty and not equal 0 then
If Trim(c.Value) <> Empty And Trim(c.Value) <> 0 And Trim(c.Value) <> "" Then
'put the cell value into the variable sTemp
sTemp = Trim(c.Value)
End If
Next c
'Loop again through cells in column S
For Each c In .Columns(11).Cells
'if cell in column J equals 01 or 11 then the cell value will be equal to sTemp
'else leave it empty
If c.Offset(, -10).Value = "01" Or c.Offset(, -10).Value = "11" Then c.Value = sTemp Else c.Value = Empty
Next c
'Loop again through cells in column S to fill the empty names
For Each c In .Columns(11).Cells
If c.Value = "" Or c.Value = Empty Then c.Value = c.Offset(-1).Value
Next c
'Loop through column AE
For Each c In .Columns(23).Cells
'If cell value is a number the convert it to positive
If IsNumeric(c.Value) Then c.Value = Abs(c.Value)
'trim the value in cell in column AL
c.Offset(, 7).Value = Trim(c.Offset(, 7).Value)
'Column J equals to 1208643 then
If c.Offset(, -21).Value = "1208643" Then
'Column J next row cell
c.Offset(1, -21).Value = "800107"
'Column P next row cell
c.Offset(1, -15).Value = "1050-101"
End If
'if the value in cell in column AE is number and the value in column J equals 1208643 then
If IsNumeric(c.Value) And c.Offset(, -21).Value = "1208643" Then
c.Offset(, -1).Value = "A0"
ElseIf IsNumeric(c.Value) Then
c.Offset(, -1).Value = "A1"
End If
Next c
End With
Next i
Application.Calculation = xlManual
Application.ScreenUpdating = True
MsgBox "Done...", 64
End Sub
Function AddZeros(makeLonger As String, numberDigits As Integer) As String
Dim x As Long
For x = 1 To (numberDigits - Len(makeLonger))
makeLonger = "0" & makeLonger
Next x
AddZeros = makeLonger
End Function
</code></pre>
<p>However when trying it with large amounts of data about 60,000 rows it took so much time .. so is it possible to optimize it to make it faster?</p>
<p>The code is looping through the specialcells in column I to get the areas (blocks of data) and sort each block and also do some calculations based on cells values in some columns ..</p>
<p>I have posted it at stackoverflow
<a href="https://stackoverflow.com/questions/57771159">https://stackoverflow.com/questions/57771159</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T21:47:24.187",
"Id": "442906",
"Score": "0",
"body": "Ok I have a few questions before I give it a go. 1) Is setting an area even useful b/c you can just set the loop to ignore the current state o the array if arrayposition(whatever, whatever) was blank? 2). Wjy are you reszing the areas? 3) wouldnt one loop do the trick here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T04:49:47.293",
"Id": "442917",
"Score": "0",
"body": "Thanks a lot. Loops are necessary as for each loop, a specific task is required and the next loop will be dependent on the results of the previous loop.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T19:00:21.700",
"Id": "443292",
"Score": "1",
"body": "Replacing `AddZeros()` with `Format(makeLonger,String(numberDigits,\"0\"))` will help. e.g. `c.Offset(, 31).Value = Format(c.Offset(, 31).Value, String(9, \"0\"))`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T05:24:33.447",
"Id": "443307",
"Score": "0",
"body": "Thanks a lot TimMan for this hint."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T05:44:17.307",
"Id": "443308",
"Score": "0",
"body": "I have replaced the lines which I used AddZeros with your sugesstion and it works well. But when compared the time I have noticed there is no difference between both methods"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T13:50:06.013",
"Id": "227396",
"Score": "1",
"Tags": [
"vba",
"excel"
],
"Title": "Using arrays instead of regular loops"
}
|
227396
|
<p>Automation refers to the process of generating tools that execute tasks without the help of human intervention. </p>
<h1>Tag Usage</h1>
<p>Use this tag for scripts, software and other tools that allow for automation.</p>
<h3>Links</h3>
<ul>
<li><a href="https://hackernoon.com/please-be-lazy-and-automate-your-coding-7a0d948324b3" rel="nofollow noreferrer">Code Automation</a></li>
<li><a href="https://www.ibm.com/support/knowledgecenter/SSANHD_7.6.0/com.ibm.mbs.doc/autoscript/c_automation_scripts.html" rel="nofollow noreferrer">IBM - Automation Scripts</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T13:50:09.920",
"Id": "227397",
"Score": "0",
"Tags": null,
"Title": null
}
|
227397
|
Automation refers to the process of generating tools that execute tasks without the help of human intervention. Use this tag for scripts, software and other tools that allow for automation.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T13:50:09.920",
"Id": "227398",
"Score": "0",
"Tags": null,
"Title": null
}
|
227398
|
<p>I have three datasets, "CV", "FV" and "LA". I have attached reproducible data for all of them. The idea is that some combination of the elements in each column of CV and FV should sum up to equal the corresponding column entry in LA. You can think of each row entry in each column as having two possible outcomes, either it equals the value in CV or it equals the value in FV.</p>
<p>My current method is a brute force one. I generate a dataframe <code>df_bob</code>, and fill it randomly with either an element from CV or FV. I then aggregate this list and check the difference between the corresponding element from LA. I save the iteration which has the smallest difference, in a list, <code>l_finals</code>. This list has the combination of elements which aggregate to get to (or as close as I can to) the corresponding LA element. And then a 1 or a 2 (1 if it is an element from CV and 2 if its an element from FV), for each column that is looped through.</p>
<p>It does the job if I set the number of iterations to a large number, but it takes ages (Three loops and the method is a purely random one). I was wondering if there was a way to perform this algorithm in a less brute force manner, therefore requiring less computing time? </p>
<p>Here is the code I am currently using:</p>
<pre><code>library(caret)
library(readxl)
set.seed(411)
df_CV <- data.frame(read_excel("CV.xlsx"))
df_FV <- data.frame(read_excel("FV.xlsx"))
df_LA <- data.frame(read_excel("LA.xlsx"))
l_dif<- c()
l_finals<- c()
for(k in 1:ncol(df_LA)){
idifMin <- 1000000000
for(j in 1:20000){
df_bob <- data.frame(df_CV[,k],df_FV[,k])
df_final <-data.frame(c())
for(i in 1:nrow(df_bob)){
r <- sample(1:2,1)
df_final[i,1]<-df_bob[i,r]
df_final[i,2]<-r
}
idif <- sum(df_final[,1])+df_LA[,k]
l_dif <- cbind(l_dif, idif)
if(abs(idif)<abs(idifMin)){
idifMin<-idif
df_best <- df_final
}
}
l_finals <- cbind(l_finals, df_best[,1], df_best[,2])
}
</code></pre>
<p>Here is the data in text form:</p>
<p>CV:</p>
<pre><code> 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
320446 558245 319873 803455 611428 596234 24215 794590 582109 736434 624491 451544 352170 889357 595392 736355 401609 613174 55810
289884 828164 228777 232580 744795 663188 182071 292221 483034 437606 420378 59116 852644 147417 997675 416773 394209 638738 111395
550053 87308 44398 784360 668998 652140 61818 971801 159877 191641 459370 654481 84116 126776 732596 109117 906246 789235 308060
513830 978509 385267 648434 968876 764889 123435 737553 431799 838237 200792 859764 61002 929356 749615 887816 989663 407719 423781
284001 165456 680800 925983 4228 593538 826030 60438 338471 427333 614914 864478 202555 264660 922667 996376 164456 757038 41524
216820 235518 959869 752077 968732 362814 926543 144529 114658 841491 897634 199295 502388 529615 113620 712583 217445 375363 187147
970890 804096 992217 316356 156105 388333 22646 305011 60412 823331 485435 164495 129206 428451 466283 988203 194960 554939 325926
399375 919320 783371 835515 310706 757646 496110 770644 401981 755272 649688 604984 61062 88031 757112 22391 129306 386872 98320
802181 779785 916936 278812 674808 675218 36786 858379 451237 832692 846785 762282 416091 414694 9497 778436 488397 64091 656841
185814 129921 564141 280941 267096 297380 981779 770693 356458 156537 897851 308764 863072 817394 730970 746977 707754 472978 954950
177836 52483 431814 436553 69959 917728 997649 146712 121617 639243 254264 630123 803449 737208 294175 318587 325157 746828 386573
755486 63142 93095 152267 147691 629833 875730 85543 297708 771018 32108 466473 94736 476150 163862 917604 648048 794561 424487
87840 283878 908415 122819 631551 446701 589510 975919 479002 923304 506093 947017 434895 603704 526757 870451 882471 698782 892288
512425 434573 978120 171493 856826 79529 137793 210719 366966 632885 729722 76110 997626 658932 129308 286892 860331 878534 91016
982957 99116 516112 482743 264943 279695 891486 971790 561111 309095 58460 2570 772052 643821 749670 871921 112301 736067 759193
868155 923438 615361 395822 938507 985002 377216 267788 467545 460758 684319 483415 620495 541584 893175 728675 320769 819886 964721
919125 699079 498845 484441 652977 402577 716249 240098 466653 374657 212141 969469 270420 780220 331123 873291 721255 373017 750047
728706 503429 215220 961123 622615 44144 710188 435457 872641 737635 224442 918631 822325 462575 698914 706752 285181 606355 149249
564834 391827 730930 519434 169706 850385 897398 720886 579479 656563 407658 510847 275319 97008 248914 204639 909146 699399 554974
796185 967337 913528 270931 112849 628608 987253 304417 941156 487738 467440 745556 70104 86071 344588 720157 616401 987281 168286
716983 234547 201438 816150 403313 126367 125333 458069 285574 765629 188019 127161 539861 162954 266894 362911 824277 342408 286639
757870 332563 478929 160129 336228 953594 832097 122727 451594 743378 286202 411519 849707 742254 478730 756942 824035 884802 480874
549164 18651 412165 608141 519700 238449 231695 788194 336208 706266 535697 980992 728326 913709 485445 569890 341405 261614 238784
298561 268305 274246 978909 578733 398048 318060 601890 404212 708631 626139 683565 492023 310107 482462 514620 298713 19482 234085
735895 885692 534791 943805 947282 434255 174084 290059 313607 324411 846567 264720 368204 627704 400863 232034 522764 830844 722255
62402 963921 604929 638554 932765 745714 3674 3155 872952 461165 272973 987795 88122 309458 667869 249983 5858 97592 654919
240528 329941 525987 462739 907254 997931 18072 322609 924250 170321 50014 583746 409207 129538 987190 721270 969110 285665 128325
822876 363262 966046 619320 285886 639508 62547 250782 282472 242169 197924 94951 102483 383397 314255 535479 261825 602068 770265
564417 651378 981389 398973 59407 520390 694047 392827 415138 952837 22319 797984 821901 335588 11113 371781 988420 645864 97539
484462 525551 729880 390995 108589 795275 332009 272572 747901 304679 89949 487863 258617 608016 131945 194957 323792 522714 116716
862922 64640 737913 943758 138025 700724 599252 280690 628719 699348 131500 981586 538477 601120 203836 79121 977685 409499 605985
464382 458084 950207 937222 982392 896130 189955 201275 813726 757086 335551 496921 254556 13020 677034 243001 611997 745279 439141
486004 771657 29590 311636 949255 178183 682477 184693 498034 478796 750617 144694 808598 911119 320403 287678 155397 462017 610196
542338 193970 641761 326487 769535 992676 72645 305463 367129 567730 481419 801079 757702 317532 258714 684985 878241 749836 965444
557606 128089 608609 299726 163102 732714 590357 760764 108804 694905 679673 965802 471091 730849 718673 818705 752045 574992 969673
724243 765106 992622 915109 5878 500440 451416 593776 801350 862788 346293 408942 746836 963678 176277 684284 166470 506039 69048
422007 400440 714317 253123 50252 574276 614477 770795 848794 790922 136601 297154 260342 735498 250444 254657 444987 693550 297673
355572 356939 520919 753175 827121 6487 689456 105840 968471 193314 789759 503568 725256 136616 226395 81951 884465 226582 710319
736649 458189 3547 104152 31104 999099 872656 365103 641860 992649 35064 970780 61495 892448 921526 201327 890856 20572 466523
647192 760844 362936 568677 855492 369064 788308 896806 809253 908882 236246 241009 651272 705953 504631 776435 242115 564729 811052
690159 96591 721702 597105 776002 824607 4393 69294 745585 760232 710240 976106 599840 843843 989611 194095 929863 257068 200316
870690 545208 790493 880531 986423 582213 199844 618766 32653 490120 71453 119617 328122 767466 700296 326958 472533 329592 678365
571276 447072 451463 947248 854832 440812 527390 598666 129901 929615 113757 394850 679019 798242 186512 249937 575797 389922 26287
393786 371085 817072 205319 775901 26866 533685 769063 242550 778544 389141 625382 874117 738516 39404 274983 34997 896976 469675
575987 397470 616140 99125 252347 398168 331558 782761 70088 3706 792742 760695 124705 47828 255914 907137 309470 578634 343958
738411 48271 734278 830171 179620 825361 588190 447256 248883 250642 51866 32620 302956 806630 935173 928321 204378 202732 989099
377440 324634 778147 608384 785065 50113 956011 489787 487493 759017 311856 260729 372281 343418 430775 577443 430364 968287 557071
265886 580527 152550 469070 326433 281973 619842 246198 593157 88762 3774 758046 814625 800907 709085 681431 819129 635700 844335
44119 671132 348749 276241 749294 4992 829247 508949 970807 565062 335222 248352 670201 742223 349451 8315 360250 308669 14237
377857 211144 681144 636528 981268 376699 808462 171592 622777 252247 189519 735690 15554 371921 451361 490911 904659 324159 464376
209587 800272 890806 449407 942824 290015 565740 739152 409083 430094 660616 479428 444625 848605 800171 490971 627733 443137 435421
801200 959933 631898 269602 405283 534671 765138 204309 453429 900143 782400 740891 186257 580689 457187 371113 784866 498480 188682
975442 849302 25310 273423 392339 344208 458617 490400 448864 996087 517646 832110 726874 703651 724241 313039 141414 652153 543798
462344 268771 297851 353763 424815 584959 249467 406309 405099 176104 367209 950205 139388 223292 822733 345252 10543 608156 631854
859965 567383 262383 19263 292267 669954 222631 865718 744915 326296 344562 783673 539245 436250 690225 795125 898847 291740 875210
930073 809653 258753 168526 294396 757218 316524 612310 274477 893636 129957 934066 512775 539139 189019 146186 477834 302953 620655
133762 250270 788392 833588 760946 101207 610591 726121 834131 926696 321708 466277 379133 953584 528395 790503 648973 347518 603546
277757 510165 47850 979389 193717 238359 262263 139203 14287 70566 473391 228220 975844 783466 277047 568291 331198 652284 201120
388306 205307 563407 329662 239544 848887 982113 117889 800065 63670 72895 965516 302481 439157 595678 656517 347904 248339 787059
700220 787740 812873 37917 591792 675882 97672 872608 421604 628763 925780 549758 71860 387410 283854 106545 421981 419242 245629
711652 16134 736305 628664 462164 494254 237210 61950 529705 506663 76148 95955 527442 374955 619310 921600 565868 716051 462091
985231 654730 553537 316747 324652 761392 679426 699474 414028 223290 435272 545735 292201 514711 663502 139547 514484 953159 810180
894485 954488 982523 99422 692732 487402 466121 594620 918078 148909 820424 254309 376446 805200 82074 955855 148013 740709 191847
217212 763700 420440 717897 802758 382660 297241 680913 111024 613197 180679 199259 774289 575545 437215 76848 226697 918854 159007
652612 962730 529373 843509 158402 345 318321 709299 505585 676879 941617 739323 853186 417987 735756 85478 432425 720372 233965
928428 919054 401691 520593 182891 105051 249395 129407 395425 154579 5546 144942 652953 729793 212303 963649 170534 254115 184373
540800 955373 33395 159030 426384 695909 377395 722850 774838 311340 615578 120019 240787 663428 443013 815084 117956 546466 186623
548160 555914 756431 524384 430584 675772 248 728842 323131 1275 959957 383312 402348 326893 471212 868213 576896 864786 237896
361442 556809 879936 125333 422895 49778 442627 612070 333626 380651 646938 477648 140864 953269 524115 815491 168527 618672 859019
132834 744569 538240 655452 414010 332317 831477 639356 51603 871713 5208 782347 352046 557404 12092 899001 898282 742830 214911
505057 461227 397586 717315 18759 219244 304442 636873 106088 769906 525908 720592 711678 827687 225601 269343 47223 169432 256030
732481 534486 256600 394657 435897 19855 67689 373244 399137 921751 580110 544637 921728 482935 824887 707240 653975 663790 764878
572824 401021 597696 959124 735963 689542 710305 632516 743957 418419 46933 502974 568653 772405 410425 263787 899568 186105 879592
46616 473752 610221 621179 659082 999457 87009 814176 3129 121649 242166 55525 413194 170760 73078 530753 210886 491578 622444
974046 750513 504529 310016 638220 72901 794357 314725 776902 715319 148480 813863 778211 3607 599711 76249 784346 195250 886200
636781 130812 753566 832410 933715 733160 586305 933737 334356 742482 21285 632534 138347 69946 936887 477200 797634 975547 207174
189180 786863 529494 949490 591354 808868 819743 370172 272304 712543 34060 851026 899957 572564 806373 751054 437675 938059 10343
305560 479746 494423 308914 234564 973241 697418 84248 875828 758942 339092 403553 182895 869334 871547 281802 341183 423756 438922
658911 220082 423792 103672 668024 112839 500680 70993 738323 947716 369506 389346 104064 23869 457034 587992 739486 368555 387691
298154 846149 602980 356295 682649 409390 185295 289400 858561 920515 475677 388118 325903 829027 144139 337369 112740 52556 449795
854973 744288 779089 447163 270094 558702 852654 24756 918089 963071 871031 617649 691172 960656 977880 338465 166115 441011 13661
793609 418894 357367 569858 654499 525229 866015 910350 172077 142441 703570 322538 77682 201059 527763 3965 587014 93933 379377
486410 380321 458750 640127 510683 532233 894934 970991 152376 743774 51955 786768 453021 935148 574774 106873 254517 114433 556221
903247 529589 380389 847973 579807 603759 943405 711176 251037 861294 237672 544132 482182 186411 339034 20488 478979 898712 394496
701768 56036 839428 72187 699857 629241 995391 775156 576022 457734 853848 352669 314344 732031 682844 381033 725514 87254 915405
79003 4044 466394 516847 296010 155027 615033 872225 523141 523977 195480 530873 502151 317306 839347 661795 58895 145101 10354
381795 316174 993065 643264 434205 43360 75263 921716 275679 784847 800414 203998 94906 28002 583691 252530 457271 890659 236033
28819 712319 284242 216089 373461 698113 361825 10271 322269 42944 703749 461261 611712 496206 447268 406644 300814 909648 353792
493469 662533 515325 51381 684592 572433 172010 510493 591274 374016 116996 51778 146956 780841 280319 71458 370418 283400 236962
200609 623542 690293 903087 176189 545805 289215 925502 300012 366547 885792 205200 788515 391806 553872 826265 510315 685833 102261
749326 892978 969112 961059 526383 744985 572758 482880 132226 524172 124638 865895 828621 398468 286405 630279 564765 850117 50185
26081 350298 386139 118241 345298 271004 561323 824411 418750 870610 590394 929985 238032 292634 534450 367813 744563 965095 550853
286804 570241 283333 199653 144629 360644 937613 879060 562589 11975 445751 883820 184707 892961 688035 970188 634831 99156 607875
605954 431241 888725 277572 949136 150898 725169 401576 798563 108644 799602 65013 99769 994719 42517 949042 448038 316379 589901
977685 56486 523254 272090 845543 536032 654179 549148 111854 871081 456879 231975 444298 171580 260610 419349 108746 665692 415049
581286 736382 79868 495052 967962 503485 508683 202321 101849 735193 518376 849113 227467 982366 885845 437313 899642 297148 887984
736835 553291 202585 304302 769207 295135 622685 932539 78545 816751 477350 371947 183467 466049 231802 607056 569631 581565 865039
568916 558151 241469 957318 168219 938892 448782 519543 834885 643491 33096 805448 337756 40841 592491 96904 6426 756154 550259
509978 757837 228617 60716 73286 866426 665747 732584 623140 375873 464018 221448 977960 719463 130463 870769 64951 615366 570500
665086 299466 152093 67353 343137 605212 571823 554080 869692 965927 756017 528018 204889 724118 40919 512464 564010 191118 944715
964078 303493 673775 147288 430143 55075 617556 830018 23918 885716 299270 680034 492501 971317 685100 156167 873702 901195 360396
787883 870703 585550 887711 681325 75471 183260 500464 740809 698800 832136 911620 881770 78110 454336 816782 690486 639617 964298
442008 335440 182245 256318 497264 239254 897779 35202 765568 527256 972705 206468 124079 131917 295612 366347 404910 909935 895872
707892 686407 95071 428524 903125 825933 863009 894263 980975 976121 283928 37457 865796 229110 527508 596445 562062 416806 155436
745200 438639 190734 292451 203563 153193 965056 318101 758591 492942 651802 935921 900035 342604 222435 436303 29005 903976 622348
785839 484399 855670 971107 683266 291946 926081 426655 736835 787246 310443 435555 314621 764247 369474 541322 521368 650995 253698
776455 469272 668961 838807 406265 619670 216162 946758 134685 926785 560635 747096 576681 78041 962667 450487 554421 364291 544767
141133 211807 656670 724810 123278 160003 346165 99137 733169 156445 251042 1044 477298 47469 745811 936871 693772 83793 533599
147589 667141 990065 293959 652065 400645 66612 494038 989615 289095 788106 311586 146039 600798 465474 31195 966597 269442 668267
125191 635710 432665 780454 936219 838125 159508 640431 608132 79189 83019 41534 759631 907946 122815 898910 455816 664078 559791
597845 505265 345815 399603 395126 491478 530707 678890 748842 338437 788861 249371 243584 218172 911879 12566 42399 796368 908716
254406 258252 65197 556329 735550 396879 448857 72318 834859 304655 936241 740373 491386 439268 44817 961427 534382 656442 851913
247282 6445 562233 34309 971116 316021 373580 251996 534036 666787 709185 469499 545264 242167 889314 955413 464460 692802 212314
634657 204454 539578 809018 60924 994138 147689 232372 250654 853609 719301 346139 90254 808568 292093 681436 795085 409476 499633
661519 46913 709321 883124 525858 165082 235928 817067 626764 469843 734286 927234 143671 392015 607337 913345 882183 800297 778919
110664 348209 276054 919019 945168 844396 340476 253456 750904 192103 849965 345017 457153 208942 502772 893283 922180 355691 792107
70286 876169 65794 447412 139224 981740 770111 658779 827639 735399 733379 628064 780522 763457 335656 643589 683319 868825 909742
258697 295944 744572 206889 508579 416230 878438 400804 830094 383960 721664 620986 437288 448897 998730 586021 458829 738807 70938
670183 375426 332485 992204 613698 457108 901012 569508 459979 994897 345589 909615 883509 475568 364747 452035 852054 826389 396530
818600 383303 556122 855915 726286 748638 405412 593755 230082 6457 183818 20053 932593 925246 713649 306591 510242 509258 603471
805735 443698 870378 548382 376867 17972 340219 899998 106978 440162 555149 834010 895801 672813 275594 4348 326480 340281 629873
765736 226981 774979 555180 96606 42928 829396 391487 683068 951396 706189 424350 993595 370190 404944 796707 881550 883980 461224
58021 608264 746418 677398 648887 527682 952638 125522 421704 884776 813701 170462 193890 693229 735933 67961 27843 477196 521466
393289 247065 567461 202455 396612 22201 45062 616931 306901 693466 199112 365071 194834 303633 891290 824889 355315 827470 696733
117197 206819 64800 247518 386012 622494 613863 560775 316668 549228 599772 948006 948343 42850 249725 501451 150523 168751 314084
180592 655086 455512 204939 746978 849494 397862 214573 485112 743647 816914 266032 939593 168326 773361 310419 774555 164293 554939
657433 888888 39315 80601 981305 28096 850576 304385 563384 940409 32346 105317 911602 88429 616910 365269 594147 704459 123462
107262 159943 975756 710212 404943 508826 935724 845386 462400 835484 505877 429618 345188 518717 550619 193971 892248 988523 187719
60873 81202 461284 940394 873515 150463 688191 997795 514722 166218 971901 838394 333424 847432 473485 27729 471001 65633 344513
85516 384013 811890 743228 172564 588404 147011 829781 815748 948995 479064 586592 302740 308698 72478 458421 489559 870788 155092
575231 933389 901617 510801 999091 345147 177610 326621 954319 181380 51335 92573 275272 81761 945970 750469 744952 537589 161434
461732 568422 474919 449031 878201 338186 377553 931436 850178 412777 857443 589208 178416 3289 752273 204440 336402 286523 65433
424427 911581 62173 168307 882454 586094 500731 206981 14309 406018 939172 95450 610226 641427 90263 665389 29433 855491 995187
825367 843348 517219 345947 729467 845274 824408 828027 439690 759021 40074 573859 183776 523734 636302 207930 959376 682751 936895
780870 397808 888793 489102 198169 628271 341953 485237 388678 921108 365399 114571 857411 498121 71407 371278 912889 228085 621163
136151 804340 881901 98266 225347 868655 683154 393583 933952 431256 607257 997728 593567 113576 608666 302670 818985 481256 149362
124037 790940 562700 436548 772538 482071 465688 642736 465876 739875 680486 271781 707162 294118 351440 169348 392888 630655 820318
326790 703722 894363 599093 673050 496538 501619 263171 812791 831805 807862 260530 379912 810442 104651 941696 515630 204147 786820
312054 749659 500991 333376 686194 771965 374005 397206 614377 857318 604041 574171 946332 552692 276387 761933 752516 451200 274526
255299 348098 789117 161950 511374 151223 273155 995514 932285 533828 494429 139599 321810 984846 995709 324797 303085 823845 846328
485973 903444 202949 401908 276332 277452 274593 629840 754061 670094 153644 753273 784348 945431 255883 967672 896893 161929 719595
606010 560818 983041 279830 538615 54711 685389 781572 141856 868555 391675 371601 597642 609119 25276 374443 688472 219493 331414
308277 196150 967154 871569 474587 473758 580366 221721 627489 328270 969555 948505 908952 281271 318817 726574 931521 495533 911382
641009 511757 213335 837406 974447 256047 14395 886320 407926 245479 476650 613563 479007 702659 777327 218251 478066 345583 844923
967413 253280 486465 4444 227356 914114 888890 319731 390571 165441 100819 737969 173510 237882 534115 706598 655609 37112 789788
996538 412902 144087 704827 617776 641652 561127 903009 598764 432959 232389 112927 960612 911599 276605 748349 182355 173422 173293
743588 130904 961020 501075 278692 895716 835047 193643 965754 175769 799782 74006 359611 871009 269309 592930 643580 173756 273484
590637 663765 538696 786559 868383 728089 867872 110034 359416 46910 75915 779881 471357 927768 108848 307323 881935 639778 20619
47809 648572 925141 773775 402651 713850 264222 8460 79187 663706 332124 34078 789564 768370 361320 944592 502113 713658 401545
576750 784409 757902 532621 866900 118685 573767 888857 479380 863636 194265 474873 710825 101026 163613 58203 442107 345117 516966
538856 485221 28821 602496 250918 966126 294166 981436 905223 215511 474454 51116 859497 567385 614398 59716 206821 416338 854558
360139 474275 112865 880039 979071 173896 56881 118170 434943 562892 600377 856361 877022 42438 386803 452436 153032 846245 695347
938064 889966 930150 202932 230431 137318 296950 139198 542135 152152 949025 444559 6673 922588 478179 371594 225563 113802 692382
271072 846829 666189 612186 236830 322138 572317 660873 111918 931795 905178 840794 166703 890589 737780 403145 195990 906554 460970
800515 728831 429182 548611 411908 687595 314929 724456 87593 89271 525111 72695 56273 900549 4619 831573 164421 617767 95990
91293 962719 968492 135614 216988 881842 582574 993364 217718 456993 69803 577865 176884 815998 468980 286537 933086 222552 537633
592881 27204 535429 734482 921660 444398 94352 823452 492918 845998 334876 222079 932269 88160 390425 105386 692076 554528 162503
311769 263534 303889 961852 855579 525766 981805 905652 11877 104419 128821 696472 151453 460143 328234 771108 75742 313797 901506
321705 105621 865695 294426 33747 679238 440031 947437 462093 325662 950254 200431 538234 165894 126401 874118 868453 230512 551667
340915 20726 910982 308927 237762 622337 510637 470515 675921 294484 796040 394231 967041 200776 152885 936684 468193 22049 577732
985728 897672 324630 915006 742442 796368 15203 898281 306794 458625 211906 268386 930987 952707 549333 900418 131276 607013 880165
502542 496310 783108 174754 868835 807230 401279 861770 239896 572216 39995 196771 782064 88447 721075 846467 205861 277152 702618
937178 304914 794858 325952 459471 561291 655450 389468 314597 747358 163239 889556 352456 477229 843076 816615 2255 138810 151957
508257 773698 505282 730447 43224 664449 296932 994427 899633 191954 630002 888545 930846 939929 415324 763724 499398 915896 838208
259916 937585 769987 567497 771998 980098 264626 383679 635034 56721 54178 819349 932215 446018 853960 696018 732195 455566 890045
25902 578414 494158 566461 511813 65501 235870 640993 589298 288635 650943 116526 523889 56499 487579 38123 987826 418645 68778
268643 428295 239305 9062 366197 723204 878032 620048 669061 154784 135266 885397 39791 151471 124341 351596 407290 153164 658612
146720 676327 661013 823045 852116 445009 747811 272816 559101 225795 261810 397561 338694 431000 797566 3381 471901 649018 915829
392739 237271 679425 642962 910705 284025 399039 54350 451219 145322 395655 387415 537390 342709 26118 569955 4636 427659 13403
350275 800724 452214 314308 64274 516782 26667 63373 501361 973188 827474 741578 375603 515753 561138 121910 289338 889295 227615
378027 557407 311362 801583 311790 221586 76456 636389 596922 90377 288871 94261 867737 191642 341197 691785 104375 785190 716690
360041 559289 357399 432565 132127 354806 277581 739598 989294 549562 980068 362462 613352 26630 664821 896537 749748 298375 605799
851663 162614 78623 973261 361094 556991 95407 43473 804665 205231 777961 945687 706064 792213 516449 368940 440362 610731 679257
3522 365661 982072 980976 40261 404079 241914 852626 377667 838455 813470 586984 625554 510609 43911 804250 993738 439076 227437
769065 925707 918767 201581 110903 613208 90553 290479 691187 295289 403640 132005 291090 64694 789149 593044 181899 195902 220791
849822 660653 825118 786683 340165 52718 128906 75277 468627 559117 545924 645847 917578 329169 642373 328911 753279 596724 683996
266131 16962 912606 743767 253974 544602 400096 384421 812591 353454 702637 914492 765021 221574 538357 175978 853892 666069 827129
570041 571713 672279 619164 442414 161853 31514 3624 338871 613593 828388 878395 54184 617369 358110 324649 740790 606588 622429
479630 960111 954497 327743 586094 107006 457941 616205 215151 679805 663132 886037 399762 23511 540794 61445 515144 991829 867251
955026 555188 545287 17813 877840 677387 765257 560629 381747 289587 971065 803763 747217 528836 794958 37097 661263 52840 395838
831738 935643 786394 570464 337923 562190 541068 225053 915686 965111 608994 897447 846860 108752 515542 836528 764000 789307 568648
723470 342739 494286 351160 190884 749632 285933 593204 853796 468531 833461 600822 177790 71903 57017 649707 814314 902198 265691
49568 736471 665268 727451 228241 735293 266214 953790 746801 445968 242866 116621 77898 24034 500331 757553 417475 584000 15633
557524 411056 61025 672145 502926 878605 900910 296864 461080 855045 218014 410273 336278 598272 800982 280759 228947 697911 891837
543467 58593 101761 606039 520769 579224 954895 303666 711070 826766 835187 922834 975887 975559 871418 911500 706658 871996 3679
70738 211416 885639 222326 932127 813172 263857 968374 331272 200031 581680 776507 929476 368018 168734 891126 829681 639437 162978
664114 204046 750930 141865 363724 776510 1027 49758 523553 304314 138587 940250 152049 401544 498491 429217 517955 227908 879362
313974 291320 485053 226156 652119 795722 249826 508193 842652 255385 750959 602417 830531 873597 156502 81403 172733 903063 300608
846077 226886 347950 354733 183161 929453 812804 548124 494858 371192 73718 717848 264585 753817 114424 870529 230068 837886 823817
659709 680097 68715 284764 52701 374669 249328 434817 929041 151048 158301 31343 406449 323024 963833 34601 150302 121669 383300
509094 369943 985701 534759 906697 707915 724234 259242 265120 889484 313892 352130 261258 912691 235167 746427 681393 78896 587756
507454 439476 282083 576648 310472 415131 945451 763859 304373 720114 364173 114039 291742 426789 432469 708446 800243 481237 629812
674372 176143 701382 664308 832567 303388 521183 623124 676197 521210 804816 657374 620040 324028 577319 737399 780091 865829 979263
724947 800513 146340 898853 743746 807026 490360 499247 539612 975203 102625 149163 582467 211472 235525 142002 967499 977292 194333
698755 657883 925237 563202 811528 499877 742543 924670 770401 382790 781910 761098 992670 822969 38111 547316 737032 514447 408979
342354 509985 15314 833975 980111 872985 53937 92361 135115 493793 26558 387989 749863 473400 14095 828533 346298 90713 549179
661293 317396 51811 570030 101184 709542 159113 933039 149081 95224 871687 675859 359861 868995 787585 839004 749815 312954 48850
254263 961809 615568 901794 133356 129135 414477 241648 139970 96901 40210 263797 652343 54635 261101 695132 344587 434734 71017
301829 560602 239117 995351 186593 706237 200285 149018 735391 615552 880644 333918 460496 79724 365075 980445 174677 342740 722726
567878 540321 725976 241799 49503 950624 709030 912228 45047 90467 662192 544900 706089 432177 830390 34270 641107 979295 180618
629513 868768 401203 786980 578171 895713 777520 448430 709841 277706 670686 65550 334298 565868 156586 539171 279713 582402 183752
818337 988697 826563 500005 514798 95384 545824 845969 571573 889383 228512 589517 532813 402211 278964 617428 822815 596597 594477
761243 535808 980674 883246 894445 167720 356057 722560 800290 277268 313019 263922 222411 998412 729962 329347 276817 289688 736167
440817 276618 296506 186137 361212 232830 607821 839875 126746 437730 968128 853883 155718 872036 346424 235862 871295 782533 499429
445919 187398 318460 4150 189620 6055 655334 502172 203042 355004 460583 72362 989439 146791 298702 933494 692845 254550 676772
</code></pre>
<p>FV:</p>
<pre><code>0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
179649 162287 315188 558753 228501 59621 714371 568347 850209 846719 167475 678523 51383 748690 76662 363069 249067 846662 390053
700267 852444 348174 597239 392771 6498 204889 688379 981302 394213 696835 556868 110040 441295 410151 768194 133584 816698 988167
614890 359655 320294 262335 114645 89746 508261 809266 690199 579084 879805 675755 607496 649244 7094 496436 417898 96573 641146
940426 824833 274368 249109 711229 587460 228851 455731 15842 715164 294340 884487 991480 771614 813940 310033 621535 322484 852765
790782 558112 520653 214459 287395 191823 707752 581333 489620 370686 46868 854189 204974 978979 789813 562844 739547 870338 670224
222022 658412 433784 991965 501848 881799 515420 102238 323596 565934 523158 990674 174526 802863 857750 372837 767927 665477 264223
941741 888673 305426 19606 344463 800571 922613 363948 989784 432094 747751 406421 367945 342563 287772 891768 373083 356337 575424
938327 664634 370378 694913 331224 161118 339929 252456 866538 984515 126731 403340 672485 550371 614551 204529 126258 690739 292861
640763 343284 549927 171331 12536 426832 388101 420322 122186 99169 166189 930257 468341 985209 718282 236464 150594 126579 657965
639419 462148 580505 159478 447775 481138 991770 951848 771566 745507 217388 197321 22588 545644 545950 162052 96006 226547 939065
52838 472172 787067 203371 969421 954374 186349 233521 877702 610792 775936 558621 685556 524084 60237 198500 708065 210410 609380
806701 217046 416264 452289 964307 743663 213364 544662 170249 657108 236755 786374 653926 929556 897227 712428 684426 404614 506199
810797 536133 293157 218807 754414 980741 178935 571046 149015 262543 520573 44001 543130 537197 707343 286510 899643 58355 144498
668244 500649 639778 789143 985868 889524 974427 351094 827237 793918 699917 286692 703557 77093 633090 686280 834005 209624 227889
894334 959536 929533 844074 139808 112510 353197 145556 408846 484932 793378 434664 878345 314541 142567 152479 524888 699946 776543
619468 705689 679435 468992 203186 699382 375687 185888 604635 747931 996590 376368 256627 913645 144239 206504 160178 819894 366485
19298 722675 411716 571684 79299 428462 882604 790594 196528 880779 157594 635893 155958 140592 372285 619659 294967 3296 998494
869440 793672 286300 116715 136643 199791 784384 281581 84242 227735 632024 629809 687930 499512 951571 538792 943883 515430 610488
994319 747497 869817 223000 683002 227138 342965 744285 883645 699714 631317 953153 758192 753375 319559 743533 576722 461995 796564
488863 70533 603197 669549 110931 856772 489350 702272 421909 184937 495246 186148 563470 365216 132100 255928 243613 524330 872870
718622 23211 62772 559587 277569 822369 70117 446651 383790 830122 638514 853866 995311 929531 523596 364609 46104 509052 294001
124866 724445 85441 805212 937835 220149 414969 894593 46959 214770 766724 515955 322454 715940 280395 342034 967671 869775 485684
118881 382419 460160 562819 190382 73175 271185 522180 848270 550684 355010 757558 673275 211685 73335 448302 323433 529942 552768
943575 279626 138873 375516 759809 713671 170098 448961 705994 990340 251376 424516 203864 388440 134114 465064 393845 111796 235562
756286 6858 630227 451748 195184 664304 851279 273110 723975 769643 951449 28985 137751 778617 378640 425406 712668 577396 252964
287833 778058 869763 867833 835946 604761 12019 190752 517321 169816 464703 780532 79885 743269 511106 220679 376626 644153 790063
825569 174231 124952 109564 225039 42698 691058 867735 36845 11738 995208 27333 63106 960545 727010 537046 399215 992443 384638
288610 759079 895006 984208 23048 815153 39275 544326 391068 1147 452709 145437 390284 430995 136148 821090 982345 532008 817538
660932 541978 767954 378680 80023 63108 869104 720178 426534 48482 194508 580453 730824 962771 523947 780672 460091 217279 869580
529745 688153 684062 739126 306484 686420 687727 671386 432804 264419 392866 814062 767772 1240 675014 983002 423432 58443 717703
278659 481321 321150 364884 699568 415333 254391 302803 842237 145841 150712 887676 703217 315794 113719 133387 74604 257217 151677
104850 516963 757495 637255 211922 285393 934227 412228 762409 143712 616984 839721 761531 438092 559089 570397 439422 576090 471306
757988 217513 368521 563080 67010 22065 760512 596295 151687 930490 863847 619409 663898 140699 445266 810606 693940 570969 353998
314272 869964 68758 308408 246026 942989 13261 324352 379017 317696 758938 187274 531902 617547 814724 202940 600856 412290 170141
235689 154283 776786 262845 299568 510934 770956 720821 309171 695709 788639 465128 860560 43298 976277 169635 944473 200222 974135
941940 663944 141857 947302 660708 171719 493140 418302 561834 192025 905450 582086 95635 130027 357817 786049 580511 123732 584032
38812 614445 88229 676741 81178 913203 679839 886066 263752 498087 620990 801694 490129 320164 195285 862965 190115 457144 328553
21573 560310 155039 751364 452285 118941 442315 265157 726780 733745 228037 564286 491752 243274 292535 353909 476821 457339 568930
605997 823308 158570 438009 104439 715894 376827 517518 541179 96469 367369 817240 700655 851544 54584 588228 306656 391562 364977
678204 872238 883149 745274 203021 250972 154794 376732 545590 421759 965385 633941 998014 495198 464487 324298 819687 777700 979363
36027 931443 712949 730806 144873 273857 171219 822766 183251 695284 286240 130142 643771 747992 935775 801851 521450 332722 129849
314355 21043 673975 495454 547874 813846 977605 76602 324709 309457 483157 549077 640746 367419 664710 709267 350499 106166 921089
721983 822608 956176 13427 805072 372044 688616 775266 845557 144367 726422 935625 794481 75928 815876 427866 473279 616397 397543
596808 87804 960186 110935 96853 99333 186428 610861 537880 714972 369126 676420 586885 888315 968183 457019 619478 766372 311518
17437 448144 957326 352495 647947 93996 987906 495160 483193 209228 791963 850365 912736 881525 207435 438710 682071 998726 747676
782796 75255 824762 511990 314953 246940 452113 242450 691857 608273 9908 772511 163487 944816 734051 740463 376928 165638 876243
83690 486554 493015 888380 960661 16212 421021 72921 220756 756836 302320 499400 975399 171606 631994 348864 586177 266066 172639
397212 678427 33663 736541 180910 295086 483103 76291 241458 829976 515771 934074 696685 161700 407355 209191 103726 105261 573469
432613 209640 871311 970587 413200 567540 741284 454050 863100 866352 874331 783859 180185 664593 911276 140207 379589 289507 353963
876299 908625 28772 97694 346916 985137 278011 19556 605302 991773 615491 959899 992104 557664 434672 811508 412882 19249 448787
592685 468711 110023 426367 416264 967413 939698 337549 711529 512917 94397 645802 755857 540972 63419 752139 845356 621269 383317
649179 206040 545528 979464 253285 701745 126068 809737 198741 791086 48370 372591 164122 640796 551710 910684 818445 969789 526020
928498 15233 185375 640356 497603 471644 811918 766132 725101 618781 393674 478194 374685 572296 678504 222693 753324 846246 993696
20494 953571 642735 363090 776420 505740 120321 454450 87627 720432 367652 496743 598094 651077 645217 15196 803896 124079 700692
902039 181661 941689 862963 604221 302717 45900 108515 155559 144651 544380 280666 350626 630494 858304 680065 479111 170564 60255
811484 536620 607813 615039 357023 120555 49624 12923 276290 494325 988804 982971 324865 896396 39738 349299 635532 448665 389862
807805 947079 293712 541071 139095 890867 859812 85023 292537 893232 237544 807966 413393 868089 106849 993610 49756 401331 864693
414280 574275 838357 336346 35990 473775 129153 663240 18251 639429 988747 901344 519596 265661 70433 788674 813646 999576 621160
180106 731990 307876 524949 115867 172937 704220 283646 432432 350521 626598 853350 666970 504578 96422 203563 903132 335734 990022
668841 928247 354197 120932 832463 402145 237365 40029 71950 293682 936109 281927 518964 516470 233366 857818 143579 347447 593620
611377 778522 782688 293225 954524 59031 691647 243724 638399 215184 471668 738497 415603 161182 412472 590239 953834 232291 715818
297478 670918 414161 897300 341715 910151 143541 646156 6803 991572 954094 558806 160379 104534 580425 599058 249164 676764 859672
23689 260248 769663 975293 700540 563052 744649 67649 222579 644715 585055 615120 851577 572084 590480 125547 820776 345874 132849
590185 131270 757081 785190 148997 335718 818715 692586 406439 560663 537337 710783 161859 626509 960874 984612 344807 144057 375571
985230 195177 175616 656569 521608 255204 939727 366718 464827 200058 284383 258611 880421 878278 356128 248271 919475 334389 960880
489130 197222 838322 950076 889214 99417 866758 833159 214594 316215 894624 46549 780666 144533 17538 945933 397382 492169 536855
900763 468533 62063 755440 900196 935356 749645 583601 643797 91487 311507 789153 797861 9944 691743 506037 917465 955302 691801
605650 786875 757671 836297 24970 767419 208177 277378 448221 811377 322610 548886 21608 747480 343097 691327 767403 148183 582492
955415 920442 145384 179469 639776 648643 25465 996683 541347 428580 546130 827810 817740 50709 573353 212326 481260 700676 20865
792244 552340 450939 197259 783307 123222 674736 775129 813823 161634 243641 296874 572592 953372 631649 764742 333953 315444 66944
467153 802145 467400 981360 85530 494883 842682 51552 328636 552205 961689 268308 567341 875604 89969 896519 336009 666224 979096
883763 988543 793639 783247 797686 61426 877798 78760 120877 413801 542042 36506 685799 968741 287553 650844 707178 744450 341400
836711 997408 684774 693653 925794 653826 691009 105016 278159 397117 903177 696091 803811 240206 716548 709385 962688 680294 799723
712989 15263 62035 352909 573733 281705 248325 439423 672082 202220 959420 413100 693204 788545 191167 549434 679965 93206 202154
884038 354171 970081 258778 657940 760783 275437 759691 217264 885595 816335 237476 592361 409723 117037 711929 87525 901186 450024
996435 2856 79636 774287 708674 16367 39389 800055 862692 507883 50709 476734 97807 619103 272966 813463 635492 491805 802460
389489 773133 786066 103858 844310 219488 534931 128900 161182 11772 127380 651775 475562 715611 424505 177167 817005 510085 171438
119748 135078 26100 646431 628242 778815 153334 357927 54901 936695 454402 574919 849882 389473 597212 670783 813403 410902 951488
646960 26384 434046 638484 811916 904287 579457 125865 162380 904054 274546 431547 144036 951655 993406 503593 129037 264663 533240
642643 354740 838874 268052 613015 880202 801108 711996 347692 641145 345936 165755 108868 263644 701297 432953 471654 93420 131661
318720 320124 835804 964529 675943 569674 341730 951951 792574 624105 606626 254515 391083 551679 356827 101130 61735 266453 528258
410333 166935 232631 623545 970378 940608 891291 131574 185341 455501 788671 313081 192399 667742 775135 154117 724485 973589 436290
458720 425066 290592 226584 121880 613355 918434 964367 914967 561789 811383 391084 956103 473023 341104 389356 55318 285442 330989
687506 629622 556030 95385 71422 557129 652512 378199 263328 657111 829056 677939 823412 62188 223826 175658 918628 756537 715753
623435 527922 640422 43749 669177 636891 320437 688196 112790 468187 976457 626189 376066 301507 389293 191839 227331 343896 203403
857091 428106 922466 593174 43882 229839 538979 214693 579404 538744 532981 602782 768227 684061 224660 69997 771861 442910 915281
202805 712171 596546 84308 247665 389822 34249 565730 862118 898577 739121 264902 587981 129755 677316 414275 178863 995157 19222
934733 801079 940076 219751 330526 723365 203720 849493 82329 718318 591392 410965 56986 712445 687912 686862 396779 193649 459354
872432 334893 865470 444696 45755 809095 507425 348440 768708 808101 674365 38301 694119 426365 636760 970465 180527 641201 545622
316408 396620 182038 806921 862933 725253 670868 456910 216942 281742 979785 738681 554452 864155 142627 445857 263100 518269 504065
281053 984551 171706 367321 723602 8712 366800 800361 59081 593664 156837 63199 936131 500236 531773 383137 687002 101699 468400
614459 738692 443825 800059 631937 367643 243201 289837 431024 430651 653182 621837 139126 963267 834190 931352 601575 229028 670554
721501 562612 249332 51289 158771 556296 319658 346314 963900 242262 366598 426893 152387 380547 262012 211065 301428 856861 217645
881544 48887 211212 103205 443655 106974 644522 392077 351972 535358 406647 111833 154863 456421 648972 835149 315320 437913 186793
969961 149401 739989 112465 810027 763428 168825 99428 707896 250090 475075 509662 775522 832315 155898 969364 437105 491023 514508
744578 754466 919765 194133 858281 455154 515105 542602 28060 846565 984894 82525 257486 451823 455882 136152 861322 246980 764093
8571 450678 738755 593426 352031 508270 553072 675983 994405 75463 295177 287166 144105 433779 27264 757618 609235 233878 342333
510462 315708 542009 533239 96732 998793 21433 455791 702055 447057 581894 170762 359967 662497 551581 733001 548785 667144 537671
562914 342131 693194 657298 461606 77308 415959 203778 482248 285318 825498 888914 44020 749472 981147 942965 425695 970762 429391
36131 684735 409422 76387 928439 693147 497097 223057 265033 692048 901812 813357 271431 551296 225198 427956 15273 457059 926890
709429 668513 957995 64099 887726 336069 113689 973359 23372 447172 551621 735937 59028 864841 381963 488771 22968 853837 100365
211264 83523 856706 98101 919230 873797 823294 598718 727599 700256 11374 835599 880250 260856 459113 707967 531872 28608 682749
252664 830554 798042 69004 204999 564128 345225 109540 775771 987706 21808 572958 236271 350106 950498 427213 619 505508 500183
2121 520945 945296 972265 347166 606923 200285 824003 15700 57917 478069 222263 598542 765389 981171 44525 591992 742786 591853
79772 541559 982846 705732 512154 370882 549200 256838 756530 440277 635768 112559 663692 626139 316119 516432 886263 920354 27932
525668 344672 399932 549308 728164 961147 877394 443972 571066 168477 279587 596991 744761 893874 942334 162452 54771 972901 855782
710146 524454 885173 232656 502815 74640 447724 551992 281656 311828 971412 139166 736143 831758 952078 684793 244148 799725 818598
422248 770858 594912 255965 315995 516641 523123 126110 208086 620259 781012 170781 177182 249989 198331 145000 101554 863473 753170
31693 497583 576295 986883 634890 248463 48259 926642 618359 339349 838520 875555 380890 19912 11406 526125 78041 693202 411822
278956 884281 579037 369305 664420 538050 694470 196648 434921 514709 855911 276530 903234 612579 866627 376780 974459 932674 827799
630121 945194 913606 173561 540960 763859 145737 370247 252667 907951 528682 457935 52989 67692 661866 196178 876508 982045 585607
591937 574533 722357 523835 110281 613923 736397 781939 457532 532644 572001 537693 890269 98084 915623 583329 501295 326532 726123
906508 123555 67802 8617 35943 175328 480783 106073 139881 926335 120713 237490 976231 538291 196999 968564 125850 776219 296739
398881 148828 825596 178834 26623 549002 957007 322468 266165 948930 519582 138826 89018 131569 645071 657622 829352 817307 722939
59471 176241 982244 53775 75695 823830 866793 734806 335034 711954 717178 635142 844898 478606 25525 517471 339792 275398 87228
566061 956553 687192 458049 942966 891974 761072 658383 713422 244489 487864 699309 118138 130267 959581 506810 152713 74033 75377
916086 135765 135040 335955 641782 169386 82877 909742 723047 536638 301360 437189 221985 677680 7999 357915 613392 244492 377316
256879 531045 500029 425202 955454 686253 71496 535254 135273 521928 960777 925276 233447 348206 973918 270400 567736 453145 723384
711964 715771 45012 465558 586443 615286 873124 78530 268219 408004 251357 110924 183815 472039 954707 729460 440907 560982 882866
387128 947077 732747 130395 157470 51538 940573 439461 69088 704808 604268 357924 608724 975261 678255 885302 524081 30353 72176
981069 870105 270510 793392 195550 422956 252414 684965 729920 679673 508979 938158 436755 647480 534354 61009 587066 167872 814966
773351 416238 340681 92799 357279 678436 14272 286097 484818 704484 991087 549837 244284 634230 244984 944080 920107 17304 753863
236648 328527 152823 165380 692929 775226 519019 326866 194084 227142 820922 30768 641782 707123 87559 481957 695458 158298 25219
18488 879238 810633 264431 708777 765658 838426 764014 907886 938456 912020 917633 664955 240446 461979 468590 625688 657471 425798
414463 56149 912400 24113 496223 496130 969167 370786 754472 363264 219195 778114 54968 278291 803670 533195 357496 456418 291100
843809 80330 893200 973729 251474 90365 196135 41890 357875 867201 467167 393438 320756 687312 404658 400995 321839 159047 976203
141274 138001 756515 265903 550214 285791 999165 624967 221251 219818 722850 254227 806782 221535 347340 238035 721158 38019 746063
580386 344664 715604 398933 380242 449519 107057 369094 694822 910130 57423 850768 936003 340973 824359 718752 635993 191328 298869
800069 446319 423230 2463 799603 185675 420049 711497 295351 684310 881099 141794 623374 387802 27089 189473 907683 485305 82671
723949 179424 873487 205908 847276 209150 828607 811771 518242 404700 96982 259916 248451 980816 866199 78653 958868 676453 161299
728195 520745 191469 934973 93977 447981 108181 943758 379032 928083 227051 471212 335662 362695 94067 3103 824215 265204 845197
79319 341384 723536 207012 926902 888845 30261 273398 959901 437240 517804 622202 149136 594278 779995 524423 660723 412892 360458
471176 752996 938976 709512 38517 594618 315618 17874 437428 918547 854895 602905 162516 769786 414977 798612 434179 413433 839661
210544 566344 490178 853324 188917 13013 760382 763468 607917 884858 294558 811264 41018 693556 757643 215748 273957 919205 416283
771100 790512 696140 659204 458530 770301 81606 115706 93395 389928 591937 936923 449557 405986 902805 98086 54971 9333 731673
729344 238320 12998 103386 814187 775964 307336 183491 446706 55238 363834 285321 434107 484004 773927 282677 559979 302337 208792
644911 267660 616672 104511 418518 681170 818364 574991 179667 616991 637781 759907 795353 420453 380216 336821 884573 373795 548283
891026 420307 706212 466893 647519 104100 521320 281025 774697 724570 416405 642985 611511 871935 265907 262653 984293 753414 744680
123129 905680 163643 225760 206939 710169 388974 442763 232448 149108 456331 588044 928644 884044 148056 961753 684251 132935 560957
804146 24219 161347 378414 391564 634004 89044 231057 890705 837352 905969 793843 149560 41592 431381 54202 81818 144377 989678
294742 596092 630688 292047 9893 817048 853045 846393 607178 364833 932631 269158 305799 358514 4283 456616 133317 626196 186678
163845 931625 561505 634358 341935 854990 828611 809382 307170 938164 178151 747656 113811 675408 2441 689382 227219 780838 855777
461074 66673 404417 693888 261447 433972 281356 395280 796092 728082 916078 968370 339529 38783 159261 709709 656197 370272 418076
783549 868860 97581 887560 991785 887042 415903 435564 923660 832875 860479 133117 265016 670677 174949 216398 113984 655009 443911
768714 666120 283994 35463 843488 873857 86535 764843 170402 227701 319297 83634 988807 56350 495236 172097 571569 776416 491891
55948 959142 735641 389746 577472 991310 896133 587795 184541 506352 673714 99642 589419 786546 75973 85623 223262 408727 449720
619881 9993 786012 252030 697427 144557 618788 32291 916909 373303 943751 474902 304890 413347 949211 565851 962346 487354 950151
152079 617170 848442 151061 173430 933770 611450 37673 443890 515295 334355 817893 404250 352756 1922 302319 570400 53096 73468
59806 674878 136954 960470 627130 277312 311874 28934 776114 98243 392836 545988 809454 188068 49637 119227 120745 703203 174484
906005 531743 922271 626838 185696 266611 912862 724622 639923 64196 600619 434123 752419 944347 271789 668377 213954 828859 697137
921590 673632 849398 540191 428976 962248 755467 280913 346356 360862 383339 906734 149527 807318 182258 704367 440168 510662 993386
768686 195082 260784 305050 696639 627455 637041 771297 203110 773906 707082 556219 257047 410515 223746 625667 923364 327525 156297
843283 91170 830 897531 445451 919034 403497 634958 617021 350236 244278 297742 599961 104779 542323 658665 940082 918909 997897
561512 810707 57110 703950 934648 351513 840899 627513 523401 349648 878084 992203 531397 460831 55896 265807 278219 344052 594754
631671 408582 913987 975719 261407 251995 17251 592582 641258 775477 872362 145335 312265 214297 802023 479500 860457 677144 836119
571626 106897 346401 928726 885515 598176 74062 815615 540206 401318 67167 537170 49649 124006 363008 597700 656327 691480 354659
432644 976736 998955 103996 507786 233115 59988 121438 722268 272442 763959 842336 883028 73210 24305 30429 977637 591975 434889
133867 615418 503824 318839 595001 252381 500848 537934 396202 234903 619850 418257 791851 357008 96189 558527 477530 909933 552426
84364 482062 285512 515375 158587 910191 38739 267899 467308 236371 79696 852202 573215 453744 85796 402494 846120 948437 305415
251569 369329 644676 712043 398891 214215 176899 165196 452909 530716 322217 680254 616559 144371 66756 806994 946223 488078 759840
140213 328037 147033 274178 341600 204597 942048 765767 718998 722677 880969 937120 797273 315514 824134 175348 695427 420540 487295
793875 571259 797669 702124 884151 349617 298285 29362 804975 764767 285860 328678 191443 322891 650823 786375 279566 894735 377120
375580 76022 433784 325357 957547 456788 544310 468943 756202 358138 61843 229303 970541 342727 549942 188997 547001 141717 152801
623670 676635 217205 590382 549068 735312 464302 550714 886286 28164 591182 311684 143552 11909 731172 724828 154985 696630 982647
594569 26940 940850 853598 70858 754410 854311 535518 15018 842493 122702 526822 840974 39215 733720 772184 840451 858886 64377
466374 589498 46498 794262 54737 466474 289714 59484 225669 651906 151975 18584 92207 523252 849031 21687 683281 34863 425480
609658 981783 942864 766901 552641 787962 631906 340178 91921 579245 346229 384542 359368 941522 229744 626278 927671 846184 638355
845556 753307 698075 526829 337107 182266 136202 288979 865658 931821 581532 339540 9970 154410 46935 227696 70172 350724 582099
133543 186141 854629 743291 649830 548360 573154 587265 23401 493041 725976 435296 787021 768329 707247 418695 68291 744932 812604
163723 913742 996955 886410 855379 737508 564817 686508 189730 351319 185751 731203 626441 572066 62894 5646 874212 117676 988632
334753 929353 417921 497138 703469 585391 538783 422704 515943 695736 459924 580051 547158 275098 179773 872337 102784 996778 469929
39813 532450 651683 68040 96422 87649 719117 116415 33799 293118 270805 192015 205274 549662 555700 904610 254321 443114 802528
815818 581640 779534 175689 274098 110418 436321 631940 175437 686062 298856 708347 641341 146583 362967 470370 557833 486154 734260
434341 628820 559657 510713 708642 712477 503071 404944 620756 143047 332150 784295 498616 270965 192978 600975 531923 23847 348395
647827 771947 607261 149625 232693 663211 696965 887143 626059 27431 129812 19579 954107 335408 293302 966546 401194 17304 156900
578717 889339 932466 771024 754838 843864 63803 192951 178667 697020 526639 433412 370837 88137 841080 599263 459241 398496 753550
608389 197078 207160 470929 107608 237117 755235 274680 641421 20576 313860 488029 23889 241411 114774 121559 859399 766290 202132
412760 482517 169021 746368 373600 283944 989648 377192 206216 18614 434761 764743 604056 905513 681107 582395 5930 921643 296427
380482 181473 301709 564340 181385 303879 809260 344523 607850 525092 484581 59539 683967 858573 547654 179116 155117 796663 858651
917506 592467 856107 722946 965877 213179 608330 33994 914932 809536 590823 31248 731764 466490 408255 90341 820245 921091 868083
239381 904314 790992 771372 648307 937306 478231 56851 728292 994699 130731 240116 556997 672967 979512 424539 645145 949376 80033
376069 114933 252972 77950 568953 108474 947428 57796 520057 854701 115488 758723 217899 960396 772640 103455 328215 804652 827252
183740 152198 424707 941553 548825 862021 291441 648452 202376 638971 232853 760596 976750 159126 643668 199208 994109 412500 609935
971147 521431 503771 605497 601658 737264 577180 855460 363816 176342 196325 415268 88978 615893 229055 177122 119093 351213 910704
927305 808198 507047 689191 159784 418740 69097 164665 14995 414261 109834 66528 173404 662247 681151 140870 829244 141776 361699
138568 657414 195503 112556 269127 922361 299806 839713 955920 147911 955444 792788 792700 72646 509249 346538 89777 106293 60242
828243 125448 905138 99214 559594 326534 931738 29761 163635 872979 842318 292945 351458 806042 561820 310174 328686 33532 755070
662312 522091 702951 413900 749826 698408 983329 659593 413124 655598 541217 542191 437954 834092 272370 264650 270820 987912 261029
501092 94149 301766 203698 327410 499336 212905 42986 86814 69631 711501 274787 626228 182062 508797 155404 265691 424643 354032
900697 813825 238371 276355 813668 569357 839097 38529 407180 62774 682983 327632 913928 526214 572000 212712 71504 144511 688901
988099 897362 440716 406339 79833 988848 315686 649094 70084 632116 670162 50371 403414 186472 501182 439162 505514 904615 651389
380528 144845 456904 403689 825977 182966 750710 967890 926831 653870 23384 540031 912556 809648 612815 575150 441352 599126 687584
85692 699975 400221 989895 435991 953983 513634 174089 3511 791734 383809 755877 346530 270640 671946 751832 800846 803517 877557
405070 589395 468552 710036 876035 967562 901229 584923 389511 534969 111974 64448 734688 385201 733643 852245 379203 507633 579576
757636 16593 795955 905394 468772 751784 274503 25031 552807 161520 31903 305083 655991 745752 207592 89362 714401 699992 127732
813867 827298 901920 285373 317359 538704 502182 583122 218651 670273 501665 109352 288617 494518 599239 831826 224813 744120 843379
595979 244522 122655 667646 31947 683452 250218 957395 972215 911029 470760 912342 484047 816387 305270 269198 891556 870994 741092
274485 750539 321025 877228 831456 290905 921043 784991 873591 280770 941027 693125 593660 3133 673661 260909 70784 193917 397727
847947 719042 971557 751218 892761 626130 896036 734037 369823 865329 847214 826694 236415 161038 478408 537714 150705 936257 733978
765058 127629 1757 738187 823362 452998 754609 297656 58245 820390 585499 999684 998929 556242 351354 35521 921111 808698 421540
878502 78379 716633 34824 551959 438968 116037 92597 259566 481417 184495 256341 183106 38808 98645 623623 36512 844824 369419
279144 490387 621378 95485 975283 630546 628910 16573 474073 979323 214927 525500 168966 312302 29359 675826 915261 65340 933208
583273 694057 281171 516631 154373 547526 616932 484924 817173 270681 43949 28758 172595 305951 531169 952478 195688 323410 602517
868980 408960 377639 243813 933843 675622 569555 227518 716140 257218 608774 325202 910659 352173 390079 600378 745698 450792 471823
539702 119923 129046 377153 416083 182765 378306 588324 72921 452447 400371 132196 555425 786773 140174 282077 597433 730597 752011
</code></pre>
<p>LA:</p>
<pre><code> 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
108502057 101127130 113821753 104723550 100424925 106417179 97368829 95380056 101339710 113636658 100785242 105127366 104402709 101579739 96902645 96765112 103895580 107746038 101792534
</code></pre>
<p>Thanks in advance, and let me know if I can be clearer about anything.</p>
|
[] |
[
{
"body": "<p>I don't know R, so I can't comment much on your code. </p>\n\n<p>If we strip away the context, then it sounds like we could phrase your question as such:</p>\n\n<blockquote>\n <p>Given a list of pairs\n <span class=\"math-container\">$$L = \\bigl[ (a_1,b_1), (a_2,b_2), ... (a_n,b_n)\\bigr]$$</span>\n and a number <em>S</em>,\n find a list \n <span class=\"math-container\">$$C = \\bigl[c_1, ... c_n\\bigr]$$</span> \n <span class=\"math-container\">$$c_i ∈ \\{first, second\\} $$</span>\n that minimizes\n <span class=\"math-container\">$$ \\left| S -\\sum_{i ∈ [1...N]} C_i(L_i)\\right|$$</span></p>\n</blockquote>\n\n<p>(Is it guaranteed that there will be a C for which that difference is 0?)</p>\n\n<p>Our total search space is then 2^n combinations .\n(for a version of the problem that represents one column of your data)</p>\n\n<p>We can improve on your random method by searching that space systematically; just count up from 0 to n in binary and those digits are your candidate lists C.</p>\n\n<p>That's still a O(2^n) process, the advantage is that you're never re-checking the same list by accident. I would bet that a O(log(n)) or O(n log(n)) algorithm exists; you could take this over to StackOverflow or the Math SE and probably get some suggestions. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T18:12:44.640",
"Id": "442658",
"Score": "0",
"body": "Thanks for your response @ShapeOfMatter . I like your suggestion it is certainly more efficient, but again it would still be a long process, especially if I increase the sample space (which is likely to happen). To answer your question, I expect it should be the case that there exists a C such that the difference is zero, I still don't want to force this as a constraint though as I can't say this with complete certainty."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T18:12:48.907",
"Id": "442659",
"Score": "1",
"body": "Please see my answer -- I show that this problem is NP-hard, so there are no known polynomial runtime algorithms for it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T17:39:02.093",
"Id": "227421",
"ParentId": "227401",
"Score": "2"
}
},
{
"body": "<p>To briefly summarize your problem, for each of your column numbers (1-19) you have two vectors (<code>FV</code> and <code>CV</code>) of the same length. For each pair of elements, you can only pick one. You want to pick the elements such that the sum is as close as possible to the target value for that column stored in <code>LA</code>.</p>\n\n<p>First, a bit of theory. If <code>FV</code> were filled with all 0's, then you can think of your problem as being equivalent to selecting the subset of elements in <code>CV</code> that sum as closely as possible to the value stored in <code>LA</code>. This is the famous Subset Sum Problem, which is NP-hard. Since the Subset Sum Problem is a special case of your problem, then we know your problem is also NP-hard. This means there is no known polynomial runtime algorithm that will always correctly solve your problem.</p>\n\n<p>That being said, people routinely solve NP-hard problems in times that they find acceptable for their problem instances using integer programming software. You could define one binary decision variable <code>x[i]</code> for each row <code>i</code> of your dataset that takes value 1 if you use the FV value and value 0 if you take the CV value, as well as decision variable <code>o</code> for your objective value (the absolute value of the difference between your selected sum and the target value). Then you could define the following integer program:</p>\n\n<pre><code>min o\ns.t. o >= \\sum_i { CV[i] + (FV[i]-CV[i])*x[i] } - LA[i]\n o >= -\\sum_i { CV[i] - (FV[i]-CV[i])*x[i] } + LA[i]\n x[i] binary\n</code></pre>\n\n<p>You can solve this in R using a package like the <code>lpSolveAPI</code> package:</p>\n\n<pre><code>library(lpSolveAPI)\nsystem.time(results <- lapply(seq_len(ncol(FV)), function(k) {\n mod <- make.lp(2, nrow(FV)+1)\n set.objfn(mod, c(1, rep(0, nrow(FV))))\n set.row(mod, 1, c(1, df_CV[,k]-df_FV[,k]))\n set.row(mod, 2, c(1, df_FV[,k]-df_CV[,k]))\n set.constr.type(mod, c(2, 2)) # >= constraints\n set.type(mod, 1, \"real\")\n set.type(mod, 2:(nrow(FV)+1), \"binary\")\n set.rhs(mod, c(1, -1) * (sum(df_CV[,k]) - df_LA[,k]))\n lp.control(mod, timeout=100)\n solve(mod)\n list(selections = 1+get.variables(mod), gap = get.objective(mod))\n}))\n# user system elapsed \n# 26.291 0.040 26.396 \n</code></pre>\n\n<p>So there's some good news -- for the problem instance you shared here, we can actually get the optimal selections very quickly (about 1 second per column). This is clearly much faster than a brute force approach, which would need to check 2^205 (more than a trillion trillion trillion trillion trillion) possibilities -- clearly not feasible. It is both faster than the approach you posted (since you were checking many randomly generated solutions), and also has the advantage of always guaranteeing that it gives you the best combination of CV and FV values possible.</p>\n\n<p>The optimal solutions are very good; all give (up to numerical precision) sums equal to the target:</p>\n\n<pre><code>sapply(results, \"[[\", \"gap\")\n# [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n</code></pre>\n\n<p>I returned the results as a list of lists, which I think should be more manageable than what you were originally returning (a matrix with a pair of columns for each original column, and each column in the pair meaning some different thing). You can build a matrix of selections for each row and column with:</p>\n\n<pre><code>sapply(results, \"[[\", \"selections\")\n</code></pre>\n\n<p>If you increase the number of samples (the length of <code>CV</code> and <code>LV</code>), then you may find that the integer program may begin to take too long to solve to optimality. I included a timeout of 100 seconds per model in my code above; you can play with that to meet your needs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T19:06:01.830",
"Id": "442681",
"Score": "0",
"body": "Nice answer. I'd be interested in making sense of your code; is it possible to improve the formatting or do I just have to learn R?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T18:11:24.257",
"Id": "227425",
"ParentId": "227401",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "227425",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T13:57:19.280",
"Id": "227401",
"Score": "4",
"Tags": [
"performance",
"r"
],
"Title": "Looping through two lists and randomly aggregating elements to equal an element from another list"
}
|
227401
|
<p>This is one of the methods in a project for generating points between two given points. We add points of route with a 25ms delay in an array and a camera on Google Maps is always at the last point. So we need to move it smoothly. This method adds those extra points between any two given points to make it move smoothly.</p>
<pre><code>public List<Tuple<double, double>> GeneratePointsForSmoothMovement(double x1, double y1, double x2, double y2, double divider)
{
// If points are same, return empty list
if (x1 == x2 && y1 == y2)
return new List<Tuple<double, double>>();
// get difference between x and y cordinates
double xi = (x2 - x1);
double yi = (y2 - y1);
// divide difference into n parts
xi = xi / divider;
yi = yi / divider;
// set new temp vars equal to first point
double xf = x1;
double yf = y1;
// initialize list to save new points
List<Tuple<double, double>> points = new List<Tuple<double, double>>();
// increment temp vars by difference-division parts
for (int i = 0; i < divider; i++)
{
xf += xi;
yf += yi;
points.Add(Tuple.Create(xf, yf));
}
// last cordinate in the list will be equal to point 2
// return
return points;
}
</code></pre>
<p>Is this the most efficient way ?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T14:51:43.160",
"Id": "442581",
"Score": "4",
"body": "What is your question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T15:02:15.067",
"Id": "442582",
"Score": "1",
"body": "@OlivierJacot-Descombes this website is for code review and improvements suggestion right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T15:15:41.523",
"Id": "442592",
"Score": "6",
"body": "Are you questioning the interpolation method, the code quality, memory or time efficiency, correctness or something, else?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T00:33:43.287",
"Id": "442710",
"Score": "3",
"body": "First of all, which distances are we talking here? If it's on the order of meters or kilometers, that's probably fine. But if you want to show the movement across hundreds or thousands of kilometers, linear interpolation won't work: the shortest path is a geodesic instead of a straight line, and if the route happens to cross the 180 meridian (e.g. Japan to Hawaii), you'll end up going the wrong way all around the globe."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T11:38:26.743",
"Id": "442799",
"Score": "0",
"body": "Also, to make it smooth, you could a variable `divider`. Start slow at `x1, y1`, accelerate, brake, stop at `x2, y2`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T18:45:49.530",
"Id": "442892",
"Score": "0",
"body": "An interesting point, note that this sort of digital signal processing is very much BUILT-IN to most devices / gpus these days: stackoverflow.com/questions/57509407"
}
] |
[
{
"body": "<p><strong>Make it an enumerator</strong> You can make the evaluation lazy and get rid of the intermediate list by changing the return type to <code>IEnumerable<></code>.</p>\n\n<p><strong>Use named tuples</strong> You can make the API more user-friendly by using named tuples. Something like a <code>readonly struct Point</code> would be preferable but if you don't have it or don't want it then named tuples are your best friend.</p>\n\n<p><strong>Interpolation</strong> The point generation you're doing is called <em>interpolation</em>. You can use this word in the method name like <code>InterpolateMovement</code>. I don't know if these calculations have any concrete name, but if they have than you may use an even more exact name like <code>InterpolateMovementByAlgorithmName</code>.</p>\n\n<p>Here's an example of how this could look like after implementing the above suggesions:</p>\n\n<pre><code>public IEnumerable<(double X, double Y)> InterpolateMovement(double x1, double y1, double x2, double y2, double divider)\n{\n // If points are same, return empty list\n if (x1 == x2 && y1 == y2)\n {\n yield break; // break the enumeration\n }\n\n // ..\n\n // increment temp vars by difference-division parts\n for (int i = 0; i < divider; i++)\n {\n xf += xi;\n yf += yi;\n\n yield return (xf, yf); // <-- return tuples\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T15:27:09.330",
"Id": "442596",
"Score": "4",
"body": "Linear interpolation"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T15:21:45.863",
"Id": "227410",
"ParentId": "227404",
"Score": "4"
}
},
{
"body": "<ul>\n<li><p>The <code>Tuple<T1, T2></code> type is a reference type requiring to create objects on the heap, what puts strain on the GC. Use a value type, i.e. a struct type. Use the new <code>ValueTuple</code> type or an existing point or vector type or create your own struct. In public API's dedicated types are preferred over tuple types.</p></li>\n<li><p>You are testing <code>x1 == x2 && y1 == y2</code>. This is a bit hazardous, since <code>double</code> values are subject to tiny rounding errors. Define a minimum allowed difference.</p>\n\n<pre><code>private const double Eps = 1e-6;\n\nif (Math.Abs(x2 - x1) < Eps && Math.Abs(y2 - y1) < Eps) \n</code></pre></li>\n<li><p>Parentheses are superfluous here. The assignment operator has always the lowest <a href=\"https://docs.microsoft.com/en-us/cpp/c-language/precedence-and-order-of-evaluation?view=vs-2019\" rel=\"nofollow noreferrer\">precedence</a> (except sequential evaluation with <code>,</code>).</p>\n\n<pre><code>double xi = x2 - x1;\n</code></pre></li>\n<li><p>You could make the divider dependent on the distance between the points. Doing this creates a more uniform camera speed. If you want to keep the original relative speeds, don't do this.</p></li>\n<li><p>Don't repeat long type names. Use <code>var</code> instead.</p>\n\n<pre><code>var points = new List<Tuple<double, double>>();\n</code></pre>\n\n<p>When to use <code>var</code> is a matter of preference. My rules are:</p>\n\n<ul>\n<li>If the type is explicitly visible (as here after the <code>new</code> keyword) or is otherwise obvious, use <code>var</code>.</li>\n<li>Don't use <code>var</code> for primitive types like <code>int</code>, <code>string</code>, or <code>double</code>.</li>\n<li>LINQ expressions often return complex nested types involving <code>IOrderedEnumerable</code> and <code>IGrouping</code> etc. nobody wants to know. These types are mostly used for temporary results either. Use <code>var</code> here.</li>\n<li>Anonymous types have no name and require <code>var</code>. <code>var a = new { Id = 1, Value = 1.4 };</code>. It's the main reason the <code>var</code> keyword has been introduced.</li>\n</ul></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T15:41:17.237",
"Id": "442606",
"Score": "0",
"body": "Do you see a case for the parentheses for readability?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T15:55:43.093",
"Id": "442617",
"Score": "2",
"body": "Parentheses can enhance readability if the expression mixes different types of operators like shift operators, arithmetic operators and others, where the operator precedence might not be obvious at a first glance, since C# has a lot of levels of precedence. In this specific case, I don’t see any advantage for parentheses."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T16:26:49.543",
"Id": "442632",
"Score": "2",
"body": "I do see advantage in parenthesses. You don't have to remember the operator precedence and any differences between languagues. You just set them the way you want them to work and you're done. No need to study the docs. cc @dfhwze :P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T16:30:25.027",
"Id": "442633",
"Score": "2",
"body": "@t3chb0t I've had several discussions about the use of parentheses. And in the end we could argue that: (https://raganwald.com/2016/03/17/programs-must-be-written-for-people-to-read.html)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T00:20:51.857",
"Id": "442708",
"Score": "1",
"body": "In addition to the `==` there's another minor issue of approximate floating-point computations. When you divide the value by, say, 1000 and then add the result a thousand times, you are not guaranteed to get the exact same value: small rounding errors accumulate. So the comment \"last coordinate in the list will be equal to point 2\" is actually wrong, though the difference will probably be negligible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T12:19:12.417",
"Id": "442805",
"Score": "0",
"body": "@IMil. The 1st point added to the list is `(x1 + xi, y1 + yi)`, so there should be no overlapping. Myself, I would have added `(x1, y1)` but omited the last one, i.e. returned `(x2 - xi, y2 - yi)` as last for each line segment. It is then the caller's responsibility to consider the very last point of the whole path."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T14:10:25.320",
"Id": "442838",
"Score": "0",
"body": "@OlivierJacot-Descombes I wasn't talking about off-by-one errors, but about floating point rounding errors. E.g. the source data was `(x2 = 1000.0, y2 = 500.0)` but the last point will be `(999.9999997, 500.000001)`, the difference growing for larger `divider`. Which probably won't matter in this case, but still worth keeping in mind."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T14:24:34.273",
"Id": "442845",
"Score": "0",
"body": "@IMil, I understood your position. With my suggestion there will never be two points which should be equal but aren't. If precision is still an issue (this could happen if we used `float` instead of `double` or if `divider` is a big number), we could calculate the points with `xf = x1 + i * xi` and `yf = y1 + i * yi` instead. The errors would not accumulate. I would also prefer the names `(x0, y0)` and `(x1, y1)` over `(x1, y1)` and `(x2, y2)`, but this is another question."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T15:38:01.020",
"Id": "227412",
"ParentId": "227404",
"Score": "5"
}
},
{
"body": "<p>The parameter name <code>divider</code> doesn't say much. I think I would call it <code>numPoints</code> or <code>countOfPoints</code> or <code>numOffsets</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>List<Tuple<double, double>> points = new List<Tuple<double, double>>();\n</code></pre>\n</blockquote>\n\n<p>You know the size of the list, so to improve performance you can set the <code>capacity</code> of the list</p>\n\n<pre><code>List<Tuple<double, double>> points = new List<Tuple<double, double>>(divider);\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>double xi = (x2 - x1);\ndouble yi = (y2 - y1);\n\n// divide difference into n parts\nxi = xi / divider;\nyi = yi / divider;\n</code></pre>\n</blockquote>\n\n<p>can be done more elegantly:</p>\n\n<pre><code>double xi = (x2 - x1) / divider;\ndouble yi = (y2 - y1) / divider;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T15:50:13.060",
"Id": "227413",
"ParentId": "227404",
"Score": "4"
}
},
{
"body": "<h2>Dividor</h2>\n\n<p><code>dividor</code> is ill-defined. It acts as a factor for quantization:</p>\n\n<blockquote>\n<pre><code> xi = xi / divider;\n</code></pre>\n</blockquote>\n\n<p>But also as threshold for yielding smoothed results:</p>\n\n<blockquote>\n<pre><code>for (int i = 0; i < divider; i++)\n</code></pre>\n</blockquote>\n\n<p>While this seems fine if <code>dividor</code> is <span class=\"math-container\">\\$integer >= 2\\$</span>, it could yield unwanted results for fractions (as it is a double precision integer). I would at least change its type to int or uint instead and add an out-of-bound guard. If you would decide to allow fractions, make it clear in the spec how the edge case near the end is handled, since you might get a scenario where you don't synchronize with the end value.</p>\n\n<hr>\n\n<h2>Usability</h2>\n\n<p><code>GeneratePointsForSmoothMovement</code> is a low level generator. The caller code should still think about technical parameters to provide. And if a caller requires several levels of smoothness, multiple calls with different parameters have to be executed. In order to provide the consumer a solution that avoids most overhead, you could write an extension method on <code>IEnumerable<Tuple<Double,Double>></code> and preferrably also on <code>IDictionary<Double,Double></code> for faster lookup.</p>\n\n<p>In pseudo code:</p>\n\n<pre><code>public static Func<Double, Double> ToContinuousFunction(\n this IDictionary<Double,Double> points)\n{\n return new Func<Double, Double>(x => \n {\n if (points.TryGetValue(x, out var y))\n {\n return y;\n }\n\n // .. perform lineair interpolation or extrapolation based on nearby points\n });\n}\n</code></pre>\n\n<p>Let's say we have points <code>(x: 1, y: 10)</code> and <code>(x: 2, y: 20)</code>:</p>\n\n<pre><code>var f = points.ToContiniousFunction();\nvar yValues = new [] \n{\n f(1) // 10 (from cache)\n ,f(1.5) // 15 (interpolation)\n ,f(2) // 20 (from cache)\n ,f(3) // 30 (extrapolation)\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T17:17:54.250",
"Id": "442640",
"Score": "1",
"body": "Very acute observation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T17:21:40.417",
"Id": "442641",
"Score": "3",
"body": "@HenrikHansen there is actually a very nice pattern you can make here by wrapping a dictionary of (double,double) in a function that performs inter- and extrapolation when a requested value is not cached in the dic. this way you could do _var f \n= pointsDic.ToFunction(); var x = 1.16f; var y = f(x);_ etc without having to worry whether _x_ is observed in the dictionary."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T17:01:37.207",
"Id": "227419",
"ParentId": "227404",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T14:44:17.233",
"Id": "227404",
"Score": "7",
"Tags": [
"c#",
"computational-geometry",
"google-maps",
"easing"
],
"Title": "Generate points for smooth movement between two given points"
}
|
227404
|
<p>I have a list of labels for printing. Now I have go over the list and print the labels. The layout is specified by how many labels per page and per row on a page I can print.</p>
<pre><code>@{
var labels = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 };
var labelsPerPage = 10;
var labelsPerRow = 2;
var labelCount = labels.Count;
}
@for (var i = 0; i < labelCount; i++) {
if (i % labelsPerPage == 0) {
@Html.Raw("<table class=\"page\">")
}
if (i % labelsPerRow == 0) {
@Html.Raw("<tr>")
}
<td class="label">@PrintLabel(labels[i])</td>
if (i % labelsPerRow == (labelsPerRow - 1)) {
@Html.Raw("</tr>")
}
if (i % labelsPerPage == (labelsPerPage - 1)) {
@Html.Raw("</table>")
}
}
@helper PrintLabel(int label) {
@label
}
</code></pre>
<p>Is there a better method (eg. using LINQ or nested <code>for</code>/<code>foreach</code> loops) for going through the list and doing something at the start and end of each page and each row?</p>
<p>I would prefer a nested structure to a flat one so it can be used inside a Razor template. The flat version fails here because Razor requires HTML tags to be closed at the end of a code block.</p>
<p>I'm not looking for performance here, I'd rather have more readable code and possibly getting rid of any <code>Html.Raw()</code> calls.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T15:32:24.017",
"Id": "442599",
"Score": "0",
"body": "I think you should add more context to it, especially how this is used. Should the results remain flat or do you create some tree later, etc? You'd get better feedback if you added more information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T15:54:31.550",
"Id": "442615",
"Score": "1",
"body": "I like your fore loop the best, it's the cleanest code and you can control your page brakes based the way you are doing it now. Sure you can page in Linq but why, your code is faster, cleaner, will not new-up anonymous classes. I like the for loop, I'd even use it if I'd have to format it in html as your foreach can't make guesses of current index and ho many are left to come nor the size of the slip, or width of slip. You see the for loop a lot when having to make ATM or cash receipts"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T16:42:41.680",
"Id": "442634",
"Score": "0",
"body": "The disadvantage of the `for`-loop is that I have to use `@Html.Raw(\"<table>\")` for printing HTML start or end tags because it is not clear for the linter or Razor compiler that the opened tag will eventually be closed later. This gets really bad if I add some CSS classes to the tags, escape the attribute quotes etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T17:38:51.250",
"Id": "442651",
"Score": "2",
"body": "I don't think it will re-open after that edit. Could you include an example of how you would use this? Is this current trivial example an actual use case? Also, it would be better to visualise the layout if you include the Console output."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T18:01:08.063",
"Id": "442654",
"Score": "0",
"body": "_because it triggered marking this question as off-topic_ - this question was off-topic way before that edit. I asked you to add more context but you just ignored that request. In that case, and seeing your comment about rendering html, I think that this code has nothing at all to with your real one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T13:47:43.930",
"Id": "442830",
"Score": "0",
"body": "I would say this should enough to reopen it. Thanks for posting the real code (I hope). It now makes sense ;-]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T13:59:54.110",
"Id": "442835",
"Score": "1",
"body": "Just for my understanding (if I get the idea to ask another question here at CR): Is it actually relevant for understanding the question that I output HTML tags (instead of printing eg. ZPL printing language commands) even if the code structure is the same? Yes this is _real code_ already in production (except that the label contains more than just a number). What context was missing? The HTML? That it is actually used in a Razor template? I thought a C# code snippet would be easier to run than some Razor template code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T14:16:02.570",
"Id": "442839",
"Score": "2",
"body": "If you want to get most out of Code Review and the best input then it's in your interest to post the code that is as real as possible. One can do plenty of mistakes or not know many great APIs that you would never hear about if you _hide_ the fact that you are working with html or razor pages. The more you tell us the better feedback you get. There is no such thing as irrelevant code here on Code Review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T14:21:31.007",
"Id": "442842",
"Score": "0",
"body": "I am much more interested which other ways there are to go through a list and split it in three dimensions or if there is no better way to do it. Next time I have the same problem in C# business logic and output XML or ZPL commands or whatever, but the problem stays the same for me. One flat `for` loop and a stack of `if`s, some nested loops or any functional programming structure. I can't be the first one to layout items coming from one list into columns, rows and pages, am I?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T14:30:07.240",
"Id": "442846",
"Score": "2",
"body": "Nope, your problem is not not splitting a list into thee dimensions but to render a table. What you are describing is a typical xy problem https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem you think the solution is a more efficient way to split a list but what you really want is a table and that splitting is only what you can think of right now so you believe you need to improve that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T16:11:58.147",
"Id": "442868",
"Score": "0",
"body": "Btw. I'm not looking for perfomance here. The goal is to have readable code and possibly getting rid of any `Html.Raw()` calls."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T16:17:40.337",
"Id": "442869",
"Score": "1",
"body": "I find your labels a bit trivial, but at least, after your last set of edits, it's clear now what you are trying to achieve."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T09:30:20.283",
"Id": "442939",
"Score": "0",
"body": "@dfhwze How does the content of the labels influence how the building of the table should be done? Do you prefer another algorithm if the labels are objects with properties in the list fetched by Entity Framework, fechted one by one from a REST service or actually just numbers printend on an A4 sticker sheet?"
}
] |
[
{
"body": "<p>You're closing tags only when a row or table is full. Is data always going to fit the table size?</p>\n\n<blockquote>\n<pre><code>if (i % labelsPerRow == (labelsPerRow - 1)) {\n @Html.Raw(\"</tr>\")\n}\n\nif (i % labelsPerPage == (labelsPerPage - 1)) {\n @Html.Raw(\"</table>\")\n}\n</code></pre>\n</blockquote>\n\n<p>You could make a functional helper and use that instead. Notice that after the loop, the row and table are ensured to be closed. The purpose is to allow the consumer to pick how to build a <code>TAggregate</code> from <code>TSource</code> items and observer methods. We're observing every item, table start/end and row start/end.</p>\n\n<pre><code>public static class GridRenderer\n{\n public static TAggregate Render<TSource, TAggregate>(IEnumerable<TSource> source, TAggregate seed, int pageSize, int rowSize,\n Func<TSource, TAggregate, TAggregate> itemObserver,\n Func<TAggregate, TAggregate> beginPageObserver,\n Func<TAggregate, TAggregate> endPageObserver,\n Func<TAggregate, TAggregate> beginRowObserver,\n Func<TAggregate, TAggregate> endRowObserver)\n {\n if (source == null) throw new ArgumentNullException(nameof(source));\n if (pageSize <= 0) throw new ArgumentOutOfRangeException(nameof(pageSize));\n if (rowSize > pageSize) throw new ArgumentOutOfRangeException(nameof(rowSize));\n // .. check observers for null\n\n var items = source.ToList();\n var result = seed;\n\n if (!items.Any()) return result;\n\n for (var i = 0; i < items.Count; i++)\n {\n if (i % pageSize == 0)\n {\n result = beginPageObserver(result);\n }\n\n if (i % rowSize == 0)\n {\n result = beginRowObserver(result);\n }\n\n result = itemObserver(items[i], result);\n\n if ((i + 1) % rowSize == 0)\n {\n result = endRowObserver(result);\n }\n\n if ((i + 1) % pageSize == 0)\n {\n result = endPageObserver(result);\n }\n }\n\n if (items.Count % rowSize != 0)\n {\n result = endRowObserver(result);\n }\n\n if (items.Count % pageSize != 0)\n {\n result = endPageObserver(result);\n }\n\n return result;\n }\n}\n</code></pre>\n\n<p>Let's say your data does not fit the table size and row size.</p>\n\n<pre><code>var renderer = new StringBuilder();\nGridRenderer.Render(new[] {1, 2, 3, 4, 5}, renderer, 4, 2,\n (item, cur) => cur.AppendLine($\" <td class=\\\"label\\\">{item}</td>\"),\n cur => cur.AppendLine(\"<table class=\\\"page\\\">\"),\n cur => cur.AppendLine(\"</table>\"),\n cur => cur.AppendLine(\" <tr>\"),\n cur => cur.AppendLine(\" </tr>\"));\nvar layout = renderer.ToString();\n</code></pre>\n\n<p>The grid still gets created correctly.</p>\n\n<pre><code><table class=\"page\">\n <tr>\n <td class=\"label\">1</td>\n <td class=\"label\">2</td>\n </tr>\n <tr>\n <td class=\"label\">3</td>\n <td class=\"label\">4</td>\n </tr>\n</table>\n<table class=\"page\">\n <tr>\n <td class=\"label\">5</td>\n </tr>\n</table>\n</code></pre>\n\n<p>Note I've used a <code>StringBuilder</code>, but you could also use any other class to render the output. You could also change the flow a bit if you want an empty table when no data is available.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T13:30:21.613",
"Id": "445013",
"Score": "1",
"body": "Your solution is great (generic, flexible) and thanks for pointing out unclosed rows/tables. I'd really like a nested version if possible so I can leverage Razor, but if there is none or nobody comes up with one I'll mark this one as an answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T05:30:02.390",
"Id": "227758",
"ParentId": "227407",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227758",
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T15:02:42.007",
"Id": "227407",
"Score": "6",
"Tags": [
"c#",
"html",
"layout"
],
"Title": "Group list items into pages, rows and columns"
}
|
227407
|
<p>I have built my own generic class to implement <code>IEqualityComparer(Of T)</code>, which takes a delegate as an input for the constructor. This delegate takes two objects of type <code>T</code> as an input and returns <code>True</code> if they are to be equal.</p>
<pre><code>''' <summary>
''' A generic equality comparer which assess the equality of two objects via the provided delegate.
''' </summary>
''' <typeparam name="T">The type of the objects to compare.</typeparam>
Public Class GenericEqualityComparer(Of T)
Implements IEqualityComparer(Of T)
''' <summary>
''' The delegate invoked to verify equality between two given objects of type <see cref="T"/>.
''' </summary>
Private Comparer As Func(Of T, T, Boolean)
Private Sub New()
Throw New NotImplementedException("User other constructor.")
End Sub
Public Sub New(Comparer As Func(Of T, T, Boolean))
Me.Comparer = Comparer
End Sub
Public Shadows Function Equals(x As T, y As T) As Boolean Implements IEqualityComparer(Of T).Equals
If x Is Nothing OrElse y Is Nothing Then
Return False
Else
Return Comparer.Invoke(x, y)
End If
End Function
Public Shadows Function GetHashCode(obj As T) As Integer Implements IEqualityComparer(Of T).GetHashCode
Return obj.GetHashCode
End Function
End Class
</code></pre>
<p>A example of usage would be</p>
<pre><code>Dim Comparer as New GenericEqualityComparer(Of Person)(function(p, q) p.Name = q.Name And p.Surname = q.Surname)
</code></pre>
<p>My concern is over the implementation of <code>GetHashCode(obj As T)</code>, which should somehow account for what the delegate focuses on.</p>
<p><strong>Am I right to be concerned? Any ideas for a fix?</strong></p>
<hr>
<p>So far I was thinking of replacing the delegate signature by <code>Func(T, IList(Of String))</code>: the delegate would be invoked on both objects X and Y, then the resulting values would be stored in their own list, then both list would be compared side by side: if all side-by-side comparisons are correct, then <code>Equals</code> returns <code>True</code>. <code>GetHashCode</code> would run a <code>.GetHashCode</code> on the list of strings returned by the same delegate.</p>
<pre><code>''' <summary>
''' A generic equality comparer which assess the equality of two objects by comparing the projection of their values via a delegate.
''' </summary>
''' <typeparam name="T">The type of the objects to compare.</typeparam>
Public Class ProjectionEqualityComparer(Of T)
Implements IEqualityComparer(Of T)
''' <summary>
''' The delegate invoked to project an object of type <see cref="T"/> onto a list of strings. Each string item correponds to the projection of a particular state or property of the object.
''' </summary>
Private Projector As Func(Of T, IList(Of String))
Private Sub New()
Throw New NotImplementedException("User other constructor.")
End Sub
Public Sub New(Projector As Func(Of T, IList(Of String)))
Me.Projector = Projector
End Sub
Public Shadows Function Equals(x As T, y As T) As Boolean Implements IEqualityComparer(Of T).Equals
If x Is Nothing OrElse y Is Nothing Then
Return False
Else
Dim xList As IList(Of String) = Me.Projector.Invoke(x)
Dim yList As IList(Of String) = Me.Projector.Invoke(y)
Dim xEnum As IEnumerator(Of String) = xList.GetEnumerator
Dim yEnum As IEnumerator(Of String) = yList.GetEnumerator
Do While xEnum.MoveNext = True And yEnum.MoveNext = True
If xEnum.Current <> yEnum.Current Then Return False
Loop
Return True
End If
End Function
Public Shadows Function GetHashCode(obj As T) As Integer Implements IEqualityComparer(Of T).GetHashCode
Return Me.Projector.Invoke(obj).GetHashCode
End Function
End Class
</code></pre>
<p>A usage would be</p>
<pre><code>Dim OtherComparer as New ProjectionEqualityComparer(Of Person)(function(p) New List(of String) From {p.Name, p.Surname}
</code></pre>
<p>This solution is not so satisfying because it adds a level of complexity for anyone who would review it. It is also hard to turn into a metaphor, hence making the documentation not so user-friendly.</p>
<hr>
<p>Having originally posted the question on SO, @pstrjds suggested to define a HashCode delegate instead of the Comparer or Projector delegates.</p>
<p>I like it, but my understanding is that <code>GetHashCode</code> would accept some collisions, whilst <code>Equals</code> should avoid at all cost. Correct?</p>
<p>Source: <a href="https://docs.microsoft.com/en-us/dotnet/api/system.object.gethashcode?view=netframework-4.8" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/dotnet/api/system.object.gethashcode?view=netframework-4.8</a></p>
<blockquote>
<p>Do not test for equality of hash codes to determine whether two objects are equal. (Unequal objects can have identical hash codes.) To test for equality, call the ReferenceEquals or Equals method. </p>
</blockquote>
|
[] |
[
{
"body": "<p><code>GetHashCode</code> will mostly be used in collections using hash tables internally, like dictionaries or hash sets. If you know that you are only going to test for equality, it is safe to not implement <code>GetHashCode</code>.</p>\n\n<ul>\n<li><p>Instead of letting the projector return a list of values, better store a list of accessor delegates. If you create a list of values, this list will have to be created each time you are comparing values. Accessors are created once.</p></li>\n<li><p><code>Private Sub New()</code> cannot be called from outside the class. No need to throw an exception. You can even drop it completely, because when you provide any other constructor with parameters, the default constructor (i.e. the constructor without parameters) will not be generated by VB.</p></li>\n<li><p>Calling <code>GetHashCode</code> on a list, only gets a hash code for the list object, without considering the list entries. We must calculate a combined hash code ourselves.</p></li>\n<li><p>Our comparer will be more generic, if we don't assume the values to be of type <code>String</code> and instead operate on <code>Object</code>.</p></li>\n</ul>\n\n<p>My suggestion:</p>\n\n<pre><code>Public Class ValuesEqualityComparer(Of T)\n Implements IEqualityComparer(Of T)\n\n ReadOnly _valueAcessors As IList(Of Func(Of T, Object))\n\n ' We can drop the parameter-less constructor. The other one replaces this one. \n ' Now, you must provide a an argument for New.\n 'Private Sub New()\n 'End Sub\n\n Public Sub New(valueAcessors As IList(Of Func(Of T, Object)))\n _valueAcessors = valueAcessors\n End Sub\n\n Public Overloads Function Equals(x As T, y As T) As Boolean _\n Implements IEqualityComparer(Of T).Equals\n\n Return _valueAcessors.All(Function(v) Object.Equals(v(x), v(y)))\n End Function\n\n Public Overloads Function GetHashCode(obj As T) As Integer _\n Implements IEqualityComparer(Of T).GetHashCode\n\n Dim hash As Integer = 17\n For Each v In _valueAcessors\n hash = hash * 23 + If(v(obj), 0).GetHashCode()\n Next\n Return hash\n End Function\nEnd Class\n</code></pre>\n\n<p>You would create a comparer like this</p>\n\n<pre><code>Dim comparer = New ValuesEqualityComparer(Of TestClass)(\n {Function(x) x.Id,\n Function(x) x.Name})\n</code></pre>\n\n<p>Note, <code>IList</code> is compatible with arrays and <code>List(Of T)</code>. I am using an array literal here. See also: <a href=\"https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/arrays/how-to-initialize-an-array-variable\" rel=\"nofollow noreferrer\">How to: Initialize an Array Variable in Visual Basic</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T05:10:16.280",
"Id": "442727",
"Score": "1",
"body": "I never thought I'd learn that much on such a small portion of code ; many thanks! A few questions: 1. Since the accessors are run and a resulting value calculated each time we compare, how is this more efficient? 2.I used to leave my Private Sub New() empty until I started to use static factories, in which case a private constructior does not necessarily mean \"don't use me\". Is it a \"standard\" to leave these private constructors empty? 3. I avoided the object type because I was afraid Object.Equals() would run an instance comparison."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T05:16:43.513",
"Id": "442729",
"Score": "0",
"body": "4. Regarding GetHashCode(), what would be wrong in doing For Dim TempStr as String: Each v In _valueAcessors: TempStr &= v(obj). GetHashCode(): Next: Return TempStr.GetHashCode()?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T12:39:04.877",
"Id": "442811",
"Score": "0",
"body": "1. Code to access the values is run every time with both variants. But your variant creates a list with the values every time. With my variant a list or array with the delegates is created only once when creating the comparer. 2. The private constructor could only be called by the class itself. An empty constructor is usual. You could add a comment saying \"Hides the default constructor\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T12:45:26.790",
"Id": "442814",
"Score": "1",
"body": "3. It is each type's responsibility to override its own `Equals` method. E.g. `String` is a reference type, but `Equals` is overridden, so that each character is compared instead of only the reference. You can see how [Object.Equals is implemented here](https://referencesource.microsoft.com/#mscorlib/system/object.cs,68).\nI.e. it first compares the reference. If the reference is different it calls the object's (possibly overridden) `Equals` method. Just below you can see how `ReferenceEquals` is implemented."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T12:55:53.280",
"Id": "442815",
"Score": "1",
"body": "4. There are many ways to calculate a hash code. Simple arithmetic is much faster than string manipulation. Each `&=` creates a new `String` object on the heap and copies each character from the old `TempStr` object and the new hash code string (also created on the heap) to the new `String` object. Then the reference to this new `String` object is assigned to `TempStr`. Note: strings are immutable! Every string manipulation creates a new string. Therefore `String` feels and behaves like a value type, but is in reality a reference type."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T12:41:14.130",
"Id": "445622",
"Score": "0",
"body": "Thanks again for the relevance of your comments! Regarding the private constructor: I now remember the very first reason I started to use this ThrowNotImplementedException \"pattern\" was for situations where a child class which has a private empty constructor inherits from a base class which also has a private empty constructor; in such case, I found convenient to `protect` rather than `private` the empty constructor of the base class; the constructor is now accessible from its child classes, so throwing the exception seemed relevant. What do you think?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T13:45:18.673",
"Id": "445627",
"Score": "0",
"body": "You can drop the parameter-less constructor completely if yo have another constructor with parameters. This replaces the parameter-less constructor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T14:36:07.577",
"Id": "445632",
"Score": "0",
"body": "If I drop it then I do not prevent anyone from instantiating the object with no parameters, which is why I had it `private` in the first place. I do not understand what your suggestion is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T14:52:17.603",
"Id": "445635",
"Score": "1",
"body": "Whenever you define a constructor with parameters, the constructor without parameters does not exist any more. Therefore, this prevents anyone from instantiating the object with no parameters."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T17:41:27.650",
"Id": "227422",
"ParentId": "227415",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "227422",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T16:03:57.710",
"Id": "227415",
"Score": "4",
"Tags": [
"generics",
"vb.net"
],
"Title": "Use a delegate to assess equality"
}
|
227415
|
<p>I try to handle or catch possible errors with PHP/MySQL for security reasons and would like to know if I'm doing it right. </p>
<p>The first case, connection: I use it as a function and call it always when I need a database connection:</p>
<pre><code>function pdo () {
try {
$pdo = new PDO('mysql:host=localhost;dbname=dbname', 'user', 'pw');
}
catch(PDOException $e) {
header("Location: handle_error.php");
exit;
}
return ($pdo);
}
</code></pre>
<p>The second case, a query: I am not sure how to handle it. I put all prepared statements in <code>IF</code> conditions but that's pretty awkward. And what about <code>$stmt->execute</code>? This could also fail or not? To handle this also in an <code>if</code> condition can really get confusing. I hope there is a better way to go. </p>
<pre><code>if ($stmt = $pdo->prepare("SELECT a FROM b WHERE c = :c")) {
$stmt->execute(array(':c' => $c));
$result = $stmt->fetch();
echo 'All fine.';
}
else {
echo 'Now we have a problem.';
}
</code></pre>
<p>Later, I would like to report the errors properly so the admin can check what's going on.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T17:35:30.717",
"Id": "442649",
"Score": "0",
"body": "As friendly advise, next time, try to give a bit more context, as your question was cumulating votes to close for lacking context. It is generally a good idea to provide reviewers real working code, rather than hypothetical/obfuscated code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T18:02:00.090",
"Id": "442655",
"Score": "0",
"body": "Thank you, I will try to pay attention. I edited the code to keep it short so you can quickly see what it is about."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T18:09:06.530",
"Id": "442657",
"Score": "0",
"body": "@dfhwze what kind of context you expect? This code is neither hypotetical/obfuscated, the context is clear - it is going to be used in every PHP script the OP writes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T18:16:13.597",
"Id": "442660",
"Score": "0",
"body": "@YourCommonSense The error handling is clear, but the trivial example used redacts real working sql statements. This is generally considered off-topic on CR, even if the main point of focus is the error handling. We require a real use case, not general best practices. https://codereview.stackexchange.com/help/how-to-ask: hypothetical identifiers."
}
] |
[
{
"body": "<p>First of all, it's a good thing that you asked, only a few do care about handling errors. </p>\n\n<p>Unfortunately, the way you choose is frowned upon, in both cases. Luckily, I've got a couple articles that cover your question in every possible detail:</p>\n\n<ul>\n<li>a generalized one, <a href=\"https://phpdelusions.net/articles/error_reporting\" rel=\"nofollow noreferrer\">PHP error reportig</a> will show you the right approach for handling errors in general</li>\n<li>a direct answer to your question, <a href=\"https://phpdelusions.net/pdo_examples/connect_to_mysql\" rel=\"nofollow noreferrer\">How to connect to MySQL using PDO</a> would provide a ready-made connection code</li>\n</ul>\n\n<h3>Error handling</h3>\n\n<p>The idea here is that a module or a part of code should never treat errors by itself. This function should be delegated to the application level. Your database interaction code should only <em>raise an error</em>, which would be handled according to the site-wide configuration elsewhere. </p>\n\n<p>So your goal with PDO is just to make it throw an error (in the form of Exception). As to how it will be handled should be defined elsewhere. It will make your error reporting uniform and both programmer- and user-friendly. </p>\n\n<h3>Connection</h3>\n\n<p>Another issue is a function. </p>\n\n<blockquote>\n <p>I use it as a function and call it always when I need a database connection. </p>\n</blockquote>\n\n<p>If you call it more than once, it will create many connections to the database server and this number is not infinite. A connection should be made only once. So in its current form this function is rather useless. Given you have to create a <code>$pdo</code> variable only once, an include file would serve as well.</p>\n\n<p>So let's create it</p>\n\n<pre><code>$host = '127.0.0.1';\n$db = 'test';\n$user = 'root';\n$pass = '';\n$charset = 'utf8mb4';\n\n$options = [\n \\PDO::ATTR_ERRMODE => \\PDO::ERRMODE_EXCEPTION,\n \\PDO::ATTR_DEFAULT_FETCH_MODE => \\PDO::FETCH_ASSOC,\n \\PDO::ATTR_EMULATE_PREPARES => false,\n];\n$dsn = \"mysql:host=$host;dbname=$db;charset=$charset\";\ntry {\n $pdo = new \\PDO($dsn, $user, $pass, $options);\n} catch (\\PDOException $e) {\n throw new \\PDOException($e->getMessage(), (int)$e->getCode());\n}\n</code></pre>\n\n<h3>Handling query errors.</h3>\n\n<p>Like it was said above, do not handle errors in your code. We already configured PDO to throw exceptions in case of error, that's all. So just write your query execution code right away, without any conditions:</p>\n\n<pre><code>$stmt = $pdo->prepare(\"SELECT a FROM b WHERE c = :c\")) {\n$stmt->execute(array(':c' => $c));\n$result = $stmt->fetch();\necho 'All fine.';\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T17:28:48.067",
"Id": "442643",
"Score": "0",
"body": "Thanks for the detailed and quick answer! Now I understand it a little better. I will read through the linked articles and try to implement it. About the function: I call it only once at the beginning. But I will include it through a separate file like you mentioned above. Thanks a lot!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T18:16:08.107",
"Id": "442891",
"Score": "0",
"body": "Just want to thank you again, now my error handler is working fine, database connection is properly configured and all my questions got answered with the 2 provided links. Im still reading, there are good articles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T06:54:17.820",
"Id": "442924",
"Score": "0",
"body": "My last question to this topic: I would like to know if its possible to redirect to a separate .html file when an exception is thrown, to show the user a general message. I tried to setup ErrorPages on the server, but it didnt work. So I tried the following code, but the redirect is also not working: function myExceptionHandler ($e)\n{\n http_response_code(500);\n if (ini_get('display_errors')) {\n echo $e;\n } else {\n error_log($e);\n header (\"Location: 500.html\");\n }\n}\n\nset_exception_handler('myExceptionHandler');"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T07:22:09.290",
"Id": "442925",
"Score": "0",
"body": "@Nino a good question. And I believe it deserves an answer on Stack Overflow a s well (especially given it was considered off topic here ¯\\_(ツ)_/¯). So. I'll write in detail there so check it out in a while, but in short, it is against the standard to redirect (by means of using an HTTP header) in case of error. It's all about HTTP codes. redirect is 301 and error is 500. Redirect will overwrite 500 telling a search engine the wrong impression. If you want to have a file, just include (or better readfile()) it inside the handler."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T08:23:37.997",
"Id": "442932",
"Score": "0",
"body": "I'll be curious to hear what you have to say. Somehow I still don't look through where my questions belong - on stack owerflow or codereview? I apologize for that, will try to find out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T08:33:28.440",
"Id": "442934",
"Score": "0",
"body": "@Nino sorry it was my fault. Looks like your question is legit in SO."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T17:16:11.533",
"Id": "227420",
"ParentId": "227418",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227420",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T16:58:24.070",
"Id": "227418",
"Score": "1",
"Tags": [
"php",
"mysql",
"error-handling",
"pdo"
],
"Title": "Connect to database, handling errors"
}
|
227418
|
<p>I'm new to PyTorch and I'm writing a unit test for an activation function I'm making.</p>
<p>I plan to test against a reference implementation for this function. I want to approach this in a test-driven way, so I learned to write a test using a known-good function: the ReLU implementation "MyReLU" from <a href="https://pytorch.org/tutorials/beginner/examples_autograd/two_layer_net_custom_function.html" rel="nofollow noreferrer">this beginner tutorial</a>.</p>
<p>The tests passed, but is there any way I can improve the code below? I worry I might not be taking full advantage of PyTorch's libraries and capabilities.</p>
<pre><code>import unittest
import numpy as np
import torch
from torch.autograd import gradcheck
from my_activation_functions import MyReLU
class ReluTest(unittest.TestCase):
def setUp(self):
self.relu = MyReLU.apply
def test_relu_values_x_leqz(self):
tin_leqz = torch.tensor(np.linspace(-10,0,300))
tout_leqz = list(self.relu(tin_leqz))
for x in tout_leqz:
self.assertEqual(x,0)
def test_relu_values_x0(self):
tin_eqz = torch.tensor([0,0,0,0,0])
tout_eqz = list(self.relu(tin_eqz))
for x in tout_eqz:
self.assertEqual(x,0)
def test_relu_values_x_geqz(self):
tin_geqz = torch.tensor(np.linspace(0.001,10,300))
tout_geqz = list(self.relu(tin_geqz))
test_geqz = list(tin_geqz)
for ii in range(len(tout_geqz)):
self.assertEqual(tout_geqz[ii], test_geqz[ii])
def test_drelu_values(self):
tin = (torch.randn(20,20,dtype=torch.double,requires_grad=True))
self.assertTrue(gradcheck(self.relu, tin, eps=1e-6, atol=1e-4))
if __name__ == '__main__':
unittest.main(verbosity=2)
</code></pre>
|
[] |
[
{
"body": "<p>Since you are asking about PyTorch's capabilities you are not taking advantage of, you might want to use:</p>\n\n<ul>\n<li><p><code>torch.linspace(-10,0,300)</code> instead of <code>torch.tensor(np.linspace(-10,0,300))</code></p></li>\n<li><p><code>torch.zeros(5, dtype=torch.long)</code> instead of <code>torch.tensor([0,0,0,0,0])</code></p></li>\n<li><p>tensor operations instead of iterating over each element of the tensor in a loop. This might not matter much in unit-tests but is important if you want to get GPU acceleration:</p>\n\n<p><code>self.assertTrue(torch.equal(tout_leqz, torch.zeros_like(tin_leqz)))</code></p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T22:08:31.317",
"Id": "228879",
"ParentId": "227423",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T17:43:37.800",
"Id": "227423",
"Score": "4",
"Tags": [
"python",
"beginner",
"unit-testing",
"pytorch"
],
"Title": "PyTorch Unit-testing in Python"
}
|
227423
|
<p>For a report, I have, among other things, to count the amount of days between two dates on the same entry and group them by month.</p>
<pre><code>select year(calendar.db_date), month(calendar.db_date), count(calendar.db_date)
FROM hospitalizacion
JOIN calendar
ON calendar.db_date >= fecha_ingreso
AND calendar.db_date <= case when fecha_alta is null then now() else fecha_alta end
where (habitacion regexp "[0-9]{3}" or habitacion like "UCI%")
group by year(calendar.db_date), month(calendar.db_date);
</code></pre>
<p>This will create a row for each day between the check-in and check-out. Now the join is a performance killer. I've removed everything but the join and can't seem to improve the query times using MariaDB. Using equal instead of less/more than makes the query much faster, since it doesn't do comparisons.</p>
<p>This is the create query for the table</p>
<pre><code>CREATE TABLE `hospitalizacion` (
`IdEncuentro` int(10) unsigned NOT NULL,
`habitacion` varchar(5) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`fecha_ingreso` date NOT NULL,
`fecha_alta` date DEFAULT NULL,
PRIMARY KEY (`IdEncuentro`),
KEY `fecha_alta_idx` (`fecha_alta`),
KEY `fecha_ingreso_idx` (`fecha_ingreso`),
KEY `hosp_fecha_ingresoidx` (`fecha_ingreso`),
KEY `hosp_fecha_altaidx` (`fecha_alta`),
KEY `hosp_habitacionidx` (`habitacion`),
KEY `habitacion_idx` (`habitacion`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
</code></pre>
<p>The calendar table:</p>
<pre><code>CREATE TABLE `calendar` (
`id` int(11) NOT NULL,
`db_date` date NOT NULL,
`year` int(11) NOT NULL,
`month` int(11) NOT NULL,
`day` int(11) NOT NULL,
`quarter` int(11) NOT NULL,
`week` int(11) NOT NULL,
`day_name` varchar(9) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`month_name` varchar(9) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`holiday_flag` char(1) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT 'f',
`weekend_flag` char(1) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT 'f',
`event` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `td_ymd_idx` (`year`,`month`,`day`),
UNIQUE KEY `td_dbdate_idx` (`db_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
</code></pre>
<p>This is the explain:</p>
<pre><code>id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE hospitalizacion ALL fecha_ingreso_idx,hosp_fecha_ingresoidx,hosp_habitacionidx,habitacion_idx [NULL] [NULL] [NULL] 28,218 Using where; Using temporary; Using filesort
1 SIMPLE calendar index td_dbdate_idx td_dbdate_idx 3 [NULL] 736,625 Using where; Using index; Using join buffer (flat, BNL join)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T19:03:18.047",
"Id": "442679",
"Score": "0",
"body": "I don't understand why you join Calendar with Hospitalizacion, since you return no information about the Hospitalizacion. Are you missing a join condition on both tables?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T19:05:19.387",
"Id": "442680",
"Score": "0",
"body": "@dfhwze the calendar is just a generated calendar. It helps creating a row for each day, such that I can group them however I like."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T19:08:02.863",
"Id": "442682",
"Score": "1",
"body": "If `calendar` is just a table that contains one entry per calendar day, then I can see why there could be scalability problems. Performance would probably be improved by just storing the holidays."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T23:26:18.280",
"Id": "442702",
"Score": "0",
"body": "@200_success how would that allow me to count days and group them into months/weeks or from/to specific dates?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T00:43:33.193",
"Id": "442712",
"Score": "0",
"body": "Use [Date & Time Functions](https://mariadb.com/kb/en/library/date-time-functions/), and generate rows on the fly using the [sequence storage engine](https://mariadb.com/kb/en/library/sequence-storage-engine/) where necessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T00:53:09.573",
"Id": "442714",
"Score": "0",
"body": "@200_success I'm not sure you understand what is the purpose of the query. Let me put an example: How many rooms/day where occupied in an hospital last month? Now lets assume room 1 to 5 were occupied between 1 and 20, that is 100 rooms/day. But room 6 to 8 were occupied the 15 and are still occupied, today. That adds 51 rooms/day. With this query, I can plug a `where calendar.db_date >= ' 2019-08-01' and calendar.db_Date <= '2019-08-01'` if the fecha_entrada y fecha_alta are correctly set and would obtain the correct value, 151 rooms day."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T00:54:20.067",
"Id": "442715",
"Score": "0",
"body": "How datetime functions and sequence storage engine is capable of that?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T18:12:03.760",
"Id": "227426",
"Score": "0",
"Tags": [
"performance",
"sql"
],
"Title": "Measure durations using a calendar table"
}
|
227426
|
<p>I have a variable, which represents a date, but I have the need of keeping it in string format. I want to be sure that this string is in a specific format, in this specific case <code>'YYYY-MM-DD'</code>.</p>
<p>In order to achieve that I used the following approach, taken from an article.</p>
<pre><code>enum DateStringBrand { _ = '' }
export type DateString = string & DateStringBrand;
function checkValidDateString(str: string): str is DateString {
return str.match(/^\d{4}-\d{2}-\d{2}$/) !== null;
}
export function toDateString(date: Date | moment.Moment | string): DateString {
const dateString = moment(date).format('YYYY-MM-DD');
if (checkValidDateString(dateString)) {
return dateString;
}
}
</code></pre>
<p>This allows me to do, for example, the following:</p>
<p><code>let startDate: DateString = toDateString(Date.new);</code></p>
<p>The discussion above this code raised if using this approach (Nominal Typing) is acceptable and should be encouraged in Typescript or if it's a trick, not designed in the language.</p>
<p>See also:</p>
<ul>
<li><a href="https://spin.atomicobject.com/2017/06/19/strongly-typed-date-string-typescript/" rel="nofollow noreferrer">https://spin.atomicobject.com/2017/06/19/strongly-typed-date-string-typescript/</a></li>
<li><a href="https://basarat.gitbooks.io/typescript/docs/tips/nominalTyping.html" rel="nofollow noreferrer">https://basarat.gitbooks.io/typescript/docs/tips/nominalTyping.html</a></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T22:30:41.867",
"Id": "442700",
"Score": "2",
"body": "This looks like a generic best practices question to me - there isn't really anything to review about your code, just the question of if this a reasonable pattern..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T06:32:41.183",
"Id": "442739",
"Score": "2",
"body": "I had doubts if this question belongs here or better in stack engineering, but since the whole topic came up while reviewing this exact piece of code, I thought this is the right place. I don't think is a generic best practice but a concrete example I am asking to review and say if it's ok or can be improved. I am open to move the question to another stack exchange that fits better."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T19:33:26.663",
"Id": "227429",
"Score": "1",
"Tags": [
"typescript"
],
"Title": "Using Nominal Typing in Typescript"
}
|
227429
|
<p><a href="https://leetcode.com/explore/interview/card/top-interview-questions-medium/108/trees-and-graphs/787/" rel="noreferrer">https://leetcode.com/explore/interview/card/top-interview-questions-medium/108/trees-and-graphs/787/</a></p>
<blockquote>
<p>Given a binary tree, return the zigzag level order traversal of its
nodes' values. (ie, from left to right, then right to left for the
next level and alternate between).</p>
<p>For example:</p>
<pre><code>Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
</code></pre>
<p>return its zigzag level order traversal as:</p>
<pre><code>[
[3],
[20,9],
[15,7]
]
</code></pre>
</blockquote>
<pre><code>/// <summary>
/// https://leetcode.com/explore/interview/card/top-interview-questions-medium/108/trees-and-graphs/787/
/// </summary>
[TestClass]
public class ZigzagLevelOrderTest
{
[TestMethod]
public void TestZigZag()
{
/* 3
/ \
9 20
/ \
15 7
*/
TreeNode root = new TreeNode(3);
root.left = new TreeNode(9);
root.right = new TreeNode(20);
root.right.left = new TreeNode(15);
root.right.right = new TreeNode(7);
IList<IList<int>> res = ZigzagLevelOrderClass.ZigzagLevelOrder(root);
CollectionAssert.AreEqual(new List<int> { 3 }, res[0].ToList());
CollectionAssert.AreEqual(new List<int> { 20, 9 }, res[1].ToList());
CollectionAssert.AreEqual(new List<int> { 15, 7 }, res[2].ToList());
}
[TestMethod]
public void FailedTest()
{
/* 1
/ \
2 3
/ \
4 5
*/
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.right.right = new TreeNode(5);
IList<IList<int>> res = ZigzagLevelOrderClass.ZigzagLevelOrder(root);
CollectionAssert.AreEqual(new List<int> { 1 }, res[0].ToList());
CollectionAssert.AreEqual(new List<int> { 3, 2 }, res[1].ToList());
CollectionAssert.AreEqual(new List<int> { 4, 5 }, res[2].ToList());
}
}
public class ZigzagLevelOrderClass
{
public static IList<IList<int>> ZigzagLevelOrder(TreeNode root)
{
List<IList<int>> result = new List<IList<int>>();
if (root == null)
{
return result;
}
Stack<TreeNode> currentLeveL = new Stack<TreeNode>();
Stack<TreeNode> nextLevel = new Stack<TreeNode>();
currentLeveL.Push(root);
while (currentLeveL.Count > 0 || nextLevel.Count > 0)
{
var nodes = new List<int>();
while (currentLeveL.Count > 0)
{
var curr = currentLeveL.Pop();
if (curr.left != null)
{
nextLevel.Push(curr.left);
}
if (curr.right != null)
{
nextLevel.Push(curr.right);
}
nodes.Add(curr.val);
}
if (nodes.Count > 0)
{
result.Add(nodes);
}
nodes = new List<int>();
while (nextLevel.Count > 0)
{
var curr = nextLevel.Pop();
if (curr.right != null)
{
currentLeveL.Push(curr.right);
}
if (curr.left != null)
{
currentLeveL.Push(curr.left);
}
nodes.Add(curr.val);
}
if (nodes.Count > 0)
{
result.Add(nodes);
}
}
return result;
}
}
</code></pre>
<p>Please review for performance. this is the second time I solved this question.
I think I did a better job now.</p>
|
[] |
[
{
"body": "<p>Your implementation is close, but it can be a bit shorter. You correctly use two stacks, but you duplicate the code alternating between using the two. That's a bit of a waste of space. Instead, at the end of the first while loop, you can just assign <code>nextLevel</code> to <code>currentLevel</code>, create a new stack to <code>nextLevel</code>, and repeat:</p>\n\n<pre><code> while (currentLeveL.Count > 0 || nextLevel.Count > 0)\n {\n var nodes = new List<int>();\n while (currentLeveL.Count > 0)\n {\n var curr = currentLeveL.Pop();\n if (curr.left != null)\n {\n nextLevel.Push(curr.left);\n }\n\n if (curr.right != null)\n {\n nextLevel.Push(curr.right);\n }\n nodes.Add(curr.val);\n }\n\n if (nodes.Count > 0)\n {\n result.Add(nodes);\n }\n currentLevel = nextLevel;\n nextLevel = new Stack<TreeNode>();\n }\n</code></pre>\n\n<p>The <code>while</code> condition can also be made easier, <code>nextLevel</code> is known to be empty when it is evaluated:</p>\n\n<pre><code>while (currentLeveL.Count > 0)\n</code></pre>\n\n<hr>\n\n<p>Since you're looping over the stack, only removing each item, not adding items back or anything, you can just replace the <code>while</code> for a <code>foreach</code>:</p>\n\n<pre><code>public static IList<IList<int>> ZigzagLevelOrder(TreeNode root)\n{\n List<IList<int>> result = new List<IList<int>>();\n if (root == null)\n {\n return result;\n }\n Stack<TreeNode> currentLeveL = new Stack<TreeNode>();\n Stack<TreeNode> nextLevel = new Stack<TreeNode>();\n currentLeveL.Push(root);\n while (currentLeveL.Count > 0)\n {\n var nodes = new List<int>();\n foreach(var curr in currentLeveL)\n { \n if (curr.left != null)\n {\n nextLevel.Push(curr.left);\n }\n\n if (curr.right != null)\n {\n nextLevel.Push(curr.right);\n }\n nodes.Add(curr.val);\n }\n\n if (nodes.Count > 0)\n {\n result.Add(nodes);\n }\n currentLeveL = nextLevel;\n nextLevel = new Stack<TreeNode>();\n }\n\n return result;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T09:05:26.083",
"Id": "442767",
"Score": "1",
"body": "Please forget I said anything: I'm clearly not thinking properly this morning! (though you can ditch the `nodes.Count > 0` check)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T17:40:35.337",
"Id": "442883",
"Score": "1",
"body": "@JAD, your code doesn't pass my unit tests. please notice when you switch between current Level and next level you also need to reverse the order of pushing first right then left node."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T18:06:00.683",
"Id": "442889",
"Score": "0",
"body": "@gilad hmm, I didn't notice the left/right switching. Let me think."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T08:22:26.563",
"Id": "227454",
"ParentId": "227434",
"Score": "4"
}
},
{
"body": "<h2>Review</h2>\n\n<ul>\n<li>I would return <code>IEnumerable<IEnumerable<int>></code> rather than <code>IList<IList<int>></code>. We don't want the caller to change the return value, only to iterate it.</li>\n<li>The two inner loops are almost exactly the same, except that the order of <code>node.left</code> and <code>node.right</code> gets swapped. This part I would refactor to get DRY code.</li>\n<li>You should use <code>var</code> a bit more often: <code>Stack<TreeNode> currentLeveL = new Stack<TreeNode>();</code> -> <code>var currentLevel = new Stack<TreeNode>();</code> (also notice the small casing typo in currentLeve<strong>L</strong>)</li>\n<li><code>if (root == null) return result;</code> -> perhaps the challenge specifies this edge case, but I would prefer an <code>ArgumentNullException</code> when the input is null and clearly shouldn't be.</li>\n</ul>\n\n<hr>\n\n<h2>Refactored</h2>\n\n<ul>\n<li>We can avoid using an outer loop with two nearly identical inner loops, if we exchange <code>currentLevel</code> for <code>nextLevel</code> after each inner loop and use a <code>bool zig</code> that toggles for every cycle of the inner loop to get the zig-zag effect. </li>\n<li>Notice I made an instance method rather than extension method, but feel free to keep an extension method instead. I find traversal to be part of the instance operations. </li>\n<li>I expect performance to remain the same. We're still using two stacks the same way.</li>\n</ul>\n\n\n\n<pre><code>public IEnumerable<IEnumerable<int>> ZigzagLevelOrder()\n{\n var levels = new List<IEnumerable<int>>();\n var currentLevel = new Stack<TreeNode>();\n var nextLevel = new Stack<TreeNode>();\n var zig = false;\n\n currentLevel.Push(this);\n\n while (currentLevel.Any())\n {\n levels.Add(currentLevel.Select(n => n.Value).ToArray());\n zig = !zig;\n\n while (currentLevel.Any())\n {\n var node = currentLevel.Pop();\n if (zig && node.left != null)\n nextLevel.Push(node.left);\n if (node.right != null)\n nextLevel.Push(node.right);\n if (!zig && node.left != null)\n nextLevel.Push(node.left);\n }\n\n currentLevel = nextLevel;\n nextLevel = new Stack<TreeNode>();\n }\n\n return levels.ToArray();\n}\n</code></pre>\n\n<p>And the unit tests pass:</p>\n\n<pre><code>[TestMethod]\npublic void Fixture()\n{\n var root = new TreeNode(3);\n root.left = new TreeNode(9);\n root.right = new TreeNode(20);\n root.right.left = new TreeNode(15);\n root.right.right = new TreeNode(7);\n\n var res = root.ZigzagLevelOrder();\n CollectionAssert.AreEqual(new List<int> { 3 }, res.First().ToList());\n CollectionAssert.AreEqual(new List<int> { 20, 9 }, res.Skip(1).First().ToList());\n CollectionAssert.AreEqual(new List<int> { 15, 7 }, res.Skip(2).First().ToList());\n\n root = new TreeNode(1);\n root.left = new TreeNode(2);\n root.right = new TreeNode(3);\n root.left.left = new TreeNode(4);\n root.right.right = new TreeNode(5);\n res = root.ZigzagLevelOrder();\n CollectionAssert.AreEqual(new List<int> { 1 }, res.First().ToList());\n CollectionAssert.AreEqual(new List<int> { 3, 2 }, res.Skip(1).First().ToList());\n CollectionAssert.AreEqual(new List<int> { 4, 5 }, res.Skip(2).First().ToList());\n}\n</code></pre>\n\n<hr>\n\n<h2>Performance Optimization</h2>\n\n<ul>\n<li><p><del>I'm not sure how or whether performance could still be optimized beyond the OP code (without falling into a micro-optimisation trap).</del></p></li>\n<li><p>In hindsight, after reading through JAD's answer, a further optimisation is to use <code>foreach (var node in currentLevel)</code> rather than <code>while (currentLevel.Any())</code> to avoid <code>var node = currentLevel.Pop();</code>, which is no longer required (as opposed to OP code) since we exchange the instance of <code>currentLevel</code> with <code>nextLevel</code> anyway.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T20:18:56.257",
"Id": "227640",
"ParentId": "227434",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "227640",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T21:20:35.043",
"Id": "227434",
"Score": "5",
"Tags": [
"c#",
"programming-challenge",
"tree"
],
"Title": "LeetCode: Binary Tree Zigzag Level Order Traversal C#"
}
|
227434
|
<p>I have a code that keeps checking a webpage with a price on it and when the price meets a number I set it to, the thing is purchased. I am looking for ways to increase the speed of it.</p>
<p>I have added multiprocessing and its performance may have improved, but I don't know if its the best-case scenario for this code and there probably are better methods for speed and efficiency.</p>
<pre class="lang-py prettyprint-override"><code>from multiprocessing.dummy import Pool
from functools import partial
session = requests.session()
session.cookies["cookie"] = ""
login = session.get("https://www.example.com")
if login.status_code == 200:
print("logged in")
else:
raise ValueError("Invalid Cookie")
crsf_token = ""
def token():
while True:
global crsf_token
crsf_token = re.search(r"<script>XsrfToken.setToken\('(.*?)'\);</script>", session.get('https://www.example.com').text).group(1)
time.sleep(5)
def _cthread():
with Pool() as pool:
while True:
try:
req = session.get(f"https://www.example.com")
if req.status_code == 429:
time.sleep(5)
continue
allposts = [f'https://www.example.com&Price={i["Price"]}'
for i in req.json()["data"]["Sellers"] if i["Price"] <= 10]
if allposts:
pool.map(partial(session.post, headers={"X-CSRF-TOKEN": crsf_token}), allposts)
except requests.urllib3.exceptions.ConnectTimeoutError as E:
pass
threading.Thread(target=_cthread).start()
threading.Thread(target=token).start()
</code></pre>
|
[] |
[
{
"body": "<h2>Constant reuse</h2>\n\n<p>Store your base URL, <code>\"https://www.example.com\"</code>, in a constant for reuse.</p>\n\n<h2>HTTP codes</h2>\n\n<p>Some status codes, such as 200, are common and obvious, while others such as 429 are less so. Fundamentally these are all magic numbers, and <code>requests.codes</code> contains symbols - including <code>too_many_requests</code>.</p>\n\n<h2>URL construction</h2>\n\n<pre><code> allposts = [f'https://www.example.com&Price={i[\"Price\"]}'\n for i in req.json()[\"data\"][\"Sellers\"] if i[\"Price\"] <= 10]\n</code></pre>\n\n<p>Firstly - you don't need to be adding the URL in here. You can move the query parameter to the <code>params</code> dict to be passed to <code>session.post</code>. Then the URL can be passed to <code>session.post</code> directly without any baked-in query parameters.</p>\n\n<h2>Variable case</h2>\n\n<pre><code>ConnectTimeoutError as E:\n</code></pre>\n\n<p>Don't capitalize <code>E</code> since it's a variable. Past that, you shouldn't even write <code>as E</code>, since you aren't using the exception.</p>\n\n<h2>Import long-form symbols</h2>\n\n<pre><code>requests.urllib3.exceptions.ConnectTimeoutError\n</code></pre>\n\n<p>would benefit from an import of this class so that you can use it without package qualification.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T00:58:13.590",
"Id": "227438",
"ParentId": "227436",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T23:35:35.573",
"Id": "227436",
"Score": "3",
"Tags": [
"python",
"performance",
"python-3.x",
"web-scraping",
"multiprocessing"
],
"Title": "Monitor a web page for when a desired price is met"
}
|
227436
|
<p>I'm writing an application where users can write <a href="https://github.com/m93a/filtrex/" rel="nofollow noreferrer">custom expressions</a> which are then converted to JavaScript functions and executed. The expressions are used for filtering and sorting data from a database and to improve performance I want to be able to run the expressions on my server without worrying about getting hijacked. So the main concern is to ensure that the user cannot do code injection to execute an arbitrary script.</p>
<p>This part of the application makes sure that any string literal present in the user's expression will get converted into a valid JavaScript string literal without any chance of containing malicious code.</p>
<p>In the user's expression, string literal should always match this regex: <code>/"(?:\\"|\\\\|[^"\\])*"/</code> (or its equivalent with single-quotes). However since the regex pattern isn't evaluated directly by JavaScript, I don't want to rely on it working exactly as I expect, so I double-check it.</p>
<pre><code>function buildString(quote, literal)
{
quote = String(quote)[0]; // for example `"`
literal = String(literal); // the user's string literal
let built = ''; // parsed string
if (literal[0] !== quote || literal[literal.length-1] !== quote)
throw new Error(`Unexpected internal error: String literal doesn't begin/end with the right quotation mark.`);
for (let i = 1; i < literal.length - 1; i++)
{
if (literal[i] === "\\")
{
i++;
if (i >= literal.length - 1) throw new Error(`Unexpected internal error: Unescaped backslash at the end of string literal.`);
if (literal[i] === "\\") built += '\\';
else if (literal[i] === quote) built += quote;
else throw new Error(`Unexpected internal error: Invalid escaped character in string literal: ${literal[i]}`);
}
else if (literal[i] === quote)
{
throw new Error(`Unexpected internal error: String literal contains unescaped quotation mark.`);
}
else
{
built += literal[i];
}
}
return JSON.stringify(built); // valid JavaScript string literal
}
</code></pre>
<p>.</p>
<p>Here are some test cases:</p>
<pre><code>expect( () => buildString(`'`, `'''` ) ).throws();
expect( () => buildString(`'`, `'\\'` ) ).throws();
expect( () => buildString(`'`, `'\\"'`) ).throws();
expect( () => buildString(`'`, `'\\n'`) ).throws();
expect( () => buildString(`"`, `"""` ) ).throws();
expect( () => buildString(`"`, `"\\"` ) ).throws();
expect( () => buildString(`"`, `"\\'"`) ).throws();
expect( () => buildString(`"`, `"\\n"`) ).throws();
// null byte
expect(eval( buildString(`'`, `'\n \\\\ \\' " \u0000'`) )).equals(`\n \\ ' " \u0000`);
// unpaired surrogate
expect(eval( buildString(`"`, `"\uD800"`) )).equals(`\uD800`);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T00:19:55.877",
"Id": "442707",
"Score": "2",
"body": "Please add your existing test cases to the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T00:23:17.380",
"Id": "442709",
"Score": "2",
"body": "Can you elaborate a bit more on the environment of the code you wrote? The combination of \"security-critical\" and \"custom JavaScript code\" sounds strange."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T09:21:43.513",
"Id": "442772",
"Score": "0",
"body": "Updated the question to hopefully reflect your comments. @RolandIllig The code written by users is not in JavaScript, but in a [custom expression language](https://github.com/m93a/filtrex). However since it compiles to JavaScript (and quite naively so, instead of abstract syntax tree it emits the source code directly as an string), injection is still an issue."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T11:15:12.337",
"Id": "442791",
"Score": "0",
"body": "Short answer not worthy of an answer-post: `(\\042|\\047)((?!\\1).)*\\1` does exactly what you want, matching valid strings, and you can join all inputs and then test this against it. It's exactly the same as `(\\'|\\\")((?!\\1).)*\\1`, and uses negative-lookaheads and group matching."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T16:07:17.307",
"Id": "442866",
"Score": "0",
"body": "@FreezePhoenix I dimly remember that JavaScript treats U+2028 and U+2029 as line separators. Your secular expression doesn't exclude these characters."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T16:11:17.267",
"Id": "442867",
"Score": "0",
"body": "@RolandIllig On the contrary, Regex is single-line by default."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T06:17:41.317",
"Id": "442920",
"Score": "0",
"body": "Thank you all for the feedback! @FreezePhoenix Sadly, single- and double-quoted literals mean different things in the expressions, so I can't use your pattern. But at least I learnt some new regex :) @RolandIllig Matching newlines is not a problem, my regex pattern matches them on purpose and `buildString` deals with that just fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T08:42:52.513",
"Id": "442936",
"Score": "0",
"body": "@m93a It didn't, oh well I will remove comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T11:13:03.857",
"Id": "442960",
"Score": "0",
"body": "@m93a Alternatively you could just use JSON.parse... also, if it's a JS Function, then you can wrap it in a VM instance, which can have controlled access to variables, and even put on another process which can be terminated if it runs too long - I use this design for arbitrary code evaluation, it's worked so far, nobody has been able to crack it."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T23:40:03.440",
"Id": "227437",
"Score": "2",
"Tags": [
"javascript",
"parsing",
"validation"
],
"Title": "Ensuring a valid JavaScript string in security-critical application"
}
|
227437
|
<p>I have been writing code to automate some weekly reports. I had <a href="https://stackoverflow.com/questions/57754503/creating-a-new-set-of-dataframes-from-dictionary">help over on Stack Overflow</a>. I have code that works for the most part, however there are a few things that I just can't seem to fix.</p>
<p>In short, I loop through the data and create a dictionary of dataframes based on 'location' key unique values. I can use the dictionary to make summary reports for each location. I wanted to make another dictionary from this based on 'sublocation.' Instead with some advice, I make a list of each sublocation, access each item in the df-dict, loop to find corresponding sublocations and make plots. </p>
<p>My problems are as follows:</p>
<ol>
<li>Code is slow</li>
<li>Graphs are not formatted properly (overlapping even with tight_layout) </li>
<li>For the reports in sublocation, I am having a hard time saving to the right folder. I think this has to do with the way I want to format the string in the savefig text. For each sublocation I want reference the name using value['location'], I think this is always updated every loop so it doesn't work. </li>
<li>I have the error exception because when looking to match subloc to loc. not every subloc will appear in the dict value dataframe</li>
</ol>
<p></p>
<pre><code>f = 'path'
d = pd.DataFrame()
d= pd.read_csv(f)
dfs = dict(tuple(d.groupby('location')))
for key, value in dfs.items():
try:
fig, axs = plt.subplots(2, 3);
sns.countplot(y='ethnic', data=value, orient='h', palette ='colorblind', ax=axs[0,0]);
sns.countplot(y='Ratio', data=value,orient='v', palette ='colorblind',ax=axs[1,0]);
sns.countplot(y='site', data = value, ax=axs[0,1]);
sns.countplot(y='STATUS', data = value, ax = axs[1,1])
sns.countplot(y='Assessment', data = value, ax = axs[0,2])
#pth = os.path.join(tmppath, '{0}'.format(key))
for p in axs.patches:
ax.text(p.get_x() + p.get_width()/2., p.get_width(), '%d' % int(p.get_width()),
fontsize=12, color='red', ha='center', va='bottom')
plt.tight_layout(pad=2.0, w_pad=1.0, h_pad=2.0);
plt.set_title('{0}'.format(key)+'Summary')
plt.savefig("basepath/testing123/{0}/{1}.pdf".format(key,key), bbox_inches = 'tight');
plt.clf()
#plt.show()
except:
plt.savefig("basepath/{0}/{1}.pdf".format(key,key), bbox_inches = 'tight');
#plt.savefig("{0}.pdf".format(key), bbox_inches = 'tight');
pass
#####Now for sublocations
dfss = dict(tuple(d.groupby('site')))
#%%
for key, value in dfss.items():
a =(repr(value['school_dbn'][:1]))
try:
fig, axs = plt.subplots(2, 3);
#tmppath = 'basepath/{0}'.format(key);
sns.countplot(y='ethnic', data=value, orient='h', palette ='colorblind', ax=axs[0,0]);
sns.countplot(y='Program]', data=value,orient='v', palette ='colorblind',ax=axs[1,0]);
sns.countplot(y='AltAssessment', data = value, ax = axs[0,2])
pth = os.path.join(tmppath, '{0}'.format(key))
plt.tight_layout(pad=2.0, w_pad=1.0, h_pad=2.0);
plt.set_title('{0}'.format(key)+'Summary')
plt.savefig("basepath/{0}/{1}_{2}.pdf".format(value['location'][-6:],value['location'][-6:],key), bbox_inches = 'tight');
plt.clf()
#plt.show()
except:
plt.savefig("basepath/testing123/{0}/{1}_{2}.pdf".format(value['location'][-6:],value['location'][-6:],key), bbox_inches = 'tight');
#plt.savefig("{0}.pdf".format(key), bbox_inches = 'tight');
pass
</code></pre>
<p>The reason why I want to save like this is because each location has a folder with same name. Sublocation belongs to only one location, therefore I want to save as 'location_sublocation.pdf'.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T02:12:34.260",
"Id": "442719",
"Score": "0",
"body": "So is the code working as intended? If not, this question is [off-topic](https://codereview.stackexchange.com/help/dont-ask)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T02:21:31.273",
"Id": "442720",
"Score": "0",
"body": "@Linny for the most part it is working, aside from the saving the second part correctly and slowness. Frankly the ugly plots are something I think I can fix but just included there for suggestions. \n\nPerhaps there is a faster way to perform these procedures, they are rather simple, essentially just filtering. Do you think this is better for overflow?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T12:27:05.673",
"Id": "442808",
"Score": "0",
"body": "Try building this script in an interactive environment so you can play around with data and graphs without running it everytime. Check out Jupyter. All the issues except slowness can be fixed by searching for answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T13:17:59.603",
"Id": "442816",
"Score": "0",
"body": "@user14492 I am using jupyter lab and notebook. Currently trying out making the subplots differently, and might just settle with saving the second set of files in some other directory and write a script to move all of them to the appropriate places."
}
] |
[
{
"body": "<p>I got this done by making a second dictionary, which takes locations as keys and values as list of sublocations</p>\n<pre><code>dfs = dict(tuple(data.groupby('location')))\ndfss = dict(tuple(data.groupby('sublocation')))\n\ndd = {}\n\nfor key, value in dfs.items(): #dictionary is made of groupby object, key is \n #location, value is datafram\n a = []\n dee={}\n for i in value['sublocation']:\n if i in a:\n pass\n else:\n a.append(str(i))\n dee = {key:a}\n dd.update(dee)\nfor key, value in dfss.items(): \n try:\n for k, v in dd.items():\n if key in v:\n dur=str(k)\n else:\n pass\n except:\n pass\n</code></pre>\n<p>Then in the next cell,</p>\n<pre><code>for key, value in dfss.items(): \n try:\n for k, v in dd.items():\n if key in v:\n dur=str(k)\n else:\n pass\n #tmp = value[value['sublocation']==i]\n sns.set(style='white', palette=sns.palplot(sns.color_palette(ui)), font='sans-serif')\n</code></pre>\n<p>I think I can make the overall script run even faster by employing more regex expressions for filtering the dataframe in various steps.</p>\n<p>This set-up works because I can save the files according to the key's from the two dictionaries. It allows me to save the nearly 375 files automatically. I use another script to move the files to their respective folders.</p>\n<pre><code>plt.savefig("path/{0}/{1} @ {2}.pdf".format(dur,dur,key), bbox_inches = 'tight')\n</code></pre>\n<p>Having a slightly different case, take three data sets and make mini data sets based on some column such as location</p>\n<pre><code>oct_dict = dict(tuple(oct.groupby('location')))\noct2_dict = dict(tuple(oct2.groupby('location'))) \nfor k, v in oct_dict.items():\n #try:\n #v2 = stu_dict[k] #sometimes using this try/else method works better\n #else:\n #v2 = pd.DataFrame()\n #try:\n #v3 = oct2_dict[k]\n #else:\n #v3 = pd.DataFrame()\n for k2, v2 in stu_dict.items(): #replace with v2 = stu_dict[k] if you know for sure it exits\n for k3, v3 in oct2_dict.items(): #replace with v3 = oct2_dict[k] if you know for sure it exits\n if k == k2 and k == k3: #can delete this if not needed\n plt.close('all')\n with PdfPages(r'path\\{}.pdf'.format(k)) as pdf:\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T15:03:06.407",
"Id": "230759",
"ParentId": "227439",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230759",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T02:04:23.267",
"Id": "227439",
"Score": "5",
"Tags": [
"python",
"pandas",
"hash-map",
"matplotlib"
],
"Title": "Automating a set a of weekly reports, including graphs and delivery of reports"
}
|
227439
|
<p>I've just started learning Rust (coming from Haskell) and decided to test a toy expression interpreter.</p>
<p>Code:</p>
<pre class="lang-rust prettyprint-override"><code>use std::rc::Rc;
pub type RAST<T> = Rc<AST<T>>;
#[derive(Debug)]
pub enum AST<T> {
ConstInt(isize, Rc<T>),
Add(RAST<T>, RAST<T>, Rc<T>),
}
pub fn eval<T>(x: &RAST<T>) -> RAST<T> {
match &**x {
AST::Add::<T>(l, r, t) => {
let el = eval(&l);
let er = eval(&r);
match (&*el, &*er) {
(AST::ConstInt::<T>(li,_q),
AST::ConstInt::<T>(ri,_r)) =>
Rc::new(AST::ConstInt::<T>(li+ri, Rc::clone(t))),
_ => mk_add(&el, &er, &t),
}
},
_ => Rc::clone(x),
}
}
pub fn mk_int<T>(i: isize, t: &Rc<T>) -> RAST<T> {
Rc::new(AST::ConstInt::<T>(i, Rc::clone(t)))
}
pub fn mk_add<T>(l: &RAST<T>, r: &RAST<T>, t: &Rc<T>) -> RAST<T> {
Rc::new(AST::Add::<T>(Rc::clone(l), Rc::clone(r), Rc::clone(t)))
}
pub fn main() {
let a = Rc::new(());
let x = mk_int(3, &a);
let y = mk_int(6, &a);
let z = mk_add(&x, &y, &a);
let c = mk_add(&x, &z, &a);
let r = eval(&c);
println!("Raw: {:?}", c);
println!("Evaluated: {:?}", r);
}
</code></pre>
<p>With this output:</p>
<pre><code>Raw: Add(ConstInt(3, ()), Add(ConstInt(3, ()), ConstInt(6, ()), ()), ())
Evaluated: ConstInt(12, ())
</code></pre>
<p>I'd really appreciate any feedback on:</p>
<ol>
<li>Am I using the "right" type for the Add subnodes (i.e. Rc)?</li>
<li>Is it possible to create eval as an AST method instead of a function? I kept fighting the borrow checking if <code>x</code> in eval was <code>self : &AST<T></code> (within the <code>impl</code> block, of course)</li>
<li>Is there any way to make this program more concise/cleaner? I think I understand <em>why</em> all the additional wrapping and sprinkling of <code>Rc::clone/new</code> and lots of reference taking is needed, but was wondering if I was perhaps missing something that might make this code cleaner to read.
Any other feedback/helpful pointers would also be appreciated. Thank you!</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T06:30:04.050",
"Id": "442738",
"Score": "1",
"body": "Hey Chetan! Can I ask what the type parameter `T` is for? It seems like removing all of the `<T>` from your code and remove the `Rc<T>` fields from your struct doesn't effect the functionality."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T11:52:14.203",
"Id": "442802",
"Score": "0",
"body": "That's just so I could tack on some additional information on the nodes later. I agree, in this example, not having `T` would make the code more concise and readable, but I wanted to have this functionality."
}
] |
[
{
"body": "<blockquote>\n <p>Am I using the \"right\" type for the Add subnodes (i.e. Rc)?</p>\n</blockquote>\n\n<p>No. You probably don't want to do that. Just use <code>AST</code>. Good Rust code rarely actually needs <code>Rc</code>. Instead of using <code>Rc<></code> in the definition of <code>AST</code>, use <code>Box</code>.</p>\n\n<pre><code>#[derive(Debug)]\npub enum AST<T> {\n ConstInt(isize, Rc<T>),\n Add(Box<AST<T>>, Box<AST<T>>, Rc<T>),\n}\n</code></pre>\n\n<p>Now <code>Rc</code> does give you the ability to reuse branches of the AST. For example, you use <code>x</code> twice. However, I've not seen a real case of ASTs where that needs to happen. As it stands you are paying the costs of RC (both in programmer effort, execution time, and memory overahead) for no good reason.</p>\n\n<p>You should also get rid of the <code>Rc<></code> for the <code>T</code>. Just store a <code>T</code>. In cases where you need to be able to copy the <code>T</code> for some reason (which is probably never), take a <code><T: Clone></code> so you can call the clone method. The client code can then put in <code>Rc<></code> in place if it wants, or if the data is trivial just allow it to be copied. </p>\n\n<p>I would also question the usefulness of a generic type here at all. Are you really going to annotate the same AST with different additional data in different places? I rather doubt it.</p>\n\n<blockquote>\n <p>Is it possible to create eval as an AST method instead of a function? I kept fighting the borrow checking if x in eval was self : &AST (within the impl block, of course)</p>\n</blockquote>\n\n<p>You'll find that if you don't try to pass ASTs in <code>Rc<></code> that this will work much better. The problem is that you can't take self to be an <code>Rc<></code>, so you don't get access to the reference counter itself which makes it difficult to do anything useful.</p>\n\n<p>Even if you use RC, you can define a static method in the impl (just don't have a self parameter. Then you can use syntax like <code>AST::eval(ast)</code>.</p>\n\n<pre><code>pub fn eval<T>(x: &RAST<T>) -> RAST<T> {\n</code></pre>\n\n<p>This function is pretty strange. Why does an evaluation function return an AST. Shouldn't it return a value? If instead this function were to return <code>isize</code> it would be a much simpler function. </p>\n\n<p>However, the logic of the function makes more sense if it is a optimization function. That is, it seeks to produce a more optimized version of the AST rather than evaluate the AST. But if that's the idea, your function takes the wrong type. It might make sense for the optimization function to take ownership of the AST, consuming the old AST reusing peices of it for the new AST. Or it might make sense to take a mutable reference to the AST, modifying the AST to make a more optimized version. </p>\n\n<blockquote>\n <p>Is there any way to make this program more concise/cleaner? I think I understand why all the additional wrapping and sprinkling of Rc::clone/new and lots of reference taking is needed, but was wondering if I was perhaps missing something that might make this code cleaner to read. </p>\n</blockquote>\n\n<p>Yes, if you follow my advice aboev you'll find the code a lot more concise and cleaner.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T07:51:42.153",
"Id": "443090",
"Score": "1",
"body": "I'd say that the real cost of `Rc` is what you call the programmer effort. The runtime overhead is likely negligible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T15:33:38.807",
"Id": "443125",
"Score": "0",
"body": "@FrenchBoiethios, it is true that Rc overhead is small. But I bring it up because many people are using Rc in a misguided attempt to optimize their code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T03:47:56.900",
"Id": "227548",
"ParentId": "227440",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227548",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T02:31:05.677",
"Id": "227440",
"Score": "3",
"Tags": [
"beginner",
"rust"
],
"Title": "Toy Expression Interpreter"
}
|
227440
|
<p>Recently I have started learning C++ and I decided to learn C along the way to improve my understanding of how computers work. For C I am using "The C Programming Language Book" by Brian Kernighan and Dennis Ritchie.</p>
<p>The exercise in question is to print all input lines disregarding trailing whitespace and empty lines.</p>
<p>Here is my code:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#define MAX_BLANKS 5
int main()
{
int c; /*holds current char to be printed*/
int* wsbuffer; /*buffer to hold possible trailing whitespace*/
int buffer_size; /*size of wsbuffer*/
int nws; /*number of whitespaces in buffer*/
int nonempty; /*0 if current line is empty, 1 else*/
int i; /*for loop*/
nonempty = nws = 0;
buffer_size = MAX_BLANKS;
wsbuffer = (int*) malloc(buffer_size*sizeof(int));
while (EOF != (c=getchar()))
{
if (c==' ' || c=='\t')
{
++nws;
if (nws>buffer_size)
{
buffer_size *=2;
wsbuffer = (int*) realloc(wsbuffer,buffer_size*sizeof(int));
}
wsbuffer[nws-1] = c;
}
else if (c=='\n')
{
if (nonempty==1) {
putchar(c);
nws = nonempty = 0;
}
}
else
{
nonempty = 1;
for (i=0;i<nws;++i)
putchar(wsbuffer[i]);
nws = 0;
putchar(c);
}
}
free(wsbuffer);
return 0;
}
</code></pre>
<p>I compiled this using <code>gcc -std=c90 -Wall -Wextra -pedantic</code> to adhere to the ISO protocol used by the book. It compiled fine with no warnings.</p>
<p>I deliberately set <code>MAX_BLANKS</code> to <code>5</code> to test the code. I tested a few cases (empty lines, lines with only space, spaces at first etc) and the result seemed okay.</p>
<p>Since memory allocation is not yet covered in the book, I'd particularly like it if someone could take a look and let me know if I have any issues particularly with memory leaking or something. Of course, any other suggestions or improvements would be welcome!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T06:32:50.860",
"Id": "442740",
"Score": "0",
"body": "Didja use a profiling tool? Those work well for discovering leaks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T13:24:51.640",
"Id": "442819",
"Score": "0",
"body": "@Richard I'm not sure what this is?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T19:34:21.787",
"Id": "442896",
"Score": "0",
"body": "Bugs are to the debugger as performance is to the profiler."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T15:20:46.527",
"Id": "442987",
"Score": "0",
"body": "@RichardBarker How do you use a profiler? I never figured out how."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T15:31:05.750",
"Id": "442990",
"Score": "0",
"body": "Depends on the language and tool but it's mostly universal. visual studio has one built in and there are plenty of resources out there about it"
}
] |
[
{
"body": "<p>Don't cast the return value from <code>malloc</code> and family - provided there's a prototype in scope (which there is here, due to our <code>#include <stdlib.h></code>), the <code>void*</code> result will convert to any pointer type.</p>\n\n<p>Always check whether the returned pointer is a null pointer before using it:</p>\n\n<pre><code>wsbuffer = malloc(buffer_size * sizeof *wsbuffer);\nif (!buffer) {\n fputs(\"Memory allocation failure\\n\", stderr);\n return EXIT_FAILURE;\n}\n</code></pre>\n\n<p>Robust code needs to take extra care when using <code>realloc()</code>. If we write something like <code>p = realloc(p, new_size);</code> then we have a problem when it fails - <code>p</code> is assigned null, and we have nothing pointing to the memory any more (i.e. a memory leak). The usual pattern looks something like:</p>\n\n<pre><code>void *new_buf = realloc(wsbuffer, buffer_size * sizeof *wsbuffer);\nif (!new_buf) {\n free(wsbuffer);\n fputs(\"Memory allocation failure\\n\", stderr);\n return EXIT_FAILURE;\n}\nwsbuffer = new_buf;\n</code></pre>\n\n<hr>\n\n<p>Minor things:</p>\n\n<ul>\n<li>Instead of <code>c==' ' || c=='\\t'</code>, we might consider <code>isspace(c)</code>, remembering that this test includes newlines and other whitespace.</li>\n<li>We can store whitespace in an array of <code>char</code> rather than <code>int</code>, since we never need to store <code>EOF</code> into that buffer.</li>\n<li>The logic might be simpler if use a larger buffer and read a whole line at a time. Then we just overwrite the start of the last whitespace found in the line, and print it. That's likely a bit more efficient than our character-at-a-time operation, too.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T13:24:15.580",
"Id": "442818",
"Score": "0",
"body": "Thanks Toby! I didn't get the last part about the larger buffer? Do you mean just storing all input and printing them out when I encounter `\\n` or `EOF`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T13:31:59.570",
"Id": "442822",
"Score": "0",
"body": "Might be better to make `isspace(c)` a link to http://www.cplusplus.com/reference/cctype/isspace/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T13:37:11.233",
"Id": "442823",
"Score": "1",
"body": "I meant that we should consider reading a whole line (using `fgets()` - **N.B. not `gets()`** which is irretrievably flawed), and then process and print the line before reading the next line."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T13:39:31.097",
"Id": "442825",
"Score": "0",
"body": "Thanks! I haven't learn about fgets yet, I'll read up on it!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T13:44:18.173",
"Id": "442829",
"Score": "1",
"body": "No need to rush; you can work your way through the book and then revisit earlier chapters and self-review your earlier work in the light of the later knowledge. I find that a good learning technique."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T09:05:44.400",
"Id": "442937",
"Score": "1",
"body": "OP's `getchar()` approach has an advantage over `fgets()`: it well handles reading/writing rare _null characters_. With `fgets()`, those readily are lost."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T07:42:58.693",
"Id": "227450",
"ParentId": "227441",
"Score": "7"
}
},
{
"body": "<p>This is in addition to @TobySpeight review.</p>\n\n<p><strong>Standard Symbolic Constants</strong><br>\nSince <code>stdlib.h</code> is included, you have access to <a href=\"https://en.cppreference.com/w/cpp/utility/program/EXIT_status\" rel=\"nofollow noreferrer\"><code>EXIT_SUCCESS</code> and <code>EXIT_FAILURE</code></a> which are standard macros implemented on all systems. These work in C++ as well as C. These are more <a href=\"https://stackoverflow.com/questions/8867871/should-i-return-exit-success-or-0-from-main\">portable than <code>return 0</code> or <code>return 1</code></a>. Most modern C compilers will append <code>return 0;</code> so it really isn't necessary in this particular case. You may have noticed the use of <code>EXIT_FAILURE</code> in @TobySpeight answer.</p>\n\n<p><strong>Sizeof in malloc and realloc</strong><br>\nA safer practice is to use what the variable points to rather than a specific type. This will allow you to change the type of the array without changing each <code>malloc</code> or <code>calloc</code>.</p>\n\n<pre><code>wsbuffer = malloc(buffer_size * sizeof(*wsbuffer));\n</code></pre>\n\n<p>As @TobySpeight mentioned the return value of every memory allocation should be tested for <code>NULL</code>.</p>\n\n<p><strong>Boolean Values</strong><br>\nSomewhere in the book you should find:</p>\n\n<pre><code>#define TRUE 1\n#define FALSE 0\n</code></pre>\n\n<p>This might make the code more readable. The C standard has progressed; since the second version of the book was written there is an additional header file that can be used for Booleans, <a href=\"//stackoverflow.com/q/6118846\"><code><stdbool.h></code></a>.</p>\n\n<p><strong>Programming Style</strong><br>\nGenerally it is better to wrap operators in expressions in spaces to make the code more readable.</p>\n\n<pre><code> for (i = 0; i < nws; ++i)\n\n if (c == ' ' || c == '\\t')\n</code></pre>\n\n<p>For code maintenance reasons, a safer practice when using control constructs (loops, <code>if</code>, <code>else</code>) is to always enclose even a single statement within a block (<code>{</code>..<code>}</code>):</p>\n\n<pre><code> for (i = 0; i < nws; ++i) {\n putchar(wsbuffer[i]);\n }\n</code></pre>\n\n<p>That reduces bugs introduced during code maintenance where a second line needs to be added within the control block.</p>\n\n<p><strong>Variable Declarations</strong><br>\nWhen the book was written, all variables had to be declared at the top of the function. This isn't true anymore.</p>\n\n<p>In C, as in C++, variables can be declared as they are needed. For instance a loop control variable such as <code>i</code> can be declared just before the loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T11:47:34.153",
"Id": "442966",
"Score": "0",
"body": "\"These are more portable than return 0 or return 1\" That's not true, where did you get that idea from?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T11:52:57.393",
"Id": "442967",
"Score": "0",
"body": "\"This wasn't true when the second version of the book came out\" This is wrong, the 2nd edition was published in 1988. It barely conforms to the C90 standard. It wasn't possible to declare variables anywhere until C99 in 1999."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T12:05:15.997",
"Id": "442969",
"Score": "0",
"body": "@Lundin I have removed the the comment about the second version of the book. I'm looking for the reference about the portability, however, I believe it was an answer on stack overflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T12:08:25.383",
"Id": "442970",
"Score": "0",
"body": "@Lundin https://stackoverflow.com/questions/8867871/should-i-return-exit-success-or-0-from-main"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T12:45:49.717",
"Id": "442975",
"Score": "0",
"body": "That's based on some subjective old crap from Unix `man` regarding portability to OpenVMS from 1977. Nothing in the C standard says that EXIT_FAILURE is more portable. Unless you are doing some dinosaur compatibility project as part of archaeology class, it doesn't matter which form you are using."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T12:50:49.070",
"Id": "442976",
"Score": "0",
"body": "@Lundin I programmed in VAX 11 C (the original VMS). I also programed C on BSD Unix and Solaris (System 5 Unix)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T01:05:50.237",
"Id": "443302",
"Score": "0",
"body": "`#define TRUE = 1` is plain wrong. `TRUE` will expand to `= 1` instead of `1`. Use `#define TRUE 1`instead, or `#include <stdbool.h>` for portable definitions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T01:25:04.040",
"Id": "443303",
"Score": "1",
"body": "@JL2210 you are correct, not enough coffee. Fixed"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T14:22:01.057",
"Id": "227467",
"ParentId": "227441",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "227450",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T02:32:10.923",
"Id": "227441",
"Score": "7",
"Tags": [
"beginner",
"c",
"strings",
"io"
],
"Title": "K&R2 solution to exercise 1-18 (discarding trailing whitespace and empty lines)"
}
|
227441
|
<p>I'm trying to loop through an array, add <code>"</code> before, <code>",</code> after each member but ommit the <code>,</code> at the very last member in order to generate a JSON string:</p>
<pre><code>const generate_list_data_attribute = (attribute_name, from_array) => {
let string = '';
from_array.forEach((element, key, array) => {
if(Object.is(array.length - 1, key)) {
string += `"${element}"`
} else {
string += `"${element}",`
}
});
return `data-${attribute_name}="[${string}]"`;
}
</code></pre>
<p>I don't like the fact that I need to <code>Object.is(array.length-1, key)</code> in order to dictate what the code should do with the last member. It should be automatically handled.</p>
<p>To note: I understand that I can just <code>return</code> to skip the usage of <code>else</code> but I'm looking for a way to automatize that "last member" check more or less.</p>
<hr>
<p>Input (array): <code>my_array = ["food", "gourmet", "foodie"]</code></p>
<p>Operation: <code>generate_list_data_attribute('random', my_array);</code></p>
<p>Output (string): <code>data-random="["food", "gourmet", "foodie"]"</code></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T11:20:31.960",
"Id": "442794",
"Score": "0",
"body": "... what's preventing you from using JSON.stringify?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T00:27:42.603",
"Id": "442913",
"Score": "0",
"body": "@FreezePhoenix Lack of knowledge. What are you suggesting exactly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T11:05:52.210",
"Id": "442958",
"Score": "0",
"body": "`JSON.stringify([\"food\", \"gourmet\", \"foodie\"]); // [\"food\", \"gourmet\", \"foodie]`. Works as long as the array / object does not contain circular references."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T14:17:35.247",
"Id": "442983",
"Score": "0",
"body": "I'd like to point out, that if this is supposed to return a HTML attribute, then you need to escape the quotes inside the value. Examples: Wrong: `data-example=\"[\"test\"]\"` Right: `data-example=\"["test"]\"`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T03:22:39.483",
"Id": "443069",
"Score": "0",
"body": "@RoToRa Thank you."
}
] |
[
{
"body": "<p>Use JavaScript's array methods to your advantage and solve you problem <a href=\"https://en.wikipedia.org/wiki/Functional_programming\" rel=\"nofollow noreferrer\">the functional way</a>:</p>\n\n<pre><code>const generate_list_data_attribute = (attribute_name, from_array) => {\n const string = from_array.map(element => `\"${element}\"`).join(\",\")\n return `data-${attribute_name}=\"[${string}]\"`\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T09:37:25.577",
"Id": "442776",
"Score": "1",
"body": "You should also avoid using snake_case variable names and parameters. This is more pythonic than usual."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T00:31:21.357",
"Id": "442914",
"Score": "0",
"body": "Got it. I'm currently churning as much knowledge about the inner works of JS as I can and it's hard to grasp all these small, but, frankly, very beautiful ways of writing code. I think that camelCase is more of an ES6 thing, right?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T07:22:52.550",
"Id": "227449",
"ParentId": "227443",
"Score": "3"
}
},
{
"body": "<ul>\n<li><p>The JS convention is to use camelCase to name variables (All versions of JS). <code>generate_list_data_attribute</code> becomes <code>generateListDataAttribute</code></p></li>\n<li><p>You don't need to use Object.is in this example. <code>if (Object.is(array.length - 1, key)) {</code> is the same as <code>if (key === array.length -1) {</code></p></li>\n<li><p>Arrays contain items, arrays reference items via an index, objects reference properties via a key, and the property contains a value. Thus using more appropriate names would change <code>from_array.forEach((element, key, array)</code> to <code>fromArray.forEach((item, index, array)</code> or <code>fromArray.forEach((item, i, array)</code></p></li>\n<li><p>You have access to <code>from_array</code> within the <code>forEach</code> iterator and thus not need to use the 3rd argument of <code>forEach</code></p></li>\n</ul>\n\n<h2>Rewrite</h2>\n\n<p>Your code is unnecessarily complex and can be done as in the example below. There are two versions as I am unsure if you intend to call the function with an empty array. The last example uses for loop, and is an alternative that avoids the need to test for the last element.</p>\n\n<p>The example you gave does not match the results you want. The space is missing after the commas. The examples add the space.</p>\n\n<h3>Example A</h3>\n\n<p>This assumes that the array contains items and will return <code>data-name=\"[\"\"]\"</code> for empty arrays which is not the same return as your function.</p>\n\n<pre><code>const arrayToNamedAttribute = (name, arr) => `data-${name}=\"[\"${arr.join('\", \"')}\"]\"`;\n</code></pre>\n\n<h3>Example B</h3>\n\n<p>This example check for an empty array using a ternary <code>arr.length ?</code>\"${arr.join('\", \"')\"<code>: \"\"</code></p>\n\n<pre><code>const namedAttr = (name, arr) => `data-${name}=\"[${arr.length ? `\"${arr.join('\", \"')}\"` : \"\"}]\"`;\n</code></pre>\n\n<p>Or as</p>\n\n<pre><code>const arrayToNamedAttribute = (name, arr) => {\n const arrStr = arr.length ? `\"${arr.join('\", \"')}\"` : \"\";\n return `data-${name}=\"[${arrStr}]\"`;\n}\n</code></pre>\n\n<p>or replacing he <code>{</code> and <code>}</code> and using comma to separate expressions avoids the need to use return, and reuses the <code>arr</code> argument to hold the string</p>\n\n<pre><code>const arrayToNamedAttribute = (name, arr) => (\n arr = arr.length ? `\"${arr.join('\", \"')}\"` : \"\", `data-${name}=\"[${arr}]\"`\n);\n</code></pre>\n\n<h3>Example C</h3>\n\n<p>This uses the variable <code>join</code> to add the comma and space to the string</p>\n\n<pre><code>const arrayToNamedAttribute = (name, arr) => {\n var arrStr = \"\", join = \"\";\n for (const item of arr) {\n arrStr += join + `\"${item}\"`;\n join = \", \";\n }\n return `data-${name}=\"[${arrStr}]\"`;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T03:47:19.007",
"Id": "227493",
"ParentId": "227443",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "227449",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T03:08:48.450",
"Id": "227443",
"Score": "4",
"Tags": [
"javascript"
],
"Title": "Wrap array operation result string inside another string"
}
|
227443
|
<p>The management of bidirectional mappings is a reoccuring topic. I took the time to write an (hopefully) efficient implementation.</p>
<pre><code>using System;
using System.Collections;
using System.Collections.Generic;
namespace buka_core.misc
{
/// <summary>
///
/// File Bijection.cs
///
/// Provides an implementation of a discrete bijective mapping
///
/// The inverses are created using shallow copies of the underlying datastructures, which leads to
/// the original object and all its derived inverses being modified if one object changes. For this
/// reason the class implements the interface ICloneable which allows the user to create deep copies
///
/// The class also implements the interface IDictionary which provides easy access to the proto-
/// type
///
/// </summary>
/// <typeparam name="T_Proto">Datatype of keys for the prototype</typeparam>
/// <typeparam name="T_Inv">Datatype of keys for its inverse</typeparam>
public class Bijection<T_Proto, T_Inv> : ICloneable, IDictionary<T_Proto, T_Inv>
{
/// <summary>
/// Creates an empty discrete bijective mapping
/// </summary>
public Bijection()
{
}
/// <summary>
/// Used internally to efficiently generate inverses
/// </summary>
/// <param name="proto">The prototype mapping</param>
/// <param name="inverse">Its inverse mapping</param>
private Bijection(IDictionary<T_Proto, T_Inv> proto, IDictionary<T_Inv, T_Proto> inverse)
{
_Proto = proto;
_Inv = inverse;
}
/// <summary>
/// Indexer to insert and modify records
/// </summary>
/// <param name="key">Object for which the corresponding dictionary entry should be returned</param>
/// <returns>The value that key maps to</returns>
public T_Inv this[T_Proto key]
{
get
{
if (!_Proto.ContainsKey(key))
{
throw new KeyNotFoundException("[Bijection] The key " + key + " could not be found");
}
return _Proto[key];
}
set
{
this.Add(key, value);
}
}
/// <summary>
/// Returns a bijection for which keys and values are reversed
/// </summary>
public Bijection<T_Inv, T_Proto> Inverse
{
get
{
if (null == _inverse)
{
_inverse = new Bijection<T_Inv, T_Proto>(_Inv, _Proto);
}
return _inverse;
}
}
private Bijection<T_Inv, T_Proto> _inverse = null; // Backer for lazy initialisation of Inverse
/// <summary>
/// Prototype mapping
/// </summary>
private IDictionary<T_Proto, T_Inv> _Proto
{
get
{
if (null == _proto)
{
_proto = new SortedDictionary<T_Proto, T_Inv>();
}
return _proto;
}
/* private */
set
{
_proto = value;
}
}
private IDictionary<T_Proto, T_Inv> _proto = null; // Backer for lazy initialisation of _Proto
/// <summary>
/// Inverse prototype mapping
/// </summary>
private IDictionary<T_Inv, T_Proto> _Inv
{
get
{
if (null == _inv)
{
_inv = new SortedDictionary<T_Inv, T_Proto>();
}
return _inv;
}
/* private */
set
{
_inv = value;
}
}
private IDictionary<T_Inv, T_Proto> _inv = null; // Backer for lazy initialisation of _Inv
#region Implementation of ICloneable
/// <summary>
/// Creates a deep copy
/// </summary>
public object Clone()
{
return new Bijection<T_Proto, T_Inv>(
new SortedDictionary<T_Proto, T_Inv>(_Proto),
new SortedDictionary<T_Inv, T_Proto>(_Inv)
);
}
#endregion
#region Implementation of IDictionary<T_Proto, T_Inv>
public ICollection<T_Proto> Keys => _Proto.Keys;
public ICollection<T_Inv> Values => _Proto.Values;
public int Count => _Proto.Count;
public bool IsReadOnly => _Proto.IsReadOnly;
public bool Contains(KeyValuePair<T_Proto, T_Inv> item)
{
return _Proto.Contains(item);
}
public bool ContainsKey(T_Proto key)
{
return _Proto.ContainsKey(key);
}
public void Clear()
{
_Proto.Clear();
_Inv.Clear();
}
public void Add(T_Proto key, T_Inv value)
{
if (_Proto.ContainsKey(key))
{
_Inv.Remove(_Proto[key]);
}
if (_Inv.ContainsKey(value))
{
throw new ArgumentException("[Bijection] The inverse already maps " + value + " to " + _Inv[value]);
}
_Proto.Add(key, value);
_Inv.Add(value, key);
}
public void Add(KeyValuePair<T_Proto, T_Inv> item)
{
this.Add(item.Key, item.Value);
}
public bool Remove(T_Proto key)
{
if (_Proto.ContainsKey(key))
{
bool removed_inv = _Inv.Remove(_Proto[key]);
bool removed_proto = _Proto.Remove(key);
return (removed_proto && removed_inv); // == true
}
else
{
return false;
}
}
public bool Remove(KeyValuePair<T_Proto, T_Inv> item)
{
return this.Remove(item.Key);
}
public bool TryGetValue(T_Proto key, out T_Inv value)
{
return _Proto.TryGetValue(key, out value);
}
public void CopyTo(KeyValuePair<T_Proto, T_Inv>[] array, int arrayIndex)
{
_Proto.CopyTo(array, arrayIndex);
}
public IEnumerator<KeyValuePair<T_Proto, T_Inv>> GetEnumerator()
{
return _Proto.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _Proto.GetEnumerator();
}
#endregion
#region Overrides
public override bool Equals(object obj)
{
Bijection<T_Proto, T_Inv> obj_bijection = (obj as Bijection<T_Proto, T_Inv>); if (null == obj) return false;
if (this.Count != obj_bijection.Count) return false;
if (!_Proto.Equals(obj_bijection._Proto)) return false;
if (!_Inv.Equals(obj_bijection._Inv)) return false;
return true;
}
public override int GetHashCode()
{
return _Proto.GetHashCode();
}
public override string ToString()
{
return _Proto.ToString();
}
#endregion
}
}
</code></pre>
<p>Instances would be used as follows</p>
<pre><code>Bijection<int, string> b = new Bijection<int, string>();
b[1] = "frog";
b[2] = "fish";
b[3] = "dog";
b[5] = "cat";
b[8] = "snake";
b[13] = "crocodile";
Console.WriteLine(b.Inverse["crocodile"]);
Console.WriteLine(b[13]);
</code></pre>
<p>Any feedback/ suggestions are welcome. Is it reasonable to keep the object and its inverse tied like this or would it be unexpected behavior that changing the inverse also changes the original object</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T05:14:17.393",
"Id": "442728",
"Score": "1",
"body": "Why are you waiting to document the code until a someone posts a review? If it's because you want reviews that are specific to a certain aspect of your code, it's better to include that in your question. As a general rule, the more information you can include, the better reviews will be."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T05:17:00.020",
"Id": "442730",
"Score": "0",
"body": "@AlexF because honestly I was worried that maybe I just did not find the official implementation of this class and somebody points to it with a oneliner"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T05:22:26.383",
"Id": "442731",
"Score": "0",
"body": "I would include that in your question with something like \"if an official implementation of a bidirectional dictionary exists, please link to it.\" I don't see how withholding the documentation would change the kind of answers you get, and even if an implementation already exists, you could still benefit from someone else reviewing your code more easily."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T05:34:40.220",
"Id": "442733",
"Score": "0",
"body": "@AlexF Alright, will add it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T05:59:55.540",
"Id": "442734",
"Score": "0",
"body": "@AlexF added documentation and an example on how to use it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T07:50:07.377",
"Id": "442745",
"Score": "0",
"body": "If your focus is an efficient implementation, why did you choose to use a `SortedDictionary` instead of a regular one?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T07:53:15.750",
"Id": "442747",
"Score": "0",
"body": "@JAD the idea is to provide two implementations. one based on `Dictionary` and one based on `SortedDictionary`"
}
] |
[
{
"body": "<blockquote>\n<pre><code>public T_Inv this[T_Proto key]\n{\n get\n {\n if (!_Proto.ContainsKey(key))\n {\n throw new KeyNotFoundException(\"[Bijection] The key \" + key + \" could not be found\");\n }\n\n return _Proto[key];\n }\n set\n {\n this.Add(key, value);\n }\n</code></pre>\n</blockquote>\n\n<p>For <code>get</code>: I would just rely on the behavior of <code>_Proto[TKey]</code> - because you're not adding any new or extended behavior with your code.</p>\n\n<p>For <code>set</code>: I would just do:</p>\n\n<pre><code>_Proto[key] = value;\n_Inv[value] = key;\n</code></pre>\n\n<p>because you're not adding to the dictionary, you're setting.</p>\n\n<p><strong>Update</strong> : As JAD points out in his comment this isn't consistent either, because it could lead to orphans in <code>_Inv</code>. So be careful.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>public void Add(T_Proto key, T_Inv value)\n{\n if (_Proto.ContainsKey(key))\n {\n _Inv.Remove(_Proto[key]);\n }\n\n _Proto.Add(key, value);\n _Inv.Add(value, key);\n}\n</code></pre>\n</blockquote>\n\n<p>There is something wrong with the workflow or logic here:</p>\n\n<p>Let's say <code>_Proto.ContainsKey(key)</code> returns true, then you remove the value from the inverse. But if <code>_Proto.ContainsKey(key)</code> is true, <code>_Proto.Add(key, value)</code> will throw an exception, and you then have an inconsistent <code>Bijection</code> object - because the existing inverse was removed while the proto was not.</p>\n\n<p>Further: doing this:</p>\n\n<pre><code> Bijection<string, int> b = new Bijection<string, int>();\n b[\"a\"] = 1;\n b.Add(\"b\", 1);\n</code></pre>\n\n<p><code>b.Add(\"b\", 1);</code> will throw an exception because <code>_Inv</code> already has a key of <code>1</code> - but now <code>b.Proto</code> contains both an entry for <code>\"a\"</code> and <code>\"b\"</code> with the value of <code>1</code>, while <code>b.Inv</code> only have the entry <code>1 = \"a\"</code>.</p>\n\n<p>You'll have to ensure that there always is a one-one correspondence between key and value, and ensure that the <code>Bijection</code> object is consistent even if a invalid operation is performed on it.</p>\n\n<p><strong>Update</strong></p>\n\n<p>I can see, that you've updated the <code>Add()</code> method after I've copied the code to my IDE, so the above relates to the first version.</p>\n\n<p>The new version:</p>\n\n<blockquote>\n<pre><code> public void Add(T_Proto key, T_Inv value)\n {\n if (_Proto.ContainsKey(key))\n {\n _Inv.Remove(_Proto[key]);\n }\n\n if (_Inv.ContainsKey(value))\n {\n throw new ArgumentException(\"[Bijection] The inverse already maps \" + value + \" to \" + _Inv[value]);\n }\n\n _Proto.Add(key, value);\n _Inv.Add(value, key);\n }\n</code></pre>\n</blockquote>\n\n<p>however, doesn't do the trick either, because it will still throw and exception if <code>_Proto</code> contains <code>key</code> leaving the dictionaries out of sync.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>public bool Remove(T_Proto key)\n{\n if (_Proto.ContainsKey(key))\n {\n bool removed_inv = _Inv.Remove(_Proto[key]);\n bool removed_proto = _Proto.Remove(key);\n\n return (removed_proto && removed_inv); // == true\n }\n else\n {\n return false;\n }\n}\n</code></pre>\n</blockquote>\n\n<p>You can simplify this by using <code>TryGetValue()</code>:</p>\n\n<pre><code>public bool Remove(T_Proto key)\n{\n if (_Proto.TryGetValue(key, out T_Inv value))\n {\n _Proto.Remove(key);\n _Inv.Remove(value);\n return true;\n }\n\n return false;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T07:51:14.770",
"Id": "442746",
"Score": "0",
"body": "For `Dictionary d` I did not expect the behavior of `d.Add(key,val)` to differ from `d[key]=val`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T07:53:26.717",
"Id": "442748",
"Score": "1",
"body": "@Benj but users expect that as this is _unfortuantelly_ how dictionaries work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T07:53:29.367",
"Id": "442749",
"Score": "0",
"body": "@Benj: but they do: If the key exists `Add()` throws an exception where the indexer just replaces the value in the entry."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T07:55:01.373",
"Id": "442750",
"Score": "0",
"body": "@HenrikHansen Learned something here. Nice. Thank you for your feedback. I will update the code later"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T07:57:36.390",
"Id": "442751",
"Score": "1",
"body": "Your suggestion for `this[]` doesn't necessarily work. Take the example code in the OP. If you run that, and afterwards run `b[13] = \"frog\";`, the OP's implementation throws an exception due to `value` already being a key in the inverse. If you do it your way, I think you lose that behaviour, and end up with two dictionaries that are not mirrors of eachother anymore."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T07:59:26.593",
"Id": "442752",
"Score": "2",
"body": "@Benj keep in mind that it's not allowed to update the code anymore. I'd invalidate the answers. Any edits will be rolledback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T08:05:09.517",
"Id": "442753",
"Score": "0",
"body": "@JAD: you have a point. It could lead to orphans in the `_Inv`. So it is necessary to do a little more validation. But maybe the indexer is a bad idea at all for this kind of data set."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T08:07:21.897",
"Id": "442754",
"Score": "1",
"body": "@HenrikHansen I'd advocate making the elements read-only. You can add and remove them, but not replace them in place. In other words, remove the `this[] getter`. This is actually what OP is doing in a roundabout way: if the setter is used, the existing item is removed and re-added."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T15:41:16.197",
"Id": "442862",
"Score": "0",
"body": "\"For get: I would just rely on the behavior of _Proto[TKey] - because you're not adding any new or extended behavior with your code\" It adds the key to the exception"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T07:43:15.253",
"Id": "227451",
"ParentId": "227445",
"Score": "10"
}
},
{
"body": "<p>In general I find this implementation is OK. It uses internally two dictionaries as it should or rather must so there is not much to get wrong. </p>\n\n<hr>\n\n<p>What I do not like is the underscore naming convention for the generic parameters and their abbrevaited names.</p>\n\n<hr>\n\n<p>I wouldn't let this class implement the <code>IDictionary</code> interface as technically it needs two of them: <code>TKey --> TValue</code> and <code>TValue --> TKey</code>. This however will lead to problems with the default indexer when <code>TKey</code> and <code>TValue</code> are of the same type you would have two identical indexers and it would be ambiguous which one should be used.</p>\n\n<p>At this point I also have to say that your API is incomplete because even though it uses two dictionaries, it doesn't allow me to get <code>TKey</code> by <code>TValue</code> as there is only one <code>TryGetValue</code> method. So your claim that it's bi-directional is <strong>false</strong>.</p>\n\n<hr>\n\n<p>Instead, I would just call it <code>Mapping</code> and implement only APIs that you need. If you need dictionaries then I think it'd be cleaner if you added such methods as <code>ToXYDictionary</code> and <code>ToYXDictionary</code>. With your custom class you can implement whatever behavior you desire. As long as you use the <code>IDictionary</code> interface you should be consistent with its behaviour (see your comment <code>Add</code> vs <code>this[]</code>).</p>\n\n<hr>\n\n<p><code>Remove</code> doesn't have to check whether any of the keys exists. Just remove them both and return the result. It's guaranteed that there are always two keys.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T08:09:35.533",
"Id": "442755",
"Score": "0",
"body": "I did not mean to say it was bidirectional. I meant to say it is a bijection saying that each `value` element _is_ addressable and it is addressable by exactly one `key` _only_ which is why I thought it makes sense to implement `IDictionary` . A corollary is that it is invertible so for convenience I supply the user the Inverse element"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T08:11:10.197",
"Id": "442756",
"Score": "1",
"body": "@Benj you titled the question with _Bidirectional dictionary_ but implemented something else :-P this is a little bit confusing, don't you think?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T08:12:34.190",
"Id": "442758",
"Score": "1",
"body": "You are correct the title is a mistake. I will suggest to add a method to fit it :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T07:55:11.550",
"Id": "227453",
"ParentId": "227445",
"Score": "9"
}
},
{
"body": "<p>Much of what I wanted to say has already been said, but there's a few points I haven't seen being addressed yet:</p>\n\n<ul>\n<li>Why are the internal dictionaries lazily created? When someone creates a <code>Bijection</code> instance then they probably intend to actually use it, so you might as well create them up-front. It'll simplify the code.</li>\n<li>When creating an inverse <code>Bijection</code>, why not link it to the current instance? That means that <code>b.Inverse.Inverse</code> will give you <code>b</code> again, instead of a new instance.\nAs with the internal dictionaries, creating the inverse instance up-front would simplify things. It's cheap, anyway - <code>Bijection</code> contains no state of its own other than the shared dictionaries.</li>\n<li>What's the reason for using <code>SortedDictionary</code> instead of <code>Dictionary</code>?</li>\n<li><code>Equals</code> contains a bug: you're performing the null-check against <code>obj</code> instead of <code>obj_bijection</code>. Note that instead of <code>var t = obj as T;</code>, followed by a null-check, you can also use <code>if (!(obj is T t))</code>.</li>\n<li>What's the idea behind those overridden methods? The way your implementation works is that two <code>Bijection</code> instances are seen as equal when they refer to the same shared dictionaries (which is only true for <code>b.Equals(b.Inverse.Inverse)</code>).\nIt won't treat different dictionaries with the same content as equal. That's (unfortunately?) the expected behavior for <code>Equals</code>, so you might as well just not override it (the same goes for <code>GetHashCode</code>).</li>\n<li><code>ToString</code>'s behavior is nonsensical - its result suggests that a <code>Bijection</code> really is a sorted dictionary.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T11:22:44.593",
"Id": "442796",
"Score": "0",
"body": "Great eye spotting the bug in Equals. And regarding Equals / GetHashcode I just blindly assumed it was properly overriden by the Dictionaries."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T09:00:15.580",
"Id": "227455",
"ParentId": "227445",
"Score": "7"
}
},
{
"body": "<h2>KISS</h2>\n\n<p>I find this class too complex. It stores 2 dictionaries, but only allows manipulations from the perspective of one the types. And it requires a second instance with the dictionaries swapped to manipulate data from the other perspective.</p>\n\n<p>Furthermore, a bijection should be seen as a function amongst two sets, rather than a dictionary from either perspective.</p>\n\n<p>How about picking no perspective at all. From the public view, it's just a collection (actually a set) of tuples of an element of set x and one of set y. Ideal usage of a bijection, in my opinion, is as follows:</p>\n\n<pre><code>var bijection = new Bijection<int, string>();\n\nbijection.Add((1, \"USA\"));\nbijection.Add((2, \"UK\"));\n\n// X and Y chosen from set theory: https://en.wikipedia.org/wiki/Bijection\nvar country = bijection.X[1];\nvar id = bijection.Y[\"UK\"];\n</code></pre>\n\n<p>You no longer have a perspective on the bijection from either the <em>proto</em> or <em>inv</em> types. Instead, you work with an atomic type <code>(X, Y)</code>. Readonly dictionaries <code>X</code> and <code>Y</code> are provided to give you the perspective of either of the types.</p>\n\n<pre><code>public class Bijection<TX, TY> : ICollection<(TX, TY)>\n{\n private readonly IDictionary<TX, TY> _x = new Dictionary<TX, TY>();\n private readonly IDictionary<TY, TX> _y = new Dictionary<TY, TX>();\n\n public IReadOnlyDictionary<TX, TY> X => new ReadOnlyDictionary<TX, TY>(_x);\n public IReadOnlyDictionary<TY, TX> Y => new ReadOnlyDictionary<TY, TX>(_y);\n\n // ICollection members ..\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T15:54:54.080",
"Id": "227471",
"ParentId": "227445",
"Score": "3"
}
},
{
"body": "<p>Since this question got over 1000 views within 24 hours I decided to completely rework the class addressing as many comments as possible</p>\n\n<p>Further remarks for improvement are appreciated</p>\n\n<p>Since editing the question would result in a rollback as mentioned by t3chb0t I decided to post the changes in a separate answer</p>\n\n<pre><code>using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Text;\n\nnamespace com.stackexchange.codereview.datastruc\n{\n /// <summary>\n /// File Bijection.cs\n /// \n /// This class implements a Bijection (which can be thought of a bidirectional Dictionary)\n /// \n /// Link to Discussion \n /// https://codereview.stackexchange.com/questions/227445/bidirectional-dictionary\n ///\n /// Link to Source \n /// https://github.com/pillepalle1/stackexchange-codereview/blob/master/datastruc/Bijection.cs\n ///\n /// </summary>\n\n /*\n * Thanks to (see below) for their valuable input\n * ---------------+---------------------------------------------------------------------------\n * Henrik Hansen | https://codereview.stackexchange.com/users/73941/henrik-hansen\n * dfhwze | https://codereview.stackexchange.com/users/200620/dfhwze\n * t3chb0t | https://codereview.stackexchange.com/users/59161/t3chb0t\n * Pieter Witvoet | https://codereview.stackexchange.com/users/51173/pieter-witvoet\n * JAD | https://codereview.stackexchange.com/users/140805/jad\n * \n * Remarks\n * -------------------------------------------------------------------------------------------\n * \n * IDictionary has been removed as suggested by dfhwze . This does not cause a loss of functionality\n * due to the introduced properties .MappingXtoY and .MappingYtoX which provide read only access to\n * the internal Dictionaries\n * \n * JAD and Pieter Witvoet seemed to be irritated by using a SortedDictionary rather than a Dictionary.\n * In the end it is a question of optimizing space or access time. Given that the structure maintains\n * two dictionaries, I first considered it reasonable to rather optimize space but it seems like that\n * the expected default behaviour is to optimize speed\n * \n * Implementation of .Equals .GetHashcode .ToString has been changed given the remarks of Pieter Witvoet\n *\n */\n\n public class Bijection<T_SetX, T_SetY> : ICollection<(T_SetX, T_SetY)>\n {\n #region Exceptions the Structure might throw\n private static ArgumentException _xCollisionEx = new ArgumentException(String.Empty\n + \"A collision occured in subset X when attempting to add the current element\"\n + \"You might want to: \"\n + \"- have a look at the property .CollisionHandlingProperty\"\n + \"- consider changing the implementation of x.Equals\"\n );\n\n private static ArgumentException _yCollisionEx = new ArgumentException(String.Empty\n + \"A collision occured in subset Y when attempting to add the current element\"\n + \"You might want to: \"\n + \"- have a look at the property .CollisionHandlingProperty\"\n + \"- consider changing the implementation of y.Equals\"\n );\n\n private static Exception _internalError = new Exception(String.Empty\n + \"[Bijection] Internal error / Inconsistent state\"\n );\n #endregion\n\n private IDictionary<T_SetX, T_SetY> _x_to_y = null; // Mapping x to y (Get y given x)\n private IDictionary<T_SetY, T_SetX> _y_to_x = null; // Mapping y to x (Get x given y)\n\n public Bijection() :\n this(new Dictionary<T_SetX, T_SetY>(), new Dictionary<T_SetY, T_SetX>())\n {\n }\n\n public Bijection(IDictionary<T_SetX, T_SetY> dict)\n {\n _x_to_y = new Dictionary<T_SetX, T_SetY>();\n _y_to_x = new Dictionary<T_SetY, T_SetX>();\n\n foreach (T_SetX x in dict.Keys)\n {\n this.Add((x, dict[x]));\n }\n }\n\n private Bijection(IDictionary<T_SetX, T_SetY> x_to_y, IDictionary<T_SetY, T_SetX> y_to_x)\n {\n _x_to_y = x_to_y;\n _y_to_x = y_to_x;\n }\n\n /// <summary>\n /// Elements of set X\n /// </summary>\n public IList<T_SetX> X => new List<T_SetX>(_x_to_y.Keys);\n\n /// <summary>\n /// Elements of set Y\n /// </summary>\n public IList<T_SetY> Y => new List<T_SetY>(_y_to_x.Keys);\n\n\n public IReadOnlyDictionary<T_SetX, T_SetY> MappingXtoY => new ReadOnlyDictionary<T_SetX, T_SetY>(_x_to_y);\n public IReadOnlyDictionary<T_SetY, T_SetX> MappingYtoX => new ReadOnlyDictionary<T_SetY, T_SetX>(_y_to_x);\n\n\n #region Indexer and Inverse\n\n /*\n * The indexer remained because some users (including me) prefer to manage the object through indices\n * rather than calling the method .Add((x,y)) even though it is conceptually not entirely appropriate\n * \n * The .Inverse has however been removed because it introduces the question on how to handle the prop\n * CollisionHandlingPolicy (is it supposed to be kept synchronous with its Inverse?) which then com-\n * plicates the code to an inappropriate extent.\n * \n * This also removed the question of how to manage the inverse as mentioned by Pieter Witvoet\n * \n * This introduces an asymmetrie and bias in favor of elements in X since elements cannot be added to\n * Y by using an indexer. This should however not cause a problem in practise, since both elements x\n * and y must be known when added to the collection as a tuple\n */\n\n public T_SetY this[T_SetX x]\n {\n get\n {\n return GetY(x);\n }\n set\n {\n Add((x, value));\n }\n }\n #endregion\n\n public T_SetX GetX(T_SetY y)\n {\n return _y_to_x[y];\n }\n\n public T_SetY GetY(T_SetX x)\n {\n return _x_to_y[x];\n }\n\n public void RemoveX(T_SetX x)\n {\n this.Remove((x, _x_to_y[x]));\n }\n\n public void RemoveY(T_SetY y)\n {\n this.Remove((_y_to_x[y], y));\n }\n\n /// <summary>\n /// Indicates the policy to be applied if an element cannot be added because it would break the bijection\n /// </summary>\n public ECollisionHandlingPolicy CollisionHandlingPolicy\n {\n get\n {\n return _collisionHandlingPolicy ?? ECollisionHandlingPolicy.ThrowX_ThrowY;\n }\n set\n {\n _collisionHandlingPolicy = value;\n }\n }\n protected ECollisionHandlingPolicy? _collisionHandlingPolicy = null;\n\n #region Implementation of Interface System.ICloneable\n\n /*\n *\n * Attempting to implement this ICloneable led to a conflict that suggested to discard it\n * alltogether\n *\n * The problem is that creating a deep copy would require T_SetX and T_SetY to implement\n * System.ICloneable which would severly limit the flexibility. It could however be reason-\n * able for immutable types but then the issue of having to properly inform the user before-\n * hand\n *\n */\n\n #endregion\n\n #region Implementation of Interface ICollection<T_SetX, T_SetY>\n public int Count => X.Count;\n\n public bool IsReadOnly => false;\n\n public void Add((T_SetX, T_SetY) item)\n {\n if (this.Contains(item)) return;\n\n if (X.Contains(item.Item1))\n {\n switch (CollisionHandlingPolicy)\n {\n case (ECollisionHandlingPolicy.ThrowX_ThrowY):\n case (ECollisionHandlingPolicy.ThrowX_ResolveY): throw _xCollisionEx;\n\n case (ECollisionHandlingPolicy.ResolveX_ThrowY):\n case (ECollisionHandlingPolicy.ResolveX_ResolveY): _x_to_y.Remove(item.Item1); break;\n\n default: throw _internalError;\n }\n }\n\n if (Y.Contains(item.Item2))\n {\n switch (CollisionHandlingPolicy)\n {\n case (ECollisionHandlingPolicy.ThrowX_ResolveY):\n case (ECollisionHandlingPolicy.ResolveX_ResolveY): _y_to_x.Remove(item.Item2); break;\n\n case (ECollisionHandlingPolicy.ThrowX_ThrowY):\n case (ECollisionHandlingPolicy.ResolveX_ThrowY): throw _yCollisionEx;\n\n default: throw _internalError;\n }\n }\n\n _x_to_y[item.Item1] = item.Item2;\n _y_to_x[item.Item2] = item.Item1;\n }\n\n public void Clear()\n {\n _x_to_y.Clear();\n _y_to_x.Clear();\n }\n\n public bool Contains((T_SetX, T_SetY) item)\n {\n if (!X.Contains(item.Item1)) return false;\n if (!Y.Contains(item.Item2)) return false;\n if (!_x_to_y[item.Item1].Equals(item.Item2)) return false;\n\n return true;\n }\n\n public void CopyTo((T_SetX, T_SetY)[] array, int arrayIndex)\n {\n foreach (T_SetX x in X)\n {\n array[arrayIndex++] = (x, _x_to_y[x]);\n }\n }\n\n public bool Remove((T_SetX, T_SetY) item)\n {\n if (!this.Contains(item)) return false;\n\n _x_to_y.Remove(item.Item1);\n _y_to_x.Remove(item.Item2);\n return true;\n }\n\n public IEnumerator<(T_SetX, T_SetY)> GetEnumerator()\n {\n return new BijectionEnumerator(this);\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return new BijectionEnumerator(this);\n }\n #endregion\n\n #region Bijection Specific Nested Data Structures\n /// <summary>\n /// Enumerator for element-wise access to a bijection\n /// </summary>\n public class BijectionEnumerator : IEnumerator<(T_SetX, T_SetY)>\n {\n private Bijection<T_SetX, T_SetY> _bijection = null;\n private List<T_SetX> _keys = null;\n private int _keyIndex;\n\n public BijectionEnumerator(Bijection<T_SetX, T_SetY> bijection)\n {\n _bijection = bijection;\n _keys = new List<T_SetX>(bijection.X);\n _keyIndex = 0;\n }\n public (T_SetX, T_SetY) Current\n {\n get\n {\n return (_keys[_keyIndex], _bijection.GetY(_keys[_keyIndex]));\n }\n }\n\n object IEnumerator.Current\n {\n get\n {\n return (_keys[_keyIndex], _bijection.GetY(_keys[_keyIndex]));\n }\n }\n\n public bool MoveNext()\n {\n return (_keyIndex < (_keys.Count - 1));\n }\n\n public void Reset()\n {\n _keyIndex = 0;\n }\n\n public void Dispose()\n {\n // This enumerator does not occupy any ressources that need to be released\n }\n\n }\n #endregion\n\n #region Overrides\n public override string ToString()\n {\n StringBuilder b = new StringBuilder();\n\n b.Append(\"Count=\" + this.Count);\n b.Append(' ');\n b.Append(\"[\" + typeof(T_SetX).ToString() + \" <-> \" + typeof(T_SetY).ToString() + \"]\");\n\n return b.ToString();\n }\n public override int GetHashCode()\n {\n return Count;\n }\n public override bool Equals(object obj)\n {\n Bijection<T_SetX, T_SetY> obj_bijection = (obj as Bijection<T_SetX, T_SetY>);\n if (null == obj_bijection) return false;\n\n if (Count != obj_bijection.Count) return false;\n\n foreach (var t in this)\n {\n if (!obj_bijection.Contains(t)) return false;\n }\n\n return true;\n }\n #endregion\n }\n\n #region Bijection Specific External Data Structures\n /// <summary>\n /// Available policies on resolving a conflict caused by attempting to map an element a to b which already maps to c\n /// - Throw will cause an ArgumentException to be thrown\n /// - Resolve will remove the existing mapping and replace it by the one provided\n /// </summary>\n public enum ECollisionHandlingPolicy\n {\n ThrowX_ThrowY,\n ThrowX_ResolveY,\n ResolveX_ThrowY,\n ResolveX_ResolveY\n }\n #endregion\n}\n</code></pre>\n\n<p>I also added a property that allows the user to decide the behavior in case of a collision</p>\n\n<p>Example on how to use the structure</p>\n\n<pre><code>public static void Main(string[] args)\n{\n Bijection<int, string> bijection = new Bijection<int, string>();\n\n bijection[1] = \"frog\";\n bijection.Add((2, \"camel\"));\n bijection.[3] = \"horse\";\n\n if(bijection.Y.Contains(\"frog\"))\n {\n bijection.RemoveY(\"frog\");\n EatFrog();\n }\n\n foreach(int i in bijection.X)\n {\n Console.WriteLine(bijection[i]);\n }\n\n foreach(var t in bijection)\n {\n Console.WriteLine(t.item2);\n }\n}\n</code></pre>\n\n<p>That should cover most of the cases</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T05:11:24.043",
"Id": "443078",
"Score": "1",
"body": "Writing a self-answer is exactly the right way to post the updated code ;-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T03:42:35.343",
"Id": "227547",
"ParentId": "227445",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227451",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T04:26:46.870",
"Id": "227445",
"Score": "8",
"Tags": [
"c#",
"hash-map",
".net-core"
],
"Title": "Bidirectional Dictionary"
}
|
227445
|
<p>I just finished a huge project of mine; a maze pathfinder. At the start, the maze that the program is traversing is randomly generated, with a 25% change to place a wall (<code>#</code>) at that position in the maze. The program uses the distance between every direction it can make at its current position, and takes the direction that puts the program closest to end. I'm looking for any feedback, as this is my first maze pathfinder. The real meat of the code is in the <code>find_next_open_space</code> function, which calculates the distance, makes the comparisons, and decides which direction to go.</p>
<p>Copy paste this code into a file, run it, and watch!</p>
<pre><code>"""
Code written by: Linny
Github: https://github.com/Linnydude3347
This program demonstrates a pathfinding algorithm
"""
from os import system, name
import time
import random
import math
def calculate_distance(x1, y1, x2, y2):
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
def print_grid(grid):
"""
Pretty prints the passed `grid`
Code from StackOverflow user "georg"
https://stackoverflow.com/a/13214945/8968906
"""
string = [[str(e) for e in row] for row in grid]
lens = [max(map(len, col)) for col in zip(*string)]
fmt = ' '.join('{{:{}}}'.format(x) for x in lens)
table = [fmt.format(*row) for row in string]
print('\n'.join(table))
def generate_maze(start_x, start_y, end_x, end_y):
"""
Generates a random maze
"""
maze = [["#"] * 40]
for _ in range(38):
row = [" "] * 40
row[0] = "#"
row[-1] = "#"
maze.append(row)
maze.append(["#"] * 40)
#Add start and end values
maze[start_x][start_y] = "S"
maze[end_x][end_y] = "E"
#Add random walls
for i, _ in enumerate(maze):
for j, _ in enumerate(maze[i]):
if maze[i][j] not in "#SE":
maze[i][j] = "#" if random.randint(1, 100) > 75 else " "
return maze
def clear_o(grid):
"""
Clears all "^v><" in the grid
"""
reset_grid = grid
for i, _ in enumerate(reset_grid):
for j, _ in enumerate(reset_grid[i]):
if reset_grid[i][j] in "^v><":
reset_grid[i][j] = " "
return reset_grid
def get_nsew_spaces(x, y):
"""
Returns a 2D array of the current spaces that are NSEW of passed (x, y)
No need to check bounds because outer layer will always be X
"""
north = [x - 1, y]
south = [x + 1, y]
east = [x, y + 1]
west = [x, y - 1]
return [north, south, east, west]
def find_next_open_space(x, y):
"""
Find the next available space, edits `GRID` to account for visitation,
and returns the x and y values of the new space
"""
spaces = get_nsew_spaces(x, y)
#Calculate boolean variables that determine if they can go a certain position
can_go_north = GRID[spaces[0][0]][spaces[0][1]] not in "^v<>#oS"
can_go_south = GRID[spaces[1][0]][spaces[1][1]] not in "^v<>#oS"
can_go_east = GRID[spaces[2][0]][spaces[2][1]] not in "^v<>#oS"
can_go_west = GRID[spaces[3][0]][spaces[3][1]] not in "^v<>#oS"
#Determine boolean determining what character to print when moving
go_up = "^" if GRID[x][y] != "S" else "S"
go_down = "v" if GRID[x][y] != "S" else "S"
go_right = ">" if GRID[x][y] != "S" else "S"
go_left = "<" if GRID[x][y] != "S" else "S"
#Get current positions of new spaces
north_position = spaces[0]
south_position = spaces[1]
east_position = spaces[2]
west_position = spaces[3]
#Calculate distance from position to E
distance_to_end_after_north = calculate_distance(north_position[0], north_position[1], 1, 1)
distance_to_end_after_south = calculate_distance(south_position[0], south_position[1], 1, 1)
distance_to_end_after_east = calculate_distance(east_position[0], east_position[1], 1, 1)
distance_to_end_after_west = calculate_distance(west_position[0], west_position[1], 1, 1)
all_distances = []
if can_go_north:
all_distances.append(distance_to_end_after_north)
if can_go_south:
all_distances.append(distance_to_end_after_south)
if can_go_east:
all_distances.append(distance_to_end_after_east)
if can_go_west:
all_distances.append(distance_to_end_after_west)
#If going north is best option and can go north:
if can_go_north and distance_to_end_after_north == min(all_distances):
GRID[x][y] = go_up
return spaces[0][0], spaces[0][1]
#If going south is best option and can go south
if can_go_south and distance_to_end_after_south == min(all_distances):
GRID[x][y] = go_down
return spaces[1][0], spaces[1][1]
#If going east is best option and can go east
if can_go_east and distance_to_end_after_east == min(all_distances):
GRID[x][y] = go_right
return spaces[2][0], spaces[2][1]
#If going west is best option and can go west
if can_go_west and distance_to_end_after_west == min(all_distances):
GRID[x][y] = go_left
return spaces[3][0], spaces[3][1]
#Now, just check if it can
if can_go_north:
if can_go_east:
GRID[x][y] = go_right
return spaces[2][0], spaces[2][1]
if can_go_west:
GRID[x][y] = go_left
return spaces[3][0], spaces[3][1]
GRID[x][y] = go_up
return spaces[0][0], spaces[0][1]
if can_go_south:
if can_go_east:
GRID[x][y] = go_right
return spaces[2][0], spaces[2][1]
if can_go_west:
GRID[x][y] = go_left
return spaces[3][0], spaces[3][1]
GRID[x][y] = go_down
return spaces[1][0], spaces[1][1]
if can_go_east:
if can_go_north:
GRID[x][y] = go_up
return spaces[0][0], spaces[0][1]
if can_go_south:
GRID[x][y] = go_down
return spaces[1][0], spaces[1][1]
GRID[x][y] = go_right
return spaces[2][0], spaces[2][1]
if can_go_west:
if can_go_north:
GRID[x][y] = go_up
return spaces[0][0], spaces[0][1]
if can_go_south:
GRID[x][y] = go_down
return spaces[1][0], spaces[1][1]
GRID[x][y] = go_left
return spaces[3][0], spaces[3][1]
return -1, -1
def find(start_x, start_y):
"""
This is the main algorithm function, nagivating
`GRID` from the start node at (start_x, start_y)
"""
attempts = 1
current_x = start_x
current_y = start_y
current_marker = GRID[current_x][current_y]
while current_marker != "E":
last_spot_x = current_x
last_spot_y = current_y
current_x, current_y = find_next_open_space(current_x, current_y)
#Restart search
if current_x == -1 and current_y == -1:
attempts += 1
clear_o(GRID)
GRID[last_spot_x][last_spot_y] = "#"
current_x, current_y = start_x, start_y
current_marker = GRID[current_x][current_y]
system("cls") if name == 'nt' else system("clear")
print_grid(GRID)
time.sleep(0.05)
print(f"E found in {attempts} attempts!")
if __name__ == '__main__':
GRID = generate_maze(35, 32, 2, 2)
START = time.time()
find(35, 32)
END = time.time()
print("Time to solve: %.2f seconds!" % (END - START))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T03:50:24.893",
"Id": "442915",
"Score": "2",
"body": "This is neither here nor there, but... as you gain more experience programming, you'll be significantly redefining what counts as a huge project :)"
}
] |
[
{
"body": "<h2>Type hints</h2>\n\n<p>Presumably all of the argument to <code>calculate_distance</code>, as well as the return value, are <code>float</code>. You should indicate so with <a href=\"https://www.python.org/dev/peps/pep-0484/\" rel=\"nofollow noreferrer\">PEP484 type hints</a>.</p>\n\n<h2>List literal unpacking</h2>\n\n<pre><code> row = [\" \"] * 40\n row[0] = \"#\"\n row[-1] = \"#\"\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>row = ['#', *[' ']*38, '#']\n</code></pre>\n\n<h2>Magic numbers</h2>\n\n<p>Assign 40 to something like <code>GRID_SIZE</code>. Rather than 38, write <code>GRID_SIZE - 2</code>.</p>\n\n<h2>Don't abuse <code>enumerate</code></h2>\n\n<pre><code>for i, _ in enumerate(maze):\n</code></pre>\n\n<p>You don't actually use the value here, so instead, do something like</p>\n\n<pre><code>for i in range(len(maze)):\n</code></pre>\n\n<h2>Loops are your friend</h2>\n\n<pre><code>can_go_north = GRID[spaces[0][0]][spaces[0][1]] not in \"^v<>#oS\"\ncan_go_south = GRID[spaces[1][0]][spaces[1][1]] not in \"^v<>#oS\"\ncan_go_east = GRID[spaces[2][0]][spaces[2][1]] not in \"^v<>#oS\"\ncan_go_west = GRID[spaces[3][0]][spaces[3][1]] not in \"^v<>#oS\"\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>possible_directions = [\n GRID[space[0]][space[1]] not in \"^v<>#oS\"\n for space in spaces]\n]\n</code></pre>\n\n<p>and so on for the other chunks of code that are repeated four times with small variations.</p>\n\n<h2>Clear</h2>\n\n<p>First of all, this:</p>\n\n<pre><code>system(\"cls\") if name == 'nt' else system(\"clear\")\n</code></pre>\n\n<p>probably belongs in a utility method. Also, <code>name</code> is ambiguous enough that it probably shouldn't be stripped of its module namespace; i.e. just <code>import os; os.name</code> instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T01:24:37.710",
"Id": "227489",
"ParentId": "227447",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "227489",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T06:22:10.457",
"Id": "227447",
"Score": "7",
"Tags": [
"python",
"algorithm",
"python-3.x",
"pathfinding"
],
"Title": "Random Maze Pathfinder"
}
|
227447
|
<p>I am trying to simplify the code so i do not need to make a new <code>add_content</code> function and home template every time my homepage content gets bigger.</p>
<p>template_class.php</p>
<pre><code>class Template{
public $arr= array();
public $arr2= array();
function __construct()
{
}
public function add_content($pag,$arr)
{
$var=file_get_contents('template/'.$pag);
foreach($arr as $key => $value)
{
$var=str_replace('{{'.$key.'}}',$value,$var);
}
$this->arr[] = $var;
}
public function add_content2($pag,$arr)
{
$var2=file_get_contents('template/'.$pag);
foreach($arr as $key => $value)
{
$var2=str_replace('{{'.$key.'}}',$value,$var2);
}
$this->arr2[] = $var2;
}
public function set_layout($lay)
{
$this->layouts=$lay;
}
public function show()
{
if(!file_exists('template/'.$this->layouts))
{
$layout=file_get_contents('template/homepage.tpl');
}
else
{
$layout=file_get_contents('template/'.$this->layouts);
}
$content='';
foreach($this->arr as $key=>$value)
{
$content .= $value;
}
$content2='';
foreach($this->arr2 as $key=>$value)
{
$content2 .= $value;
}
$layout=str_replace('{{CONTENT}}',$content,$layout);
$layout=str_replace('{{CONTENT2}}',$content2,$layout);
echo $layout;
}
}
</code></pre>
<p>home.php</p>
<pre><code>$template= new Template();
$template->set_layout('homepage.tpl');
$sql="SELECT * FROM $tbl_name ORDER BY id ASC";
$result=mysqli_query($link,$sql);
$visib='';
if(isset($_COOKIE['Access']) & isset($visib))
{
$visib='visible';
}
else
{
$visib='invisible';
}
$template->add_content('home.tpl',array(
'visibility' => $visib,
));
while($rows=mysqli_fetch_array($result))
{
$template->add_content2('home2.tpl',array(
'id' => $rows['id'],
'topic' => $rows['topic'],
'datetime' => $rows['datetime'],
'visibility' => $visib,
));
}
$template->show();
mysqli_close($link);
</code></pre>
<p>homepage.tpl</p>
<pre><code> <form name="actualizare" method="post" action="admin.php">
<table class="table table-dark">
<thead>
<tr>
<th>#</th>
<th>TOPIC</th>
<th>DATE/TIME</th>
{{CONTENT}}
</tr>
</thead>
<tbody>
{{CONTENT2}}
</tbody>
</table>
</form>
</code></pre>
<p>home.tpl</p>
<pre><code><th class="{{visibility}}">DELETE</th>
</code></pre>
<p>home2.tpl</p>
<pre><code><tr>
<td>{{id}}</td>
<td> <a href="view_topic.php?id={{id}}"> {{topic}} </a></td>
<td>{{datetime}}</td>
<td><a href="delete.php?id={{id}}" class="btn btn-outline-dark text-white {{visibility}}" role="button" >Delete Post</a></td>
</tr>
</code></pre>
<p><strong>I made some changes to the code:</strong>
I put the content from home.tpl and content from home2.tpl in a single file named home.tpl</p>
<pre><code><th class="{{visibility}}">DELETE</th>
<tr>
<td>{{id}}</td>
<td> <a href="view_topic.php?id={{id}}"> {{topic}} </a></td>
<td>{{datetime}}</td>
<td><a href="delete.php?id={{id}}" class="btn btn-outline-dark text-white {{visibility}}" role="button" >Delete Post</a></td>
</tr>
</code></pre>
<p>In the template_class I deleted the</p>
<pre><code> $content2='';
foreach($this->arr2 as $key=>$value)
{
$content2 .= $value;
}
$layout=str_replace('{{CONTENT2}}',$content2,$layout);
</code></pre>
<p>and change the <code>add_content2</code> function to:</p>
<pre><code> public function contents($pag,$arr)
{
$var2=file_get_contents('template/'.$pag);
foreach($arr as $key => $value)
{
$var2=str_replace('{{'.$key.'}}',$value,$var2);
}
return $var2;
}
</code></pre>
<p>in the homepage.tpl change the <code>{{CONTENT2}}</code> to <code>{{CONTENT}}</code></p>
<p>in the home.php I changes this <code>$template->add_content2('home2.tpl'</code> in <code>$template->contents('home.tpl'</code></p>
<p>And now when I go to my table is not displaying the content the right way like it was before making this changes.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T10:14:37.577",
"Id": "442781",
"Score": "3",
"body": "Welcome to Code Review! Please add a description to your question to tell us what to code is supposed to do. After that, change the question title to reflect that, and [not state the main concerns about your code](/help/how-to-ask). See also [ask] in the Help Center for more details."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T11:23:43.413",
"Id": "442797",
"Score": "1",
"body": "That title isn't what we had in mind. Please state, in the title, what the code does. Not what your concerns are. Put the concerns in the question body. Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T12:22:40.563",
"Id": "443337",
"Score": "0",
"body": "Is there any foreseeable scenario where you have a placeholder name conflict between two templates? I don't see the benefit of separate sets of replacements. Why not make placeholders unique on a given document?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T09:59:14.240",
"Id": "227457",
"Score": "1",
"Tags": [
"php",
"mysqli",
"twitter-bootstrap"
],
"Title": "The code is displaying my mysql table in a bootstrap table using php templates"
}
|
227457
|
<p>I have this simple Rust program, which creates a file called <code>numbers.txt</code> and writes the numbers 1 to N (N is here 10000000) to it, separated with newlines:</p>
<pre><code>use std::fs::File;
use std::io::Write;
const N: i32 = 1e7 as i32;
fn main() {
let mut data = String::new();
for i in 1..=N {
data.push_str(&format!("{0}\n", i));
}
let mut f = File::create("numbers.txt").expect("Unable to create file");
f.write_all(data.as_bytes()).expect("Unable to write data");
}
</code></pre>
<p>I've been running and timing the program with:</p>
<pre><code>$ time cargo run --release
</code></pre>
<p><code>numbers.txt</code> after running:</p>
<pre class="lang-none prettyprint-override"><code>1
2
3
4
...
9999999
10000000
</code></pre>
<p>I've timed the execution of the program, and it takes around 4.8 seconds to run on my machine. I tried timing just the string building, by commenting out the last two lines, and the time taken stayed pretty much the same. We can conclude that the bottleneck is the <code>data</code> string building and not writing to the file.</p>
<p><strong>How could I make building <code>data</code> faster? Should I use something else than a <code>String</code>?</strong></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T13:37:58.560",
"Id": "442824",
"Score": "0",
"body": "You've run the test in debug mode, don't you? You must benchmark it in release mode."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T13:41:37.593",
"Id": "442826",
"Score": "0",
"body": "No, I used `cargo run --release` to run the code. And actually `$ time cargo run --release`, when I needed to see the execution time."
}
] |
[
{
"body": "<p>This cuts the runtime by about a third (4.8s -> 3.2s):</p>\n\n<pre><code>use std::fs::File;\nuse std::io::Write;\n\nconst N: i32 = 1e7 as i32;\n\nfn main() {\n let data = (1..=N)\n .map(|n| n.to_string())\n .collect::<Vec<String>>()\n .join(\"\\n\");\n\n let mut f = File::create(\"numbers.txt\").expect(\"Unable to create file\");\n f.write_all(data.as_bytes()).expect(\"Unable to write data\");\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T13:53:05.920",
"Id": "442831",
"Score": "0",
"body": "I'd like to see your benchmark: because that code is actually slower in the playground: https://play.integer32.com/?version=stable&mode=release&edition=2018&gist=d0553c164ed0a6fc0db9b3b61aa2c012"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T14:05:33.050",
"Id": "442836",
"Score": "0",
"body": "@FrenchBoiethios Sure! I repeated this multiple times and always got practically identical results: https://i.imgur.com/gJq5Ugx.png"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T13:46:02.210",
"Id": "227463",
"ParentId": "227461",
"Score": "0"
}
},
{
"body": "<p>I improved the performances (and simplicity) like this:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>use std::fs::File;\nuse std::io::Write;\nuse std::io::BufWriter;\n\nconst N: i32 = 1e7 as i32;\n\nfn main() {\n let mut f = BufWriter::new(File::create(\"numbers.txt\").expect(\"Unable to create file\"));\n for i in 1..=N {\n write!(f, \"{0}\\n\", i);\n }\n\n}\n</code></pre>\n\n<p>I just don't store the strings in a gigantic buffer but asks the BufWriter to manage the buffering. As a side effect, it's now possible to write bigger files without holding too much RAM.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T14:17:32.400",
"Id": "442840",
"Score": "0",
"body": "Nice! This cut the runtime on my system from 4.8s to 1.4s!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T14:12:56.867",
"Id": "227466",
"ParentId": "227461",
"Score": "5"
}
},
{
"body": "<p>How about some threads?</p>\n\n<pre><code>use rayon::prelude::*;\nuse std::fs::File;\nuse std::io::Write;\n\nconst N: i32 = 1e7 as i32;\n\nfn main() {\n let mut output = File::create(\"numbers.txt\").unwrap();\n\n let data: Vec<String> = (1..=N)\n .into_par_iter()\n .fold(String::new, |mut lhs, rhs| {\n use std::fmt::Write;\n write!(&mut lhs, \"{}\\n\", rhs).unwrap();\n lhs\n })\n .collect();\n\n for part in data {\n output.write_all(&part.into_bytes()).unwrap();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T16:38:27.670",
"Id": "443132",
"Score": "0",
"body": "Did you benchmark this compared to my original or @DenysSéguret's answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T18:00:48.680",
"Id": "443154",
"Score": "0",
"body": "@ruohola, I did. On my machine mine is much faster. Of course, threads are involved so its going to be very different machine to machine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T18:01:33.430",
"Id": "443155",
"Score": "0",
"body": "Ok, would this be possible to be written without the `rayon` external dependency."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T18:03:26.077",
"Id": "443158",
"Score": "1",
"body": "@ruohola, you could, of course, write threading code directly using the stdlib instead of using rayon, but why would you want to?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T16:37:13.783",
"Id": "227582",
"ParentId": "227461",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "227466",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T12:52:52.930",
"Id": "227461",
"Score": "2",
"Tags": [
"performance",
"rust"
],
"Title": "15 line Rust program, which writes the numbers 1 to N to a file"
}
|
227461
|
<p><em>This may be better suited on Stackoverflow, in which case, please let me know and I will move it over...</em></p>
<h1>Background</h1>
<p>Consider the following file structure:</p>
<pre><code>/config
│ index.js
│ app.js
│ api.js
│ ...
</code></pre>
<p>The purpose of the above is to provide global configuration throughout a static frontend application, <strong>including</strong> within the webpack build configuration.</p>
<p>My original intention was to provide a global function called <code>config</code> which would behave much like the Laravel <code>config</code> function.</p>
<p>For example:</p>
<p><code>config('app.name')</code> would return the <code>name</code> property from the <code>app.js</code> configuration file</p>
<p>Instead, my solution simply provides an object which is used like so:</p>
<ul>
<li><code>config.app.name</code></li>
<li><code>config.api.url</code></li>
</ul>
<h1>My Code</h1>
<p>The way I am doing this is extremely simple:</p>
<p><strong>/config/index.js</strong></p>
<pre><code>module.exports = {
app: require('./app'),
company: require('./company'),
api: require('./api'),
locales: require('./locales')
};
</code></pre>
<p><strong>/config/app.js</strong></p>
<pre><code>module.exports = {
name: 'Foobar',
// etc...
};
</code></pre>
<p><strong>Example Usage</strong></p>
<pre><code>import config from './config';
console.log(config.app.name);
</code></pre>
<h1>My Question</h1>
<p>Whilst I am not bothered whether <code>/config</code> provides an object, or a function, I am unsure as to whether the solution I have put together is the cleanest way of achieving this...</p>
<p>I appreciate this question might be considered 'subjective' but does anyone have any alternative ways in which they would go about doing this?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T12:53:25.980",
"Id": "227462",
"Score": "1",
"Tags": [
"javascript",
"laravel",
"configuration"
],
"Title": "Providing JavaScript Configuration (Laravel config() style)"
}
|
227462
|
<p>As a self-teaching Python beginner for almost 4 months, I have mostly been doing online challenges including Project Euler problems.</p>
<p><a href="https://projecteuler.net/problem=45" rel="noreferrer">Problem 45</a> asks:</p>
<blockquote>
<p>Triangle, pentagonal, and hexagonal numbers are generated by the
following formulae:</p>
<p><span class="math-container">$$
\begin{array}{lll}
\textrm{Triangle} & T_n=n(n+1)/2 & 1, 3, 6, 10, 15, \ldots \\
\textrm{Pentagonal} & P_n=n(3n−1)/2 & 1, 5, 12, 22, 35, \ldots \\
\textrm{Hexagonal} & H_n=n(2n−1) & 1, 6, 15, 28, 45, \ldots \\
\end{array}
$$</span></p>
<p>It can be verified that <span class="math-container">\$T_{285} = P_{165} = H_{143} = 40755\$</span>.</p>
<p>Find the next triangle number that is also pentagonal and hexagonal.</p>
</blockquote>
<p>I encountered this problem and was able to write the code without much problem although most of the solutions I write are mostly brute force. However I am not satisfied with the time the coding took to find the answer as it took 530.7 seconds to find the solution with this code:</p>
<pre><code>import time
startTime = time.time()
limit = 1000000
triangle = []
pentagonal = []
hexagonal = []
triangle_number = []
class Shape:
def __init__(self, term):
self.term = term
def triangle(self):
return int(self.term * (self.term + 1) / 2)
def pentagonal(self):
return int(self.term * (3 * self.term -1) / 2)
def hexagonal(self):
return int(self.term * (2 * self.term - 1))
def generate():
for terms in range(1, limit + 1):
product = Shape(terms)
triangle.append(product.triangle())
pentagonal.append(product.pentagonal())
hexagonal.append(product.hexagonal())
def main():
generate()
for _, terms in enumerate(hexagonal):
if len(triangle_number) == 3:
break
elif terms in triangle and terms in pentagonal:
triangle_number.append(terms)
print(terms)
print(triangle_number)
print(time.time() - startTime, "seconds")
main()
</code></pre>
<p>I am aware that using the class is unecessary for this problem, but I want to include it as a practice of getting used to writing solutions that require classes.</p>
<p>Alternatively I have re-written another solution of this problem without any classes included but keeping the same style, however it still took 328.2 seconds.</p>
<p>So what suggestions are there to improve the code to run faster? I have tried to review other solutions from the solution page however I do not understand how it was simplified so much to make it run more efficient.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T06:07:23.010",
"Id": "442919",
"Score": "1",
"body": "Profile before optimisation"
}
] |
[
{
"body": "<blockquote>\n <p>I want to include it as a practice of getting used to writing solutions that require classes.</p>\n</blockquote>\n\n<p>No solution \"requires\" classes, although some situations are better represented with classes than with other techniques.</p>\n\n<p>In this particular case, <code>Shape</code> doesn't really need to exist - as you've already identified. Since each of those methods only depends on <code>term</code>, you can simply have three functions all accepting one integer.</p>\n\n<p>Some other things that can improve:</p>\n\n<h2>Int division</h2>\n\n<p>This:</p>\n\n<pre><code>return int(self.term * (self.term + 1) / 2)\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>return self.term * (self.term + 1) // 2\n</code></pre>\n\n<h2>Enumerate-to-<code>/dev/null</code></h2>\n\n<p>You don't need to call enumerate - you aren't using the index. Just use <code>for terms in hexagonal</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T17:06:08.593",
"Id": "443017",
"Score": "1",
"body": "Note: While somewhat more obscure, for maximum speed, it looks like at least for CPython 3.7, it runs a titch faster with `>> 1` rather than `// 2`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T11:59:54.063",
"Id": "443102",
"Score": "0",
"body": "You can of course avoid the division completely by checking which numbers are twice a triangular, pentagonal, and hexagonal number."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T15:31:13.000",
"Id": "227469",
"ParentId": "227464",
"Score": "8"
}
},
{
"body": "<h2>Code</h2>\n\n<blockquote>\n<pre><code>limit = 1000000\ntriangle = []\npentagonal = []\nhexagonal = []\ntriangle_number = []\n</code></pre>\n</blockquote>\n\n<p>Global variables do not help readability.</p>\n\n<p>What's the difference between <code>triangle</code> and <code>triangle_number</code>? Those names don't help me understand what they represent.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>class Shape:\n def __init__(self, term):\n self.term = term\n\n def triangle(self):\n return int(self.term * (self.term + 1) / 2)\n\n def pentagonal(self):\n return int(self.term * (3 * self.term -1) / 2)\n\n def hexagonal(self):\n return int(self.term * (2 * self.term - 1))\n</code></pre>\n</blockquote>\n\n<p>A shape doesn't have a term: it has <em>sides</em>. Concretely, since we're talking regular shapes, it has two properties: the number of sides and the length of each side. This class doesn't make sense to me.</p>\n\n<p>If you really want to practise structuring code with classes, the class should probably be a <code>Solver</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> for _, terms in enumerate(hexagonal):\n if len(triangle_number) == 3:\n break\n elif terms in triangle and terms in pentagonal:\n triangle_number.append(terms)\n print(terms)\n</code></pre>\n</blockquote>\n\n<p>If you're testing <code>x in ys</code> then <code>ys</code> had better be a <code>set</code>, not a <code>list</code>, or you have to do a linear search.</p>\n\n<hr>\n\n<h2>Algorithm</h2>\n\n<p>The current algorithm can be summed up as such:</p>\n\n<pre><code>fix a large limit\ngenerate `limit` terms in each of the sequences\nfor term in first_sequence\n if term in second_sequence and term in third_sequence:\n term is a candidate solution\n</code></pre>\n\n<p>The limit is guesswork, so it might be too small and not find the solution, or be too large and waste lots of time generating terms.</p>\n\n<p>If you note that all of the sequences are strictly increasing, you can instead do a kind of merge:</p>\n\n<pre><code>while problem not solved:\n initialise each of the sequences at the first term\n if all sequences have the same current term:\n term is a candidate solution\n advance one of the sequences which has the smallest current term\n</code></pre>\n\n<hr>\n\n<p>Project Euler is more about maths than programming. Let's look again at those term formulae: <span class=\"math-container\">$$T_n = \\frac{n(n+1)}{2} \\\\ H_n = n(2n−1)$$</span>\nWe can rewrite the latter as <span class=\"math-container\">$$H_n = \\frac{(2n−1)(2n)}{2}$$</span>\nCan you spot a major simplification which you can make to the search?</p>\n\n<p>There are more sophisticated mathematical improvements, but this isn't the place. Check out the Project Euler discussion thread which you gain access to after solving the problem, and if you can distill out questions from that then ask them on our sister site <a href=\"//math.stackexchange.com\">math.stackexchange.com</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T16:07:24.803",
"Id": "227472",
"ParentId": "227464",
"Score": "13"
}
},
{
"body": "<p>The main reason why your code is so slow is because your for loop in main spends most of the time checking for things that are logically impossible to be true. You have one million elements in every number group, every iteration of the for loop you are comparing one value to 2 million other values, when most of them can not be true.</p>\n\n<blockquote>\n<pre><code>for _, terms in enumerate(hexagonal):\n if len(triangle_number) == 3:\n break\n elif terms in triangle and terms in pentagonal:\n triangle_number.append(terms)\n print(terms)\n</code></pre>\n</blockquote>\n\n<p>With changing as little as possible and taking into account that as <a href=\"https://codereview.stackexchange.com/users/1402/peter-taylor\">@Peter Taylor</a> said all of the <code>sequences are increasing</code>. I was able to get the runtime of the program from 452.8s to 3.2s</p>\n\n<pre><code>t_iterator = 0\np_iterator = 0\nfor _, terms in enumerate(hexagonal):\n if len(triangle_number) == 3:\n break\n while (pentagonal[p_iterator] <= terms):\n if pentagonal[p_iterator] == terms:\n while (triangle[t_iterator] <= terms):\n if triangle[t_iterator] == terms:\n print(terms)\n triangle_number.append(terms)\n t_iterator += 1\n p_iterator += 1\n</code></pre>\n\n<p>This code I gave is still far from nice, it can be optimised further. You really should consider what the other answers have highlighted. It's not just that it does not look good and would be hard to understand. If you add another arbitrary 0 to the arbitrary <code>\"limit\"</code> you will probably run out of memory very quickly. You do not actually need to pre-calculate any of the values to solve the problem. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T20:38:30.857",
"Id": "227480",
"ParentId": "227464",
"Score": "6"
}
},
{
"body": "<h2>Arithmetic</h2>\n\n<p>Project Euler questions are meant to educate you about both mathematics and programming. It would be a good idea to understand what these <a href=\"https://en.wikipedia.org/wiki/Polygonal_number\" rel=\"noreferrer\">triangular, pentagonal, and hexagonal numbers</a> actually are, rather than blindly applying the given formulas.</p>\n\n<p>One performance improvement would be to find a way to generate successive elements of each sequence without plugging <span class=\"math-container\">\\$n\\$</span> into the formulas, which involve division. (Division tends to be slow. Floating-point division, using the <code>/</code> instead of the <code>//</code> operator, is even slower, and it also causes you to have to cast the result back to an <code>int</code>.)</p>\n\n<p>If you take the formula for pentagonal numbers <span class=\"math-container\">\\$P_n\\$</span>, you can figure out another formula for the difference between successive elements in the sequence.</p>\n\n<p><span class=\"math-container\">$$\n\\begin{align}\nP_n &= \\frac{n(3n-1)}{2} = \\frac{3n^2-n}{2} \\\\\nP_{n+1} &= \\frac{(n+1)(3(n+1)-1)}{2} = \\frac{(n+1)(3n+2)}{2} = \\frac{3n^2+5n+2}{2} \\\\\nP_{n+1} - P_n &= \\frac{(3n^2+5n+2)-(3n^2-n)}{2} = \\frac{6n+2}{2} = 3n + 1\n\\end{align}\n$$</span></p>\n\n<p>If you do the same for triangular, square, and hexagonal numbers, you'll find:</p>\n\n<p><span class=\"math-container\">$$\n\\begin{align}\nT_{n+1} - T_n &= n+1 \\\\\nP_{n+1} - P_n &= 3n+1 \\\\\nH_{n+1} - H_n &= 4n+1\n\\end{align}\n$$</span></p>\n\n<p>Considering that square numbers would be <span class=\"math-container\">\\$S_{n+1} - S_n = 2n+1\\$</span>, you can see a pattern to produce polygonal numbers in general.</p>\n\n<h2>Algorithm</h2>\n\n<p>Your strategy is to generate a million elements of each sequence and find the elements that exist in common.</p>\n\n<p>First of all, one million is an arbitrary limit. You might need fewer than a million to find the next element in common (in which case you've wasted execution time), or you might need more than a million (in which case you would have to raise the limit and run your code again). It would be nice if your algorithm did not have to rely on a guess.</p>\n\n<p>Secondly, the millionth hexagonal number is certainly going to be much larger than the millionth triangular number. There is no way that the millionth hexagonal number is going to coincide with anything, so that's wasted work.</p>\n\n<p>Thirdly, you store the sequences as lists. Searching a list (e.g. <code>terms in triangle</code>) involves inspecting every element in that list (a so-called O(n) operation). Searching a <a href=\"https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset\" rel=\"noreferrer\"><code>set</code></a> takes only O(1) time. Therefore, simply changing</p>\n\n<blockquote>\n<pre><code>triangle = []\npentagonal = []\nhexagonal = []\n</code></pre>\n</blockquote>\n\n<p>and</p>\n\n<blockquote>\n<pre><code> triangle.append(product.triangle())\n pentagonal.append(product.pentagonal())\n hexagonal.append(product.hexagonal())\n</code></pre>\n</blockquote>\n\n<p>to</p>\n\n<pre><code>triangle = set()\npentagonal = set()\nhexagonal = set()\n</code></pre>\n\n<p>and</p>\n\n<pre><code> triangle.add(product.triangle())\n pentagonal.add(product.pentagonal())\n hexagonal.add(product.hexagonal())\n</code></pre>\n\n<p>brings the execution time down from hundreds of seconds down to about 2 seconds. Better yet, your <code>main()</code> function could be simplified using the set intersection operator <code>&</code>:</p>\n\n<pre><code>def main():\n generate()\n triangle_number = triangle & pentagonal & hexagonal\n print(sorted(triangle_number))\n print(time.time() - startTime, \"seconds\")\n</code></pre>\n\n<h2>Pythonicity</h2>\n\n<p>Be consistent with your naming. If you write \"pentagonal\" and \"hexagonal\", then use \"triangular\" rather than \"triangle\".</p>\n\n<p>The <code>Shape</code> class shouldn't exist at all. It's just a very weird and cryptic way to call three functions that take a numerical parameter.</p>\n\n<p><code>for _, terms in enumerate(hexagonal)</code> is a nonsensical use of <code>enumerate</code>. If you're going to throw away the index anyway, why not just write <code>for terms in hexagonal</code>? And why is your iteration variable pluralized (<code>terms</code> rather than <code>term</code>)?</p>\n\n<p>Your code would be much more expressive if you could say \"give me the next pentagonal number\". A good way to do that in Python is to define a <a href=\"https://docs.python.org/3/tutorial/classes.html#generators\" rel=\"noreferrer\">generator</a>, so that you can write <code>next(pentagonal_numbers)</code>.</p>\n\n<h2>Suggested solution</h2>\n\n<pre><code>from itertools import count\n\ndef polygonal_numbers(sides):\n result = 0\n for n in count():\n yield result\n result += (sides - 2) * n + 1\n\ntt, pp, hh = polygonal_numbers(3), polygonal_numbers(5), polygonal_numbers(6)\nt = p = 0 \nfor h in hh:\n while p < h: p = next(pp)\n while t < h: t = next(tt)\n if t == p == h > 40755:\n print(h)\n break\n</code></pre>\n\n<p>If you take into account that <a href=\"https://en.wikipedia.org/wiki/Polygonal_number#Every_hexagonal_number_is_also_a_triangular_number\" rel=\"noreferrer\">every hexagonal number is also a triangular number</a>, you can ignore the triangular numbers altogether:</p>\n\n<pre><code>from itertools import count\n\ndef polygonal_numbers(sides):\n result = 0\n for n in count():\n yield result\n result += (sides - 2) * n + 1\n\npentagonal_numbers = polygonal_numbers(5)\np = 0\nfor h in polygonal_numbers(6):\n while p < h: p = next(pentagonal_numbers)\n if p == h > 40755:\n print(h)\n break\n</code></pre>\n\n<p>My last solution takes about 50 milliseconds to run on my machine.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T21:09:33.097",
"Id": "442902",
"Score": "3",
"body": "By the way, Project Euler 45 is just [A046180](https://oeis.org/A046180). [Other intersections of polygonal numbers](https://en.wikipedia.org/wiki/Polygonal_number#Combinations) are also documented."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T12:10:15.770",
"Id": "442971",
"Score": "0",
"body": "While this is fairly fast for finding the third hexagonal pentagonal number it is slow for finding the fourth such number. That would require even more sophistication."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T13:36:40.113",
"Id": "442978",
"Score": "0",
"body": "From @200_success' Oeis link, `a(n) = 37635*a(n-1) - 37635*a(n-2) + a(n-3)` is probably unbeatable for speed. Just hardcode the first three numbers. Then again, the question is about the third number..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T16:05:21.407",
"Id": "442993",
"Score": "0",
"body": "Minor correction to your assertion \"Floating-point division, using the / instead of the // operator, is even slower\". The raw processor instructions usually do FP division faster (e.g. on Skylake-X, 32 bit `int` `DIV/IDIV` family have a latency of ~24 cycles, and take 6 cycles to complete and 64 bit `int` is substantially slower, while `FDIV` is 14-16 cycle latency, 4-5 cycles to complete), and on CPython, the `int` related work is more expensive, since it needs to account for infinite precision `int`s, where `float` just does the raw C `double` division."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T16:13:36.493",
"Id": "442994",
"Score": "0",
"body": "Qualification: `int / int` will be ever so slightly slower than `int // int` when the `int`s are small, simply because of the cost to convert from `int` to C `double`. But for apples to apples comparisons, `float / float` *always* beats `int // int`. Point is, speed shouldn't really be the consideration here, just use whichever makes logical sense (obviously, if you need floor division, use floor division instead of `int(float / float)`, because the conversion back will more than wipe out any \"savings\")."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T18:31:33.013",
"Id": "443029",
"Score": "0",
"body": "Some optimizations are available here to reduce work further: 1) Change `polygonal_numbers` to loop over `for n in count(1, sides - 2):`, which lets the accumulate step be just `result += n`, and removes a constant subtraction and an unnecessary multiplication from each loop, reducing runtime by ~40% (on CPython 3.7 x64). Or for ~55% runtime reduction, replace the body of the function entirely with `yield 0` followed by `yield from accumulate(count(1, sides - 2))` (`accumulate` also comes from `itertools`, but unfortunately doesn't take a `start` value, thus the explicit `yield 0`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T18:44:27.770",
"Id": "443033",
"Score": "0",
"body": "2) Change `while p < h: p = next(pentagonal_numbers)` to `for p in pentagonal_numbers: if p >= h: break`. Since `pentagonal_numbers` advances slower than `polygonal_numbers(6)` you can safely advance the iterator at least once, and letting the `for` loop do the work instead of manually calling `next` makes a surprisingly big difference on CPython. 3) Put the code into a `main` function, and invoke it with `if __name__ == '__main__': main()` at the bottom; run in global scope, every variable access requires a `dict` lookup; in function scope, it's just an array lookup with a constant index."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T18:53:44.993",
"Id": "443036",
"Score": "2",
"body": "With all three optimizations, on my local CPython 3.7.2 x64 machine, the runtime reduces from ~25 ms to ~8.5 ms (#1 drops it to ~19.5 ms, #1+#2 gets it to ~13 ms, with #1+#2+#3 dropping it down to 8.5 ms), a nearly 2/3rds reduction in runtime, for code that is (to me at least) equally readable; no really tricky code used solely to squeeze out a few nanoseconds."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T17:06:14.297",
"Id": "443139",
"Score": "0",
"body": "`tt, pp, hh` is rather opaque."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T20:54:16.987",
"Id": "227483",
"ParentId": "227464",
"Score": "42"
}
},
{
"body": "<p>You can easily check that H(n) = T(2n - 1). So all hexagonal numbers are triangular numbers, meaning we can ignore the triangular numbers altogether. </p>\n\n<p>To compute pentagonal numbers: Start with p = 1, dp = 4. To get the next pentagonal number, let p = p + dp, dp = dp + 3. </p>\n\n<p>To compute hexagonal numbers: Start with h = 1, dh = 5. To get the next hexagonal number, let h = h + dh, dh = dh + 4. </p>\n\n<p>So here is simple pseudo-code that finds all numbers that are both pentagonal and hexagonal (and therefore triangular):</p>\n\n<pre><code>Let p = 1, dp = 4\nLet h = 1, dh = 5\n\nForever:\n If p = h then output p. \n Let h = h + dh, dh = dh + 4\n Repeat\n Let p = p + dp, dp = dp + 3\n While p < h\n</code></pre>\n\n<p>Implemented in a low-level language like C or C++, this should find all 64 bit numbers in a few seconds. If you want to go further, change the code slightly: \"diff\" equals h - p from the previous code, but it will be a lot smaller, so you get much further with 64 bit integers.</p>\n\n<pre><code>Let dp = 4, np = 1\nLet dh = 5, nh = 1\nLet diff = 0\n\nForever:\n If diff = then output \"np'th pentagonal number = nh'th pentagonal number\". \n Let diff = diff + dh, dh = dh + 4, nh = nh + 1\n Repeat\n Let diff = diff - dp, dp = dp + 3, np = np + 1\n While p < h\n</code></pre>\n\n<p>This outputs the indexes of pentagonal and hexagonal numbers that are equal. On an eight year old MacBook it takes less than six nanoseconds to examine each index, more than 10 billion indexes per minute, or about 150 trillion indexes per day. Hn with n = 1,042,188,953 is also pentagonal and triangular. There is another such Hn with n a bit over 201 billions; Hn is about 8.175 x 10^22. Finding another solution with this method will likely take a few days or weeks.</p>\n\n<p>If you want to go further, solve p(m) = h(n), for integer n, calculating m as a real number. As n gets large, m as a function of n will be getting closer and closer to a linear function. Then you can use the GCD algorithm to quickly find values where m is close to an integer. You will need multi-precision arithmetic, but it should get you arbitrary large solutions very quickly. (If P(m) = H(n), then m ≈ n * sqrt (4/3) - (sqrt (1/12) - 1/6), with an error less than 4 / n^2, so starting with some n, you use the GCD algorithm to find the next n where m = n * sqrt (4/3) - (sqrt (1/12) - 1/6) is within 3.5 / n^2 of an integer).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T08:28:17.473",
"Id": "227556",
"ParentId": "227464",
"Score": "0"
}
},
{
"body": "<p>Python is a great choice of language for a challenge like this, mainly because of how easy it is to use <code>set</code>s. Basically, any challenge which states \"find a number that matches these criteria\" can be thought of as a set intersection problem. We want to find <span class=\"math-container\">\\$T \\cap P \\cap H\\$</span>, the intersection of triangular, pentagonal, and hexagonal numbers.</p>\n\n<p>Depending on your Python version, you might not have access to the \"walrus operator\" <code>:=</code>. But for this case, it's quite handy.</p>\n\n<pre><code>upper_limit = 10000\nhexs = set()\nwhile len(hexs) < 2:\n tris = {n*(n+1)//2 for n in range(2, upper_limit)}\n pents = {v for n in range(upper_limit) if (v := n*(3*n-1)//2) in tris}\n hexs = {v for n in range(upper_limit) if (v:= n*(2*n-1)) in pents}\n upper_limit *= 10\n\nprint(hexs)\n</code></pre>\n\n<p>To find the number, we create larger and larger sets of triangular numbers, pentagonal numbers, and hexagonal numbers. However, we can filter out the pentagonal numbers which are not triangular, and the filter out the hexagonal numbers which are neither pentagonal nor triangular. </p>\n\n<p>By using the optimizations presented in other answers, this could also be written as:</p>\n\n<pre><code>upper_limit = 10000\npents = set()\nwhile len(pents) < 2:\n hexs = {n*(2*n-1) for n in range(2, upper_limit) if n*(2*n-1)}\n pents = {n*(3*n-1)//2 for n in range(upper_limit) if n*(3*n-1)//2 in hexs}\n upper_limit *= 10\n\nprint(pents)\n</code></pre>\n\n<p>The advantage of this approach is that it can easily be adapted for multiple different problems, and provides a lot of abstraction along with its performance. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T11:59:11.580",
"Id": "227563",
"ParentId": "227464",
"Score": "1"
}
},
{
"body": "<p>As 200_success says, you can look at how the numbers are derived to generate the numbers one by one. </p>\n\n<p>So rather than creating all the numbers and checking for an intersection, a simple algorithm is to look at a pentagon and hexagon number. If they are equal, you're done. If the pentagon number is larger than the hexagon number, then check whether the next hexagon number is equal. If the hexagon number is larger, then check the next pentagon number.</p>\n\n<pre><code>pentagon_index = 165\npentagon_number = 40755+3*165+1\n\nhexagon_index = 143\nhexagon_number = 40755+4*143+1\n\nmax_tries = 10**6\n\nfor i in range(max_tries):\n if pentagon_number < hexagon_number:\n pentagon_index +=1\n pentagon_number += 3*pentagon_index+1\n if pentagon_number > hexagon_number:\n hexagon_index +=1\n hexagon_number += 4*hexagon_index+1\n if pentagon_number == hexagon_number:\n break\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T17:52:56.160",
"Id": "227589",
"ParentId": "227464",
"Score": "0"
}
},
{
"body": "<p><strong><em>Laziness is a programmer virtue.</em></strong></p>\n\n<p>These folks are spending more time on theory than doing it the lazy way would take in practice.</p>\n\n<p>The big problem here is you're doing a bunch of unnecessary work, particularly around storage.</p>\n\n<p>You're constantly appending to arrays for no apparent reason. You don't need the history of old numbers. Throw them away. Appending to arrays is <em>expensive</em> - it often has to reallocate the whole range into a new array then copy from the old one.</p>\n\n<p>The question is \"find the first 3 that's also a 5 and a 6.\"</p>\n\n<p>Notice that you can rearrange those with no impact. That's the same question as \"find the first 5 that's also a 3 and a 6,\" because they all go straight upwards, meaning the first of any will be the first of all.</p>\n\n<p>Fine. You don't need to track anything. Iterate one of the columns. At each three, ask \"is this one of the others?\" If it is, ask \"is this also the other other?\" If it is, return success; otherwise keep marching.</p>\n\n<p>So really, what you need is an efficient way to be able to ask \"is this a foo-angular number?\"</p>\n\n<p>Right now you're doing that by building and searching a table. That's silly. Just reverse the math on the two \"is it also\" columns.</p>\n\n<p>Almost all of this work can go.</p>\n\n<p>Triangular and hexagonal are easy to reverse, so pentagonal is the one I'll keep in the original direction.</p>\n\n<p>if triangular is \"triangular x is (x * (x+1)) / 2,\" </p>\n\n<p>then in math, you have \"n = x(x+1)/2\". </p>\n\n<p>solve for n, you get \"x^2 + x - 2n = 0\", or \"x = (sqrt(1 + 8n) - 1)/2\"</p>\n\n<p>Therefore,</p>\n\n<pre><code>const triangle_from = x => (Math.sqrt(1+(x*8))-1)/2;\n\nfunction is_triangular(x) {\n const pip = triangle_from(x);\n return pip == Math.floor(pip);\n}\n</code></pre>\n\n<p>Now, you can actually throw that away; Euler is playing a trick on you, and I'm abusing that to show you how to do the work without actually doing it for you.</p>\n\n<p>Why?</p>\n\n<p>Because every hexagonal number is also a triangular number. By the time you've tested if it's hexagonal, that it's triangular is already in the bag. You can just skip that wholesale, as such.</p>\n\n<p>You can retain the pentagonal in its existing notation, since we're using it to drive the bus. Also, TEST YOUR FUCKING CODE. I got this wrong because of order of operations differences between math and JS the first time. Just run it on 165 and see if it matches the problem description.</p>\n\n<pre><code>const to_pentagon = x => (x * ((3 * x)-1)) / 2;\n</code></pre>\n\n<p>Then it's just</p>\n\n<pre><code>function find_triple(cursor = 165, bail = 1000000) { // question says \"after 40755,\" which is pentagonal #165\n while (true) {\n if (from_start >= bail) { throw new RangeException(\"exceeded safety cap\"); }\n const current = to_pentagon(cursor);\n if (is_hexagonal(current)) { return cursor; } \n ++cursor;\n }\n}\n</code></pre>\n\n<p>Which, if you're feeling tricky, you could write as</p>\n\n<pre><code>function find_triple(cursor = 165, bail = 1000000) { // question says \"after 40755,\" which is pentagonal #165\n while (true) {\n if (from_start >= bail) { throw new RangeException(\"exceeded safety cap\"); }\n if (is_hexagonal(to_pentagon(cursor++))) { return --cursor; } \n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T21:39:24.910",
"Id": "227604",
"ParentId": "227464",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227483",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T14:00:08.233",
"Id": "227464",
"Score": "32",
"Tags": [
"python",
"performance",
"beginner",
"python-3.x",
"programming-challenge"
],
"Title": "Project Euler Problem 45"
}
|
227464
|
<p>I maintain a C library project both on gcc and clang.</p>
<p>I am looking for advice on how to make the following macros more portable, terse, readable or standard abiding.</p>
<p>When I compile</p>
<pre><code>#define STRINGIFY(arg) STRINGIFY_(arg)
#define STRINGIFY_(arg) #arg
#define VERSION 1.01
#define PROJECT myProject
#define SUB_PROJECT mySub
#define DASH -
#include STRINGIFY(PROJECT DASH SUB_PROJECT DASH VERSION.c)
</code></pre>
<p>I get</p>
<p>clang 6.0.0 standard C99</p>
<pre><code>myProject - mySub - 1.01.c
</code></pre>
<p>gcc 7.4.0 standard C99</p>
<pre><code>myProject-mySub-1.01.c
</code></pre>
<p>I came up with the following solution</p>
<pre><code>#define STRINGIFY(arg) STRINGIFY_(arg)
#define STRINGIFY_(arg) #arg
#define ID(arg) arg
#define VERSION 1.01
#define PROJECT myProject
#define LIB myLib
#define DASH -
#define DOTC .c
#define FILEVERSION(a, b, c, d, e) STRINGIFY(ID(a)ID(b)ID(c)ID(d)ID(e)ID(DOTC))
#include FILEVERSION(PROJECT, DASH, LIB, DASH, VERSION)
</code></pre>
|
[] |
[
{
"body": "<p>I think this is beyond the jurisdiction of the C standard. See <a href=\"https://stackoverflow.com/questions/37796947/spaces-inserted-by-the-c-preprocessor\">https://stackoverflow.com/questions/37796947/spaces-inserted-by-the-c-preprocessor</a>. All the standard says on the topic is a footnote:</p>\n\n<blockquote>\n <p>Note that adjacent string literals are not concatenated into a single string literal (see the translation phases in 5.1.1.2); thus, an expansion that results in two string literals is an invalid directive.</p>\n</blockquote>\n\n<p><a href=\"https://port70.net/~nsz/c/c11/n1570.html#note170\" rel=\"nofollow noreferrer\">https://port70.net/~nsz/c/c11/n1570.html#note170</a></p>\n\n<p>But this doesn't really matter since you are not making multiply strings.</p>\n\n<hr>\n\n<p>Investigating GCC and Clang...</p>\n\n<p>GCC does different things depending on what you ask for:</p>\n\n<pre><code>STRINGIFY(PROJECT DASH SUB_PROJECT DASH VERSION.c)\n</code></pre>\n\n<p>... gets me <code>\"myProject - mySub - 1.01.c\"</code> with GCC 9.3 and <code>-E</code>, but ...</p>\n\n<pre><code>#include STRINGIFY(PROJECT DASH SUB_PROJECT DASH VERSION.c)\n</code></pre>\n\n<p>gets me <code>myProject-mySub-1.01.c: No such file or directory</code>. So <code>-E</code> has spaces and <code>#include</code> doesn't.</p>\n\n<p>Clang is at least consistent. With Clang 10, <code>#include</code> has spaces: <code>fatal error: 'myProject - mySub - 1.01.c' file not found</code> And Clang 10 and <code>-E</code> also has spaces <code>myProject - mySub - 1.01.c</code>.</p>\n\n<p>In my opinion, Clang's behavior makes the most sense. Suppose you wanted a space -- how else could you do that?</p>\n\n<hr>\n\n<pre><code>#define ID(arg) arg\n</code></pre>\n\n<p>This is a common trick. I think it's a good idea although it looks a little ugly when you have to use it in so many spots.</p>\n\n<hr>\n\n<pre><code>#define STRINGIFY(arg) STRINGIFY_(arg)\n#define STRINGIFY_(arg) #arg\n</code></pre>\n\n<p>This is fine, but I think it'd be clearer to define <code>STRINGIFY</code> below the helper macro it uses.</p>\n\n<hr>\n\n<p>Can you get away with something like:</p>\n\n<pre><code>#if VERSION == 1\n#include \"library-version-1.h\"\n#else\n#include \"library-version-other.h\"\n#endif\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-02T05:19:35.677",
"Id": "241597",
"ParentId": "227465",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T14:10:56.230",
"Id": "227465",
"Score": "3",
"Tags": [
"c",
"macros",
"c99",
"gcc"
],
"Title": "Clang preprocessor concatenates an extra space vs. gcc - standard C99"
}
|
227465
|
<p>Inspired by <a href="https://codereview.stackexchange.com/questions/227445/bidirectional-dictionary">this question and its answers</a>, I've made my own version.</p>
<pre><code> /// <summary>
/// A one-one relation bidirectional map.
/// <para>
/// A one-one relation means that each entry of type <typeparamref name="TFirst"/> can correspond to exactly one
/// entry of type <typeparamref name="TSecond"/> and visa versa.
/// </para>
/// The map doesn't support null objects because each element is both key and value in its relation and keys can't be null.
/// </summary>
/// <typeparam name="TFirst">Any type</typeparam>
/// <typeparam name="TSecond">Any type</typeparam>
public class BidirectionalMap<TFirst, TSecond> : IEnumerable<KeyValuePair<TFirst, TSecond>>
{
private readonly Dictionary<TFirst, TSecond> primary;
private readonly Dictionary<TSecond, TFirst> secondary;
public BidirectionalMap()
{
primary = new Dictionary<TFirst, TSecond>();
secondary = new Dictionary<TSecond, TFirst>();
}
/// <summary>
/// Creates a BidirectionalMap initialized with the specified <paramref name="capacity"/>.
/// </summary>
/// <param name="capacity">The desired capacity for the map.</param>
/// <exception cref="ArgumentOutOfRangeException">If capacity is out of range (&lt; 0)</exception>
public BidirectionalMap(int capacity)
{
primary = new Dictionary<TFirst, TSecond>(capacity);
secondary = new Dictionary<TSecond, TFirst>(capacity);
}
/// <summary>
/// Creates a BidirectionalMap with the specified equality comparers.
/// </summary>
/// <param name="firstComparer">Equality comparer for <typeparamref name="TFirst"/>. If null, the default comparer is used.</param>
/// <param name="secondComparer">Equality comparer for <typeparamref name="TSecond"/>. If null, the default comparer is used.</param>
public BidirectionalMap(IEqualityComparer<TFirst> firstComparer, IEqualityComparer<TSecond> secondComparer)
{
primary = new Dictionary<TFirst, TSecond>(firstComparer);
secondary = new Dictionary<TSecond, TFirst>(secondComparer);
}
/// <summary>
/// Creates a BidirectionalMap from the <paramref name="source"/> dictionary.
/// </summary>
/// <param name="source">The source dictionary from which to create a one-one relation map</param>
/// <exception cref="ArgumentException">If <paramref name="source"/> contains doublets in values</exception>
/// <exception cref="ArgumentNullException">If <paramref name="source"/> contains null values</exception>
public BidirectionalMap(IDictionary<TFirst, TSecond> source)
{
primary = new Dictionary<TFirst, TSecond>(source);
secondary = source.ToDictionary(kvp => kvp.Value, kvp => kvp.Key);
}
/// <summary>
/// Creates a BidirectionalMap from the <paramref name="inverseSource"/> dictionary.
/// </summary>
/// <param name="inverseSource">The source dictionary from which to create a one-one relation map</param>
/// <exception cref="ArgumentException">If <paramref name="inverseSource"/> contains doublets in values</exception>
/// <exception cref="ArgumentNullException">If <paramref name="inverseSource"/> contains null values</exception>
public BidirectionalMap(IDictionary<TSecond, TFirst> inverseSource)
{
primary = inverseSource.ToDictionary(kvp => kvp.Value, kvp => kvp.Key);
secondary = new Dictionary<TSecond, TFirst>(inverseSource);
}
public int Count => primary.Count;
public ICollection<TFirst> PrimaryKeys => primary.Keys;
public ICollection<TSecond> SecondaryKeys => secondary.Keys;
// This should be useful only for enumeration by TSecond as key
public IReadOnlyDictionary<TSecond, TFirst> Inverse => secondary;
public TSecond this[TFirst first]
{
get { return primary[first]; }
set { Set(first, value); }
}
public TFirst this[TSecond second]
{
get { return secondary[second]; }
set { Set(value, second); }
}
private void Set(TFirst first, TSecond second)
{
// Remove both the entries related to first and second if any
Remove(first);
Remove(second);
// Now it should be safe to add the new relation.
Add(first, second);
}
public void Add(TFirst first, TSecond second)
{
try
{
primary.Add(first, second);
}
catch (ArgumentNullException)
{
// If first is null, we end here and can rethrow with no harm done.
throw new ArgumentNullException(nameof(first));
}
catch (ArgumentException)
{
// If the key is present in primary, then we end here and can rethrow with no harm done.
throw new ArgumentException(nameof(first), $"{first} already present in the dictionary");
}
try
{
secondary.Add(second, first);
}
catch (ArgumentNullException)
{
// If second is null, we end here, and primary must be rolled back - because first was added successfully
primary.Remove(first);
throw new ArgumentNullException(nameof(second));
}
catch (ArgumentException)
{
// If second exists in secondary, secondary throws, and primary must be rolled back - because first was added successfully
primary.Remove(first);
throw new ArgumentException(nameof(second), $"{second} already present in the dictionary");
}
}
public bool Remove(TFirst first)
{
if (primary.TryGetValue(first, out var second))
{
secondary.Remove(second);
primary.Remove(first);
return true;
}
return false;
}
public bool Remove(TSecond second)
{
if (secondary.TryGetValue(second, out var first))
{
primary.Remove(first);
secondary.Remove(second);
return true;
}
return false;
}
public bool TryGetValue(TFirst first, out TSecond second)
{
return primary.TryGetValue(first, out second);
}
public bool TryGetValue(TSecond second, out TFirst first)
{
return secondary.TryGetValue(second, out first);
}
public bool Contains(TFirst first)
{
return primary.ContainsKey(first);
}
public bool Contains(TSecond second)
{
return secondary.ContainsKey(second);
}
public void Clear()
{
primary.Clear();
secondary.Clear();
}
public IEnumerator<KeyValuePair<TFirst, TSecond>> GetEnumerator()
{
return primary.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
</code></pre>
<p>It doesn't implement <code>IDictionary<T, S></code> for either directions, but has just about the same public interface for both. The directions should therefore be regarded as equal.</p>
<hr>
<p>Here are a set of unit tests - not complete but covering the most parts:</p>
<pre><code> [TestClass]
public class BidirectionalMapTests
{
class TestObject<T>
{
public TestObject(T value)
{
Value = value;
}
public T Value { get; }
public static implicit operator T(TestObject<T> to) => to.Value;
public static implicit operator TestObject<T>(T value) => new TestObject<T>(value);
public override string ToString()
{
return Value?.ToString() ?? "";
}
}
[TestMethod]
public void InitializeFromSourceDictionary()
{
Dictionary<string, int> source = new Dictionary<string, int>
{
{ "a", 1 },
{ "b", 2 }
};
BidirectionalMap<string, int> map = new BidirectionalMap<string, int>(source);
Assert.AreEqual(1, map["a"]);
Assert.AreEqual("b", map[2]);
}
[TestMethod]
public void InvalidInitializeFromSourceDictionary()
{
TestObject<string> one = new TestObject<string>("1");
Dictionary<string, TestObject<string>> source = new Dictionary<string, TestObject<string>>
{
{ "a", one },
{ "b", one }
};
BidirectionalMap<string, TestObject<string>> map = null;
Assert.ThrowsException<ArgumentException>(() => map = new BidirectionalMap<string, TestObject<string>>(source));
Dictionary<TestObject<string>, string> inverseSource = new Dictionary<TestObject<string>, string>
{
{ "a", "1" },
{ "b", "1" }
};
Assert.ThrowsException<ArgumentException>(() => map = new BidirectionalMap<string, TestObject<string>>(inverseSource));
source = new Dictionary<string, TestObject<string>>
{
{ "a", null },
{ "b", "1" }
};
Assert.ThrowsException<ArgumentNullException>(() => map = new BidirectionalMap<string, TestObject<string>>(source));
}
[TestMethod]
public void Add()
{
BidirectionalMap<string, int> map = new BidirectionalMap<string, int>();
map.Add("a", 1);
map.Add("b", 2);
Assert.AreEqual(1, map["a"]);
Assert.AreEqual("b", map[2]);
Assert.AreEqual(2, map.Count);
}
[TestMethod]
public void InvalidAdd()
{
BidirectionalMap<string, int> map = new BidirectionalMap<string, int>();
map.Add("a", 1);
Assert.ThrowsException<ArgumentException>(() => map.Add("a", 2));
Assert.ThrowsException<ArgumentException>(() => map.Add("b", 1));
Assert.AreEqual(1, map["a"]);
}
[TestMethod]
public void AddNull()
{
BidirectionalMap<string, string> map = new BidirectionalMap<string, string>();
Assert.ThrowsException<ArgumentNullException>(() => map.Add(null, "a"));
Assert.ThrowsException<ArgumentNullException>(() => map.Add("a", null));
Assert.AreEqual(0, map.Count);
}
[TestMethod]
public void Remove()
{
BidirectionalMap<string, int> map = new BidirectionalMap<string, int>();
map.Add("a", 1);
map.Add("b", 2);
Assert.AreEqual(2, map.Count);
map.Remove("a");
Assert.AreEqual(1, map.Count);
map.Remove(2);
Assert.AreEqual(0, map.Count);
}
[TestMethod]
public void RemoveNonExistingValue()
{
BidirectionalMap<string, int> map = new BidirectionalMap<string, int>();
map.Add("a", 1);
map.Add("b", 2);
Assert.IsFalse(map.Remove("c"));
Assert.AreEqual(2, map.Count);
}
[TestMethod]
public void Set()
{
BidirectionalMap<string, int> map = new BidirectionalMap<string, int>();
map.Add("a", 1);
map.Add("b", 2);
map["a"] = 3;
Assert.AreEqual(2, map.Count);
Assert.IsTrue(map.TryGetValue("a", out int second));
Assert.AreEqual(3, second);
Assert.IsTrue(map.TryGetValue(3, out string first));
Assert.AreEqual("a", first);
Assert.IsFalse(map.TryGetValue(1, out _));
}
[TestMethod]
public void SetWithExistingSecondValue()
{
BidirectionalMap<string, int> map = new BidirectionalMap<string, int>();
map.Add("a", 1);
map.Add("b", 2);
map["a"] = 2;
Assert.AreEqual(1, map.Count);
Assert.IsTrue(map.TryGetValue("a", out int second));
Assert.AreEqual(2, second);
Assert.IsTrue(map.TryGetValue(2, out string first));
Assert.AreEqual("a", first);
Assert.IsFalse(map.TryGetValue("b", out _));
}
[TestMethod]
public void TryGetValue()
{
BidirectionalMap<string, int> map = new BidirectionalMap<string, int>
{
{ "a", 1 },
{ "b", 2 }
};
Assert.IsTrue(map.TryGetValue("a", out int second));
Assert.AreEqual(1, second);
Assert.IsTrue(map.TryGetValue(2, out string first));
Assert.AreEqual("b", first);
Assert.IsFalse(map.TryGetValue("c", out _));
Assert.IsFalse(map.TryGetValue(3, out _));
}
}
</code></pre>
<hr>
<p>Any comments are welcome, but the implementation of <code>Add()</code>, <code>Set()</code> and <code>Remove()</code> are the most vulnerable parts.</p>
<p>I think that the naming <code>TFirst</code>, <code>TSecond</code>, <code>primary</code> and <code>secondary</code> could be better in order to reflect their equal status, but I didn't find any better. May be you have any suggestions?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T08:18:11.310",
"Id": "442929",
"Score": "2",
"body": "This solution is an example of how enthusiasm can make one blind about the obvious pitfalls - as mentioned by Peter in his answer - embarrassing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T08:32:06.687",
"Id": "442933",
"Score": "2",
"body": "I know this feeling. Code Review is sometimes cruel ;-P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T11:44:00.217",
"Id": "442964",
"Score": "0",
"body": "for the naming: https://en.wikipedia.org/wiki/Bijection they mention X and Y. But I'm not sure we should use these mathematical names as member names in C#. What do you think?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T12:14:39.903",
"Id": "442973",
"Score": "0",
"body": "@dfhwze: I don't like single char names, but they are at least neutral. I'll consider that."
}
] |
[
{
"body": "<p>If <code>TFirst</code> and <code>TSecond</code> are the same, nearly all of the API becomes useless because the compiler can't disambiguate the method calls.</p>\n\n<p>I think a better design would be for <code>Inverse</code> to be a <code>BidirectionalMap<TSecond, TFirst></code>, so that the methods don't need to be duplicated. Then one obvious unit test would be <code>ReferenceEquals(map, map.Inverse.Inverse)</code>. And I think the obstacle to implementing at least <code>IReadOnlyDictionary<TFirst, TSecond></code> would have been removed.</p>\n\n<hr>\n\n<p><code>Add</code> seems overly complicated and slightly fragile. I don't think the tiny performance improvement justifies the complexity over</p>\n\n<pre><code> public void Add(TFirst first, TSecond second)\n {\n if (first == null) throw new ArgumentNullException(nameof(first));\n if (primary.ContainsKey(first)) throw new ArgumentException(nameof(first), $\"{first} already present in the dictionary\");\n if (second == null) throw new ArgumentNullException(nameof(second));\n if (secondary.ContainsKey(second)) throw new ArgumentException(nameof(second), $\"{second} already present in the dictionary\");\n\n primary.Add(first, second);\n secondary.Add(second, first);\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T08:10:18.747",
"Id": "442928",
"Score": "0",
"body": "Oh, I just realized that you mentioned the same bug but with different examples hehe."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T08:21:12.413",
"Id": "442931",
"Score": "1",
"body": "@HenrikHansen then let it be a _secret_ review ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T07:52:34.130",
"Id": "227495",
"ParentId": "227474",
"Score": "4"
}
},
{
"body": "<p><code>Set</code> and <code>Remove</code> are compact and clean code. <code>Add</code> is convoluted with these exception handlers:</p>\n\n<blockquote>\n<pre><code> try\n {\n primary.Add(first, second);\n }\n catch (ArgumentNullException)\n {\n // If first is null, we end here and can rethrow with no harm done.\n throw new ArgumentNullException(nameof(first));\n }\n catch (ArgumentException)\n {\n // If the key is present in primary, then we end here and can rethrow with no harm done.\n throw new ArgumentException(nameof(first), $\"{first} already present in the dictionary\");\n }\n</code></pre>\n</blockquote>\n\n<p>I would opt for calling sand-box methods <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.tryadd?view=netstandard-2.1\" rel=\"nofollow noreferrer\">TryAdd</a> and <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.remove?view=netframework-4.8\" rel=\"nofollow noreferrer\">Remove</a> instead:</p>\n\n<pre><code>public void Add(TFirst first, TSecond second)\n{\n if (!primary.TryAdd(first, second) && !secondary.TryAdd(second, first))\n {\n primary.Remove(first);\n throw new InvalidOperationException(\"The tuple violates the bijective constraint\");\n }\n}\n</code></pre>\n\n<p>You can make the body a bit more verbose if you which to notify the caller which of the arguments violates the constraint.</p>\n\n<pre><code>public void Add(TFirst first, TSecond second)\n{\n if (!primary.TryAdd(first, second))\n {\n throw new InvalidOperationException(\"The first arg violates the bijective constraint\");\n }\n\n if (!secondary.TryAdd(second, first))\n {\n primary.Remove(first);\n throw new InvalidOperationException(\"The second arg violates the bijective constraint\");\n }\n}\n</code></pre>\n\n<p>You could even check for a combination if you really need to:</p>\n\n<pre><code>public void Add(TFirst first, TSecond second)\n{\n var primaryAdded = primary.TryAdd(first, second);\n var secondaryAdded = secondary.TryAdd(second, first);\n\n if (primaryAdded && !secondaryAdded)\n {\n primary.Remove(first);\n throw new InvalidOperationException(\"The second arg violates the bijective constraint\");\n }\n\n if (!primaryAdded && secondaryAdded)\n {\n secondary.Remove(second);\n throw new InvalidOperationException(\"The first arg violates the bijective constraint\");\n }\n\n if (!primaryAdded && !secondaryAdded)\n {\n throw new InvalidOperationException(\"Both args violate the bijective constraint\");\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T11:58:00.800",
"Id": "442968",
"Score": "1",
"body": "I didn't know about `TryAdd()` as it is still in preview for .NET Standard. But I could maybe make an extension. My argument for the convoluted approach was to let the dictionaries handle invalid input for performance reasons. Personally I don't find it that convoluted - the workflow and logic is easy followed IMO. I'll make a self-answer later in the evening that - I think - will build on the idea of an Inverse."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T11:30:25.277",
"Id": "227507",
"ParentId": "227474",
"Score": "4"
}
},
{
"body": "<p>My question is a disaster, and I don't know where my thoughts were while writing it. Funny enough I managed to write a lot of unittest even with the same type for the two keys without getting any compiler errors. Anyway below is a new version that builds on the <code>Inverse</code> concept, and it seems to do the trick all the way - but I'm sure someone can find something to criticize. I have experimented with the naming, but I'm not sure if they are final.</p>\n\n<pre><code> /// <summary>\n /// A one-one relation bidirectional map.\n /// <para>\n /// A one-one relation means that each entry of type <typeparamref name=\"TPrimary\"/> can correspond to exactly one \n /// entry of type <typeparamref name=\"TSecondary\"/> and visa versa.\n /// </para>\n /// The map doesn't support null elements because each element is both key and value in its relation and keys can't be null.\n /// </summary>\n /// <typeparam name=\"TPrimary\">Any type</typeparam>\n /// <typeparam name=\"TSecondary\">Any type</typeparam>\n public sealed class BidirectionalMap<TPrimary, TSecondary> : IEnumerable<KeyValuePair<TPrimary, TSecondary>>\n {\n private readonly Dictionary<TPrimary, TSecondary> map;\n private readonly Dictionary<TSecondary, TPrimary> inverseMap;\n\n /// <summary>\n /// Creates a BidirectionalMap from the provided dictionaries.\n /// Should be used only to create the Inverse.\n /// </summary>\n /// <param name=\"map\"></param>\n /// <param name=\"inverseMap\"></param>\n private BidirectionalMap(BidirectionalMap<TSecondary, TPrimary> inverse, Dictionary<TPrimary, TSecondary> map, Dictionary<TSecondary, TPrimary> inverseMap)\n {\n this.map = map;\n this.inverseMap = inverseMap;\n Inverse = inverse;\n }\n\n private BidirectionalMap(int capacity, IEqualityComparer<TPrimary> primaryComparer, IEqualityComparer<TSecondary> secondaryComparer)\n {\n map = new Dictionary<TPrimary, TSecondary>(capacity, primaryComparer);\n inverseMap = new Dictionary<TSecondary, TPrimary>(capacity, secondaryComparer);\n Inverse = new BidirectionalMap<TSecondary, TPrimary>(this, inverseMap, map);\n }\n\n public BidirectionalMap()\n {\n map = new Dictionary<TPrimary, TSecondary>();\n inverseMap = new Dictionary<TSecondary, TPrimary>();\n Inverse = new BidirectionalMap<TSecondary, TPrimary>(this, inverseMap, map);\n }\n\n /// <summary>\n /// Creates a BidirectionalMap initialized with the specified <paramref name=\"capacity\"/>.\n /// </summary>\n /// <param name=\"capacity\">The desired capacity for the map.</param>\n /// <exception cref=\"ArgumentOutOfRangeException\">If capacity is out of range (&lt; 0)</exception>\n public BidirectionalMap(int capacity) : this(capacity, null, null)\n {\n }\n\n /// <summary>\n /// Creates a BidirectionalMap with the specified equality comparers.\n /// </summary>\n /// <param name=\"mapComparer\">Equality comparer for <typeparamref name=\"TPrimary\"/>. If null, the default comparer is used.</param>\n /// <param name=\"inverseComparer\">Equality comparer for <typeparamref name=\"TSecondary\"/>. If null, the default comparer is used.</param>\n public BidirectionalMap(IEqualityComparer<TPrimary> mapComparer, IEqualityComparer<TSecondary> inverseComparer)\n : this(0, mapComparer, inverseComparer)\n {\n }\n\n /// <summary>\n /// Creates a BidirectionalMap from the <paramref name=\"source\"/> dictionary.\n /// </summary>\n /// <param name=\"source\">The source dictionary from which to create a one-one relation map</param>\n /// <exception cref=\"ArgumentException\">If <paramref name=\"source\"/> contains doublets in values</exception>\n /// <exception cref=\"ArgumentNullException\">If <paramref name=\"source\"/> contains null keys and/or values</exception>\n public BidirectionalMap(IDictionary<TPrimary, TSecondary> source)\n {\n map = new Dictionary<TPrimary, TSecondary>(source);\n inverseMap = new Dictionary<TSecondary, TPrimary>(source.ToDictionary(kvp => kvp.Value, kvp => kvp.Key));\n Inverse = new BidirectionalMap<TSecondary, TPrimary>(this, inverseMap, map);\n }\n\n /// <summary>\n /// Creates a BidirectionalMap from the <paramref name=\"inverseSource\"/> dictionary.\n /// </summary>\n /// <param name=\"inverseSource\">The source dictionary from which to create a one-one relation map</param>\n /// <exception cref=\"ArgumentException\">If <paramref name=\"inverseSource\"/> contains doublets in values</exception>\n /// <exception cref=\"ArgumentNullException\">If <paramref name=\"inverseSource\"/> contains null keys and/or values</exception>\n public BidirectionalMap(IDictionary<TSecondary, TPrimary> inverseSource)\n {\n map = new Dictionary<TPrimary, TSecondary>(inverseSource.ToDictionary(kvp => kvp.Value, kvp => kvp.Key));\n inverseMap = new Dictionary<TSecondary, TPrimary>(inverseSource);\n Inverse = new BidirectionalMap<TSecondary, TPrimary>(this, inverseMap, map);\n }\n\n public BidirectionalMap<TSecondary, TPrimary> Inverse { get; }\n public int Count => map.Count;\n\n public ICollection<TPrimary> Keys => map.Keys;\n public ICollection<TSecondary> InverseKeys => inverseMap.Keys;\n\n public TSecondary this[TPrimary key]\n {\n get { return map[key]; }\n set { Set(key, value); }\n }\n\n public void Set(TPrimary primary, TSecondary secondary)\n {\n // Remove both the entries related to primary and secondary if any\n Remove(primary, secondary);\n // Now it should be safe to add the new relation.\n Add(primary, secondary);\n }\n\n public void Add(TPrimary primary, TSecondary secondary)\n {\n if (primary == null) throw new ArgumentNullException(nameof(primary));\n if (map.ContainsKey(primary)) throw new ArgumentException(nameof(primary), $\"{primary} already present in the dictionary\");\n if (secondary == null) throw new ArgumentNullException(nameof(secondary));\n if (inverseMap.ContainsKey(secondary)) throw new ArgumentException(nameof(secondary), $\"{secondary} already present in the dictionary\");\n\n map.Add(primary, secondary);\n inverseMap.Add(secondary, primary);\n }\n\n private bool Remove(TPrimary primary, TSecondary secondary)\n {\n bool result = false;\n\n if (map.TryGetValue(primary, out var primaryValue))\n {\n inverseMap.Remove(primaryValue);\n map.Remove(primary);\n result = true;\n }\n\n if (inverseMap.TryGetValue(secondary, out var secondaryValue))\n {\n map.Remove(secondaryValue);\n inverseMap.Remove(secondary);\n result = true;\n }\n\n return result;\n }\n\n public bool Remove(TPrimary primary)\n {\n if (map.TryGetValue(primary, out var secondary))\n {\n inverseMap.Remove(secondary);\n map.Remove(primary);\n return true;\n }\n\n return false;\n }\n\n public bool TryGetValue(TPrimary primary, out TSecondary secondary)\n {\n return map.TryGetValue(primary, out secondary);\n }\n\n public bool ContainsKey(TPrimary primary)\n {\n return map.ContainsKey(primary);\n }\n\n public void Clear()\n {\n map.Clear();\n inverseMap.Clear();\n }\n\n public IEnumerator<KeyValuePair<TPrimary, TSecondary>> GetEnumerator()\n {\n return map.GetEnumerator();\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n }\n</code></pre>\n\n<hr>\n\n<p>The corresponding unittests:</p>\n\n<pre><code> [TestClass]\n public class BidirectionalMapTests\n {\n class TestObject<T>\n {\n public TestObject(T value)\n {\n Value = value;\n }\n\n public T Value { get; }\n\n public static implicit operator T(TestObject<T> to) => to.Value;\n public static implicit operator TestObject<T>(T value) => new TestObject<T>(value);\n\n public override string ToString()\n {\n return Value?.ToString() ?? \"\";\n }\n }\n\n [TestMethod]\n public void InitializeFromSourceDictionary()\n {\n Dictionary<string, int> source = new Dictionary<string, int>\n {\n { \"a\", 1 },\n { \"b\", 2 }\n };\n\n BidirectionalMap<string, int> map = new BidirectionalMap<string, int>(source);\n\n Assert.AreEqual(1, map[\"a\"]);\n Assert.AreEqual(\"b\", map.Inverse[2]);\n }\n\n [TestMethod]\n public void InvalidInitializeFromSourceDictionary()\n {\n TestObject<string> one = new TestObject<string>(\"1\");\n\n Dictionary<string, TestObject<string>> source = new Dictionary<string, TestObject<string>>\n {\n { \"a\", one },\n { \"b\", one }\n };\n\n BidirectionalMap<string, TestObject<string>> map = null;\n\n Assert.ThrowsException<ArgumentException>(() => map = new BidirectionalMap<string, TestObject<string>>(source));\n\n Dictionary<TestObject<string>, string> inverseSource = new Dictionary<TestObject<string>, string>\n {\n { \"a\", \"1\" },\n { \"b\", \"1\" }\n };\n\n Assert.ThrowsException<ArgumentException>(() => map = new BidirectionalMap<string, TestObject<string>>(inverseSource));\n\n source = new Dictionary<string, TestObject<string>>\n {\n { \"a\", null },\n { \"b\", \"1\" }\n };\n\n Assert.ThrowsException<ArgumentNullException>(() => map = new BidirectionalMap<string, TestObject<string>>(source));\n }\n\n [TestMethod]\n public void Add()\n {\n BidirectionalMap<string, int> map = new BidirectionalMap<string, int>();\n\n map.Add(\"a\", 1);\n map.Add(\"b\", 2);\n\n Assert.AreEqual(1, map[\"a\"]);\n Assert.AreEqual(\"b\", map.Inverse[2]);\n Assert.AreEqual(2, map.Count);\n }\n\n [TestMethod]\n public void InvalidAdd()\n {\n BidirectionalMap<string, int> map = new BidirectionalMap<string, int>();\n\n map.Add(\"a\", 1);\n Assert.ThrowsException<ArgumentException>(() => map.Add(\"a\", 2));\n Assert.ThrowsException<ArgumentException>(() => map.Add(\"b\", 1));\n Assert.AreEqual(1, map[\"a\"]);\n }\n\n [TestMethod]\n public void AddNull()\n {\n BidirectionalMap<string, string> map = new BidirectionalMap<string, string>();\n\n Assert.ThrowsException<ArgumentNullException>(() => map.Add(null, \"a\"));\n Assert.ThrowsException<ArgumentNullException>(() => map.Add(\"a\", null));\n Assert.AreEqual(0, map.Count);\n }\n\n [TestMethod]\n public void Remove()\n {\n BidirectionalMap<string, int> map = new BidirectionalMap<string, int>();\n\n map.Add(\"a\", 1);\n map.Add(\"b\", 2);\n Assert.AreEqual(2, map.Count);\n\n map.Remove(\"a\");\n Assert.AreEqual(1, map.Count);\n\n map.Inverse.Remove(2);\n Assert.AreEqual(0, map.Count);\n }\n\n [TestMethod]\n public void RemoveNonExistingValue()\n {\n BidirectionalMap<string, int> map = new BidirectionalMap<string, int>();\n\n map.Add(\"a\", 1);\n map.Add(\"b\", 2);\n\n Assert.IsFalse(map.Remove(\"c\"));\n Assert.AreEqual(2, map.Count);\n }\n\n [TestMethod]\n public void Set()\n {\n BidirectionalMap<string, int> map = new BidirectionalMap<string, int>();\n\n map.Add(\"a\", 1);\n map.Add(\"b\", 2);\n\n map[\"a\"] = 3;\n\n Assert.AreEqual(2, map.Count);\n Assert.IsTrue(map.TryGetValue(\"a\", out int second));\n Assert.AreEqual(3, second);\n Assert.IsTrue(map.Inverse.TryGetValue(3, out string first));\n Assert.AreEqual(\"a\", first);\n\n Assert.IsFalse(map.Inverse.TryGetValue(1, out _));\n }\n\n [TestMethod]\n public void SetWithExistingSecondValue()\n {\n BidirectionalMap<string, int> map = new BidirectionalMap<string, int>();\n\n map.Add(\"a\", 1);\n map.Add(\"b\", 2);\n\n map[\"a\"] = 2;\n\n Assert.AreEqual(1, map.Count);\n Assert.IsTrue(map.TryGetValue(\"a\", out int second));\n Assert.AreEqual(2, second);\n Assert.IsTrue(map.Inverse.TryGetValue(2, out string first));\n Assert.AreEqual(\"a\", first);\n\n Assert.IsFalse(map.TryGetValue(\"b\", out _));\n }\n\n [TestMethod]\n public void TryGetValue()\n {\n BidirectionalMap<string, int> map = new BidirectionalMap<string, int>\n {\n { \"a\", 1 },\n { \"b\", 2 }\n };\n\n Assert.IsTrue(map.TryGetValue(\"a\", out int second));\n Assert.AreEqual(1, second);\n\n Assert.IsTrue(map.Inverse.TryGetValue(2, out string first));\n Assert.AreEqual(\"b\", first);\n\n Assert.IsFalse(map.TryGetValue(\"c\", out _));\n Assert.IsFalse(map.Inverse.TryGetValue(3, out _));\n }\n\n [TestMethod]\n public void Indexer()\n {\n BidirectionalMap<string, string> map = new BidirectionalMap<string, string>\n {\n { \"a\", \"1\" },\n { \"b\", \"2\" }\n };\n\n Assert.AreEqual(\"1\", map[\"a\"]);\n Assert.AreEqual(\"b\", map.Inverse[\"2\"]);\n }\n\n [TestMethod]\n public void Inverse()\n {\n BidirectionalMap<string, int> map = new BidirectionalMap<string, int>();\n Assert.AreEqual(map, map.Inverse.Inverse);\n\n map = new BidirectionalMap<string, int>(10);\n Assert.AreEqual(map, map.Inverse.Inverse);\n\n map = new BidirectionalMap<string, int>(EqualityComparer<string>.Default, EqualityComparer<int>.Default);\n Assert.AreEqual(map, map.Inverse.Inverse);\n\n map = new BidirectionalMap<string, int>(EqualityComparer<string>.Default, EqualityComparer<int>.Default);\n Assert.AreEqual(map, map.Inverse.Inverse);\n\n Dictionary<string, int> source = new Dictionary<string, int>\n {\n { \"a\", 1 },\n { \"b\", 2 }\n };\n map = new BidirectionalMap<string, int>(source);\n Assert.AreEqual(map, map.Inverse.Inverse);\n\n Dictionary<int, string> inverseSource = new Dictionary<int, string>\n {\n { 1, \"a\" },\n { 2, \"b\" }\n };\n map = new BidirectionalMap<string, int>(inverseSource);\n Assert.AreEqual(map, map.Inverse.Inverse);\n\n\n\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T18:17:27.760",
"Id": "443027",
"Score": "2",
"body": "This would be cool if you named the dictionaries `map` and `pam` for the inverted one :-P The code would nicely align then in a couple of places."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T18:25:01.853",
"Id": "443028",
"Score": "1",
"body": "I also think that now with single APIs for each operation it'd should be save to actually implement the `IDictionary` interface."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T18:33:06.390",
"Id": "443030",
"Score": "0",
"body": "@t3chb0t: ha, ha, I'll consider that :-). Implementing `IDictionary`, I should definitely do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T18:50:47.270",
"Id": "443035",
"Score": "2",
"body": "I'm shocked that they actually allow the comparer to be `null`. I first thought it was a bug in your code but then checked the docs and indeed, it is ok to pass a `null` :-\\ everytime I think I know the framework they have to surprise me with new _(un)consistency_ conventions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T19:00:23.777",
"Id": "443038",
"Score": "1",
"body": "@t3chb0t: Initially I actually threw `ArgumentNullException` in a null check, but also realized that it was unnecessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T19:00:51.710",
"Id": "443039",
"Score": "1",
"body": "oh, I'v just found that there are still two constructors that with same types are ambigous and won't allow you to create it from a dictionary like `new BidirectionalMap<string, string>(new Dictionary<string, string> { .. })`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T19:06:30.987",
"Id": "443041",
"Score": "0",
"body": "@t3chb0t: OK, but can we fix that in any way?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T19:08:56.010",
"Id": "443042",
"Score": "2",
"body": "I think we can, I would leave only one of the constructors `TPrimary, TSecondary` in order to be consistent with the other APIs and add a factory method `FromInverse` instead, to still support what the now removed cunstructor allowed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T19:15:48.940",
"Id": "443043",
"Score": "0",
"body": "@t3chb0t: Of course - got it. Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T05:39:46.780",
"Id": "443079",
"Score": "1",
"body": "I would remove _InverseKeys_ it's redundant as you can call _Inverse.Keys_."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T06:20:33.107",
"Id": "443083",
"Score": "0",
"body": "@dfhwze: You're right - it's a leftover from the original concept."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T18:08:09.297",
"Id": "227527",
"ParentId": "227474",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227495",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T16:32:38.260",
"Id": "227474",
"Score": "4",
"Tags": [
"c#",
"hash-map"
],
"Title": "Bidirectional Map in C#"
}
|
227474
|
<p>I'm trying out a new continuous histogram coloring method for Mandelbrot rendering in R, and since it requires three loops (three passes), each of them doubly nested, there should be a way to vectorize the code to speed it up. </p>
<p>However, I'm not yet familiar enough with vectorization in R, especially when conditionals are involved, and I would appreciate the help.</p>
<p>I know there's a <code>which</code> function which gives an array of indices of the elements which obey a condition, but I'm not sure how to make it work in this case.</p>
<p>Basically, I would like to make some zoom animations which is why I want the code to run faster than it does now.</p>
<p>If any additional improvements are possible, I would very much appreciate the advice as well.</p>
<p>While it's not very relevant for the question, the coloring method is as follows: instead of escape count, as usual, we are counting a kind of "cumulative convergence/divergence speed", which is defined as the sum of <code>min(1/|z_n|^2,|z_n|^2)</code> over the whole iterations run. It is continuous, and allows for interior coloring. The disadvantage is that we have to use floating point numbers, so very deep zooms are hard, if not impossible to render.</p>
<p>Here is the R code I've created, with comments:</p>
<pre><code>library("jcolors")
It <- 400; #Max iterations
Es <- 10^3; #Escape radius squared (much larger than 4, intentionally)
Xm <- 1600; #x pixels
Ym <- 900; #y pixels
Mxy <- matrix(rep(1,Xm*Ym),nrow=Xm,ncol=Ym); #initiate Mandelbrot array
Hxy <- Mxy; #Histogram index array
Nb <- 40; #Number of bins
hb <- rep(0,Nb); #Histogram heights vector
Mb <- rep(0,Nb); #Bin boundaries, for later
mx <- 1:Xm;
my <- 1:Ym;
Cx <- -0.5+(-1+mx/Xm*2)*1.6; #Re(C) vector
Cy <- (-1+my/Ym*2)*0.9; #Im(C) vector
ny <- 1; #First pass loop, computing Mxy
while(ny <= Ym){nx <- 1;
while(nx <= Xm){
j <- 1;
x0 <- 0;
y0 <- 0;
s <- 1;
while(j <= It){r <- x0^2+y0^2; #|z|^2
if(r<Es){x1 <- x0^2-y0^2+Cx[nx];
y1 <- 2*x0*y0+Cy[ny]}
else{x1 <- x0; y1 <- y0; break};
x0 <- x1;
y0 <- y1;
if(r>0){s <- s+min(r,1/r)}; #this is what we measure instead of escape count
j <- j+1}
Mxy[nx,ny] <- s;
nx <- nx+1}
ny <- ny+1}
Mmax <- max(Mxy);
Mmin <- min(Mxy);
DM <- Mmax-Mmin;
dM <- DM/Nb; #Bin size
Mxy <- Mxy-Mmin; #Shifting the array values so they start with 0
ny <- 1; #Second pass loop, computing the histogram
while(ny <= Ym){nx <- 1;
while(nx <= Xm){
nb <- 1;
while(nb <= Nb){if(Mxy[nx,ny] < (nb+0.01)*dM && Mxy[nx,ny] > (nb-1.01)*dM) #Bins overlap a little to avoid missed pixels
{hb[nb] <- hb[nb]+1; #Bin height increases
Hxy[nx,ny] <- nb}; #Each pixel is assigned its bin index
nb <- nb+1}
nx <- nx+1}
ny <- ny+1}
hb <- hb/max(hb); #Normalizing the histogram
nb <- 1; #computing the new bin boundaries
while(nb < Nb){Mb[nb+1] <- Mb[nb]+dM*hb[nb];
nb <- nb+1}
ny <- 1; #Third pass loop, scaling the array according to the histogram (multiply each interval by the bin height)
while(ny <= Ym){nx <- 1;
while(nx <= Xm){
nb <- 1;
while(nb <= Nb){
if(Hxy[nx,ny]==nb){Mxy[nx,ny] <- Mb[nb]+(Mxy[nx,ny]-(nb-1)*dM)*hb[nb]; break}
nb <- nb+1}
nx <- nx+1}
ny <- ny+1};
image(Mxy, col = jcolors_contin(palette = "rainbow", reverse=FALSE)(200), axes=FALSE, xlab="", ylab="", useRaster=TRUE)
#done
</code></pre>
<p>And here's the resulting image:</p>
<p><img src="https://i.imgur.com/mfB3mwq.png" alt="Manderbrot set"></p>
<p>And an example of a zoom <code>*1.0625^(-225)</code> at the point <code>x=0.3602404434376143632361252444</code>, <code>y=-0.641313061064803174860375015</code>.</p>
<p><img src="https://i.imgur.com/yZtD8PD.png" alt="Manderbrot set zoom"></p>
<p>Another zoom at the same point, <code>*1.0625^(-300)</code> and <code>1700</code> iterations.</p>
<p><img src="https://i.imgur.com/FUidJXv.png" alt="Mandelbrot set zoom"></p>
<hr>
<p><strong>Edit:</strong></p>
<p>I accepted the answer, so here's an additional comment on the coloring method itself, for future reference.</p>
<p>I've read a dozen posts on Mandelbrot coloring, and usually histogram coloring is used with discrete escape count measure, which is then interpolated to form a continuous image.</p>
<p>Using histogram coloring with bins for continuous measure is not ideal, and leads to the loss of important details (like minibrots) and highlights less important details (the "rings" and "webs" of color you can see in the images above).</p>
<p>I found that the best way so far is to mix the arrays without histogram scaling (a "single bin" histogram) and with histogram scaling. Then the details look good, and the colors are rich even at very high interation counts.</p>
<p>Here's an example of low zoom with high iteration count <code>It=3000</code> and <code>Nb=100</code> bins, where I use the arithmetic mean of <code>Mxy</code> without histogram scaling and with it.</p>
<p><a href="https://i.stack.imgur.com/OuJNL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OuJNL.jpg" alt="enter image description here"></a></p>
<p>And a <code>8.2E-9</code> zoom with the same parameters:</p>
<p><a href="https://i.stack.imgur.com/PJiu7.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PJiu7.jpg" alt="enter image description here"></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T16:56:44.107",
"Id": "442873",
"Score": "0",
"body": "Are you looking for anything specific in a review or just a general review?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T16:59:29.063",
"Id": "442874",
"Score": "1",
"body": "@dfhwze, I would mostly like to know about vectorization, and other possible ways to increase efficiency. This is my first time on this site, but as far as I see, this kind of questions is allowed here. If I need to clarify something, I will be happy to"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T17:01:11.040",
"Id": "442875",
"Score": "0",
"body": "This question is fine. It's just that if you specify explicitly what you are looking for in a review, you are more likely to get that concern reviewed :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T17:04:28.800",
"Id": "442876",
"Score": "1",
"body": "@dfhwze, I would like to know how to improve the speed and use R more efficiently. Because R is all about vectors and parallellization, while I'm mostly using loops here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T17:07:42.153",
"Id": "442877",
"Score": "0",
"body": "Ok I glanced over your concerns in the question. Those blockquotes are usually used to indicate the task description."
}
] |
[
{
"body": "<p>There's a couple of things you can do to improve the R-style and the efficiency of your code.</p>\n\n<p>Let's first look at your while loops:</p>\n\n<p>After putting your comments before the code they correspond to, removing the unnecessary semicolons, and normalising your white space, the final while loop looks like this:</p>\n\n<pre><code># Third pass loop, scaling the array according to the histogram (multiply each interval by the bin height)\nny <- 1\nwhile (ny <= Ym) {\n nx <- 1\n while (nx <= Xm) {\n nb <- 1\n while (nb <= Nb) {\n if (Hxy[nx, ny] == nb) {\n Mxy[nx, ny] <- Mb[nb] + (Mxy[nx, ny] - (nb - 1) * dM) * hb[nb]\n break\n }\n nb <- nb + 1\n }\n nx <- nx + 1\n }\n ny <- ny + 1\n}\n</code></pre>\n\n<p>We can rewrite this using a slightly more condensed form:</p>\n\n<pre><code># Third pass loop, scaling the array according to the histogram (multiply each interval by the bin height)\nfor (ny in seq(Ym)) {\n for (nx in seq(Xm)) {\n for (nb in seq(Nb)) {\n if (Hxy[nx, ny] == nb) {\n Mxy[nx, ny] <- Mb[nb] + (Mxy[nx, ny] - (nb - 1) * dM) * hb[nb]\n break\n }\n }\n }\n}\n</code></pre>\n\n<p>The <code>break</code> in there isn't necessary, it just speeds things up a bit (Hxy isn't updated during the loop, and for any given (i,j), Hxy[i,j] == nb can only be true for one value of <code>nb</code>). So we can remove the <code>break</code>. But then we can also rearrange the loop; let's put the <code>nb</code> loop on the outside:</p>\n\n<pre><code># Third pass loop, scaling the array according to the histogram (multiply each\n# interval by the bin height)\nfor (nb in seq(Nb)) {\n for (ny in seq(Ym)) {\n for (nx in seq(Xm)) {\n if (Hxy[nx, ny] == nb) {\n Mxy[nx, ny] <- Mb[nb] + (Mxy[nx, ny] - (nb - 1) * dM) * hb[nb]\n }\n }\n }\n}\n</code></pre>\n\n<p>There are a few ways to vectorise this. You could:</p>\n\n<ul>\n<li><p>update each row in turn</p></li>\n<li><p>update each column in turn</p></li>\n<li><p>or update the whole matrix</p></li>\n</ul>\n\n<p>To update each column:</p>\n\n<pre><code>for (nb in seq(Nb)) {\n for (ny in seq(Ym)) {\n # find those entries that need updating\n idx <- which(Hxy[, ny] == nb)\n # compute the replacement value for those entries\n replacement <- Mb[nb] + (Mxy[idx, ny] - (nb - 1) * dM) * hb[nb]\n # update the entries\n Mxy[idx, ny] <- replacement\n }\n}\n\n# or alternatively:\nfor (nb in seq(Nb)) {\n for (ny in seq(Ym)) {\n Mxy[, ny] <- ifelse(\n Hxy[, ny] == nb,\n # value if true\n Mb[nb] + (Mxy[, ny] - (nb - 1) * dM) * hb[nb],\n # value if false\n Mxy[, ny]\n )\n }\n}\n</code></pre>\n\n<p>Importantly, a matrix is a vector. So you can actually update a whole matrix in a similar vectorised way (this uses a slightly different indexing syntax to typical matrix operations - in a 2d matrix you can index an entry by either two-coordinates (the row and column) or by one (by counting down each column in turn)):</p>\n\n<pre><code>for (nb in seq(Nb)) {\n # which entries need updating:\n idx <- which(Hxy == nb)\n # what value should they take:\n replacement <- Mb[nb] + (Mxy[idx] - (nb - 1) * dM) * hb[nb]\n # update those values\n Mxy[idx] <- replacement\n}\n</code></pre>\n\n<p>[edit:]\nNow, we still don't have a fully vectorised version of that loop.</p>\n\n<p>How could that loop over <code>Seq(Nb)</code> be vectorised out?</p>\n\n<p>For a given value of <code>nb</code> we find all entries in <code>Hxy</code> that match <code>nb</code> and we refer to their position in Hxy or Mxy by <code>idx</code>; so whereever we use <code>nb</code> in the definition of <code>replacement</code>, we could use <code>Hxy[idx]</code> instead (<code>Mb[Hxy[idx]]</code>, <code>Hxy[idx]</code>, <code>hb[Hxy[idx]]</code> are all vectors, because <code>idx</code> is a vector); so we have:</p>\n\n<pre><code>for (nb in seq(Nb)) {\n # which entries need updating:\n idx <- which(Hxy == nb)\n # what value should they take:\n replacement <- Mb[Hxy[idx]] + (Mxy[idx] - (Hxy[idx] - 1) * dM) * hb[Hxy[idx]]\n # update those values\n Mxy[idx] <- replacement\n}\n</code></pre>\n\n<p>You can now throw away those index vectors:</p>\n\n<pre><code># begone `for` loop\nreplacement <- Mb[Hxy] + (Mxy - (Hxy - 1) * dM) * hb[Hxy]\nMxy <- replacement\n</code></pre>\n\n<p>You've vectorised out the whole of that final loop.</p>\n\n<hr>\n\n<p>However, I suspect the main limitation on the speed of your code will be the first loop rather than the second or third; and I can't see how to readily vectorise the first loop.</p>\n\n<p>You might want to split the code up into three functions, one for each of the loops, and time each of them; or use <code>profvis</code> to work out where your code spends most of its time (<a href=\"https://github.com/rstudio/profvis\" rel=\"nofollow noreferrer\">https://github.com/rstudio/profvis</a>)</p>\n\n<hr>\n\n<p>If it's of use, I modified your original code, putting the matrix computation bit into a function so I could play with it. The modified code looks like this:</p>\n\n<pre><code>mandelbrot_array <- function(\n # Max iterations\n n_iter,\n # x pixels\n n_row,\n # y pixels\n n_col\n) {\n # Escape radius squared (much larger than 4, intentionally)\n Es <- 10^3\n Xm <- n_row\n Ym <- n_col\n\n # initiate Mandelbrot array\n Mxy <- matrix(rep(1, Xm * Ym), nrow = Xm, ncol = Ym)\n # Histogram index array\n Hxy <- Mxy\n\n # Number of bins\n Nb <- 40\n # Histogram heights vector\n hb <- rep(0, Nb)\n # Bin boundaries, for later\n Mb <- rep(0, Nb)\n mx <- 1:Xm\n my <- 1:Ym\n # Re(C) vector\n Cx <- -0.5 + (-1 + mx / Xm * 2) * 1.6\n # Im(C) vector\n Cy <- (-1 + my / Ym * 2) * 0.9\n\n # First pass loop, computing Mxy\n for (ny in seq(Ym)) {\n for (nx in seq(Xm)) {\n x0 <- 0\n y0 <- 0\n s <- 1\n for (j in seq(n_iter)) {\n r <- x0^2 + y0^2 #|z|^2\n if (r < Es) {\n x1 <- x0^2 - y0^2 + Cx[nx]\n y1 <- 2 * x0 * y0 + Cy[ny]\n }\n else {\n x1 <- x0\n y1 <- y0\n break\n }\n x0 <- x1\n y0 <- y1\n if (r > 0) {\n s <- s + min(r, 1 / r)\n } # this is what we measure instead of escape count\n }\n Mxy[nx, ny] <- s\n }\n }\n Mmax <- max(Mxy)\n Mmin <- min(Mxy)\n DM <- Mmax - Mmin\n # Bin size\n dM <- DM / Nb\n # Shifting the array values so they start with 0\n Mxy <- Mxy - Mmin\n # Second pass loop, computing the histogram\n\n for (nb in seq(Nb)) {\n idx <- which(\n Mxy < (nb + 0.01) * dM &\n Mxy > (nb - 1.01) * dM\n )\n hb[nb] <- hb[nb] + length(idx)\n Hxy[idx] <- nb\n }\n\n # Normalizing the histogram\n hb <- hb / max(hb)\n # computing the new bin boundaries\n for (nb in seq(Nb - 1)) {\n Mb[nb + 1] <- Mb[nb] + dM * hb[nb]\n }\n # Third pass loop, has now been vectorised completely:\n Mxy <- Mb[Hxy] + (Mxy - (Hxy - 1) * dM) * hb[Hxy]\n\n Mxy\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T15:33:11.803",
"Id": "444764",
"Score": "1",
"body": "Thank you for the improvements and the review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T15:46:08.257",
"Id": "444767",
"Score": "0",
"body": "No problem. I did look into the earlier loop in a bit more detail and may post some updated code. Although vectorised code can be used to replace some of the first loop, I couldn't get more than a three fold speed up (and had to use ~ 1000x more memory) for your actual use case. You might need to use Rcpp or something to really speed up that first loop."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T17:44:12.513",
"Id": "227526",
"ParentId": "227476",
"Score": "2"
}
},
{
"body": "<p>Can we do anything about that first loop? It's currently written in a very <code>C</code> style, modifying single elements in the matrix Mxy. Ideally, in a vectorised implementation, you'd be able to update the whole of the matrix Mxy in one go.</p>\n\n<p>Since the code is pretty complicated and slow, we might need some tests and some benchmarking to ensure that after any changes we introduce the code i) still works properly, and ii) is more efficient.</p>\n\n<p>I pulled out the first loop into a function:</p>\n\n<pre><code># Some of the variables have been renamed\ncompute_mxy_initial <- function(\n n_iter,\n n_row,\n n_col,\n r_escape) {\n # Initial Mandelbrot array\n m_xy <- matrix(1, nrow = n_row, ncol = n_col)\n m_x <- seq(n_row)\n m_y <- seq(n_col)\n\n # Re(C) vector\n c_x <- -0.5 + (-1 + m_x / n_row * 2) * 1.6\n c_y <- (-1 + m_y / n_col * 2) * 0.9\n\n # Compute the matrix\n for (ny in seq(n_col)) {\n for (nx in seq(n_row)) {\n x0 <- 0\n y0 <- 0\n s <- 1\n for (j in seq(n_iter)) {\n # should it be called r2 ?\n r <- x0^2 + y0^2\n if (r < r_escape) {\n x1 <- x0^2 - y0^2 + c_x[nx]\n y1 <- 2 * x0 * y0 + c_y[ny]\n } else {\n # are x1 / y1 just discarded here?\n x1 <- x0\n y1 <- y0\n break\n }\n x0 <- x1\n y0 <- y1\n if (r > 0) {\n s <- s + min(r, 1 / r)\n }\n }\n m_xy[nx, ny] <- s\n }\n }\n m_xy\n}\n</code></pre>\n\n<p>.. and made another function <code>compute_mxy_test</code> with the same body (this one will be updated).</p>\n\n<p>To check that the two functions give the same results you can add a few <code>test_that</code> tests:</p>\n\n<pre><code>set.seed(1)\n\ntest_that(\n \"mxy values generated by the refactored function match the original values\", {\n for (i in 1:30) {\n n_iter <- 1 + rpois(1, 10)\n n_row <- 1 + rpois(1, 10)\n n_col <- 1 + rpois(1, 10)\n r_escape <- rexp(1, 1 / 1000)\n expect_equal(\n compute_mxy_test(n_iter, n_row, n_col, r_escape),\n compute_mxy_initial(n_iter, n_row, n_col, r_escape),\n tolerance = 1e-4\n )\n }\n }\n)\n</code></pre>\n\n<p>Anytime that you modify <code>compute_mxy_test</code> rerun the test. (You could alternatively, and more efficiently, precompute the expected values for the matrix and just compare the values created by <code>compute_mxy_test</code> to these).</p>\n\n<p>You can also use the <code>bench</code> package to compare timings, but do this sparingly because your code is pretty slow:</p>\n\n<pre><code>timings <- bench::press(\n n_iter = c(10, 100, 400),\n n_row = c(10, 100, 1600),\n n_col = c(10, 100, 900),\n {\n bench::mark(\n initial = compute_mxy_initial(n_iter, n_row, n_col, r_escape = 1000),\n vectorised = compute_mxy_test(n_iter, n_row, n_col, r_escape = 1000)\n )\n }\n)\n</code></pre>\n\n<hr>\n\n<p>Modifications to the first loop:</p>\n\n<p>What I'm trying to do here is get the <code>for (j in seq(n_iter))</code> outside the positional for-loops. Unfortunately, the only way I could see to do that, was to store lots more information in RAM. You could add a data.frame that stores the coordinates, squared-radius etc for each <code>nx,ny</code> pair such that at each new iteration, those points with small radii get updated.</p>\n\n<p>Here's the basic data structure:</p>\n\n<pre><code>compute_mxy_test <- function(\n n_iter,\n n_row,\n n_col,\n r_escape) {\n # Initial Mandelbrot array\n m_xy <- matrix(1, nrow = n_row, ncol = n_col)\n\n # Re(C) vector\n c_x <- -0.5 + (-1 + seq(n_row) / n_row * 2) * 1.6\n c_y <- (-1 + seq(n_col) / n_col * 2) * 0.9\n\n # construct a data-frame for use in vectorised updates\n coords <- expand.grid(\n nx = seq(n_row),\n ny = seq(n_col)\n ) %>%\n dplyr::mutate(\n # starting values for each nx/ny pair\n x0 = 0,\n y0 = 0,\n s = 1,\n r = 0\n )\n\n # Compute the matrix\n\n # iterate over the rows of `coords` and then extract nx/ny from each row\n for (i in seq(nrow(coords))) {\n nx <- coords[i, \"nx\"]\n ny <- coords[i, \"ny\"]\n x0 <- coords[i, \"x0\"]\n y0 <- coords[i, \"y0\"]\n s <- coords[i, \"s\"]\n r <- coords[i, \"r\"]\n for (j in seq(n_iter)) {\n # should it be called r2 ?\n if (r < r_escape) {\n x1 <- x0^2 - y0^2 + c_x[nx]\n y1 <- 2 * x0 * y0 + c_y[ny]\n s <- ifelse(r > 0, s + min(r, 1 / r), s)\n x0 <- x1\n y0 <- y1\n r <- x0^2 + y0^2\n }\n }\n # update the values for x0 etc for this row\n coords[i, c(\"x0\", \"y0\", \"s\", \"r\")] <- c(x0, y0, s, r)\n }\n m_xy[cbind(coords$nx, coords$ny)] <- coords$s\n m_xy\n}\n</code></pre>\n\n<p>THen, still working with one row at a time, we can introduce a function that\nwill update all the coordinate-data for that row:</p>\n\n<pre><code>compute_mxy_test <- function(\n n_iter,\n n_row,\n n_col,\n r_escape) {\n # Initial Mandelbrot array\n m_xy <- matrix(1, nrow = n_row, ncol = n_col)\n\n # Re(C) vector\n c_x <- -0.5 + (-1 + seq(n_row) / n_row * 2) * 1.6\n c_y <- (-1 + seq(n_col) / n_col * 2) * 0.9\n\n # construct a data-frame for use in vectorised updates\n coords <- expand.grid(\n nx = seq(n_row),\n ny = seq(n_col)\n ) %>%\n dplyr::mutate(\n x0 = 0,\n y0 = 0,\n s = 1,\n r = 0,\n # note these additive offsets are used in .update_coords()\n cx = c_x[nx],\n cy = c_y[ny]\n )\n\n .update_coords <- function(df) {\n # can assume that r >= r_escape\n x1 <- with(df, x0^2 - y0^2 + cx)\n y1 <- with(df, 2 * x0 * y0 + cy)\n df %>%\n dplyr::mutate(\n # pmin does pairwise `min` between matched elements in two equal-sized vectors\n s = ifelse(r > 0, s + pmin(r, 1 / r), s),\n x0 = x1,\n y0 = y1,\n r = x0^2 + y0^2\n )\n }\n\n # Compute the matrix\n for (i in seq(nrow(coords))) {\n # working with a single row, but will soon generalise\n my_coords <- coords[i, ]\n for (j in seq(n_iter)) {\n # only update a row if it's coords are near zero\n rows <- which(my_coords$r < r_escape)\n my_coords[rows, ] <- .update_coords(my_coords)\n }\n coords[i, ] <- my_coords\n }\n # note the use of MATRIX[cbind(vec1, vec2)], this allows you to update\n # a set of specific entries in a matrix, rather than contiguous blocks of\n # entries\n m_xy[cbind(coords$nx, coords$ny)] <- coords$s\n m_xy\n}\n</code></pre>\n\n<p>Rather than doing <code>for(index) ... for(iteration){}</code> and updating a single row: for a given iteration, we could determine all rows that need to be updated and then update those rows. That is we can do <code>for (iteration){find-the-relevant-rows; update-those-rows}</code>. The final code looks like this:</p>\n\n<pre><code>compute_mxy_test <- function(\n n_iter,\n n_row,\n n_col,\n r_escape) {\n # Initial Mandelbrot array\n m_xy <- matrix(1, nrow = n_row, ncol = n_col)\n\n # Re(C) vector\n c_x <- -0.5 + (-1 + seq(n_row) / n_row * 2) * 1.6\n c_y <- (-1 + seq(n_col) / n_col * 2) * 0.9\n\n # construct a data-frame for use in vectorised updates\n coords <- expand.grid(\n nx = seq(n_row),\n ny = seq(n_col)\n ) %>%\n dplyr::mutate(\n x0 = 0,\n y0 = 0,\n s = 1,\n r = 0,\n cx = c_x[nx],\n cy = c_y[ny]\n )\n\n .update_coords <- function(df) {\n # can assume\n # - nx, ny, x0, y0, s, r, cx, cy are columns in `df`\n # - that r >= r_escape\n x1 <- with(df, x0^2 - y0^2 + cx)\n y1 <- with(df, 2 * x0 * y0 + cy)\n df %>%\n dplyr::mutate(\n s = ifelse(r > 0, s + pmin(r, 1 / r), s),\n x0 = x1,\n y0 = y1,\n r = x0^2 + y0^2\n )\n }\n\n # Compute the matrix\n for (j in seq(n_iter)) {\n rows <- which(coords$r < r_escape)\n coords[rows, ] <- .update_coords(coords[rows, ])\n }\n\n m_xy[cbind(coords$nx, coords$ny)] <- coords$s\n m_xy\n}\n</code></pre>\n\n<p>Now, you can compare the values returned, and you can compare the speed of the original implementation, and the vectorised implementation. IN my hands, for (400, 1600, 900) the vectorised code was ~ 3x as fast as the imperative for-loop code. But it used <em>way</em> more memory. If you run the benchmark code above, you should be able to convince yourself of this. (But you might notice that the vectorised code is considerably slower for less demanding arguments)</p>\n\n<p>Although vectorised code is (usually) faster, because it pushes more work down into a lower level, the data-structures you have to set up to make it work, and the way the code looks sometimes makes it less appealing. As I said in a comment earlier, you might be better moving this code all the way down into the C level, eg by rewriting your original for-loop implementation using Rcpp.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T18:22:18.440",
"Id": "444783",
"Score": "0",
"body": "This was a nice challenge, thanks. Can I reiterate that when you try to refactor code in R (or in other languages) you really need to ensure that you have tests around that code and your refactorings should be done in steps that are as small as possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T18:37:32.157",
"Id": "444785",
"Score": "0",
"body": "Thank you again, I'll do some tests later to see if this works for my (moderate) zooming needs. I won't pretend to understand everything you say here, because I'm not a programmer, but I understand that working with C should be better, I think most fractal renders are made in C."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T18:40:39.543",
"Id": "444786",
"Score": "0",
"body": "Sorry, I didn't mean you should disregard r, you can write c code that you can call from r"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T18:45:46.937",
"Id": "444788",
"Score": "0",
"body": "Oh, no problem, I got that part, R has some advantages, especially when it comes to actually rendering the pictures, and it's easy to use. Not sure if I ever manage to learn C"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T09:18:30.067",
"Id": "444863",
"Score": "0",
"body": "I think you'd be pleasantly surprised by how similar the code in `compute_mxy_initial` is to an equivalent C++ function. Try working through a few of the Rcpp exercises in the book 'Advanced R': http://adv-r.had.co.nz/Rcpp.html ; perhaps someone else could do an R -> C++ refactoring for just that section. (The figures look great btw)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T18:18:33.627",
"Id": "228862",
"ParentId": "227476",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227526",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T16:48:24.700",
"Id": "227476",
"Score": "6",
"Tags": [
"performance",
"r",
"data-visualization",
"fractals"
],
"Title": "Mandelbrot rendering code in R"
}
|
227476
|
<p>Currently my code (at <a href="https://github.com/schuelermine/gaussian/tree/39d34c7a70c98152756377b9b39fb300635daac7" rel="nofollow noreferrer">GitHub</a>) is this:</p>
<pre><code>module Gaussian where
import qualified Data.Complex as Complex
-- Enables toComplex.
-- Qualified to avoid clashing.
data Gaussian = (:+)
{
real :: Integer,
imaginary :: Integer
} deriving
(Show, Read, Eq)
-- The gaussian integer type.
-- A gaussian integer is a complex number of the form a + bi where a and b are integers.
instance Num Gaussian
where
(a1 :+ b1) + (a2 :+ b2) = (a1 + a2) :+ (b1 + b2)
(a1 :+ b1) - (a2 :+ b2) = (a1 - a2) :+ (b1 - b2)
(a1 :+ b1) * (a2 :+ b2) = (a1 * a2 - b1 * b2) :+ (a1 * b2 + a2 * b1)
abs (a :+ b) = ((a ^ two) + (b ^ two)) :+ 0
where
two = 2 :: Integer
-- This prevents compiler warnings about defaulting types.
signum = id
negate (a :+ b) = negate a :+ negate b
fromInteger x = x :+ 0
-- The Num instance for Gaussian.
-- We use the euclidean norm as abs. norm(a + bi) = a^2 + b^2
i :: Gaussian
i = 0 :+ 1
-- The imaginary unit, equal to sqrt(-1).
magnitude :: Floating c => Gaussian -> c
magnitude (a :+ b) = sqrt $ (fromInteger a ^ two) + (fromInteger b ^ two)
where
two = 2 :: Integer
-- This prevents compiler warnings about defaulting types.
norm :: Gaussian -> Integer
norm (a :+ b) = (a ^ two) + (b ^ two)
where
two = 2 :: Integer
-- This prevents compiler warnings about defaulting types.
conjugate :: Gaussian -> Gaussian
conjugate (a :+ b) = (a :+ negate b)
-- The complex conjugate.
-- Effectively flips about the real axis.
rotate_cw :: Gaussian -> Gaussian
rotate_cw (a :+ b) = (b :+ negate a)
-- Rotate a gaussian integer clockwise.
-- Equivalent to multiplying by i.
rotate_ccw :: Gaussian -> Gaussian
rotate_ccw (a :+ b) = (negate b :+ a)
-- Rotate a gaussian integer counterclockwise.
-- Equivalent to multiplying by -i.
flip_x :: Gaussian -> Gaussian
flip_x (a :+ b) = (negate a :+ b)
-- Flips on imaginary axis.
-- Analogous to conjugate.
flip_y :: Gaussian -> Gaussian
flip_y = conjugate
-- Alias for conjugate.
-- See conjugate.
swap_x_y :: Gaussian -> Gaussian
swap_x_y (a :+ b) = (b :+ a)
-- Utility function, swaps real and imaginary axes.
toComplex :: Num p => Gaussian -> Complex.Complex p
toComplex (a :+ b) = (fromInteger a Complex.:+ fromInteger b)
-- Converts a Gaussian to any complex number (Num p => Complex p)
-- Fully qualified operators to avoid clashing.
</code></pre>
<p>As far as I know, my brace/indentation style isn't used anywhere else, so I'm a bit worried about that.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T19:21:16.263",
"Id": "442894",
"Score": "1",
"body": "I wonder what the exact compiler warnings are and what code triggers them. It should be quite normal and allowed to compute the square of an integer. You could also define a function `sqr` for this purpose."
}
] |
[
{
"body": "<p>This looks good. All necessary type signatures are there, no type is too strict nor too generic. The indentation style is familiar, and the braces on <code>data Gaussian</code> are easy to read, so no worries about that.</p>\n\n<p>However, there are a few oddities. Let's face them.</p>\n\n<h1><code>Num</code>'s <code>signum</code></h1>\n\n<p>There aren't any laws for <a href=\"https://hackage.haskell.org/package/base-4.12.0.0/docs/Prelude.html#t:Num\" rel=\"noreferrer\"><code>Num</code></a> in the Haskell report, however there are some expectations. The operations on <code>(+)</code> and <code>(*)</code> should implement a <a href=\"https://en.wikipedia.org/wiki/Ring_(mathematics)\" rel=\"noreferrer\">ring</a> and that's certainly true here. However, <code>Num</code>'s documentation indicates that the following should hold:</p>\n\n<pre><code>abs x * signum x = x -- (1)\n</code></pre>\n\n<p>Unfortunately, we cannot take the easy way and just use</p>\n\n<pre><code>signum x = x / abs x\n</code></pre>\n\n<p>since the result is unlikely to be in <code>Gaussian</code>'s domain. As we cannot hold (1), we're free to do whatever we want, but it should be reasonable. How does it become reasonable? By <em>documenting your decision</em>:</p>\n\n<pre><code>signum = id -- < your documentation here >\n</code></pre>\n\n<h1>Prefix vs. postfix documentation</h1>\n\n<p>That took me by surprise. Most of Haskell's documentation is placed <em>before</em> the documented item, not after. The same holds for most other documentation in other languages, where the documentation is placed before or in the function itself:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>/** @brief Calculates the absolute value of a Gaussian integer.\n * @param x is a Gaussian integer\n * @returns x's absolute value\n*/\nint g_abs(gint x) {\n return x.r * x.r + x.i * x.i;\n}\n</code></pre>\n\n<pre class=\"lang-py prettyprint-override\"><code>def g_abs(x):\n \"\"\"Returns the absolute value of x\"\"\"\n return x.r * x.r + x.i * x.i\n</code></pre>\n\n<p>The usual <a href=\"https://haskell-haddock.readthedocs.io/en/latest/markup.html\" rel=\"noreferrer\">Haddock documentation</a> also placed the documentation before the item, although it's possible to use postfix.</p>\n\n<p>You're welcome to stay in the postfix style, but you should indicate that your documentation refers to the preceding item, for example with Haddock's <code>^</code>:</p>\n\n<pre><code>i :: Gaussian\ni = 0 :+ 1\n--^ The imaginary unit, equal to sqrt(-1).\n</code></pre>\n\n<p>That removes possible ambiguity.</p>\n\n<h1><code>two = 2 :: Integer</code> and <code>x ^ two</code></h1>\n\n<p>The line <code>two = 2 :: Integer</code> violates the DRY principle, thus any optimization or bugfix on <code>x ^ two</code> needs to get repeated throughout the program, which is error prone.</p>\n\n<p>However, there is a greater issue. GHC rewrites <code>x ^ 2</code> to <code>x * x</code> (see <a href=\"https://hackage.haskell.org/package/base-4.12.0.0/docs/src/GHC.Real.html#%5E\" rel=\"noreferrer\">Note [Inlining (^)</a> in <code>base</code>'s documention). An explicit variable <em>might</em> hinder that process.</p>\n\n<p>Instead, you should provide a <code>square</code> function or just immediately multiply a value with itself. Both variants will get rid of the warnings and additional bindings, for example:</p>\n\n<pre><code>--| The Num instance for Gaussian.\n-- We use the euclidean norm as abs. norm(a + bi) = a^2 + b^2\ninstance Num Gaussian\n where\n ...\n abs (a :+ b) = (a * a + b * b) :+ 0\n signum = id -- chosen at random\n ...\n</code></pre>\n\n<p>By the way: if you chose <code>square x = x ^ (2 :: Int)</code> you won't need to repeat your documentation.</p>\n\n<h1>Precision</h1>\n\n<p>You always want to stay as precise as possible, unless you are aiming for speed. Therefore, you should try to stay in exact types till the very last moment in <code>magnitude</code>.</p>\n\n<p>Instead of</p>\n\n<pre><code>magnitude :: Floating c => Gaussian -> c\nmagnitude (a :+ b) = sqrt $ (square $ fromInteger a) + (square $ fromInteger b)\n</code></pre>\n\n<p>use</p>\n\n<pre><code>magnitude :: Floating c => Gaussian -> c\nmagnitude (a :+ b) = sqrt $ fromInteger (square a + square b)\n</code></pre>\n\n<p>You could also reuse <code>abs</code> if you split it into two functions:</p>\n\n<pre><code>instance Num Gaussian where\n ...\n abs x = (absIntegral x :+ 0)\n ...\n\nabsIntegral :: Gausian -> Integer\nabsIntegral (a :+ b) = square a + square b\n\nmagnitude :: Floating c => Gaussian -> c\nmagnitude = sqrt . fromInteger . absIntegral\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T17:56:08.137",
"Id": "443472",
"Score": "0",
"body": "Do you accept answers on this StExN?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T06:21:43.437",
"Id": "444699",
"Score": "0",
"body": "@schuelermine see https://codereview.meta.stackexchange.com/questions/54/which-answer-to-accept. If you don't think that this answer scratches all (or at least the right) spots, feel free to unaccept it. Keep in mind that a question with at least one positive scored answer [is not marked as unanswered](https://meta.stackexchange.com/questions/18870/why-does-the-unanswered-questions-tab-show-questions-that-have-answers). Therefore, accepting an answer won't hurt any visibility, if that's something you have in mind."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T18:35:12.943",
"Id": "227530",
"ParentId": "227478",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "227530",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T18:34:28.550",
"Id": "227478",
"Score": "5",
"Tags": [
"haskell",
"complex-numbers"
],
"Title": "Implementing Gaussian integers in Haskell"
}
|
227478
|
<p>This is a program for converting English to the pseudo-language Pig Latin. Not the strictest form of Pig Latin but it most likely will accurately output an argument in Pig Latin. I got the idea from a list of ideas on <a href="https://github.com/karan/Projects" rel="nofollow noreferrer">Github</a>. Is there any way I can improve it concisely?</p>
<pre><code>def pig_latin(message):
consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y',
'z']
new_message = ''
for word in message.split():
ay = ['a', 'y']
listed_word = list(word)
word_copy = word
moved_consonants = ''
for letter in listed_word.copy():
if letter.lower() == 'y':
if letter in word_copy[0]:
moved_consonants += letter
listed_word.remove(letter)
else:
break
elif letter.lower() in consonants:
moved_consonants += letter
listed_word.remove(letter)
else:
break
listed_word.append('-' + moved_consonants + ''.join(ay))
new_message += ''.join(listed_word) + ' '
return new_message
print(pig_latin('Can you read pig latin?'))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T20:19:26.967",
"Id": "442898",
"Score": "8",
"body": "To the close voter (/ presumably downvoter), they said they got the *idea* from a github list, not the implementation. I don't see an authorship issue here."
}
] |
[
{
"body": "<p>First, at the top you list all the consonants out. There are two things that can be improved here:</p>\n\n<ul>\n<li><p>Since you only use it to check whether or not something is a consonant, it should be a <a href=\"https://docs.python.org/3.7/library/stdtypes.html#set-types-set-frozenset\" rel=\"noreferrer\">set</a>. It's much more efficient to to a membership lookup on a set than it is to do one on a list. Just replace the <code>[]</code> with <code>{}</code>.</p>\n\n<pre><code>consonants = {'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'}\n</code></pre></li>\n<li><p>Second, there's a slightly less painful way to generate those letters. Python's <code>string</code> module contains a <code>ascii_lowercase</code> built-in that holds <code>'abcdefghijklmnopqrstuvwxyz'</code>. You can use that along with a set of vowels to limit what letters need to be hard-coded:</p>\n\n<pre><code>import string as s\n\nvowels = {'a', 'e', 'i', 'o', 'u'}\nconsonants = set(s.ascii_lowercase) - vowels # Consonants are the set of letters, minus the vowels\n</code></pre>\n\n<p>I personally prefer this way.</p></li>\n</ul>\n\n<p>You could also just change your algorithm to use <code>vowels</code> directly.</p>\n\n<hr>\n\n<p>Just to clear something up, </p>\n\n<pre><code>word_copy = word\n</code></pre>\n\n<p>does <em>not</em> create a copy of <code>word</code>. This just creates a second name for the <code>word</code> string. For Strings this doesn't matter because Strings are immutable, but with a mutable object, this will bite you:</p>\n\n<pre><code>my_list = []\nlist_copy = my_list # Does not actually create a copy!\nmy_list.append(1)\nprint(my_list, list_copy) # prints [1] [1]\n</code></pre>\n\n<p>Notice how <em>both</em> lists were added to. This happens because there's actually only one list. Both names are referring to the same list.</p>\n\n<p>For the sake of clarity, I'd rename it to say what it's <em>purpose</em> is. Offhand though, I can't see the need for <code>word_copy</code> at all! It would make sense if it was being used as an accumulator for a loop or something, but the only time its ever used is at <code>word_copy[0]</code>, and since you never reassign <code>word</code>, you could just do <code>word[0]</code>. I'd simply get rid of <code>word_copy</code>.</p>\n\n<p>Along the same lines, I'd reconsider <code>ay</code>. The name you've given it is exactly as descriptive as the string it contains, and is only ever used in one place. At the very least, I'd rename it to something meaningful:</p>\n\n<pre><code>pig_latin_suffix = ['a', 'y']\n</code></pre>\n\n<p>I'll also note that there's no reason to use a list of Strings here instead of a multi-character String. They behave the same in this case:</p>\n\n<pre><code>\" \".join(['a', 'y'])\n'a y'\n\n\" \".join(\"ay\")\n'a y'\n</code></pre>\n\n<p>Strings are iterable just like lists are.</p>\n\n<hr>\n\n<p>I think <code>pig_latin</code> is too big. It's doing two main jobs: breaking the message into words, and processing the words. I would make the processing step its own function:</p>\n\n<pre><code>def process_word(word):\n ay = ['a', 'y']\n listed_word = list(word)\n word_copy = word\n moved_consonants = ''\n\n for letter in listed_word.copy():\n if letter.lower() == 'y':\n if letter in word_copy[0]:\n moved_consonants += letter\n listed_word.remove(letter)\n else:\n break\n elif letter.lower() in consonants:\n moved_consonants += letter\n listed_word.remove(letter)\n else:\n break\n\n listed_word.append('-' + moved_consonants + ''.join(ay))\n\n return ''.join(listed_word)\n\ndef pig_latin(message):\n new_message = ''\n\n for word in message.split():\n processed_word = process_word(word)\n\n new_message += processed_word + ' '\n\n return new_message\n</code></pre>\n\n<p><code>process_word</code> could arguably be broken down further. This is already much better though. The immediate benefit is now you can test individual words, and not have to worry about how the rest of the code will react:</p>\n\n<pre><code>print(process_word(\"Can\")) # Prints 'an-Cay'\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T12:43:27.700",
"Id": "442974",
"Score": "0",
"body": "`print(process_word(\"Can?\"))` \"an?-Cay\" probably isn't what OP wanted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T13:41:19.210",
"Id": "442979",
"Score": "2",
"body": "@Griffin That's what their's prints. I was just rolling with it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T20:43:36.943",
"Id": "443056",
"Score": "0",
"body": "for what its worth if you do need to create a genuine copy the way to do that would be: `from copy import deepcopy; word_copy = deepcopy(word)`. That way you're actually creating a copy and not just a reference to the original"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T22:09:59.277",
"Id": "443061",
"Score": "0",
"body": "@TheSaint321 I can't think of a circumstance where you would ever need to copy a String though. I wouldn't be surprised if `deepcopy` just immediately returns Strings passed to it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T01:47:31.903",
"Id": "443068",
"Score": "1",
"body": "yup thought about it for another second you're right. There's no point in deep copying a string. Its still a pretty useful tool nevertheless for more complicated objects"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T17:28:56.603",
"Id": "443144",
"Score": "0",
"body": "Is there a reason for implementing the loop explicitly in `pig_latin` instead of a simple `return ' '.join(process_word(word) for word in message.split())`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T17:34:19.873",
"Id": "443145",
"Score": "0",
"body": "@PiCTo Honestly, I was (and still am) suffering from the stomach flu. I only had the will to point out what was immediately obvious to me. You could post an answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T17:41:45.813",
"Id": "443147",
"Score": "0",
"body": "@Carcigenicate Sorry to read that; I hope I did not offend you. I was asking a genuine question as I believed that might be an improvement. I don't have the will to write a throughout answer to this question but, if you agree that the one-liner I propose is better (and that there are no reason not to use it), I will gladly edit your answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T17:43:04.933",
"Id": "443148",
"Score": "0",
"body": "@PiCTo No worries, it's potentially a legitimate recommendation. I'll look at it when staring at screens stops making me nauseous."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T20:45:59.577",
"Id": "227481",
"ParentId": "227479",
"Score": "18"
}
},
{
"body": "<p>As this is a simple text transformation, the regular-expression module <code>re</code> is your friend.</p>\n\n<p>Processing letters one at a time is h-a-r-d. It would be simpler to process things one word at a time, as suggested by @Carcigenicate.</p>\n\n<p>The <a href=\"https://docs.python.org/3/library/re.html?highlight=re#re.sub\" rel=\"noreferrer\"><code>re.sub(pattern, repl, text, ...)</code></a> function is interesting in that it allows you to specify a string <strong>or a function</strong> for the replacement. As a first approximation:</p>\n\n<pre><code>import re\n\ndef pig_latin(text):\n\n def transform(match):\n first, rest = match.group(1, 2)\n if first.lower() in \"aeiou\":\n return first + rest + 'way'\n else:\n return rest + first + 'ay'\n\n return re.sub(r'(\\w)(\\w*)', transform, text)\n\nprint(pig_latin(\"Can you read pig latin?\"))\n</code></pre>\n\n<blockquote>\n <p>anCay ouyay eadray igpay atinlay?</p>\n</blockquote>\n\n<p>Here, the regex is extracting entire words with two capturing groups. The first group is simply the first letter <code>\\w</code>, an the second group is the rest of the letters (if any) in the word <code>\\w*</code>. The <code>match</code> is passed to the <code>transform</code> function, from which groups #1 and #2 are extracted and assigned to <code>first</code> and <code>rest</code>. If the <code>first</code> letter is a vowel, the replacement text is generated one way; if not it is generated a second way. The returned value is used as the replacement in the <code>re.sub(...)</code> call.</p>\n\n<p>The <code>transform</code> function can easily be modified to include the <code>-</code>, if desired, as well as additional special handling of <code>y</code>, if required.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T21:57:19.753",
"Id": "227487",
"ParentId": "227479",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T19:32:49.020",
"Id": "227479",
"Score": "16",
"Tags": [
"python",
"beginner",
"python-3.x",
"programming-challenge",
"pig-latin"
],
"Title": "Translate English to Pig Latin"
}
|
227479
|
Doxygen is a multi-language documentation generation application for C++, C, Java, Objective-C, Python, IDL, Fortran, VHDL, PHP and C# that supports a wide variety of output formats including RTF, HTML, XML and PDF.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T02:32:22.703",
"Id": "227491",
"Score": "0",
"Tags": null,
"Title": null
}
|
227491
|
<p>I have two Models in my Rails 6 / PostgreSQL application which have a many to many relation; <code>Car</code> and <code>Driver</code>. The goal is to get all records (Cars) which have no association at all (Drivers). At the moment this is done using Ruby (2.6.3) like this:</p>
<pre><code>result = []
Car.all.each do |car|
result << car.id if car.drivers.empty?
end
</code></pre>
<p>Is there an ActiveRecord expression which avoids instantiating each record?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T16:55:49.887",
"Id": "445046",
"Score": "0",
"body": "Have a look at the [ActiveRecord Query Interface](https://guides.rubyonrails.org/active_record_querying.html)."
}
] |
[
{
"body": "<p>To produce the set of records only in <code>cars</code>, but not in <code>drivers</code>, you perform a left outer join, then exclude the records you don't want from the right side via a where clause.</p>\n\n<p>In Rails 6 you do this in this way:</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>Car.left_outer_joins(:drivers).where(car_drivers: { id: nil })\n</code></pre>\n\n<p>Take a look at this article: <a href=\"https://blog.codinghorror.com/a-visual-explanation-of-sql-joins/\" rel=\"nofollow noreferrer\">A Visual Explanation of SQL Joins</a>. It may help you figure out how to do some queries.</p>\n\n<p>Aside from this, a good way to iterate over an array to select some elements according to a condition is to use the <a href=\"https://ruby-doc.org/core-2.6.5/Enumerable.html#method-i-select\" rel=\"nofollow noreferrer\"><code>select</code></a> method. Using <code>select</code> your code would be like this:</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>result = Car.all.select { |car| car.drivers.empty? }\n</code></pre>\n\n<p>But that is not the way to go here, I'm just showing how to use <code>select</code>.</p>\n\n<p>Also, if you want only the <code>id</code> from the cars, you can add <code>pluck(:id)</code> at the end of the query. This is going to get only the <code>id</code> field from the database. Or you just use the method <code>ids</code> but the <code>pluck</code> method works for any field.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T11:55:25.610",
"Id": "232793",
"ParentId": "227498",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T09:07:53.470",
"Id": "227498",
"Score": "0",
"Tags": [
"ruby",
"ruby-on-rails",
"active-record"
],
"Title": "ActiveRecord Query for many to many association"
}
|
227498
|
<p>I made the acquaintance of big-O a couple of weeks ago and am trying to get to grips with it, but although there's a lot of material out there about calculating time complexity, I can't seem to find out how to make algorithms more efficient.</p>
<p>I've been practising with the the demo challenge in Codility:</p>
<blockquote>
<p>Write a function that, given an array A of N integers, returns the
smallest positive integer (greater than 0) that does not occur in A.
For example, given A = [1, 3, 6, 4, 1, 2], the function should return
5. The given array can have integers between -1 million and 1 million.</p>
</blockquote>
<p>I started with a brute-force algorithm:</p>
<pre><code>public int solution(int[] A)
{
for ( int number = 1; number < 1000000; number ++)
{
if (doesContain(A, number)){}
else return i;
}
return 0;
}
</code></pre>
<p>This passed all tests for correctness but scored low on performance because the running time was way past the limit, time complexity being <span class="math-container">\$O(N^2)\$</span>.</p>
<p>I then tried putting the array into an arraylist, which reduces big-O since each object is "touched" only once, and I can use .Contains which is more efficient than iteration (not sure if that's true; I just sort of remember reading it somewhere).</p>
<pre><code>public int solution(int[] A)
{
ArrayList myArr = new ArrayList();
for (int i=0; i<A.Length; i++)
{
myArr.Add(A[i]);
}
for ( int i = 1; i < 1000000; i++)
{
if (myArr.Contains(i)){}
else return i;
}
return 0;
}
</code></pre>
<p>Alas, the time complexity is still at <span class="math-container">\$O(N^2)\$</span> and I can't find explanations of how to cut down time.</p>
<p>I know I shouldn't be using brute force, but can't seem to think of any other ways... Anyone have an explanation of how to make this algorithm more efficient?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T09:24:51.070",
"Id": "442938",
"Score": "0",
"body": "`ArrayList`, as its name says, is implemented using an array. So `Contains` is just iterating all elements, just like your manual solution did."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T09:30:33.130",
"Id": "442941",
"Score": "0",
"body": "Your title mentions sorting, but you're not doing any sorting. Hint: recall that sorting an array is O(n log n), which is less than O(n^2)."
}
] |
[
{
"body": "<blockquote>\n <p>I then tried putting the array into an arraylist, which reduces big-O since each object is \"touched\" only once, and I can use .Contains which is more efficient than iteration (not sure if that's true; I just sort of remember reading it somewhere).</p>\n</blockquote>\n\n<p>As was mentioned in the comments, for your purpose, there is no significant difference in performance between <code>int[]</code> and <code>ArrayList</code>. Both store their data in a similar way, and both will have to iterate through the array to check for <code>Contains</code>. So that doesn't help anything.</p>\n\n<hr>\n\n<h1>Sorting</h1>\n\n<p>You mention sorting in the title of your question. But you don't actually do any sorting. Let's look at the challenge:</p>\n\n<blockquote>\n <p>Write a function that, given an array A of N integers, returns the smallest >positive integer (greater than 0) that does not occur in A. For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5. The given array can have integers between -1 million and 1 million.</p>\n</blockquote>\n\n<p>We need to know whether 1, 2, 3, etc are in the input. You can do this, by checking each and every option, one at a time. Since you don't know whether 1 would be at the start, or at the end of the array, you have to check the entire thing each and every time. That's inefficient.</p>\n\n<p>However, if you sort the input, the array becomes somewhat predictable. You can loop through the sorted array until you find the first positive number. Is it higher than 1? Then we can return 1, since that is the smallest possible integer that's not in the list - the smallest positive integer is >1 after all. If it equals 1, we can go to the next element and check its value. If it is another 1, move on. If it is >2, we can return 2, else we must move on. And repeat.</p>\n\n<p>In that way, what we have done, is sorting the array (<span class=\"math-container\">\\$O(n logn)\\$</span>), and then looping through it once. All in all, that's still <span class=\"math-container\">\\$O(n logn)\\$</span>.</p>\n\n<pre><code>public int solution(int[] a) {\n // sort\n Array.Sort(a);\n var answerCandidate = 1;\n\n // Find the first nonzero positive number.\n for(var index = 0; index < a.Length; index++) {\n if (a[index] < answerCandidate) {\n continue;\n } else if(a[index] == answerCandidate) {\n // Oops, we found our candidate in the list, so we move to the next one.\n // Since the list is sorted, we know the next one can only be farther\n // on in the list, so we don't need to restart the loop.\n answerCandidate++;\n } else {\n // In this case a[index] > answerCandidate. This means that we haven't found\n // the candidate in the list, so we can return answerCandidate. Break so\n // that we can handle the case where we pass the end of the array at the same time.\n break;\n }\n }\n\n return answerCandidate;\n}\n</code></pre>\n\n<p>We can still make a marginal improvement by searching for the first positive number using a binary search on our sorted list.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T06:55:39.750",
"Id": "443085",
"Score": "0",
"body": "And what if you only sorted the positive numbers? Would mean a custom sort routine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T07:07:59.267",
"Id": "443086",
"Score": "0",
"body": "@AJD you could spend one pass over the list to remove all the negative numbers, I suppose. I guess some benchmarks could shed some light"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T09:48:56.623",
"Id": "227503",
"ParentId": "227500",
"Score": "9"
}
},
{
"body": "<p>Better complexity can be achieved using a heap. The input array can be organized into a min-heap in <span class=\"math-container\">\\$O(n)\\$</span> time with negative integers dropped. Then the smallest number can be popped one by one until the target number is found. The complexity of this algorithm is <span class=\"math-container\">\\$O(n + klogn)\\$</span> where <span class=\"math-container\">\\$k\\$</span> is the insertion index of the target number among the sorted sequence of positive numbers.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T14:57:26.797",
"Id": "227510",
"ParentId": "227500",
"Score": "7"
}
},
{
"body": "<p>The algorithm provided by the OP presumes that the array is important and preserves the original array. In addition, the displayed algorithm seeks an \"instantaneous answer\", as if the routine may be interrogated at any point to get that answer at the point in time. </p>\n\n<p>All that is important here is the output - a single number. Any other information used to get that output can be discarded. As such, any information that is not useful for the solution (such as negative elements of the array) can be discarded with extreme prejudice. And once an element has been used to work towards a solution, it too can be discarded or forgotten.</p>\n\n<p>Thus, the algorithm should not be trying to find the contiguous elements, but rather the hole that is there (as is stated in the original question).</p>\n\n<p>I am not a java programmer, so I will answer with pseudo-code. The following alternative approach focuses on the speed, and in doing so is willing to sacrifice space. Because the input array is random, some semblance of state (i.e. the contiguous blocks) is required.</p>\n\n<pre><code>input: array [A]\n\nCreate capture array of size 1 million Boolean[B]\ntraverse [A] (read values)\n discard values <= 0\n set [B](value) = true\ntraverse [B]\n Stop at first false. \n\nSolution: index[B] at the stopping point\n</code></pre>\n\n<p>This is a potential max of <span class=\"math-container\">\\$O(2n)\\$</span> if a random access array is used.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T07:45:34.603",
"Id": "443089",
"Score": "0",
"body": "Very good in terms of time-complexity, not so much in memory, but in some circumstances, that might be acceptable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T13:52:41.313",
"Id": "443111",
"Score": "2",
"body": "In Java, you'd use a BitSet for that, and be at about 125 KB, which is close to nothing in the year 2019. Especially, if the calculation is really time-critical, this is a good trade-off."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T06:29:31.517",
"Id": "443309",
"Score": "0",
"body": "This is fine for an algorithm within the constraints given, but the answer seems less of a review and more of an alternative implementation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T19:55:30.483",
"Id": "443392",
"Score": "0",
"body": "@Josiah: you are right. Amended."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T07:10:14.437",
"Id": "227554",
"ParentId": "227500",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "227503",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T09:20:59.490",
"Id": "227500",
"Score": "9",
"Tags": [
"java",
"algorithm",
"programming-challenge",
"time-limit-exceeded",
"complexity"
],
"Title": "Find the smallest positive integer that is absent from a given array"
}
|
227500
|
<p>msoGraphic is an MsoShapeType enumeration that is available in Office PowerPoint 2016 and later (versions which can handle svg graphics). If you attempt to check an MsoShapeType against msoGraphic in earlier versions of Office you will get a compile error - as msoGraphic is not defined (in any module containing Option Explicit). I am handling this by putting this property in a module where Option Explicit is NOT declared - and calling it from anywhere that needs the value of the constant. The module only contains this property (and any other properties that need to handle any other constants in this way).</p>
<pre><code>Public Property Get myMsoGraphic() As Long
If msoGraphic = 0 Then
myMsoGraphic = 28
Else
myMsoGraphic = msoGraphic
End If
End Property
</code></pre>
<p>I could of course have just re-declared msoGraphic as a constant with value 28, but best practice seems to be that you should avoid using the actual value and use the enumerate constant instead - in case the value gets changed at some point in the future (which I guess is probably highly unlikely).</p>
<p>Does this seem like the best way to handle this situation?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T13:41:29.723",
"Id": "442980",
"Score": "0",
"body": "\"Does this seem like the best way to handle this situation?\" Not a bad workaround I guess, did you find any side-effects yet?"
}
] |
[
{
"body": "<p>Without <code>Option Explicit</code>, the <code>msoGraphic</code> identifier in that property scope is a <code>Variant/Empty</code>; there's an implicit type conversion happening when you do this:</p>\n\n<blockquote>\n<pre><code>If msoGraphic = 0 Then\n</code></pre>\n</blockquote>\n\n<p>Sure <code>vbEmpty</code> will equate to <code>0</code>, or even <code>vbNullString</code> or <code>\"\"</code>, but that's after converting to a comparable type (<code>Integer</code>, or <code>String</code>). There's a better way.</p>\n\n<pre><code>If IsEmpty(msoGraphic) Then\n</code></pre>\n\n<p>The <code>IsEmpty</code> function will only ever return <code>True</code> when given a <code>Variant/Empty</code> value - which is exactly what we're dealing with here.</p>\n\n<blockquote>\n <p><em>I could of course have just re-declared msoGraphic as a constant with value 28, but best practice seems to be that you should avoid using the actual value and use the enumerate constant instead</em></p>\n</blockquote>\n\n<p>One doesn't exclude the other. If you define a public constant in an appropriately named standard module (e.g. <code>OfficeConstants</code>), <em>and use it</em>, then you <em>are</em> adhering to the best practice. What happens then is deliberate <em>shadowing</em> of the <code>MsoShapeType.msoGraphic</code> declaration - something <a href=\"http://rubberduckvba.com/Inspections/Details/ShadowedDeclaration\" rel=\"nofollow noreferrer\">Rubberduck would normally warn about</a>, but with a descriptive <code>@Ignore</code> or <code>@IgnoreModule</code> annotation comment, the intention is clarified, and the static code analysis tool knows to ignore them - and with a link to the official documentation, you ensure the values correctly match the actual documented underlying values for each identifier:</p>\n\n<pre><code>'@IgnoreModule ShadowedDeclaration: these constants are only available in Office 2016+\nOption Explicit\n'https://docs.microsoft.com/en-us/office/vba/api/office.msoshapetype\nPublic Const msoGraphic As Long = 28\n'...\n</code></pre>\n\n<p>What you want to avoid, is code like this, where <code>28</code> is some magic value that has no clear meaning:</p>\n\n<pre><code>If shapeType = 28 Then\n</code></pre>\n\n<blockquote>\n <p><em>Does this seem like the best way to handle this situation?</em></p>\n</blockquote>\n\n<p>The problem is that you can't name your property <code>msoGraphic</code> (well you <em>could</em>, but then you'd have to fully-qualify the <code>msoGraphic</code> constant, and then that wouldn't be compilable, even without <code>Option Explicit</code>), so any code (hopefully with <code>Option Explicit</code> specified) that means to use the name <code>msoGraphic</code> now needs to use <code>myMsoGraphic</code> instead, and that isn't ideal, because it <em>adds</em> to the overall cognitive load: you, future you, and eventual maintainers have to remember to avoid <code>msoGraphic</code> and use <code>myMsoGraphic</code> instead, whereas with a <code>Public Const</code> in a standard module that hides/shadows the constant from the referenced PowerPoint library when it exists, usage is much more seamless.</p>\n\n<p>That said, while VBA is case-insensitive, a <code>camelCase</code> public member clashes with the naming convention of pretty much <em>everything else</em> in your standard libraries - enum members only have a lowercase prefix as a namespace surrogate; every type, method, member, property, procedure, function, constant, in every standard library, uses <code>PascalCase</code>. There's no reason to not make every single one of your own procedures use this naming convention too; also while the <code>my</code> prefix is ubiquitous in so many VB examples, it's not a good prefix to use in actual code.</p>\n\n<p>One last thing:</p>\n\n<blockquote>\n <p><em>in case the value gets changed at some point in the future</em></p>\n</blockquote>\n\n<p>It won't: <code>MsoShapeType</code> is defined in a shared Office library that isn't only referenced by PowerPoint projects - VBA is ridiculously backward-compatible (line numbers, <code>GoSub</code>/<code>Return</code> statements, <code>Call</code>, <code>Let</code>, <code>DefBool</code> keywords, to name a few <em>should-be-extinct-but-aren't-because-backward-compatibility</em> still-supported language features): there is no way any constant ever released into the wild is ever going to get a new value in any future release. Not going to happen.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T11:47:37.250",
"Id": "444735",
"Score": "1",
"body": "In your `'@IgnoreModule` annotation you have a semicolon to add some additional info; is this something you can actually do with RubberDuck? I've not been having much success..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T12:40:56.120",
"Id": "444745",
"Score": "1",
"body": "@Greedo I haven't had any issues doing that, but the grammar rules around annotations have changed recently, did it break (try with a colon)? What does \"not having much success\" means? Is the annotation getting flagged as illegal or malformed? Please open an issue on the repo with the info - parsing annotations is challenging, because the arguments list needs to parse as such (same rules as a procedure call), but the rest of the comment needs to parse as a comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T14:06:36.907",
"Id": "444753",
"Score": "2",
"body": "Interesting, works with a colon, not a semi-colon (not much success = the annotation is being ignored, as if it were an ordinary comment, no illegal annotation inspection, but also no @Ignoring of inspections either). Only posted here because I didn't know what the intended behaviour was"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T15:18:52.137",
"Id": "227515",
"ParentId": "227505",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "227515",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T10:24:24.413",
"Id": "227505",
"Score": "9",
"Tags": [
"vba",
"powerpoint"
],
"Title": "VBA - new built-in enumerations and backwards compatibility"
}
|
227505
|
<p>The code is to check the rows in a table. If in a table two non consecutive rows are checked then all the in between rows should be selected by itself. Also, after selecting two rows, on selection of third row it should throw an error.</p>
<p>How can I simplify this code?</p>
<pre><code>onSelectionChange: function(oEvent) {
var aIndex = [];
var k = 0;
var z = 0;
var sItem;
var sContext;
var vMatched;
if (oEvent.getParameters().listItems[0].getSelected() === true) {
if (oEvent.getParameters().selectAll === true) {
for (var a = 0; a < this.getView().byId("monTable").getItems().length; a++) {
aIndex.push(a);
}
} else {
for (k = 0; k < this.getView().byId("monTable").getItems().length; k++) {
sItem = this.getView().byId("monTable").getItems()[k].getBindingContext().sPath;
for (z = 0; z < this.getView().byId("monTable").getSelectedContextPaths().length; z++) {
sContext = this.getView().byId("monTable").getSelectedContextPaths()[z];
if (sItem === sContext) {
aIndex.push(k);
}
}
}
}
} else {
for (k = 0; k < this.getView().byId("monTable").getItems().length; k++) {
sItem = this.getView().byId("monTable").getItems()[k].getBindingContext().sPath;
for (z = 0; z < this.getView().byId("monTable").getSelectedContextPaths().length; z++) {
sContext = this.getView().byId("monTable").getSelectedContextPaths()[z];
if (sItem) {
vMatched = k;
}
}
}
if (oEvent.getParameters().selectAll === false && this.getView().byId("monTable").getSelectedContextPaths().length === 0) {
aIndex.splice(0, aIndex.length);
} else {
for (var j = 0; j < aIndex.length; j++) {
if (aIndex[j] === vMatched) {
aIndex.splice(j, 1);
}
}
}
}
var maxValue = aIndex[0];
var minValue = aIndex[0];
for (var i = 0; i < aIndex.length; i++) {
if (aIndex[i] > maxValue) {
maxValue = aIndex[i];
}
if (aIndex[i] < minValue) {
minValue = aIndex[i];
}
}
if (maxValue - minValue > 1) {
if (aIndex.length > 2 && aIndex.length !== this.getView().byId("monTable").getItems().length) {
for (var y = minValue; y <= maxValue; y++) {
if (this.getView().byId("monTable").getItems()[y].getSelected() === false) {
var sText = this.getOwnerComponent().getModel("i18n").getResourceBundle().getText("msgTxtgapSelection");
var sTitle = this.getOwnerComponent().getModel("i18n").getResourceBundle().getText("msgTitleInf");
this.dynamicNoneMessage(sText, sTitle);
//MessageBox.show("Bitte wählen Sie eine Folge ohne Lücken");
}
}
} else {
for (var m = minValue; m <= maxValue; m++) {
this.getView().byId("monTable").getItems()[m].setSelected(true);
}
}
}
}<span class="math-container">`</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T11:46:45.707",
"Id": "442965",
"Score": "1",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask) for examples, and revise the title accordingly."
}
] |
[
{
"body": "<p>Easiest thing you can do is properly name your variables and add comments.</p>\n\n<p>Seeing things like this is very frustrating:</p>\n\n<pre><code>aIndex.push(k);\nvMatched = k;\n</code></pre>\n\n<p>It's completely meaningless except to the developer who wrote it. It's a form of hungarian notation, except nothing is preventing you from making <code>aIndex</code> a String instead of an Array or <code>vMatched</code> and array instead of a var. (I'm assuming <code>v</code> is for var, which is also a hint this naming style isn't going to work here).</p>\n\n<p>I'd expect for-loops to start using <code>i</code> not <code>k</code>. No need to declare it at the top either. You should always declare variables in the most local scope.</p>\n\n<p>Here you're adding the numbers <code>0-a</code> onto a list. You don't need to do that since you already have <code>a</code>. If you need to store the length at that time, you can.</p>\n\n<pre><code>for (var a = 0; a < this.getView().byId(\"monTable\").getItems().length; a++) {\n aIndex.push(a);\n}\n</code></pre>\n\n<p>In your nested loops it looks like you are getting the indexes that match based on a criteria. You should really do this in a method, hopefully with comments to make it easier to read. You can use lambdas expressions if you're comfortable with them. However without better context I cannot provide a concrete alternative.</p>\n\n<p>You should use a method for getting the min/max amounts from an array. Methods make everything easier to read & easier to refactor.</p>\n\n<p>You can use <code>Arrays.sort()</code> then take the first / last item of the array to get the min/max.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T12:27:12.820",
"Id": "227508",
"ParentId": "227506",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227508",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T10:37:46.900",
"Id": "227506",
"Score": "1",
"Tags": [
"javascript",
"event-handling",
"dom",
"cyclomatic-complexity"
],
"Title": "Automatically select the table rows between two selected rows"
}
|
227506
|
<p>I have a data file and a rules file. First column of rules file will have columns from the data file and the second column has an pandas operation which has to be performed on the respective Column. Please refer below details:</p>
<p>This is the input data:</p>
<pre><code>d={'Name': ['Ankan', 'Shiv', nan, 'Sandeep'],
'email': ['ankan@domain.com', 'shiv.com', 'something@someting.com', 'sandeep@domain.com'],
'Street 1': ['Street Name 1', 'Street name 2', 'Street name 3', nan],
'LastName': [nan, nan, 'LastName1', 'LastName2'],
'Outlet_Code': ['123abc', nan, 12345, 'bca12']}
df= pd.DataFrame(d)
</code></pre>
<hr>
<p>Which looks like:</p>
<pre><code> Name email Street 1 LastName Outlet_Code
0 Ankan ankan@domain.com Street Name 1 NaN 123abc
1 Shiv shiv.com Street name 2 NaN NaN
2 NaN something@someting.com Street name 3 LastName1 12345
3 Sandeep sandeep@domain.com NaN LastName2 bca12
</code></pre>
<p>Now the rules file:</p>
<pre><code>d1={'Column_Name': ['Name', 'LastName'], 'Rule': ['.isna()', '.isna()']}
file_rules=pd.DataFrame(d1)
</code></pre>
<hr>
<pre><code> Column_Name Rule
0 Name .isna()
1 LastName .isna()
</code></pre>
<p>I am trying to flag the cells in excel where the condition matches per column name. I have a working code which is :</p>
<pre><code>m=df.eval([f'{a}{b}' for a,b in zip(file_rules['Column_Name'],file_rules['Rule'])])
cond=pd.DataFrame(m,index=file_rules['Column_Name'].to_numpy()).T
</code></pre>
<hr>
<pre><code>def dummy_color(x):
c1='background-color:red'
c2=''
df1 = pd.DataFrame(np.where(cond,c1,c2),columns=x.columns,index=x.index)
return df1
df.style.apply(dummy_color,axis=None,subset=file_rules.Column_Name)
</code></pre>
<hr>
<p>Output:
<a href="https://i.stack.imgur.com/kjv7Q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kjv7Q.png" alt="enter image description here"></a></p>
<p>I want to know if there is any better way of doing this,(since this would be handled by someone else)? Can I do this without <code>df.eval()</code>? Kindly suggest.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T15:27:18.063",
"Id": "442988",
"Score": "1",
"body": "How complex can the content of `Rule` be? Are there only a few supported rules, or should it be as free as possible? Can you combine multiple operations?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T15:34:18.270",
"Id": "442991",
"Score": "0",
"body": "@Graipher Thanks for taking a look, the rules can be a regex for example for checking valid email address , also there can be maximum 2 rules combined with an `&` , where both would be pandas standard `str` accessors, except the regex. Please let me know if you have any questions :)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T14:57:27.890",
"Id": "227511",
"Score": "4",
"Tags": [
"python",
"pandas"
],
"Title": "Data profiling in a dataframe based on an input file-pandas"
}
|
227511
|
<p>My company wants me to build a serverless component (AWS Lambda) that checks every minute for our system components health.</p>
<p>The data model (classes structure) I have devised so far is as pasted below.
The main problem I am trying to address is I wanted to have a collection of all our system metrics. At first I thought of having <code>clsMetric<T></code> where <code>T</code> would determine the type of <code>Value</code> and <code>Threshold</code> properties. But I can't have a collection of a generic class (at least not a generic collection of generic classes).</p>
<p>So I ended up creating subclasses of <code>clsMetric</code> for each metric value type I have, and left in the parent class a string representation of those properties for accessing them while looping over my collection of <code>clsMetric</code>.</p>
<p>Is this the way to go ? Current C# capabilities offer something else I do not know? Any design pattern suitable to apply here I am not aware of ?</p>
<pre><code>public abstract class clsMetric
{
public string Name { get; }
public abstract string ValueAsStr { get; }
public abstract eLogicalOperator LogicalOperator { get; }
public abstract string ThresholdAsStr { get; }
public abstract bool Faulty();
public clsMetric(string name)
{
Name = name ?? string.Empty;
}
public override string ToString()
{
return Name;
}
}
public class IntegerMetric : clsMetric
{
eLogicalOperator _logicalOperator;
#region Properties
public int Value { get; private set; }
public override string ValueAsStr => Value.ToString();
public override eLogicalOperator LogicalOperator => _logicalOperator;
public int Threshold { get; private set; }
public override string ThresholdAsStr => Threshold.ToString();
#endregion
#region Constructors
public IntegerMetric(string name, int value, eLogicalOperator logicalOperator, int threshold) : base(name)
{
Value = value;
_logicalOperator = logicalOperator;
Threshold = threshold;
}
public override bool Faulty()
{
if (LogicalOperator == eLogicalOperator.Equal)
return Value == Threshold;
else if (LogicalOperator == eLogicalOperator.GreaterOrEqualThan)
return Value >= Threshold;
else if (LogicalOperator == eLogicalOperator.GreaterThan)
return Value > Threshold;
else if (LogicalOperator == eLogicalOperator.LowerOrEqualThan)
return Value <= Threshold;
else if (LogicalOperator == eLogicalOperator.LowerThan)
return Value < Threshold;
return false;
}
#endregion
}
public class StringMetric : clsMetric
{
eLogicalOperator _logicalOperator;
#region Properties
public string Value { get; private set; }
public override string ValueAsStr => Value.ToString();
public override eLogicalOperator LogicalOperator => _logicalOperator;
public string Threshold { get; private set; }
public override string ThresholdAsStr => Threshold.ToString();
#endregion
#region Constructors
public StringMetric(string name, string value, eLogicalOperator logicalOperator, string threshold) : base(name)
{
Value = value;
_logicalOperator = logicalOperator;
Threshold = threshold;
}
public override bool Faulty()
{
if (LogicalOperator == eLogicalOperator.Equal)
return string.Equals(Value, Threshold);
else if (LogicalOperator == eLogicalOperator.Contains)
return ValueAsStr.Contains(ThresholdAsStr, StringComparison.InvariantCultureIgnoreCase);
return false;
}
#endregion
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T16:25:53.213",
"Id": "442996",
"Score": "2",
"body": "Where did you get this naming convention from? This is so old school."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T16:28:03.220",
"Id": "442998",
"Score": "1",
"body": "I'm voting-to-close this question for the lack of context. We need to see how you use this code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T11:45:34.900",
"Id": "443430",
"Score": "0",
"body": "@t3chb0t There are still companies using conventions from 25 years ago and even books sold teaching them, unfortunately. Considering this question has been answered now, closing isn't helpful. OP should however take your advice for next time."
}
] |
[
{
"body": "<p>A design pattern often used, is to have a non generic base type and a generic type derived from it or a type implementing a non generic as well as a generic interface. An example is</p>\n\n<pre><code>public abstract class Comparer<T> :\n System.Collections.Generic.IComparer<T>, System.Collections.IComparer\n</code></pre>\n\n<p>You can see the full implementation here <a href=\"https://referencesource.microsoft.com/#mscorlib/system/collections/generic/comparer.cs\" rel=\"nofollow noreferrer\"><code>public abstract class Comparer<T> : IComparer, IComparer<T></code></a>.</p>\n\n<p>You can see that it does an explicit implementaion of <code>IComparer</code> members and an implicit implementation of <code>IComparer<T></code>. This hides the <code>IComparer</code> members when not accessed through this very interface. Original code:</p>\n\n<pre><code>public abstract int Compare(T x, T y);\n\nint IComparer.Compare(object x, object y) {\n if (x == null) return y == null ? 0 : -1;\n if (y == null) return 1;\n if (x is T && y is T) return Compare((T)x, (T)y);\n ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArgumentForComparison);\n return 0;\n}\n</code></pre>\n\n<p>A possible approach for your metric class, would be to implement two interfaces <code>IMetric</code> and <code>IMetric<T></code>. The collection would then have an element type of <code>IMetric</code>.</p>\n\n<pre><code>public interface IMetric\n{\n string Name { get; }\n object Value { get; }\n eLogicalOperator LogicalOperator { get; }\n object Threshold { get; }\n bool Faulty();\n}\n\npublic interface IMetric<out T> : IMetric\n{\n new T Value { get; }\n new T Threshold { get; }\n}\n</code></pre>\n\n<p>Implementation:</p>\n\n<pre><code>public class Metric<T> : IMetric<T>\n{\n public Metric(string name, eLogicalOperator logicalOperator, T value, T threshold)\n {\n Name = name ?? String.Empty;\n LogicalOperator = logicalOperator;\n Value = value;\n Threshold = threshold;\n }\n\n public T Value { get; }\n public T Threshold { get; }\n\n object IMetric.Value => Value;\n object IMetric.Threshold => Threshold;\n\n public string Name { get; }\n public eLogicalOperator LogicalOperator { get; }\n\n public bool Faulty()\n {\n //TODO: implement;\n }\n}\n</code></pre>\n\n<p>I don't know, however, how you would implement the <code>Faulty</code> method in a generic way. Maybe you could inject the logic and use a factory method to create metric objects.</p>\n\n<p>Probably a better approach is to create an abstract <code>Metric<T></code> class having only the <code>Faulty</code> method abstract to be able to implement specialized variants.</p>\n\n<pre><code>public class DecimalMetric : IMetric<decimal>\n</code></pre>\n\n<p>Yet another, elegant possibility is to pass a delegate doing the comparison, instead of the operator enum.</p>\n\n<pre><code>public Metric(string name, T value, T threshold, Func<T,T,bool> isValid)\n</code></pre>\n\n<p>This allows you to provide a type specific comparison and saves you a complex processing for different operators. I prefer to ask the positive question \"is valid\". It feels better than specifying what is wrong. You can call it like this</p>\n\n<pre><code>new Metric<int>(\"int test\", 5, 10, (v, threshold) => v < threshold)\n</code></pre>\n\n<p>Usage (still with you original constructor):</p>\n\n<pre><code>var list = new List<IMetric>();\nlist.Add(new Metric<int>(\"int\", eLogicalOperator.LowerThan, 5, 10));\nlist.Add(new Metric<double>(\"double\", eLogicalOperator.LowerThan, 2.45, 10.0));\n\nobject value = list[0].Value;\n\nswitch (list[0]) {\n case Metric<int> intMetric:\n int i = intMetric.Value;\n break;\n case Metric<double> doubleMetric:\n double d = doubleMetric.Value;\n break;\n default:\n break;\n}\n\n// or\n\nswitch (list[0].Value) { // of type object\n case int i:\n int myInt = i;\n break;\n case double d:\n double myDouble = d;\n break;\n default:\n break;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T07:53:32.640",
"Id": "443323",
"Score": "0",
"body": "Thanks. My initial design indeed had a Precidate<T> Property as a member of the Metric class, but I need to explicitly know both the operator and the \"threshold\" value for reporting purposes, so I gave up the Predicate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T11:46:59.230",
"Id": "443334",
"Score": "0",
"body": "Does this design scenario constitute a formal known design pattern I can search and learn more ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T12:36:04.987",
"Id": "443338",
"Score": "0",
"body": "It's not a named (and known) design pattern, but it is used at different places in the .NET Framework library. [public interface IEnumerable<out T> : System.Collections.IEnumerable](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.ienumerable-1?view=netframework-4.8) is a very prominent use case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T12:39:21.430",
"Id": "443339",
"Score": "1",
"body": "Thanks a lot for sharing your time and knowledge here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T12:44:56.483",
"Id": "443340",
"Score": "0",
"body": "You are welcome."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T15:49:51.130",
"Id": "227517",
"ParentId": "227514",
"Score": "5"
}
},
{
"body": "<p>I just have a couple of minor points to add to <a href=\"/a/227517\">Olivier Jacot-Descombes' excellent answer</a>.</p>\n\n<blockquote>\n<pre><code> public override bool Faulty()\n {\n if (LogicalOperator == eLogicalOperator.Equal)\n return Value == Threshold;\n else if (LogicalOperator == eLogicalOperator.GreaterOrEqualThan)\n return Value >= Threshold;\n else if (LogicalOperator == eLogicalOperator.GreaterThan)\n return Value > Threshold;\n else if (LogicalOperator == eLogicalOperator.LowerOrEqualThan)\n return Value <= Threshold;\n else if (LogicalOperator == eLogicalOperator.LowerThan)\n return Value < Threshold;\n\n return false;\n }\n</code></pre>\n</blockquote>\n\n<p>Enums support <code>switch</code>, and I don't think you'll find many people who claim that a chain of <code>if</code>/<code>else</code> is better style than a <code>switch</code>.</p>\n\n<p>Also, most of the comparisons are fairly generic, in the sense that if you choose to follow Olivier's suggestion about a base non-generic class/interface and a generic implementation but not the suggestion about passing a delegate, it could have a base implementation using <code>Comparer<T>.Default()</code>:</p>\n\n<pre><code>public class Metric<T> : IMetric<T>\n{\n private static readonly IComparer<T> Comparer = Comparer<T>.Default;\n\n ...\n\n public T Value { get; }\n public T Threshold { get; }\n public eLogicalOperator LogicalOperator { get; }\n\n public virtual bool Faulty()\n {\n switch (LogicalOperator)\n {\n case eLogicalOperator.Equal:\n return Comparer.Compare(Value, Threshold) == 0;\n case eLogicalOperator.GreaterOrEqualThan:\n return Compare.Compare(Value, Threshold) >= 0;\n case eLogicalOperator.GreaterThan:\n return Comparer.Compare(Value, Threshold) > 0;\n case eLogicalOperator.LowerOrEqualThan:\n return Comparer.Compare(Value, Threshold) <= 0;\n case eLogicalOperator.LowerThan:\n return Comparer.Compare(Value, Threshold) < 0;\n default:\n throw new NotSupportedException($\"Operator {LogicalOperator} is not supported for {typeof(T)}\");\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T18:33:30.177",
"Id": "443163",
"Score": "0",
"body": "Now we can take this a step further and make this an extension method _public static bool Evaluate<T>(this IComparer<T> comparer, LogicalOperator operator, T operand1, T operand2)_ to me, this feels even more appropriate than an instance method of _Metric_"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T21:12:31.480",
"Id": "443177",
"Score": "0",
"body": "@dfhwze, no, although I goofed by missing `virtual`. E.g. `StringMetric` will want to override to add support for `eLogicalOperator.Contains`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T18:25:33.013",
"Id": "227594",
"ParentId": "227514",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "227517",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T15:03:19.187",
"Id": "227514",
"Score": "2",
"Tags": [
"c#",
"object-oriented",
"inheritance",
"status-monitoring"
],
"Title": "C# classes for system health metrics"
}
|
227514
|
<p>This is the first application or really any Scala I have every written. So far it functions as I would hope it would. I just found this community and would love some peer review of possible improvements or just tell me flat out what I'm doing wrong. </p>
<p>This code is supposed to read a table of tables then take all of the values from that table transpose the columns into rows and write them all to a master table with three additional columns. So far it does everything except the looping which I just haven't gotten to yet. This question is not about how to do the looping and really only hoping to critique what I have here so far. I did change some variable names and a few things I had to mask.</p>
<pre><code>//how to call
//spark-submit --verbose --deploy-mode cluster --master yarn --class App scala-maven-0.1-SNAPSHOT.jar
import org.apache.spark.sql.{ SQLContext, SparkSession }
import org.apache.spark.sql._
import org.apache.spark.sql.types._
import org.apache.spark.sql.functions._
import java.util.Calendar
//this will call createStuff function for each table_name value in table
//TODO: Add loop and call CreateStuff with values from list returned from stuff_to_run
object App {
def main(args: Array[String]) {
//do I have to create the SparkSession value twice or can I pass this into the function?
val spark = SparkSession.builder().appName("App").enableHiveSupport().getOrCreate()
val stuff_to_run = spark.sql("select table_name from schema.table").rdd.map(r => r(0)).collect.toList
println(stuff_to_run)
CreateStuff("stuff");
}
def CreateStuff(stuffName: String): Unit = {
var tablename = stuffName
var column_stack = ""
val spark = SparkSession.builder().appName("App").enableHiveSupport().getOrCreate()
//is there a better way to get year and month
val Year = Calendar.getInstance.get(Calendar.YEAR)
val Month = Calendar.getInstance.get(Calendar.MONTH) + 1
val twodigitmonth = "%02d".format(Month)
val yrmnth = Year.toString + twodigitmonth.toString
//get all of the data from the base table
val raw_table = spark.sql("select *, '" + tablename + "' as stuffname, '" + yrmnth + "' as yrmnth from schema." + tablename)
//transpose all columns into rows
val string_table = raw_table.select(raw_table.columns.map(c => col(c).cast(StringType)): _*)
//get column besides 3 defined these are the only ones which are not dynamic
val selectColumns2 = string_table.columns.toSeq.filter(x => (x != "val1" && x != "stuffname" && x != "yrmnth"))
val columnCount = selectColumns2.size
//comma and quote
selectColumns2.foreach { e =>
column_stack += "'" + e + "', " + e + ", "
}
val collist = column_stack.mkString("").dropRight(1)
import spark.sqlContext.implicits._
val unPivotDF = string_table.select($"val1", $"stuffname", $"yrmnth",
expr("stack(" + selectColumns2.size + ", " + collist.dropRight(1) + ") as (fieldname, fieldvalue)"))
//unPivotDF.show()
//insert records into combined table
unPivotDF.createOrReplaceTempView("stuff_temp")
spark.sql("insert into schema.combined_stuff select * from stuff_temp")
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Immediately I'd ask if there's any specific style guide that allows\nthese vastly different names, otherwise I'd suggest following IDE hints\nand/or a linter and rename the variables and methods to be more\nconsistent (e.g. <code>[cC]amelCase</code> for everything).</p>\n\n<p>Also, \"stuff\" is not a great name for anything ... what stuff are we\ntalking about? In fact the first line of <code>CreateStuff</code> already shows\nthat there's a better name, <code>tableName</code> for the parameter, probably\n<code>createTable</code> for the method. <code>yrmnth</code> is especially bad too, three\nvowels saved from <code>yearMonth</code> and in the process made the name\nunreadable for the casual observer.</p>\n\n<p>Seems like the spark session is created twice and the comment even says\nso - I'd suggest passing the variable into the method, that's fairly\nstraightforward by either passing it as a parameter, or extending <code>App</code>\nwith a member variable.</p>\n\n<p>The SQL queries are created by concatenating strings and there's usually\nbetter ways, here probably a query builder.</p>\n\n<p><code>columnCount</code> is unused, <code>selectColumns2</code> has <code>2</code> as the suffix, even\nthough there's no <code>1</code>, that can just be <code>selectColumns</code>.</p>\n\n<p>The loop for <code>columnStack</code> could be in its own method so it's a little\nsmall section that could be tested on its own too, returning what is now\n<code>collist</code>, <code>formatColumnsList(columns: Seq[String]): String</code> perhaps.\nAgain, if a query builder could do all this it would be a bit cleaner\nthan concatenating strings.</p>\n\n<p>The construction for <code>yrmnth</code> is pretty convoluted for what it does, I'd\nsuggest finding a more succinct approach, e.g.</p>\n\n<pre><code>val yearMonth = DateTimeFormatter.ofPattern(\"yyyyMM\").format(LocalDateTime.now())\n</code></pre>\n\n<p>That would require a recent Java for <code>java.time.LocalDateTime</code> and\n<code>java.time.format.DateTimeFormatter</code>. But even without there should be\nbetter ways. If everything fails the whole section should at least be\nin its own method, e.g. <code>formatDate(calendar Calendar): String</code>.</p>\n\n<p>The bottom part of <code>unPivotDF</code> uses a temporary table - is that the best\nway to go, or could the data be inserted directly?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T14:58:05.793",
"Id": "227665",
"ParentId": "227516",
"Score": "1"
}
},
{
"body": "<p><code>tablename</code> doesn't need to be a <code>var</code>, it's never mutated, and it appears to be totally unneeded. Use the method's passed parameter directly.</p>\n\n<p><code>column_stack</code> is also unneeded. You can go directly from <code>selectColumns2</code> to <code>collist</code> without an intermediate variable or <code>dropRight()</code> adjustments.</p>\n\n<pre><code>val collist = selectColumns2.flatMap(e => Seq(s\"'$e'\",e)).mkString(\", \")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T00:16:51.430",
"Id": "227749",
"ParentId": "227516",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T15:19:20.620",
"Id": "227516",
"Score": "2",
"Tags": [
"beginner",
"scala",
"apache-spark"
],
"Title": "Scala app to transpose columns into rows"
}
|
227516
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.