body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>Assuming I have the following slice:</p>
<pre><code>mySlice := []string{"one", "two", "three"}
</code></pre>
<p>and I want to know whether or not it contains a given string, say <code>"three"</code>.</p>
<p>I could iterate over each entry:</p>
<pre><code>for i, v := range mySlice {
if v == "three" {
return i
}
}
</code></pre>
<p>But I could also convert the slice to a map:</p>
<pre><code>myMap := make(map[string]string)
for i, v := range mySlice {
myMap[v] = i
}
if v, ok := myMap["three"]; ok {
// three exists in original slice
}
</code></pre>
<p>I think that the first is faster than the second for a single lookup, but at what point does the second method become faster? Would converting to a map be more performant if I'm doing 2 or more lookups? Or does it depend on the size of the array?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T09:28:35.303",
"Id": "444979",
"Score": "0",
"body": "please see https://forum.golangbridge.org/t/how-about-performance-of-map-against-slice/4415"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T16:02:37.860",
"Id": "227518",
"Score": "1",
"Tags": [
"performance",
"comparative-review",
"go",
"hash-map"
],
"Title": "Checking for a values existence: slice iteration vs map lookups in Go"
}
|
227518
|
<p>(There is a follow-up question available to this: <a href="https://codereview.stackexchange.com/questions/227633/fast-algorithms-in-javascript-for-shortest-path-queries-in-directed-unweighted-g">Follow-Up Question</a>)</p>
<p>So I have this:</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-html lang-html prettyprint-override"><code><html>
<body>
<div id="output">
</div>
<script>
function NodeSet() {
this.array = [];
}
NodeSet.prototype.clear = function() {
this.array = [];
}
NodeSet.prototype.add = function(node) {
this.array[node.id] = node;
}
NodeSet.prototype.includes = function(node) {
return this.array[node.id] !== undefined;
}
NodeSet.prototype.size = function() {
return this.array.length;
}
function Node(id) {
this.id = id;
this.children = [];
this.parents = [];
}
Node.prototype.toString = function() {
return "[Node " + this.id + "]";
}
function nodeEq(nodeA, nodeB) {
return nodeA.id === nodeB.id;
}
function connect(tail, head) {
tail.children.push(head);
head.parents.push(tail);
}
function BuildPath(s, mu, B) {
let pi = FindShortestPath(s, mu);
pi.splice(-1, 1);
pi.push(...B);
return pi;
}
function DepthLimitedSearchForward(u, Delta, F) {
if (Delta === 0) {
F.add(u);
return;
}
u.children.forEach(function(child) {
DepthLimitedSearchForward(child, Delta - 1, F);
});
}
function DepthLimitedSearchBackward(u, Delta, B, F) {
B.unshift(u);
if (Delta === 0) {
if (F.includes(u)) {
return u;
}
B.shift();
return null;
}
for (var i = 0; i !== u.parents.length; i++) {
let parent = u.parents[i];
let mu = DepthLimitedSearchBackward(parent, Delta - 1, B , F);
if (mu !== null) {
return mu;
}
}
B.shift();
return null;
}
function FindShortestPath(s, t) {
if (s.id === t.id) {
return [s];
}
let F = new NodeSet();
let B = [];
let Delta = 0;
while (true) {
DepthLimitedSearchForward(s, Delta, F);
for (var i = 0; i < 2; i++) {
let mu = DepthLimitedSearchBackward(t,
Delta + i,
B,
F);
if (mu !== null) {
return BuildPath(s, mu, B);
}
B = [];
}
F.clear();
Delta++;
}
}
function DequeNode(elem) {
this.next = undefined;
this.elem = elem;
}
function Deque() {
this.head = undefined;
this.tail = undefined;
this.size = 0;
}
Deque.prototype.shift = function() {
let ret = this.head.elem;
this.head = this.head.next;
this.size--;
return ret;
}
Deque.prototype.push = function(elem) {
let newNode = new DequeNode(elem);
if (this.head) {
this.tail.next = newNode;
} else {
this.head = newNode;
}
this.size++;
this.tail = newNode;
}
Deque.prototype.length = function() {
return this.size;
}
Deque.prototype.front = function() {
return this.head.elem;
}
let NULL = "NULL";
function tracebackPath(touchNode, parentsA, parentsB) {
let path = [];
let current = touchNode;
while (current != NULL) {
path.push(current);
current = parentsA.get(current);
}
path.reverse();
current = parentsB.get(touchNode);
while (current != NULL) {
path.push(current);
current = parentsB.get(current);
}
return path;
}
function NodeMap() {
this.array = [];
}
NodeMap.prototype.put = function(key, value) {
this.array[key.id] = value;
}
NodeMap.prototype.get = function(key) {
return this.array[key.id];
}
NodeMap.prototype.containsKey = function(key) {
return this.array[key.id] !== undefined;
}
function FindShortestPathWithBiBFS(s, t) {
let queueA = new Deque();
let queueB = new Deque();
let parentsA = new NodeMap();
let parentsB = new NodeMap();
let distanceA = new NodeMap();
let distanceB = new NodeMap();
queueA.push(s);
queueB.push(t);
parentsA.put(s, NULL);
parentsB.put(t, NULL);
distanceA.put(s, 0);
distanceB.put(t, 0);
let bestCost = 1000 * 1000 * 1000;
let touchNode = undefined;
while (queueA.length() > 0 && queueB.length() > 0) {
let distA = distanceA.get(queueA.front());
let distB = distanceB.get(queueB.front());
if (touchNode && bestCost < distA + distB) {
return tracebackPath(touchNode,
parentsA,
parentsB);
}
if (distA < distB) {
let current = queueA.shift();
if (distanceB.containsKey(current)
&&
bestCost > distA + distB) {
bestCost = distA + distB;
touchNode = current;
}
for (let i = 0; i < current.children.length; i++) {
let child = current.children[i];
if (!distanceA.containsKey(child)) {
distanceA.put(child, distanceA.get(current) + 1);
parentsA.put(child, current);
queueA.push(child);
}
}
} else {
let current = queueB.shift();
if (distanceA.containsKey(current)
&&
bestCost > distA + distB) {
bestCost = distA + distB;
touchNode = current;
}
for (let i = 0; i < current.parents.length; i++) {
let parent = current.parents[i];
if (!distanceB.containsKey(parent)) {
distanceB.put(parent, distanceB.get(current) + 1);
parentsB.put(parent, current);
queueB.push(parent);
}
}
}
}
return [];
}
let outputDiv = document.getElementById("output");
let graph = [];
const NODES = 100000;
const ARCS = 500000;
for (var id = 0; id < NODES; id++) {
graph.push(new Node(id));
}
for (var i = 0; i < ARCS; i++) {
let tailIndex = Math.floor(Math.random() * NODES);
let headIndex = Math.floor(Math.random() * NODES);
connect(graph[tailIndex], graph[headIndex]);
}
let sourceIndex = Math.floor(Math.random() * NODES);
let targetIndex = Math.floor(Math.random() * NODES);
let sourceNode = graph[sourceIndex];
let targetNode = graph[targetIndex];
console.log("Source node: " + sourceNode);
console.log("Target node: " + targetNode);
outputDiv.innerHTML += "Source node: " + sourceNode + "<br>" +
"Target node: " + targetNode;
outputDiv.innerHTML += "<br>BIDDFS:<br>";
var startTime = new Date().getMilliseconds();
var path = FindShortestPath(sourceNode, targetNode);
var endTime = new Date().getMilliseconds();
var num = 1;
for (var i = 0; i < path.length; i++) {
let node = path[i];
outputDiv.innerHTML += "<br>" + num + ": " + node;
console.log(num++ + ": " + node);
}
let duration = endTime - startTime;
console.log("Duration: " + duration + " ms.");
outputDiv.innerHTML += "<br>Duration: " + duration + " ms.";
outputDiv.innerHTML += "<br><br>Bidirectional BFS:";
startTime = new Date().getMilliseconds();
var path2 = FindShortestPathWithBiBFS(sourceNode, targetNode);
endTime = new Date().getMilliseconds();
duration = endTime - startTime;
num = 1;
for (var i = 0; i < path2.length; i++) {
let node = path2[i];
outputDiv.innerHTML += "<br>" + num + ": " + node;
console.log(num++ + ": " + node);
}
console.log("Duration: " + (endTime - startTime) + " ms.");
outputDiv.innerHTML += "<br>Duration: " + duration + " ms.";
</script>
</body>
</html></code></pre>
</div>
</div>
</p>
<p><strong>Critique request</strong></p>
<p>Could you please tell me how to improve my code in any way?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T16:05:31.090",
"Id": "227519",
"Score": "3",
"Tags": [
"javascript",
"algorithm",
"pathfinding"
],
"Title": "Fast algorithms in Javascript for shortest path queries in directed unweighted graphs"
}
|
227519
|
<p>The below code was written to generate <a href="https://en.wikipedia.org/wiki/Euler%E2%80%93Mascheroni_constant" rel="nofollow noreferrer">γ</a>, for educational purposes.</p>
<p>Single threaded, no functional zeroes required, no binary splitting(which can all be used to compute competitively like y-cruncher, that version in works).
Uses the Arithmetic Geometric Mean to calculate large logarithms quickly.
Uses decimal module for precision management. </p>
<p>I've computed 3000 digits in a few hours with it, and 200 in about a minute. I am happy calculating.</p>
<pre><code>import decimal
D = decimal.Decimal
def agm(a, b): #Arithmetic Geometric Mean
a, b = D(a),D(b)
for x in range(prec):
a, b = (a + b) / 2, (a * b).sqrt()
return a
def pi_agm(): #Pi via AGM and lemniscate
a, b, t, p, pi, k = 1, D(2).sqrt()/2, 1/D(2), 2, 0, 0
while 1:
an = (a + b) / 2
b = (a * b).sqrt()
t -= p * (a - an)**2
a, p = an, 2**(k+2)
piold = pi
pi = (a + b) * (a + b) / (2*t)
k += 1
if pi == piold:
break
return pi
def factorial(x): #factorial fast loop
x = int(x)
factorial = D(1)
for i in range(1, x+1):
factorial *= i
return factorial
def lntwo(): #Fast converging Ln 2
logsum, logold, n = D(0), D(0), 0
while 1:
logold = logsum
logsum += D(1/((D(961**n))*((2*n)+1)))
n += 1
if logsum == logold:
logsum1 = (D(14)/D(31))*logsum
break
logsum, logold, n = D(0), D(0), 0
while 1:
logold = logsum
logsum += D(1/((D(25921**n))*((2*n)+1)))
n += 1
if logsum == logold:
logsum2 = (D(6)/D(161))*logsum
break
logsum, logold, n = D(0), D(0), 0
while 1:
logold = logsum
logsum += D(1/((D(2401**n))*((2*n)+1)))
n += 1
if logsum == logold:
logsum3 = (D(10)/D(49))*logsum
break
ln2 = logsum1 + logsum2 + logsum3
return ln2
def lnagm(x): #Natural log via AGM,
try:
if int(x) == 1:
return 0
if int(x) == 2:
return lntwo()
except:
pass
m = prec*2
ln2 = lntwo()
decimal.getcontext().prec = m
pi = D(pi_agm())
twoprec = D(2**(2-D(m)))/D(x)
den = agm(1, twoprec)*2
diff = m*ln2
result = (D(pi/den) - D(diff))
logr = D(str(result)[:m//2])
decimal.getcontext().prec = prec
return logr
def gamma(): #Compute Gamma from Digamma Expansion
print('Computing Gamma!')
k = D(prec/2)
print('Calculating Logarithms...')
lnk = lnagm(k)
logsum = D(0)
upper = int((12*k)+2)
print('Summing...')
for r in range(1, upper):
logsum += D((D(-1)**D(r-1))*D(k**D(r+1)))/D(factorial(r-1)*D(r+1))
if r%1000==0:
print(str((D(r)/D(upper))*100)[:5], '% ; Sum 1 of 2')
logsum1 = D(0)
print('...')
for r in range(1, upper):
logsum1 += D((D(-1)**D(r-1))*(k**D(r+1)))/D(factorial(r-1)*D(D(r+1)**2))
if r%1000==0:
print(str((D(r)/D(upper))*100)[:5], '% ; Sum 2 of 2')
twofac = D(2)**(-k)
gammac = str(D(1)-(lnk*logsum)+logsum1+twofac)
return D(gammac[:int(prec//6.66)])
#Calling Gamma
prec = int(input('Precision for Gamma: '))*8
decimal.getcontext().prec = prec
gam = gamma()
print(gam)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T16:35:31.043",
"Id": "443000",
"Score": "0",
"body": "From purely mathematical point of view, you might be interested in [this post](https://math.stackexchange.com/q/129777/269624), which has a collection of different algorithms for this constant"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T16:41:03.273",
"Id": "443002",
"Score": "0",
"body": "That is excellent, thank you! I need to learn to write latex. The top answer is indeed the algorithm I wrote here :) I believe the only way I can go faster, is to use the algorithm involving a(log(a)-1)=1 and binary splitting.(ignoring its python)."
}
] |
[
{
"body": "<ul>\n<li><p>Computation of <code>logsum</code> and <code>logsum1</code> in <code>gamma()</code> are suboptimal. You do costly operations of raising to power, and recompute factorial on each iteration (the latter invokes the quadratic time complexity BTW). Notice that in the <span class=\"math-container\">\\$\\sum \\dfrac{(-1)^{r-1} k^{r+1}}{(r+1)(r-1)!}\\$</span> a consecutive term can be expressed via the previous one, as<span class=\"math-container\">\\$T_{r+1} = -k\\dfrac{r+1}{(r+2)r} T_n\\$</span>. Instead of computing each term from scratch, use this recurrence, and enjoy a significant performance boost.</p>\n\n<p>Converting the summation into a <a href=\"https://en.wikipedia.org/wiki/Horner%27s_method\" rel=\"noreferrer\">Horner schema</a> would likely improve the accuracy, that is to achieve the desired number of digits you'd need less number of terms.</p></li>\n<li><p>Tree loops in <code>lntwo</code> cry to become a function.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T17:04:57.033",
"Id": "443016",
"Score": "0",
"body": "Thank you! I will implement everything you have said. However I believe using the recurrence and/or the Horner schema will prevent me from multi-threading in the future, just as an FYI to readers."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T16:40:12.320",
"Id": "227523",
"ParentId": "227520",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "227523",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T16:12:19.170",
"Id": "227520",
"Score": "4",
"Tags": [
"python",
"performance",
"python-3.x",
"mathematics",
"numerical-methods"
],
"Title": "Calculate the Euler-Mascheroni constant without the math module"
}
|
227520
|
<p>I'm creating a 2D game in JS, and I've made the generic class that all objects in the game will be (I've decided they are all circular for now).</p>
<p>An object has <code>motion</code> and <code>angMotion</code> <code>array</code> properties which contain the 0th, 1st and 2nd derivatives of the object's (angular) motion.</p>
<p>I've also introduced aliases for each of these derivatives (like <code>acc</code> for acceleration, etc).</p>
<p>Upon initialization, the default for all derivatives should be 0.</p>
<p>I'm satisfied with how the class works as it is now as long as it remains 2 dimensional and I don't need higher derivatives of (angular) motion.</p>
<hr>
<p>However, I feel that my code is repetitive in some places which would require changes in multiple places supposing I want to change how it works slightly.</p>
<p>Eg. I've considered the possibility of wanting to include higher derivatives of motion (without introducing more aliases like <code>jerk</code>) or changing the dimension I'm working in (ignore angular motion in this case).</p>
<hr>
<p>Note: I wanted the derivatives of (angular) motion to be stored in arrays so that I can loop over them to simulate Physics using Taylor's Expansion as shown below. The <code>simulatePhysics</code> function works regardless of the number of derivatives or dimension.</p>
<p>I'm also wondering from a design point of view - would it be a better idea to put <code>simulatePhysics</code> as a method of the game instead of the object?</p>
<pre><code>class Game2DObject {
constructor(options) {
if (options) {
this.motion = options.motion || []
this.angMotion = options.angMotion || []
this.dis = options.dis || [0, 0]
this.vel = options.vel || [0, 0]
this.acc = options.acc || [0, 0]
this.angDis = options.angDis || 0
this.angVel = options.angVel || 0
this.angAcc = options.angAcc || 0
this.radius = options.radius || 0
this.mass = options.mass || 0
} else {
this.motion = [[0, 0], [0, 0], [0, 0]]
this.angMotion = [0, 0, 0]
this.radius = 0
this.mass = 0
}
}
//motion
get dis() {
return this.motion[0]
}
set dis(x) {
this.motion[0] = x
}
get vel() {
return this.motion[1]
}
set vel(x) {
this.motion[1] = x
}
get acc() {
return this.motion[2]
}
set acc(x) {
this.motion[2] = x
}
//angMotion
get angDis() {
return this.angMotion[0]
}
set angDis(x) {
this.angMotion[0] = x
}
get angVel() {
return this.angMotion[1]
}
set angVel(x) {
this.angMotion[1] = x
}
get angAcc() {
return this.angMotion[2]
}
set angAcc(x) {
this.angMotion[2] = x
}
simulatePhysics(dt) {
function taylor(arr) {
return arr.reduceRight((acc, cur, i) => acc * dt / (i + 1) + cur, 0)
}
for (var dim = 0; dim < this.motion[0].length; dim++) {
for (var deriv = 0; deriv < this.motion.length; deriv++) {
this.motion[deriv][dim] = taylor(this.motion.slice(deriv).map((cur) => cur[dim]))
}
}
for (var deriv = 0; deriv < this.angMotion.length; deriv++) {
this.angMotion[deriv] = taylor(this.angMotion.slice(deriv))
}
}
}
//*DEBUG
var a = new Game2DObject({acc: [-6, 0], angVel: 9})
console.log(a)
console.log(a.dis[0] = 1)
console.log(a.dis[1] = 5)
console.log(a.acc[1] = -2)
console.log(a)
a.simulatePhysics(1)
console.log(a)
a.simulatePhysics(1)
console.log(a)
a.simulatePhysics(1)
console.log(a)
</code></pre>
<p>Output:</p>
<p><a href="https://i.imgur.com/CTc8zx7.png" rel="nofollow noreferrer"><img src="https://i.imgur.com/CTc8zx7.png" alt="enter image description here"></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T16:39:51.560",
"Id": "443001",
"Score": "2",
"body": "How many derivatives do you think you would use? Should someone be able to get the 21st derivative?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T16:42:48.933",
"Id": "443003",
"Score": "0",
"body": "The main purpose of this is for a basic game at the moment (in which case, the 1st 2 will do).\n\nBut I'm also considering more complex games/physics simulation in future."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T16:43:42.130",
"Id": "443005",
"Score": "0",
"body": "I don't think you'll ever need more than _jounce_, I would just include upto this one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T16:51:25.477",
"Id": "443007",
"Score": "0",
"body": "ok :D But I think quite a few more than 3 dimensions is a possibility to consider?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T16:52:32.187",
"Id": "443008",
"Score": "0",
"body": "sure :) it depends on the game you're going to make .. or do you wish to make this a reusable object for any kind of scenario where motion derivatives are required?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T16:58:39.317",
"Id": "443011",
"Score": "1",
"body": "Reusable for future games/simulations. The game I'm making now can use the class as is with no problems."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T18:37:47.383",
"Id": "443032",
"Score": "0",
"body": "There is a difference between a constructor with no options argument, and options argument without no properties. Is this intentional?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T19:57:42.337",
"Id": "443050",
"Score": "0",
"body": "Hmm... yes, I guess. To allow lazily writing `new GameObject()`..."
}
] |
[
{
"body": "<h2>Poor performance</h2>\n\n<p>For games performance dominates all levels of design but becomes critical as you approach the low level building blocks of the game. Every increase in performance opens up your market, there are far more low end devices than high end with a 20% performance increase doubling the number of devices that can run the game at acceptable levels.</p>\n\n<p>If you are not interested in marketing and its just for fun, then you can solve performance problems with hardware and ignore this answer.</p>\n\n<h2>Some points on performance</h2>\n\n<ul>\n<li>Avoid getters and setters as they are slower than direct property access.</li>\n<li>Avoid array iteration for small arrays. Inline the operations.</li>\n<li>Be memory efficient, pre-allocate, reuse rather than deference (delete)</li>\n<li>Use small generic objects to cover a wide range of uses, rather than many complex targeted objects</li>\n</ul>\n\n<p><code>Array.slice</code> and <code>Array.map</code> require allocation and GC overhead. \n<code>Array</code> iterators require closure, counters, and logic overheads. For large arrays the overheads become insignificant, but for small arrays 2,3 items long the overhead becomes a significant part of the processing.</p>\n\n<p>One of the biggest overheads of using array iteration is that the coder hides a large number of redundant operations because the iterators obscure the expanded calculations.</p>\n\n<h2>Needless CPU wastage</h2>\n\n<p>Lets analyze and simplify the function <code>simulatePhysics</code> as it is very inefficient with a lot of repeated calculations, or completely unneeded calculations. Every time it is called it create a lot of garbage for GC to clean up (15 new Array objects)</p>\n\n<blockquote>\n<pre><code> simulatePhysics(dt) {\n function taylor(arr) {\n return arr.reduceRight((acc, cur, i) => acc * dt / (i + 1) + cur, 0)\n }\n\n for (var dim = 0; dim < this.motion[0].length; dim++) {\n for (var deriv = 0; deriv < this.motion.length; deriv++) {\n this.motion[deriv][dim] = taylor(this.motion.slice(deriv).map((cur) => cur[dim]))\n }\n }\n\n for (var deriv = 0; deriv < this.angMotion.length; deriv++) {\n this.angMotion[deriv] = taylor(this.angMotion.slice(deriv))\n }\n }\n</code></pre>\n</blockquote>\n\n<p>This function requires the creation of 15 new arrays, 27 call stack push and pops, 30 temp variable, and 108 math operations. </p>\n\n<p>It can be significantly reduced to no new arrays, no call stack overhead, 6 temp variable, and 19 math operations.</p>\n\n<h3>Reducing <code>simulatePhysics</code></h3>\n\n<p>The steps I used to simplify the function and remove unneeded overhead.</p>\n\n<p><strong>1</strong> First to remove all the coding noise we can create some aliases for the names.</p>\n\n<pre><code> const m = this.motion;\n const aM = this.angMotion;\n</code></pre>\n\n<p><strong>2</strong> Inline the 2 loops removing all the iterators <code>slice</code> and <code>map</code> overhead.</p>\n\n<pre><code> m[0][0] = taylor([m[0][0], m[1][0], m[2][0]])\n m[1][0] = taylor([m[1][0], m[2][0]])\n m[2][0] = taylor([m[2][0]])\n m[0][1] = taylor([m[0][1], m[1][1], m[2][1]])\n m[1][1] = taylor([m[1][1], m[2][1]])\n m[2][1] = taylor([m[2][1]]) \n\n\n aM[0] = taylor([aM[0], aM[1], aM[2]]) \n aM[1] = taylor([aM[1], aM[2]]) \n aM[2] = taylor([aM[2]]) \n</code></pre>\n\n<p><strong>3</strong> Replace the <code>taylor</code> function with inlined calculations </p>\n\n<pre><code> m[0][0] = ((0 * dt / 3 + m[2][0]) * dt / 2 + m[1][0]) * dt / 1 + m[0][0]\n m[1][0] = (0 * dt / 2 + m[2][0]) * dt / 1 + m[1][0]\n m[2][0] = 0 * dt / 1 + m[2][0]\n m[0][1] = ((0 * dt / 3 + m[2][1]) * dt / 2 + m[1][1]) * dt / 1 + m[0][1]\n m[1][1] = (0 * dt / 2 + m[2][1]) * dt / 1 + m[1][1]\n m[2][1] = 0 * dt / 1 + m[2][1]\n\n\n aM[0] = ((0 * dt / 3 + aM[2]) * dt / 2 + aM[1]) * dt / 1 + aM[0]\n aM[1] = (0 * dt / 2 + aM[2]) * dt / 1 + aM[1]\n aM[2] = 0 * dt / 1 + aM[2]\n</code></pre>\n\n<p><strong>4</strong> Remove the multiply by zero and divide by ones</p>\n\n<pre><code> m[0][0] = (m[2][0] * dt / 2 + m[1][0]) * dt + m[0][0]\n m[1][0] = m[2][0] * dt + m[1][0]\n m[2][0] = m[2][0]\n m[0][1] = (m[2][1] * dt / 2 + m[1][1]) * dt + m[0][1]\n m[1][1] = m[2][1] * dt + m[1][1]\n m[2][1] = m[2][1]\n\n\n aM[0] = (aM[2] * dt / 2 + aM[1]) * dt + aM[0]\n aM[1] = aM[2] * dt + aM[1]\n aM[2] = aM[2]\n</code></pre>\n\n<p><strong>5</strong> Cache and substitute with constants, remove unneeded assignments.</p>\n\n<pre><code> const dt2 = dt / 2;\n\n m[0][0] = (m[2][0] * dt2 + m[1][0]) * dt + m[0][0]\n m[1][0] = m[2][0] * dt + m[1][0]\n m[0][1] = (m[2][1] * dt2 + m[1][1]) * dt + m[0][1]\n m[1][1] = m[2][1] * dt + m[1][1]\n\n aM[0] = (aM[2] * dt2 + aM[1]) * dt + aM[0]\n aM[1] = aM[2] * dt + aM[1]\n</code></pre>\n\n<p><strong>6</strong> More aliases to reduce indexing overhead and rebuild the function</p>\n\n<pre><code>simulatePhysics(dt) {\n const m = this.motion, m0 = m[0], m1 = m[1], m2 = m[2];\n const aM = this.angMotion;\n const dt2 = dt / 2;\n\n m0[0] = (m2[0] * dt2 + m1[0]) * dt + m0[0];\n m1[0] = m2[0] * dt + m1[0];\n m0[1] = (m2[1] * dt2 + m1[1]) * dt + m0[1];\n m1[1] = m2[1] * dt + m1[1];\n aM[0] = (aM[2] * dt2 + aM[1]) * dt + aM[0];\n aM[1] = aM[2] * dt + aM[1];\n\n}\n</code></pre>\n\n<h2>Whats the gain</h2>\n\n<p>Arguably there is some loss in readability, personally it makes a lot more sense than a collection of arrays iterators and copying. But the gain is (tested on chrome) huge.</p>\n\n<pre><code>// tested on random set of 1000 objects\n// µs is 1/1,000,000th second. OPS is operations per second. \n// An operation is a single call to the function being tested.\nOptimized..: MeanTime 0.175µs OPS 5,710,020 Test Total 322ms 1,836,000 operations\nOriginal...: MeanTime 4.198µs OPS 238,185 Test Total 6,566ms 1,564,000 operations\n</code></pre>\n\n<p>The optimized version is 25 times faster, able to do 5.7million operations in the same time as the original could do 0.3million</p>\n\n<p>Is readability more important than performance? for games you must seriously consider what you lose via traditional coding styles.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T09:42:43.717",
"Id": "443091",
"Score": "0",
"body": "Thanks for the great answer on optimizing the code. Being new to game development this is new for me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T10:00:09.487",
"Id": "443092",
"Score": "0",
"body": "Would having 9 variables (`sx`, `sy`, `vx`, `vy`, `ax`, `ay`, `as`, `av`, `aa`) be more efficient than storing them in a 2D array? (I'm going to forget about aliasing now)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T10:35:11.717",
"Id": "443097",
"Score": "0",
"body": "If so, I'll go with this revamped version https://pastebin.com/v42ukRZS. Is it worth it to create an alias for 2 lookups as I've done in the `simulatePhysics` function here, or is it only worth it for arrays (you mentioned reducing indexing overhead)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T20:23:47.360",
"Id": "443393",
"Score": "0",
"body": "@Shuri2060 Alias lookups is preferred for properties and array indexing when using Chrome, For FF aliases actually present a loss in performance."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T03:57:28.473",
"Id": "227549",
"ParentId": "227522",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "227549",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T16:34:56.620",
"Id": "227522",
"Score": "4",
"Tags": [
"javascript",
"physics"
],
"Title": "Making basic physics object class"
}
|
227522
|
<p>I have a list of 9000 dictionaries and I am sending them to an API in batches of 100 (limit of the API). The API returns the list of 100 dictionaries just expanded with more key/value pairs. So both lists look something like this:</p>
<pre><code>[
{Key1:Val1, Key2:Val2},
{Key1:Val3, Key2:Val4},
...
]
</code></pre>
<p>and returns:</p>
<pre><code>[
{Key1:Val1, Key2:Val2,Key3:Val1, Key4:Val4},
{Key1:Val3, Key2:Val4,Key3:Val1, Key4:Val4},
...
]
</code></pre>
<p>Now, I have to create a list that has all 9000 returned dictionaries in them, because the original input receives a batch of 9000 so it needs to output them all at once as well. I have accomplished this with the following code:</p>
<pre><code>dict_list = [This is the list with 9000 dicts]
batch_list = []
return_list = []
for i in dictlist:
batch_list.append(i)
if len(batch_list) == 100:
api_batch = API_CALL_FUNCTION(batch_list)
for j in api_batch:
return_list.append(j)
batch_list.clear()
else:
continue
if batch_list:
api_batch = API_CALL_FUNCTION(batch_list)
for k in api_batch:
return_list.append(k)
</code></pre>
<p>This code does what I want it to, but I really don't like the nested for loop and I'm sure there's probably a more efficient way to do this. Any suggestions?</p>
|
[] |
[
{
"body": "<p>You should just be able to append the returned API list directly to return_list:</p>\n\n<pre><code>dict_list = [This is the list with 9000 dicts]\nbatch_list = []\nreturn_list = []\n\nfor i in dictlist:\n batch_list.append(i)\n if len(batch_list) == 100:\n return_list.append(API_CALL_FUNCTION(batch_list))\n batch_list.clear()\n\nif batch_list:\n return_list.append(API_CALL_FUNCTION(batch_list))\n</code></pre>\n\n<p>and your else clause is un-needed.</p>\n\n<p>You should also explore slicing the dictlist instead of iterating through each one.\nYou can call dictlist[0:100] and it will return a list containing the first 100 elements. dictlist[100:200] will return the next chunck, etc.</p>\n\n<p>Hope this helped! Good luck.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T20:42:40.007",
"Id": "227536",
"ParentId": "227532",
"Score": "4"
}
},
{
"body": "<p>There is a pretty definitive post by Ned Batchelder on how to chunk a list over on SO: <a href=\"https://stackoverflow.com/a/312464/4029014\">https://stackoverflow.com/a/312464/4029014</a></p>\n\n<p>The Python3 version looks like this:</p>\n\n<pre><code>def chunks(l, n):\n \"\"\"Yield successive n-sized chunks from l.\"\"\"\n for i in range(0, len(l), n):\n yield l[i:i + n]\n</code></pre>\n\n<p>So you could process your list using this structure:</p>\n\n<pre><code>MAX_API_BATCH_SIZE = 100\n\nfor batch in chunks(dict_list, MAX_API_BATCH_SIZE):\n batch_done = API_CALL_FUNCTION(batch)\n</code></pre>\n\n<p>Note that there is already a method on lists for concatenating a second list: it's <a href=\"https://docs.python.org/3/tutorial/datastructures.html?highlight=extend#more-on-lists\" rel=\"nofollow noreferrer\"><code>extend</code></a>. So you can say:</p>\n\n<pre><code> return_list.extend(batch_done)\n</code></pre>\n\n<p>Your code is obviously example code, which is a violation of how CodeReview works (so this question probably should have been asked on SO directly). Regardless, it should be in a function either way:</p>\n\n<pre><code>MAX_API_BATCH_SIZE = 100\n\ndef process_records_through_api(records, batch_size=None):\n \"\"\" Process records through the XYZ api. Return resulting records. \"\"\"\n\n batch_size = (MAX_API_BATCH_SIZE if batch_size is None or batch_size < 1 \n else batch_size)\n result = []\n\n for batch in chunks(records, batch_size):\n result.extend(api_function(batch))\n\n return result\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T21:35:51.707",
"Id": "227539",
"ParentId": "227532",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "227536",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T19:51:21.707",
"Id": "227532",
"Score": "2",
"Tags": [
"python",
"hash-map"
],
"Title": "Python, Iterate through a list sending batches of 100 records at a time to an API, then appending results to another list"
}
|
227532
|
<p>I wrote a filter for pandas that converts <code>:-)</code> to <code>☺</code> but not in inline code or code blocks. Pandoc makes it so the <code>applyExceptOnCodeBlock smileyfy</code> function trickles through the whole tree. But since I operate on <code>Block</code>s and <code>Inline</code>s I need to handle every data constructor for <code>Block</code> that takes <code>Inline</code>s.</p>
<pre><code>import Text.Pandoc.JSON
import Text.Pandoc.Walk
import Data.List (intercalate)
import Data.List.Split (splitOn)
main :: IO ()
main = toJSONFilter $ applyExceptOnCodeBlock smileyfy
smileyfy :: String -> String
smileyfy = intercalate "☺" . splitOn ":-)"
applyExceptOnCodeInline :: (String -> String) -> Inline -> Inline
applyExceptOnCodeInline f (Str s) = Str (f s)
applyExceptOnCodeInline f (Code attr s) = Code attr s -- for code nothing shall happen
applyExceptOnCodeInline _ x = x
applyExceptOnCodeBlock :: (String -> String) -> Block -> Block
applyExceptOnCodeBlock f (Plain is) = Plain $ applyExceptOnCodeInline f <$> is
applyExceptOnCodeBlock f (Para is) = Para $ applyExceptOnCodeInline f <$> is
applyExceptOnCodeBlock f (LineBlock iss) = LineBlock $ (fmap . fmap) (applyExceptOnCodeInline f) iss
applyExceptOnCodeBlock f (RawBlock format s) = RawBlock format $ f s
applyExceptOnCodeBlock f (DefinitionList [(is, bss)]) = DefinitionList [(applyExceptOnCodeInline f <$> is
,fmap (fmap (applyExceptOnCodeBlock f)) bss)]
applyExceptOnCodeBlock f (Header i attr is) = Header i attr $ applyExceptOnCodeInline f <$> is
applyExceptOnCodeBlock f (Table is as ds tcs tcss) = Table (applyExceptOnCodeInline f <$> is) as ds tcs tcss
applyExceptOnCodeBlock _ x = x --this covers CodeBlock as well
</code></pre>
<p>And thus it looks very convoluted. Is there a clearer way to express this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T05:43:50.777",
"Id": "443208",
"Score": "0",
"body": "For possible future visitors, I'd like to add that a small Lua filter is easier to apply, as you don't need a fully Haskell stack installed."
}
] |
[
{
"body": "<p>There's a much shorter way to express the same functionality, but I'm not sure you'll immediately find it to be clearer.</p>\n\n<pre><code>import Data.List (intercalate)\nimport Data.List.Split (splitOn)\nimport Text.Pandoc.JSON\n\nmain :: IO ()\nmain = toJSONFilter smile\n\nsmile :: Inline -> Inline\nsmile (Str s) = Str . intercalate \"☺\" . splitOn \":-)\" $ s\nsmile x = x\n</code></pre>\n\n<p>I think the insight you missed is that the <code>Block</code> constructor <code>CodeBlock</code> contains no <code>Inline</code>s, so you can trust the <code>Walkable</code> typeclass machinery to ignore them if your smiley making code <em>only</em> works on <code>Inline</code>s. That eliminates the entire <code>applyExceptOnCodeBlock</code> function.</p>\n\n<p>Similarly it isn't necessary to include a case for <code>Inline</code>'s <code>Code</code> constructor, constructors like <code>Code</code> and <code>Math</code> contain their own raw strings and are safely ignored. Pandoc's datatypes are already structured to divide prose text from markup making it easy to define transformations by only matching on the things you <em>do</em> want to modify.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T11:58:35.510",
"Id": "443252",
"Score": "0",
"body": "Thanks! I originally wanted the filter to ignore `BlockQuote` but when I switched to `Code` I didn't realize that I no longer had a problem."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T19:40:40.037",
"Id": "227599",
"ParentId": "227533",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227599",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T20:12:52.960",
"Id": "227533",
"Score": "2",
"Tags": [
"parsing",
"haskell"
],
"Title": "Apply smiley replacement filter to Pandoc but not in code segments"
}
|
227533
|
<p>I have a primary table, <code>REP_ASSIST.ES_LOG</code> with multiple columns that are foreign keys to another table, <code>REP_ASSIST.ES_DOCUMENT_STATUSES</code>. Here is an example of what my main table looks like:</p>
<pre><code>+-------------------------+-----------+-------------------------+-----------------------+
| created_at | filing_id | prior_dd_rcvd_status_id | new_dd_rcvd_status_id |
+-------------------------+-----------+-------------------------+-----------------------+
| 2019-09-04 10:58:48.000 | 988 | 2 | 2 |
| 2019-09-04 10:47:03.000 | 988 | 1 | 2 |
| 2019-08-28 23:56:47.000 | 988 | null | 1 |
+-------------------------+-----------+-------------------------+-----------------------+
</code></pre>
<p>Both the <code>prior_dd_rcvd_status_id</code> and <code>new_dd_rcvd_status_id</code> are foreign keys to the other table, a sample of which is here:</p>
<pre><code>+------------------+--------------------+
| dd_doc_status_id | dd_doc_status_name |
+------------------+--------------------+
| 1 | RECEIVED |
| 2 | MISSING |
| 3 | NOT_NEEDED |
| 4 | UNKNOWN |
+------------------+--------------------+
</code></pre>
<hr>
<p>I need to pull in the values from the lookup table for a printable report; right now I'm using a subquery to get the <code>dd_doc_status_name</code> as a user-friendly name instead of the <code>dd_doc_status_id</code>.</p>
<pre><code>SELECT created_at,
filing_id,
(
SELECT dd_doc_status_name
FROM REP_ASSIST.ES_DOCUMENT_STATUSES
WHERE ES_DOCUMENT_STATUSES.dd_doc_status_id = prior_dd_rcvd_status_id
) AS 'prior_dd_status',
(
SELECT dd_doc_status_name
FROM REP_ASSIST.ES_DOCUMENT_STATUSES
WHERE ES_DOCUMENT_STATUSES.dd_doc_status_id = new_dd_rcvd_status_id
) AS 'new_dd_status'
FROM REP_ASSIST.ES_LOG
WHERE filing_id = 988;
</code></pre>
<p>However, I'm concerned that using subqueries like this may be a bit of a hack and affect performance (especially if I end up adding additional columns that need this information).</p>
<p>I'm getting the correct results (see below), but I'd like to know if there is a more efficient and more standard way.</p>
<pre><code>+-------------------------+-----------+----------------------+--------------------+
| created_at | filing_id | prior_dd_rcvd_status | new_dd_rcvd_status |
+-------------------------+-----------+----------------------+--------------------+
| 2019-09-04 10:58:48.000 | 988 | MISSING | MISSING |
| 2019-09-04 10:47:03.000 | 988 | RECEIVED | MISSING |
| 2019-08-28 23:56:47.000 | 988 | null | RECEIVED |
+-------------------------+-----------+----------------------+--------------------+
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T04:19:00.947",
"Id": "443070",
"Score": "0",
"body": "This is SQL will [not work](http://sqlfiddle.com/#!9/d0a511/4) on MySQL as the columns in the subqueries are unknown. Regarding the suggestions, just 2 `left join`s on your `ES_DOCUMENT_STATUSES` table instead of the subqueries will be fine, I don't know about `sql-server` so forgive me from putting a complete answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T04:27:26.477",
"Id": "443071",
"Score": "0",
"body": "Could you include the DDL statements (create table)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T04:30:32.160",
"Id": "443072",
"Score": "0",
"body": "I tried your query on SQL Server fiddle [website](http://sqlfiddle.com/#!18/fbb7a/2), and **it fails** for the same reason! your subquery is using unknown columns `prior_dd_rcvd_dd_status_id` and `new_dd_rcvd_dd_status_id` !"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T04:38:52.263",
"Id": "443073",
"Score": "2",
"body": "Here is that fiddle for sql server: http://sqlfiddle.com/#!18/bdf74/5"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T04:39:26.113",
"Id": "443074",
"Score": "1",
"body": "@Accountantم the query in question does not work, OP should edit his field names. I'm voting to close this question for not working SQL."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T07:44:38.630",
"Id": "443088",
"Score": "1",
"body": "When you edit your question, please update your title to describe the *purpose* of the code, rather than the *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T12:23:54.077",
"Id": "443106",
"Score": "1",
"body": "@dfhwze - Thank you for correcting the fiddle for SQL Server."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T12:24:43.600",
"Id": "443107",
"Score": "0",
"body": "@Accountantم - Thank you. I've corrected the typo in my field names and the query now works in dfhwze's [fiddle](http://sqlfiddle.com/#!18/bdf74/9)."
}
] |
[
{
"body": "<p>I've updated the <a href=\"http://sqlfiddle.com/#!18/bdf74/10\" rel=\"nofollow noreferrer\">Fiddle</a> with your initial query and 2 alternatives.</p>\n\n<p>This is the initial query plan:</p>\n\n<p><a href=\"https://i.stack.imgur.com/tJgx2.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tJgx2.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>Using <code>OUTER APPLY</code> instead of the nested <code>SELECT</code> statements.</p>\n\n<pre><code>select created_at, prior_dd_rcvd_status_id, \n new_dd_rcvd_status_id, prior_dd_status, new_dd_status, filing_id\nfrom ES_LOG\nouter apply (\n select dd_doc_status_name as prior_dd_status \n from ES_DOCUMENT_STATUSES where dd_doc_status_id = prior_dd_rcvd_status_id\n) a\nouter apply (\n select dd_doc_status_name as new_dd_status \n from ES_DOCUMENT_STATUSES where dd_doc_status_id = new_dd_rcvd_status_id\n) b\nwhere filing_id = 988;\n</code></pre>\n\n<p>The query plan gets simplified:</p>\n\n<p><a href=\"https://i.stack.imgur.com/GTxlh.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GTxlh.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>And using <code>LEFT OUTER JOIN</code> instead of the <code>OUTER APPLY</code>.</p>\n\n<pre><code>select created_at, prior_dd_rcvd_status_id, \n new_dd_rcvd_status_id, \n a.dd_doc_status_name as prior_dd_status, \n b.dd_doc_status_name as new_dd_status, \n filing_id\nfrom ES_LOG\nleft outer join ES_DOCUMENT_STATUSES a \n on a.dd_doc_status_id = prior_dd_rcvd_status_id\nleft outer join ES_DOCUMENT_STATUSES b \n on b.dd_doc_status_id = new_dd_rcvd_status_id\nwhere filing_id = 988;\n</code></pre>\n\n<p>With an even more simplified query plan:</p>\n\n<p><a href=\"https://i.stack.imgur.com/AkyEh.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AkyEh.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>However, as you can see, the table scans take most of the time. So I'm not sure how much performance you could gain by picking either of the alternatives.</p>\n\n<p>Further improvements require the use of indexes (<a href=\"https://www.itprotoday.com/sql-server/which-faster-index-access-or-table-scan\" rel=\"nofollow noreferrer\">Table Scan vs Index Scan</a>). Deciding which index to provide depends not only on this query, but also the general design of how these tables will be used for other queries and CRUD operations. I would advise you learn about them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T15:07:42.717",
"Id": "443120",
"Score": "1",
"body": "Great answer! One thing that is probably worth calling out is that with the volumes of these tables, SQL Server is pretty much guaranteed to nested loop and not try to do anything fancy with them. If production table sizes are different then this might be very different, and is at least a grain of salt with looking at the plans."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T14:28:57.220",
"Id": "227574",
"ParentId": "227541",
"Score": "3"
}
},
{
"body": "<blockquote>\n <p>However, I'm concerned that using subqueries like this may be a bit of a hack and affect performance (especially if I end up adding additional columns that need this information).</p>\n</blockquote>\n\n<p>Whenever you find yourself including a subquery as part of your <code>SELECT</code> list, you're right to question whether or not you're doing the correct thing. These can often suffer from performance issues, and are much harder to read and troubleshoot.</p>\n\n<p>I wouldn't worry as much about the second half of your question:</p>\n\n<blockquote>\n <p>especially if I end up adding additional columns that need this information</p>\n</blockquote>\n\n<p>Unless you know that you're likely to do this in the future, you're likely micro- and pre-optimizing.</p>\n\n<p>That being said, ultimately your solution is very straightforward. All you want is a join from table <code>A</code> to table <code>B</code> on two different columns. You might recognize that what you actually need is <em>two</em> joins from table <code>A</code> to table <code>B</code>. That would just look like this:</p>\n\n<pre><code>SELECT created_at,\n filing_id,\n PriorStatuses.dd_doc_status_name prior_dd_status,\n NewStatuses.dd_doc_status_name new_dd_status\n FROM REP_ASSIST.ES_LOG\n LEFT OUTER JOIN REP_ASSIST.ES_DOCUMENT_STATUSES PriorStatuses\n ON ES_LOG.prior_dd_rcvd_status_id = PriorStatuses.dd_doc_status_id\n LEFT OUTER JOIN REP_ASSIST.ES_DOCUMENT_STATUSES NewStatuses\n ON ES_LOG.new_dd_rcvd_status_id = NewStatuses.dd_doc_status_id\n WHERE filing_id = 988;\n</code></pre>\n\n<p>I did my best to come up with meaningful names based on context, but you should just pick some domain-relevant alias as appropriate.</p>\n\n<p>If you do find yourself with a really large number of these columns, you might want to consider a new table design. For example, it might then be easier to have a table like this:</p>\n\n<pre><code>CREATE TABLE REP_ASSIST.ES_LOG_STATUSES\n(\n filing_id bigint NOT NULL,\n doc_status_type nvarchar(50) NOT NULL,\n status_id bigint NOT NULL\n);\n</code></pre>\n\n<p>Then you can add new status types (or whatever the appropriate domain terminology would be) ad-hoc to this table, and your query then becomes something like this</p>\n\n<pre><code>SELECT ES_LOG.created_at,\n ES_LOG.filing_id,\n ES_LOG_STATUSES.doc_status_type,\n ES_DOCUMENT_STATUSES.dd_doc_status_name\n FROM REP_ASSIST.ES_LOG\n INNER JOIN REP_ASSIST.ES_LOG_STATUSES\n ON ES_LOG.filing_id = ES_LOG_STATUSES.filing_id\n LEFT OUTER JOIN REP_ASSIST.ES_DOCUMENT_STATUSES \n ON ES_LOG_STATUSES.status_id = ES_DOCUMENT_STATUSES.status_id\n WHERE ES_LOG.filing_id = 988;\n</code></pre>\n\n<p>If its important to have the output be one row per <code>filing_id</code> instead of one row per <code>filing_id</code> and <code>doc_status_type</code> combination, you could always <a href=\"https://docs.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-2017\" rel=\"nofollow noreferrer\"><code>PIVOT</code></a> your result set. If the set of possible status types is unknown or changes rapidly, there are <a href=\"https://stackoverflow.com/q/10404348/3076272\">plenty</a> of ways to do that dynamically</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T14:29:30.493",
"Id": "227575",
"ParentId": "227541",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T22:22:52.157",
"Id": "227541",
"Score": "5",
"Tags": [
"sql",
"sql-server",
"t-sql"
],
"Title": "Query with multiple foreign keys to the same table"
}
|
227541
|
<p>In a university library, there was copy of "Making The Most Of Your ZX 81" by Tim Hartnell. I flipped to an interesting page from the index and found this program in BASIC, and thought it interesting enough to rewrite in Python. It's a number guessing game.</p>
<pre class="lang-py prettyprint-override"><code>from random import random
from sys import exit
print("LOST IN SPACE:\nYou have fifteen hours to find a capsule lost in a SEVEN kilometer cube of space.\n")
def main():
def winCondition(i):
print("You found it with {} hours of air left".format(15 - i))
end()
def end():
print("Play again? Y/N")
response = input()
if response.lower() == "y":
game()
else:
exit(0)
def game():
A = int(7 * random() + 1)
B = int(7 * random() + 1)
C = int(7 * random() + 1)
"""
Ripped from https://stackoverflow.com/questions/57813858/iteratively-assigning-variables-in-python/57813901#57813901
"""
def get_input(axis):
while True:
user_input = input(f"{axis}-Axis: ")
try:
axis_int = int(user_input)
assert(axis_int <= 7)
except:
print("Enter a natural number in the range!")
continue
else:
break
return axis_int
for i in range(15):
print("Input 3 search coordinates")
D, E, F = [get_input(axis) for axis in "YXZ"]
print(str(D) + str(E) + str(F))
if A == D and B == E and F == C:
winCondition(i)
else:
print("You have {} hours of air left.".format(15 - i))
if A > D:
print("UP")
elif A < D:
print("DOWN")
if B > E:
print("PORT")
elif B < E:
print("STARBOARD")
if C > F:
print("FORWARD")
elif C < F:
print("BACKWARD")
if i == 14:
print("Choose your next move carefully... HYPOXIA IMMINENT.")
print("Fail, astronaut dead; capsule was at coords {}.{}.{}".format(A, B, C))
end()
main()
</code></pre>
<p>I first of all want to improve concision before anything else.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T00:19:50.993",
"Id": "443064",
"Score": "4",
"body": "Can you provide the original BASIC source for comparison? How important is it to you to be compatible with the original?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T01:36:29.727",
"Id": "443067",
"Score": "0",
"body": "It isn't important that it compares to the original. It just does the same thing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T12:16:31.730",
"Id": "443103",
"Score": "1",
"body": "Hmm. First thing’s first: The program doesn’t do anything. It prints a message and then immediately exits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T01:36:47.457",
"Id": "443194",
"Score": "1",
"body": "As opposed to the reboot of the TV show Lost in Space where all the characters are played by pythons."
}
] |
[
{
"body": "<h2>Nested functions</h2>\n\n<p>Not really sure what your motivation was, here, but this Russian nesting doll of functions is not really necessary. Under certain narrow circumstances, like limiting the number of publicly visible methods in a library, it might be called-for - but not really here. You don't need closures for this code, so just move things up to global namespace.</p>\n\n<h2>Variable case</h2>\n\n<p><code>A</code>-<code>C</code> should be lower-case because they aren't types.</p>\n\n<h2>Random unpacking</h2>\n\n<pre><code>a, b, c = (int(7*random() + 1) for _ in range(3))\n</code></pre>\n\n<h2>Never <code>except:</code></h2>\n\n<p>Currently, you can't Ctrl+C out of the program, because you're catching all exceptions. Narrow your exception type.</p>\n\n<h2>Don't materialize generators</h2>\n\n<pre><code>D, E, F = [get_input(axis) for axis in \"YXZ\"]\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>d, e, f = (get_input(axis) for axis in \"YXZ\")\n</code></pre>\n\n<p>because you don't need to keep that list in memory.</p>\n\n<h2>Format strings</h2>\n\n<pre><code>print(str(D) + str(E) + str(F))\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>print(f'{d}{e}{f}')\n</code></pre>\n\n<h2>Stack abuse</h2>\n\n<p>You call <code>game</code>, which calls <code>end</code>, which calls <code>game</code>... Don't do this. Just loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T09:21:33.903",
"Id": "443234",
"Score": "0",
"body": "The last suggestion assumes OP is using Python >= 3.6 (they should, but they don't necessarily have to)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T10:54:56.537",
"Id": "443247",
"Score": "0",
"body": "Because `end()` is the last function call in `game` doesn't that allow the interpreter to make a tail-call optimization?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T11:50:59.397",
"Id": "443250",
"Score": "0",
"body": "@EmanuelVintilă Python (or at least CPython, as far as my knowledge) does not optimize rail recursive calls."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T23:25:42.700",
"Id": "444803",
"Score": "0",
"body": "I accepted this one because you reminded me of the call stack. I shudder."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T00:23:31.563",
"Id": "227544",
"ParentId": "227543",
"Score": "16"
}
},
{
"body": "<h1>General structure</h1>\n\n<p>You are using a lot of nested functions and recursion. It makes it hard to figure out what is going on just at a glance. I would go with a main function to be a pythonic do-while:</p>\n\n<pre><code>def main()\n while True:\n game()\n if end():\n break\n</code></pre>\n\n<p>Note that you'll have to modify <code>end()</code> to return a bool, and <code>game()</code> to not call <code>end()</code> but just finnish instead.</p>\n\n<h1>Error and input handling</h1>\n\n<p>The next thing I would do is change <code>get_input</code>. Its bad to catch all errors - if there would be some unrelated error you would get stuck in an infintie loop. </p>\n\n<p>Using <code>assert</code> to control program flow is also a bit unexpected. As Ben points out in comments, it can be dangerous since asserts can be turned off with a command line options.</p>\n\n<p>One way to do it is to break out the parsing and validation bit into a new function <code>parse_input</code> that returns the integer or throw an exception if the input is invalid:</p>\n\n<pre><code>def get_input(axis):\n while True:\n user_input = input(f\"{axis}-Axis: \")\n try:\n return parse_input(user_input)\n except InvalidInputError:\n print(\"Enter a natural number in the range!\")\n\ndef parse_input(input_str):\n try:\n input_int = int(input_str)\n except ValueError:\n raise InvalidInputError()\n if input_int > 7:\n raise InvalidInputError()\n return input_int\n\nclass InvalidInputError(Exception):\n pass\n</code></pre>\n\n<p>This code is longer, but I would argue that it is more readable. Opinions may differ.</p>\n\n<h1>Variable names</h1>\n\n<p>What does <code>A > D</code> mean? I don't know! Something like <code>guess_x > goal_x</code> would be much easier to understand.</p>\n\n<h1>A bug!</h1>\n\n<p>What happends if the user enters a negative number?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T10:48:47.420",
"Id": "443100",
"Score": "0",
"body": "I just noticed the bottom line of the question! Unfortunately this isn't very helpful when it comes to making things more concice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T12:05:51.950",
"Id": "443253",
"Score": "1",
"body": "Using `assert` to control program flow is actively dangerous in production code; [assertions will be ignored if the user calls python with the -O switch](https://docs.python.org/3/reference/simple_stmts.html#grammar-token-assert-stmt)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T09:28:25.047",
"Id": "227557",
"ParentId": "227543",
"Score": "4"
}
},
{
"body": "<p>In python, code clarity and readability is more important than conciseness. If you want concise code, go play code-golf. However, sometimes they align a bit.</p>\n\n<p>This is what I'd make of it, and why I would make the changes:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from random import random\nimport sys # sys.exit is a different function than the builtin exit. Importing it by name will rename that builtin\n# for this script, which should be avoided. Instead, we'll use sys.exit() explicitly.\n\n\ndef get_input(axis): # De-nest this. Flat is better than nested.\n while True:\n position = input(f\"{axis}-Axis: \") # Short, clear variable naming\n try:\n position = int(position) # this will raise a ValueError when it's not a valid int\n if not 0 < position < 8: # same as 1 <= position <= 7. Use whichever one you like.\n raise ValueError # ValueError is for invalid values, like out of range.\n except ValueError: # Only catch strings which aren't ints and ints out of range. That's the only expected problem here, so other Exceptions should propagate.\n print(\"Please enter an integer between 1 and 7 inclusive.\")\n continue\n return position # Why use else: break? Returning also breaks.\n\n\ndef game(): # Module level function. Avoid deep nesting if you can.\n \"\"\"\n Ripped from https://stackoverflow.com/questions/57813858/iteratively-assigning-variables-in-python/57813901#57813901\n \"\"\" # Looks like a docstring. Let's position it correctly\n a, b, c = (int(7 * random() + 1) for _ in range(3)) # Like @Reinderien said\n # I'd prefer meaningful names here as well, but it's short enough that it's not a huge issue, and hard to come up\n # with.\n print(\"LOST IN SPACE:\\nYou have fifteen hours to find a capsule lost in a SEVEN kilometer cube of space.\\n\")\n # Intro for every new game, instead of only the first game.\n for turn in range(5): # Variable names should be meaningful\n # 15 turns is enough to figure out a 2^15 = 32768 Kilometer cubed space, since you can solve all axis at the \n # same time. 5 turns is plenty. If you go for 15 turns, you can return only 1 distance identifier to make it\n # more challenging. Simply continue after printing any of them.\n print(f\"You have {5 - turn} hours of air left.\") # This makes more sense -before- coordinate input\n print(\"Input 3 search coordinates\")\n d, e, f = [get_input(axis) for axis in \"YXZ\"]\n print(f\"Searching at ({d}, {e}, {f})\") # f-strings are amazing. Also, explain what you're doing instead of\n # dumping variables to the console.\n if a > d: # If victorious, this won't print anything anyway:\n print(\"UP\")\n elif a < d:\n print(\"DOWN\")\n if b > e:\n print(\"PORT\")\n elif b < e:\n print(\"STARBOARD\")\n if c > f:\n print(\"FORWARD\")\n elif c < f:\n print(\"BACKWARD\")\n # Lets do all program flow changes at the end of the loop instead of halfway.\n if a == d and b == e and c == f: # Old: A == D and B == E and F == C. Why was the order of F == C mixed up\n # compared to the other comparisons ?\n # Since you just spend an hour searching, you have 1 hour less left. This lets you complete the game with \n # 0 hours left - just in time.\n print(f\"You found the capsule with {4 - turn} hours of air left\") # f-strings! Also, explain what you found.\n return # Back to main menu. No dedicated function needed.\n if turn == 3: # python iteration starts at zero, so the last iteration will be 4, and the warning at 3.\n print(\"Choose your next move carefully... HYPOXIA IMMINENT.\")\n\n print(f\"Fail, astronaut dead; capsule was at coordinates ({a}, {b}, {c})\") # f-string. Also, coordinates are \n # generally given as (1, 2, 3) instead of 1.2.3\n\n\ndef main():\n # Use this function as main menu.\n game() # Run once, then ask for playing again.\n while True:\n # If we only us a function result once, don't store it in a variable but use it directly. Also, make use of the\n # fact that input() prints a message.\n if input(\"Play again? Y/N\").lower() == \"y\":\n game()\n else:\n return 0 # Perhaps another script imports this function to play this game. That only works if we don't call\n # sys.exit directly. \n\n\nif __name__ == \"__main__\":\n # This activates the script when we run it.\n sys.exit(main())\n</code></pre>\n\n<p>Highlights:</p>\n\n<ol>\n<li>Removed 1-line function of winCondition. It didn't serve a purpose.</li>\n<li>When quitting a game, it's better to return than call another function. We don't need to remember anything anymore.</li>\n<li>Don't nest functions without a really good reason. Good reasons are things like factory functions. If you want them private instead of public, simply prefix them with an underscore.</li>\n<li>We don't need new classes like @Anders InvalidInputError. This error exactly matches the builtin ValueError in purpose, so we use that instead. (his variable naming point is good, even if I chose to not include it.)</li>\n<li>Separation of concerns. The game() function runs just a single game. The main() (menu) starts games. The get_input() earns it's keep with it's error checking.</li>\n<li>Removed end() function. It did the work of the main menu, so that's where it's code went.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T12:43:23.303",
"Id": "443109",
"Score": "4",
"body": "*\"In python, code clarity and readability is more important than conciseness.\"* That is almost universally true, not just for Python."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T12:48:55.293",
"Id": "443110",
"Score": "0",
"body": "Question was about conciseness, so I wanted to give a counterpoint as to why I didn't consider that a high priority. Perhaps I shouldn't restrict it like that, but IMO there's a few reasons Python has it more important than some others - primarily the syntactic meaning of indentation and related concepts."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T11:01:27.310",
"Id": "227561",
"ParentId": "227543",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "227544",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T23:39:04.330",
"Id": "227543",
"Score": "13",
"Tags": [
"python",
"number-guessing-game",
"basic-lang"
],
"Title": "Python reimplementation of Lost In Space by Tim Hartnell"
}
|
227543
|
<p>The following code solves Project Euler Problem <a href="https://projecteuler.net/problem=121" rel="nofollow noreferrer">121</a>. I will quote the description of the problem</p>
<blockquote>
<p>A bag contains one red disc and one blue disc. In a game of chance a player takes a disc at random and its colour is noted. After each turn the disc is returned to the bag, an extra red disc is added, and another disc is taken at random.</p>
<p>The player pays £1 to play and wins if they have taken more blue discs
than red discs at the end of the game.</p>
<p>If the game is played for four turns, the probability of a player
winning is exactly 11/120, and so the maximum prize fund the banker
should allocate for winning in this game would be £10 before they
would expect to incur a loss. Note that any payout will be a whole
number of pounds and also includes the original £1 paid to play the
game, so in the example given the player actually wins £9.</p>
<p>Find the maximum prize fund that should be allocated to a single game
in which fifteen turns are played.</p>
</blockquote>
<p>I will explain my reasoning using example provided by the Euler:</p>
<p>So we have 4 turns (N = 4). Problem specifies that we need to pick more blue discs than red discs. In other words, we need to pick either 3 blue discs of 4 blue discs in order to win. </p>
<p>If we pick 4 blue discs, calculating probability is simple: 1/2 * 1/3 * 1/4 * 1/5 = 1/120</p>
<p>However, with 3 blue discs, situation is slightly more complicated, because there 4 ways to pick 3 blue discs in 4 turns, i.e</p>
<ol>
<li><p>Blue Blue Blue Red</p></li>
<li><p>Blue Blue Red Blue</p></li>
<li><p>Blue Red Blue Blue</p></li>
<li><p>Red Blue Blue Blue</p></li>
</ol>
<p>And because for each turn we put an extra red disc into the bag, the probability of picking disc at attempt n will be different from picking disc at attempt n±1, hence we need to calculate probabilities for each variation separately. </p>
<p>After we calculated probabilities for 3 blue discs we end up with 10/120. Adding up probability of picking 4 blue discs, we have:</p>
<p>10/120 + 1/120 = 11/120</p>
<p>And to find the maximum prize fund, we divide 1 by 11/120:</p>
<p>1/(11/120) = 120/11 ~ 10.9</p>
<p>And take floor of that value:</p>
<p>floor(10.9) = 10. Which tallies with the Euler's answer.</p>
<p>The code is following:</p>
<pre><code>import math
from itertools import combinations
import time
start = time.time()
def _121_(N): #N - number of turns
TOTAL_PROBABILITY = 0
#Calclulate min number of blue discs you need to pick in order to win the game
if N % 2 == 1: minimum_picks = int(math.ceil(N/2))
else: minimum_picks = int((N/2) +1)
#Calculate probabilities for picking blue or red disc at nth attempt
blue = [1/x for x in range(2,N+2)]
red = [1-x for x in blue]
#Calculate probabilities of all variations
indeces_chain = set(range(N))
for V in range(minimum_picks,N+1):
blue_indeces = list(combinations(indeces_chain,V))
for M in blue_indeces:
cumul = 1
for blue_prob in M:
cumul*= blue[blue_prob]
for red_prob in indeces_chain.difference(set(M)):
cumul*=red[red_prob]
TOTAL_PROBABILITY+=cumul
return TOTAL_PROBABILITY
print(math.floor(1/(_121_(15))))
print(time.time() - start)
</code></pre>
<hr>
<p>I suppose there are a <em>lot</em> of things that may be improved. Hence I'm glad to hear any suggestions/remarks. Thanks!</p>
<p>P.S I believe the part of the code after "#Calculate probabilities of all variations" is the most confusing. Because the post is already lengthy, I decided not to elaborate on that part. However, if you think that I must explain that too, I will edit my post to do so.</p>
|
[] |
[
{
"body": "<p>For a start, the code is missing several items of whitespace which PEP8 says it should have. There are automated PEP8 checkers which will tell you more.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>def _121_(N): #N - number of turns\n</code></pre>\n</blockquote>\n\n<p>The Pythonic way to document the arguments is with a docstring.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> TOTAL_PROBABILITY = 0\n</code></pre>\n</blockquote>\n\n<p>This use of upper case is also not conventional.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> #Calclulate min number of blue discs you need to pick in order to win the game\n if N % 2 == 1: minimum_picks = int(math.ceil(N/2))\n else: minimum_picks = int((N/2) +1)\n</code></pre>\n</blockquote>\n\n<p>This can be simplified. The first line says that if <span class=\"math-container\">\\$n = 2k + 1\\$</span> then we want <span class=\"math-container\">\\$k+1\\$</span>; the second line says that if <span class=\"math-container\">\\$n = 2k\\$</span> then we want <span class=\"math-container\">\\$k+1\\$</span>. So</p>\n\n<pre><code> minimum_picks = 1 + N // 2\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> #Calculate probabilities of all variations\n indeces_chain = set(range(N))\n</code></pre>\n</blockquote>\n\n<p>The plural of <em>index</em> is <em>indexes</em> or <em>indices</em>, depending on the context. But spelling aside, I'm not sure what this name means. To me, <em>chain</em> implies ordering, and a <code>set</code> is unordered.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> for V in range(minimum_picks,N+1):\n blue_indeces = list(combinations(indeces_chain,V))\n for M in blue_indeces:\n cumul = 1\n for blue_prob in M:\n cumul*= blue[blue_prob]\n for red_prob in indeces_chain.difference(set(M)):\n cumul*=red[red_prob]\n</code></pre>\n</blockquote>\n\n<p>I think it would be simpler to turn the combination into a <code>set</code> and then iterate over the indexes:</p>\n\n<pre><code>blue_indexes = set(combinations(range(N), V))\ncumul = 1\nfor index in range(N):\n cumul *= blue[index] if index in blue_indexes else red[index]\n</code></pre>\n\n<hr>\n\n<p>Also, although this finishes inside the minute, it's not very efficient. Specifically, the number of combinations is exponential in the input. I would encourage you as an exercise to try to find a way of solving the problem which is quadratic in the input.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T12:17:22.223",
"Id": "443104",
"Score": "0",
"body": "Thank you for your response! One question: Why is the use of the upper case when naming variables not conventional (TOTAL_PROBABILITY)? And how would you name this variable then?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T12:23:06.787",
"Id": "443105",
"Score": "2",
"body": "@Nelver, see [PEP8's prescriptions on naming conventions](https://www.python.org/dev/peps/pep-0008/#prescriptive-naming-conventions). It's a local variable, so it would be `total_probability`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T10:58:59.620",
"Id": "227560",
"ParentId": "227559",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227560",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T10:20:15.033",
"Id": "227559",
"Score": "2",
"Tags": [
"python",
"programming-challenge"
],
"Title": "Project Euler 121"
}
|
227559
|
<p>The below code was written to generate γ, for educational purposes.</p>
<p>My general methodology is as follows:
Compute Gamma via the accepted answer's algorithm <a href="https://math.stackexchange.com/questions/129777/what-is-the-fastest-most-efficient-algorithm-for-estimating-eulers-constant-g">here</a>.</p>
<p>In order to do this I need to compute the natural log of a large k. </p>
<ol>
<li><p>Compute Pi via the AGM as <a href="https://en.wikipedia.org/wiki/Gauss%E2%80%93Legendre_algorithm" rel="nofollow noreferrer">here</a>.</p></li>
<li><p>Compute the natural log of 2 via the last algorithm <a href="https://en.wikipedia.org/wiki/Natural_logarithm_of_2#BBP-type_representations" rel="nofollow noreferrer">here</a>.</p></li>
<li><p>Compute the natural log of a large k via Gauss's AGM method <a href="https://en.wikipedia.org/wiki/Logarithm#Arithmetic%E2%80%93geometric_mean_approximation" rel="nofollow noreferrer">here</a>.</p></li>
<li><p>Compute Gamma as described in the accepted answer <a href="https://math.stackexchange.com/questions/129777/what-is-the-fastest-most-efficient-algorithm-for-estimating-eulers-constant-g">here</a>.
I am very grateful to the community for sharing the knowledge and I have improved the speed by orders of magnitude <a href="https://codereview.stackexchange.com/q/227520/">compared to the previous version</a> (because of the accepted answers improvements).</p></li>
</ol>
<p>One can pip3 install tqdm to see progress, I've wrapped a few ranges with it.</p>
<pre><code>import decimal
#non-builtin
from tqdm import tqdm
D = decimal.Decimal
def agm(a, b): #Arithmetic Geometric Mean
a, b = D(a),D(b)
for x in tqdm(range(prec)):
a, b = (a + b) / 2, (a * b).sqrt()
return a
def pi_agm(): #Pi via AGM and lemniscate
print('Computing Pi...')
a, b, t, p, pi, k = 1, D(2).sqrt()/2, 1/D(2), 2, 0, 0
while 1:
an = (a+b)/2
b = (a*b).sqrt()
t -= p*(a-an)**2
a, p = an, 2**(k+2)
piold = pi
pi = ((a+b)**2)/(2*t)
k += 1
if pi == piold:
break
return pi
def factorial(x ,pfact, pfactprd):
x = int(x)
if pfact == (x-1):
return pfactprd*x
else:
factorial = D(1)
for i in range(1, x+1):
factorial *= i
return factorial
def lntwo(): #Fast converging Ln 2
print('Computing Ln(2)...')
def lntwosum(n, d, b):
logsum, logold, e = D(0), D(0), 0
while 1:
logold = logsum
logsum += D(1/((D(b**e))*((2*e)+1)))
e += 1
if logsum == logold:
return (D(n)/D(d))*logsum
logsum1 = lntwosum(14, 31, 961)
logsum2 = lntwosum(6, 161, 25921)
logsum3 = lntwosum(10, 49, 2401)
ln2 = logsum1 + logsum2 + logsum3
return ln2
def lnagm(x): #Natural log of via AGM,
try:
if int(x) == 1:
return 0
if int(x) == 2:
return lntwo()
except:
pass
m = prec*2
ln2 = lntwo()
decimal.getcontext().prec = m
pi = D(pi_agm())
print('Computing Ln(x)...')
twoprec = D(2**(2-D(m)))/D(x)
den = agm(1, twoprec)*2
diff = m*ln2
result = (D(pi/den) - D(diff))
logr = D(str(result)[:m//2])
decimal.getcontext().prec = prec
return logr
def gamma(): #Compute Gamma from Digamma Expansion
print('Computing Gamma!')
k = D(prec//2)
lnk = lnagm(k)
upper = int((12*k)+2)
print('Summing...')
# First Sum
logsum = D(0)
pterm = D((k**2)/2)
for r in tqdm(range(1, upper)):
r = D(r)
logsum += pterm
nterm = D(((-1)*D(k)*D(r+1))/(r*(r+2)))*pterm
pterm = nterm
logsum1 = D(0)
print('...')
pfact, pfactprd = 1, 1
for r in tqdm(range(1, upper)):
calfact = factorial((r-1), pfact, pfactprd)
pfact, pfactprd = (r-1), calfact
logsum1 += D((D(-1)**D(r-1))*(k**D(r+1)))/D(calfact*D(D(r+1)**2))
twofac = D(2)**(-k)
gammac = str(D(1)-(lnk*logsum)+logsum1+twofac)
return D(gammac[:int(prec//6.66)])
#Calling Gamma
prec = int(input('Precision for Gamma: '))*8
decimal.getcontext().prec = prec
gam = gamma()
print('\n')
print(gam)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T11:41:19.380",
"Id": "443101",
"Score": "2",
"body": "Please pardon my ignorance: What are “functional zeroes” and “binary splitting” (in this context)? – It might also help to understand (and judge) your code if you shortly present (or give links to) the underlying formulae."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T17:02:32.637",
"Id": "443138",
"Score": "0",
"body": "Pardon my lack of explanation, I was referring to avoiding the Brent-McMillan being computed via the binary splitting method as seen on the last entry here http://www.numberworld.org/y-cruncher/internals/binary-splitting-library.html"
}
] |
[
{
"body": "<p>Firstly, this code has a couple of dozen PEP8 formatting violations. Following conventions generally helps readability.</p>\n\n<p>Also on the subject of readability, comments providing references for the formulae used should be considered essential in mathematical software.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>def agm(a, b): #Arithmetic Geometric Mean\n</code></pre>\n</blockquote>\n\n<p>The conventional way of documenting a function is with a docstring. That also allows you to document the expected input types (<code>decimal.Decimal</code>? <code>float</code>?).</p>\n\n<hr>\n\n<blockquote>\n<pre><code>def pi_agm(): #Pi via AGM and lemniscate\n print('Computing Pi...')\n a, b, t, p, pi, k = 1, D(2).sqrt()/2, 1/D(2), 2, 0, 0\n while 1:\n an = (a+b)/2\n b = (a*b).sqrt()\n t -= p*(a-an)**2\n a, p = an, 2**(k+2)\n piold = pi\n pi = ((a+b)**2)/(2*t)\n k += 1\n if pi == piold:\n break\n return pi\n</code></pre>\n</blockquote>\n\n<p>The <code>while</code> loop is unnecessarily ugly: <code>while True</code> would be preferable. I would say that it would be even better to use the loop index as a loop index with <code>for k in itertools.count()</code>, but actually that variable is wholly unnecessary.</p>\n\n<p>If find it unhelpful to initialise six variables in one line where some of them are quite complicated. On the other hand, it could be more helpful to combine some of the updates in the loop body. Perhaps the happy medium is something like</p>\n\n<pre><code> a, b, t = 1, D(0.5).sqrt(), 1\n p, pi = 1, 0\n while True:\n a, b, t = (a+b)/2, (a*b).sqrt(), t - p*(a-b)**2\n p, piold, pi = 2*p, pi, (a+b)**2 / t\n</code></pre>\n\n<p>I'm not entirely convinced by</p>\n\n<blockquote>\n<pre><code> if pi == piold:\n break\n</code></pre>\n</blockquote>\n\n<p>Sometimes iterative approaches in finite data types oscillate around the solution rather than converging definitively. It might be more robust to track the last two or three values and, on finding a loop, return the average of the values in the loop.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>def factorial(x ,pfact, pfactprd): \n x = int(x)\n</code></pre>\n</blockquote>\n\n<p>Do you expect to pass a non-<code>int</code>? See previous note about using docstrings to document types.</p>\n\n<blockquote>\n<pre><code> if pfact == (x-1):\n return pfactprd*x\n else:\n factorial = D(1)\n for i in range(1, x+1):\n factorial *= i\n return factorial\n</code></pre>\n</blockquote>\n\n<p>Is the <code>else</code> ever actually used? Might it be more maintainable to remove this function entirely?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> def lntwosum(n, d, b):\n logsum, logold, e = D(0), D(0), 0\n while 1:\n logold = logsum\n logsum += D(1/((D(b**e))*((2*e)+1)))\n e += 1\n if logsum == logold:\n return (D(n)/D(d))*logsum\n</code></pre>\n</blockquote>\n\n<p>Here the previous comment about <code>itertools.count</code> is relevant.</p>\n\n<p>I'm confused as to why <code>D</code> is invoked where it is. Without any comments to justify it, it appears to be done at random.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>def lnagm(x): #Natural log of via AGM,\n try:\n if int(x) == 1:\n return 0\n if int(x) == 2:\n return lntwo()\n except:\n pass\n</code></pre>\n</blockquote>\n\n<p>??? Are you expecting <code>int(x)</code> to throw an exception?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> pi = D(pi_agm())\n</code></pre>\n</blockquote>\n\n<p>See previous comments about appearing to use <code>D</code> at random. Here, if <code>pi_agm()</code> returns a <code>decimal.Decimal</code> then it's unnecessary, and if it doesn't then surely that would be a bug because <code>pi</code> won't have the necessary precision? I don't see any further polishing of its error.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> decimal.getcontext().prec = m\n ...\n logr = D(str(result)[:m//2])\n decimal.getcontext().prec = prec\n return logr\n</code></pre>\n</blockquote>\n\n<p>Would the following work?</p>\n\n<pre><code> decimal.getcontext().prec = m\n ...\n decimal.getcontext().prec = prec\n return D(result)\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> k = D(prec//2)\n ...\n upper = int((12*k)+2)\n</code></pre>\n</blockquote>\n\n<p>Why not just <code>upper = 6*prec + 2</code> with no need to coerce?</p>\n\n<hr>\n\n<p>Other earlier comments also apply to <code>gamma</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>#Calling Gamma\nprec = int(input('Precision for Gamma: '))*8\ndecimal.getcontext().prec = prec\ngam = gamma()\nprint('\\n')\nprint(gam)\n</code></pre>\n</blockquote>\n\n<p>It's a Python best practice, which serves to make the file reusable as a library, to guard this with <code>if __name__ == \"__main__\":</code>.</p>\n\n<p>A comment explaining the <code>*8</code> would be useful. At a guess, <code>prec</code> is in bits?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T16:54:08.107",
"Id": "443135",
"Score": "0",
"body": "Prec in bits- correct. Thank you for corrections. I do realize this is quite a pep felon. I appreciate you pointing out the type and functional redundancies. You have given me a good guide to clean up this code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T12:15:45.173",
"Id": "227565",
"ParentId": "227562",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227565",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T11:03:38.863",
"Id": "227562",
"Score": "1",
"Tags": [
"python",
"mathematics",
"numerical-methods"
],
"Title": "Euler-Mascheroni Single Thread Speed Improvements"
}
|
227562
|
<p>I've implemented the <a href="https://en.wikipedia.org/wiki/Pig_(dice_game)" rel="nofollow noreferrer">game of Pig</a> in JavaScript. My implementation has the following rules:</p>
<ul>
<li>Two players take turns playing in rounds.</li>
<li>In a round, the player rolls a single die as many times as they wish, with the sum of their results becoming their score for that round.</li>
<li>If the player rolls a 1, then their score for that round goes to 0 and the other player takes a turn.</li>
<li>At any point in time, the current play may choose to <em>hold</em>, which adds their round score to their total score, and play passes to the other player.</li>
<li>The first player whose total score reaches 100 wins the game.</li>
</ul>
<p>For my assignment, I had to add the following additional rules:</p>
<blockquote>
<ol>
<li>A player loses his <em>entire</em> score when he rolls two 6 in a row. After that, it's the next player's turn. (Hint: Always save the
previous dice roll in a separate variable)</li>
<li>Add an input field to the HTML where players can set the winning score, so that they can change the predefined score of 100. (Hint:
you can read that value with the <code>.value</code> property in JavaScript. This
is a good opportunity to use Google to figure this out :)</li>
<li>Add another die to the game, so that there are two dice now. The player loses his current score when one of them is a 1. (Hint: you
will need CSS to position the second die, so take a look at the CSS
code for the first one.)</li>
</ol>
</blockquote>
<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>/*
YOUR 3 CHALLENGES
Change the game to follow these rules:
1. A player looses his ENTIRE score when he rolls two 6 in a row. After that, it's the next player's turn.
(Hint: Always save the previous dice roll in a separate variable)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2. Add an input field to the HTML where players can set the winning score, so that they can change the predefined score of 100.
(Hint: you can read that value with the .value property in JavaScript. This is a good oportunity to use google to figure this out :)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3. Add another dice to the game, so that there are two dices now. The player looses his current score when one of them is a 1.
(Hint: you will need CSS to position the second dice, so take a look at the CSS code for the first one.)
*/
var scores , roundScore , activePlayer , gamePlaying , i , array , changeScore ;
init();
document.querySelector('.btn-roll').addEventListener( 'click' , function () {
if (gamePlaying) {
var dice = Math.floor(Math.random()*6)+1;
var diceTwo = (Math.floor(Math.random()*6)+1);
var diceDOM= document.querySelector('.dice');
diceDOM.style.display = 'block';
document.querySelector('.dice-two').style.display = 'block';
diceDOM.src = 'dice-' + dice +'.png';
document.querySelector('.dice-two').src = 'dice-' + diceTwo +'.png';
if (dice !== 1 && diceTwo !== 1) {
roundScore =roundScore + dice + diceTwo;
document.getElementById('current-'+ activePlayer).textContent = roundScore;
array[i]=dice;
i = i +1 ;
if (dice == 6 && array[i-2] == 6 ) {
nextPlayer();
}
} else {
nextPlayer();
}
}
})
document.querySelector('.btn-hold').addEventListener( 'click' , function () {
if (gamePlaying) {
scores[activePlayer] += roundScore;
document.querySelector('#score-'+ activePlayer).textContent = scores[activePlayer];
if (scores[activePlayer] >= changeScore ) {
document.getElementById('name-'+ activePlayer).textContent = "Winner!";
document.querySelector('.dice').style.display = 'none';
document.querySelector('.player-' + activePlayer +'-panel').classList.add('winner');
document.querySelector('.player-' + activePlayer +'-panel').classList.remove('active');
gamePlaying = false ;
} else {
nextPlayer();
}
}
})
function nextPlayer () {
activePlayer === 1 ? activePlayer = 0 : activePlayer = 1;
roundScore = 0;
document.getElementById('current-0').textContent = '0';
document.getElementById('current-1').textContent = '0';
document.querySelector('.player-0-panel').classList.toggle('active');
document.querySelector('.player-1-panel').classList.toggle('active');
document.querySelector('.dice').style.display = 'none';
document.querySelector('.dice-two').style.display = 'none';
array = [];
}
document.querySelector('.btn-new').addEventListener( 'click' , init);
document.getElementById('changeScore-btn').addEventListener( 'click' , function(){
changeScore = document.getElementById("changeScore-input").value;
alert("to win you need "+changeScore+" score points ");
});
function init() {
scores = [0,0];
roundScore = 0;
activePlayer = 0;
gamePlaying = true;
document.getElementById('score-0').textContent = '0';
document.getElementById('score-1').textContent = '0';
document.getElementById('current-0').textContent = '0';
document.getElementById('current-1').textContent = '0';
document.querySelector('.dice').style.display = 'none';
document.querySelector('.dice-two').style.display = 'none';
document.getElementById('name-0').textContent = "Player 1!";
document.getElementById('name-1').textContent = "Player 2!";
document.querySelector('.player-0-panel').classList.remove('active');
document.querySelector('.player-1-panel').classList.remove('active');
document.querySelector('.player-0-panel').classList.add('active');
i = 0;
array = [];
changeScore = 20;
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>/**********************************************
*** GENERAL
**********************************************/
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.clearfix::after {
content: "";
display: table;
clear: both;
}
body {
background-image: linear-gradient(rgba(62, 20, 20, 0.4), rgba(62, 20, 20, 0.4)), url(back.jpg);
background-size: cover;
background-position: center;
font-family: Lato;
font-weight: 300;
position: relative;
height: 100vh;
color: #555;
}
.wrapper {
width: 1000px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: #fff;
box-shadow: 0px 10px 50px rgba(0, 0, 0, 0.3);
overflow: hidden;
}
.player-0-panel,
.player-1-panel {
width: 50%;
float: left;
height: 600px;
padding: 100px;
}
/**********************************************
*** PLAYERS
**********************************************/
.player-name {
font-size: 40px;
text-align: center;
text-transform: uppercase;
letter-spacing: 2px;
font-weight: 100;
margin-top: 20px;
margin-bottom: 10px;
position: relative;
}
.player-score {
text-align: center;
font-size: 80px;
font-weight: 100;
color: #EB4D4D;
margin-bottom: 130px;
}
.active { background-color: #f7f7f7; }
.active .player-name { font-weight: 300; }
.active .player-name::after {
content: "\2022";
font-size: 47px;
position: absolute;
color: #EB4D4D;
top: -7px;
right: 10px;
}
.player-current-box {
background-color: #EB4D4D;
color: #fff;
width: 40%;
margin: 0 auto;
padding: 12px;
text-align: center;
}
.player-current-label {
text-transform: uppercase;
margin-bottom: 10px;
font-size: 12px;
color: #222;
}
.player-current-score {
font-size: 30px;
}
button {
position: absolute;
width: 200px;
left: 50%;
transform: translateX(-50%);
color: #555;
background: none;
border: none;
font-family: Lato;
font-size: 20px;
text-transform: uppercase;
cursor: pointer;
font-weight: 300;
transition: background-color 0.3s, color 0.3s;
}
button:hover { font-weight: 600; }
button:hover i { margin-right: 20px; }
button:focus {
outline: none;
}
i {
color: #EB4D4D;
display: inline-block;
margin-right: 15px;
font-size: 32px;
line-height: 1;
vertical-align: text-top;
margin-top: -4px;
transition: margin 0.3s;
}
.btn-new { top: 45px;}
.btn-roll { top: 403px;}
.btn-hold { top: 467px;}
.dice {
position: absolute;
left: 50%;
top: 178px;
transform: translateX(-50%);
height: 100px;
box-shadow: 0px 10px 60px rgba(0, 0, 0, 0.10);
}
.dice-two {
position: absolute;
left: 50%;
top: 287px;
transform: translateX(-50%);
height: 100px;
box-shadow: 0px 10px 60px rgba(0, 0, 0, 0.10);
}
.winner { background-color: #f7f7f7; }
.winner .player-name { font-weight: 300; color: #EB4D4D; }</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css?family=Lato:100,300,600" rel="stylesheet" type="text/css">
<link href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css">
<link type="text/css" rel="stylesheet" href="style.css">
<title>Pig Game</title>
</head>
<body>
<div class="wrapper clearfix">
<div class="player-0-panel active">
<div class="player-name" id="name-0">Player 1</div>
<div class="player-score" id="score-0">43</div>
<div class="player-current-box">
<div class="player-current-label">Current</div>
<div class="player-current-score" id="current-0">11</div>
</div>
</div>
<div class="player-1-panel">
<div class="player-name" id="name-1">Player 2</div>
<div class="player-score" id="score-1">72</div>
<div class="player-current-box">
<div class="player-current-label">Current</div>
<div class="player-current-score" id="current-1">0</div>
</div>
</div>
<button class="btn-new"><i class="ion-ios-plus-outline"></i>New game</button>
<button class="btn-roll"><i class="ion-ios-loop"></i>Roll dice</button>
<button class="btn-hold"><i class="ion-ios-download-outline"></i>Hold</button>
<img src="dice-5.png" alt="Dice" class="dice">
<img src="dice-5.png" alt="Dice" class="dice-two">
</div>
<input type="text" id="changeScore-input" >
<button id="changeScore-btn">change score</button>
<script src="app.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T14:09:51.567",
"Id": "443114",
"Score": "0",
"body": "Welcome to Code Review! From your question, it seems like you are unsure of whether or not your code is functioning correctly - \"Who can evaluate the completion of tasks\". Code Review is only for reviewing complete and functional code; we don't help you meet the task, but we may suggest better ways to complete the task. Can you please [edit][https://codereview.stackexchange.com/posts/227564/edit] your question to clarify whether or not the code is complete and correct to the best of your knowledge?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T14:15:46.320",
"Id": "443115",
"Score": "0",
"body": "Additionally, your code doesn't seem to run correctly as a snippet. Is it not working correctly at all, or is it an issue with how it transformed into a snippet? Can you update it to function correctly in the snippet or provide a link to see it working correctly?"
}
] |
[
{
"body": "<p>Whenever possible put the styling in the CSS. Avoid doing it in the JavaScript like this.\nFor example, you could add it to your <code>.dice</code> style. (Note: same goes for other parts of your code)</p>\n\n<pre><code>diceDOM.style.display = 'block';\n</code></pre>\n\n<p>Use shorthand <code>+=</code>. (Note: same goes for other parts of your code)</p>\n\n<pre><code>roundScore =roundScore + dice + diceTwo;\n</code></pre>\n\n<p>'array' is a bad name for a variable. It's not descriptive.\nIt's also a keyword in a lot of languages, so you should avoid it anyway</p>\n\n<pre><code>array[i]=dice;\n</code></pre>\n\n<p>No need for an if statement here, both paths do the same thing</p>\n\n<pre><code>if (dice == 6 && array[i-2] == 6 ) {\n nextPlayer();\n}\n\n} else { \n nextPlayer();\n}\n</code></pre>\n\n<p>Change your ternary from this:</p>\n\n<pre><code>activePlayer === 1 ? activePlayer = 0 : activePlayer = 1;\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>activePlayer = activePlayer === 1 ? 0 : 1;\n</code></pre>\n\n<p>Hopefully your 'challenges' were posted by a mistake, as a result of copying & pasting the instructions.\nIt wouldn't be right to do any part of your assignment for you. Code reviewing it is already crossing a line, probably.</p>\n\n<p>However I will say the challenge should definitely get you thinking about ways to refactor your code.\nIn real life changes happen all the time. The customer suddenly wants this or that feature added. You should always write you code in such a way it can be changed easily.</p>\n\n<p>For example what if you want to erase the score on a '6' roll? You'd need to scroll through your code looking for the area that handles dice rolls.\nBut if you had a method it's blanetly obvious (As an added bonus, easier to read the code):</p>\n\n<pre><code>function shouldScoreBeErased(dice1, dice2)\n{\n return dice1 == 1 || dice2 == 1;\n}\n</code></pre>\n\n<p>You should also have a method for erasing the score etc.\nTo add the dice being 6 twice in a row feature, you'd need to keep track of previous rolls as well. (Tbh you should be anyways, showing the history of the game at the end could be a nice feature!)</p>\n\n<p>You should also have a method for writing the score, dice etc to the DOM. Again making it easier for maintanability.</p>\n\n<p>Instead of 'dice1' and 'dice2' I strongly recommend using an array of dice. Again for maintanability (adding new dice or removing one). It also gets rid of the grammer awkwardness ('1 Dice' is actually called a 'die')</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T13:59:59.800",
"Id": "227569",
"ParentId": "227564",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T11:59:32.893",
"Id": "227564",
"Score": "0",
"Tags": [
"javascript",
"html",
"game",
"css",
"homework"
],
"Title": "The Game of Pig in JavaScript"
}
|
227564
|
<p><a href="https://projecteuler.net/problem=112" rel="noreferrer">Problem</a> statement:</p>
<blockquote>
<p>Working from left-to-right if no digit is exceeded by the digit to its
left it is called an increasing number; for example, 134468.</p>
<p>Similarly if no digit is exceeded by the digit to its right it is
called a decreasing number; for example, 66420.</p>
<p>We shall call a positive integer that is neither increasing nor
decreasing a "bouncy" number; for example, 155349.</p>
<p>Clearly there cannot be any bouncy numbers below one-hundred, but just
over half of the numbers below one-thousand (525) are bouncy. In fact,
the least number for which the proportion of bouncy numbers first
reaches 50% is 538.</p>
<p>Surprisingly, bouncy numbers become more and more common and by the
time we reach 21780 the proportion of bouncy numbers is equal to 90%.</p>
<p>Find the least number for which the proportion of bouncy numbers is
exactly 99%.</p>
</blockquote>
<p>My code:</p>
<pre><code>import time
start = time.time()
def bouncy(N):
'''Function determines whether arbitrary number N is a bouncy number.'''
number = list(str(N))
n1 = list(str(N))
n2 = list(str(N))
n1.sort()
n2.sort(reverse=True)
if (number != n1 and number != n2):
return True
else:
return False
def find():
start = 1
total = 0
bou = 0
while True:
total += 1
if bouncy(start):
bou += 1
if bou/total >= 0.99:
break
start += 1
return start
print(find())
print(time.time() - start)
</code></pre>
<hr>
<p>What can be improved?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T18:29:26.467",
"Id": "443288",
"Score": "1",
"body": "Just FYI, [here](https://www.hackerrank.com/contests/projecteuler/challenges/euler112/problem) is an extended version of the same problem that requires to accept larger inputs (the website provides tests for the extended versions of the [first 239 Project Euler problems](https://www.hackerrank.com/contests/projecteuler/challenges)). For those inputs, a better algorithm is necessary to pass the tests."
}
] |
[
{
"body": "<h1>Code structure</h1>\n\n<p>The most common and widely accepted structure found in Python scripts from a high-level point of view looks something like:</p>\n\n<pre><code># imports\nimport\n...\n\n# functions and classes, aka \"library code\"\nclass Foo:\n ...\n\ndef bar(batz):\n ...\n\nif __name__ == \"__main__\":\n # part that is supposed to be run as script\n ...\n\n</code></pre>\n\n<p>Your code on the other hand does not follow this structure since there is some script code at the top (<code>start = time.time()</code>), then come your functions, followed by another block of script code. I highly recommend to follow that structure.</p>\n\n<p><strong>Further reading:</strong> Explanation of <code>if __name__ == \"__main__\":</code> from the <a href=\"https://docs.python.org/3/library/__main__.html\" rel=\"noreferrer\">official Python documentation</a>.</p>\n\n<h1>The code itself</h1>\n\n<h2><code>bouncy</code></h2>\n\n<p>The most striking aspect of <code>bouncy</code> from a stylistic point is the capital <code>N</code> as parameter name that goes against the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">official Style Guide for Python Code</a> (often just called PEP8). Usually parameter and variable names are written in <code>snake_case</code>, e.g. small letters, possibly separated by underscores. </p>\n\n<p>With that said, let's look at the actual algorithm: </p>\n\n<blockquote>\n<pre><code>number = list(str(N))\nn1 = list(str(N))\nn2 = list(str(N))\n</code></pre>\n</blockquote>\n\n<p>Lots of repeated code here. An easy way out would be to do the conversion once, and copy the results afterwards. This can be done using slicing like <code>n1 = number[:]</code>, the <code>list</code> constructor <code>n1 = list(number)</code> or the <a href=\"https://docs.python.org/3/library/copy.html\" rel=\"noreferrer\"><code>copy</code></a> module. Also, <code>sorted</code> would create a copy indirectly, so no need to do this manually (see the next point).</p>\n\n<p>The next thing you do in your code is sorting those lists. Once ascending, then descending. Since the second one should by definition be the mirror of the previous one, you can use slicing again to avoid that second sort.</p>\n\n<pre><code>sorted_number = sorted(number) # <- also does a copy\n</code></pre>\n\n<p>Oh, and did you know that <code>sorted</code> does work on strings as well and simply returns a new list? (<code>sorted_number = sorted(N)</code>)</p>\n\n<p>You could also use the result of the condition directly as return value of your function.</p>\n\n<p>With some other minor changes you might end up with something like</p>\n\n<pre><code>def is_bouncy(number):\n '''Function determines whether arbitrary number N is a bouncy number.'''\n digits = list(str(number))\n sorted_digits = sorted(digits)\n return digits != sorted_digits and digits != sorted_digits[::-1]\n</code></pre>\n\n<h2><code>find</code></h2>\n\n<p><code>find</code> is almost as straightforward as it gets. I would advise to change the variable name <code>bou</code> to <code>bouncy</code> or <code>n_bouncy</code> now that the checking function is called <code>is_bouncy</code>. IMHO <code>current</code> would also likely be a better name for <code>start</code>. Also <code>find_bouncy_boundary</code>, maybe even with an optional \"expected bounciness percentage\" might be worth a thought.</p>\n\n<p>From an optimization point of view, you could also start from 1000 if you're only looking for that 99%, since the task description tells you that there are exactly 525 bouncy numbers below 1000 ;-) But there is likely not much to gain from that. </p>\n\n<h2>The rest</h2>\n\n<p>Now all there is left to do is to take the spread out script code, wrap it up in <code>if __name__ == \"__main__\":</code>, and collect it at the bottom of the script:</p>\n\n<pre><code>if __name__ == \"__main__\":\n start = time.time()\n print(find())\n print(time.time() - start)\n</code></pre>\n\n<p>If the script part becomes more complex, this part is often put into a separate <code>main()</code> method.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T15:07:21.173",
"Id": "443119",
"Score": "0",
"body": "`number != sorted_digits[::-1]` should be `digits != sorted_digits[::-1]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T15:28:03.967",
"Id": "443124",
"Score": "0",
"body": "@GZ0: you're correct. Will fix it :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T06:43:32.663",
"Id": "443210",
"Score": "0",
"body": "Actually, it is better to start from 21780 given from the problem statement that there are 2178 bouncy numbers among them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T07:36:16.493",
"Id": "443212",
"Score": "0",
"body": "@sanyash: That would be 10% then. The task states that exactly 90% are bouncy numbers below 21780, which would be about 19,602 then. Right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T07:49:01.490",
"Id": "443213",
"Score": "0",
"body": "@AlexV yeah, my mistake :) 2178 non-bouncy and 19602 bouncy."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T14:02:44.983",
"Id": "227570",
"ParentId": "227567",
"Score": "8"
}
},
{
"body": "<p>First of all, the question asks for the least number which the proportion is <strong>exactly</strong> 99%. Your code finds the first number that the proportion is more or equal to 99%. That is not quite right. Also, comparing floating-numbers is inaccurate and you should change it to integer comparision for exactness: <code>bou * 100 == total * 99</code></p>\n\n<p>Secondly, in the <code>bouncy</code> function, <code>list(str(N))</code> is repeated three times unnecessarily. The twice <code>sort</code> calls are also unnecessary. It can be improved as follows</p>\n\n<pre><code>def bouncy(n):\n number = [*str(n)]\n sorted_n = sorted(number)\n return sorted_n != number and sorted_n[::-1] != number\n</code></pre>\n\n<p>Thirdly, the overall algorithm is a naive one. If you need a better performance, a better approach is needed, e.g. by exploiting the fact that if <span class=\"math-container\">\\$n\\$</span> is a bouncy number, then <span class=\"math-container\">\\$10n+b\\$</span> for any <span class=\"math-container\">\\$b\\in[0,9]\\$</span> is also a bouncy number and does not need to be checked again.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T14:05:36.060",
"Id": "227571",
"ParentId": "227567",
"Score": "8"
}
},
{
"body": "<h1>Speed up the bouncy function</h1>\n\n<p>Since you are timing it, I guess speed if of essence. You are sorting a list twice, while you actually don't need to sort it at all. Instead, just check the digits two at a time and see that the difference never change sign. That is <code>O(n)</code> instead of <code>O(n*log(n))</code> as sorting.</p>\n\n<p>Here's the code. Further changes are highlighted in comments. It only runs slightly faster, 5.8 seconds instead of 8.1 on my machien. My guess is that the reason for the small performance improvement is that Python sorts in C, which makes it comparably fast. But that's just a guess.</p>\n\n<pre><code>import time\n\n\n# The big change is speeding up this function.\ndef bouncy(n): # Lower case n\n '''Function determines whether arbitrary number N is a bouncy number.'''\n # We can index directly into the string. No need to make a list of it.\n number = str(n)\n allowed_direction = 0\n # This could probably be done with cool fancy iterators somehow.\n for i in range(0, len(number) - 1):\n direction = cmp(number[i], number[i + 1])\n if allowed_direction == 0:\n allowed_direction = direction\n elif direction != 0 and allowed_direction != direction:\n return True\n return False\n\ndef cmp(a, b):\n return (a > b) - (a < b) \n\ndef find():\n # Clearer variable names.\n # The start variable was the same as total, so I removed it.\n total_count = 100 # Start at 100, no bouncy numbers below anyway!\n bouncy_count = 0\n while True:\n if bouncy(total_count):\n bouncy_count += 1\n if bouncy_count / total_count >= 0.99:\n # No need for a break here. We can just return instead.\n return total_count\n total_count += 1\n\n# Cleaner to have this together.\nstart = time.time()\nprint(find())\nprint(time.time() - start)\n</code></pre>\n\n<h1>You want it faster?</h1>\n\n<p>This brute force approach of checking each number is simple, but not fast. When you are at 150 000, you know that the next non bouncy number is going to be 155 555. The 5 555 number in between that you are checking is just a waste of CPU cycles.</p>\n\n<p>Implementing this is significantly harder, and is therefore left as an exercise for the reader.</p>\n\n<p><em>Edit: <a href=\"https://repl.it/repls/AlienatedWobblyImplementation\" rel=\"nofollow noreferrer\">Here's</a> a ballpark non solution using the above approach. It runs in 0.15 s on my machine.</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T14:10:57.757",
"Id": "227572",
"ParentId": "227567",
"Score": "6"
}
},
{
"body": "<h1><code>bouncy</code></h1>\n\n<p>You did a good job by extracting the check for bouncyness to a separate function. Plus points for the docstringThe function itself can be a bit better:</p>\n\n<p>You can use the builtin <code>sorted</code> instead of <code>list.sort</code>. And since a string is an iterable too, you don't need the explicit casts to <code>list</code>\nYou can also immediately return the result of the test <code>number != n1 and number != n2</code></p>\n\n<p>I don't like the names <code>n1</code> and <code>n2</code>. They are the increasing and decreasing order of digits, so call em that. <code>N</code></p>\n\n<pre><code>def bouncy(number):\n \"\"\"Function determines whether arbitrary number N is a bouncy number.\"\"\"\n digits = list(str(number))\n increasing = sorted(digits)\n decreasing = increasing[::-1]\n return digits != decreasing and digits != increasing\n</code></pre>\n\n<p>I've checked a few variations of this bouncyness check, but this is the fastest I can find.</p>\n\n<pre><code>def pairwise(iterable):\n \"s -> (s0,s1), (s1,s2), (s2, s3), ...\"\n a, b = tee(iterable)\n next(b, None)\n return zip(a, b)\n\ndef bouncy_pairwise(number):\n \"\"\"\n tests whether a number is bouncy\n \"\"\"\n digits = str(number)\n increasing = decreasing = False\n for a, b in pairwise(digits):\n if not increasing and a > b:\n increasing = True\n if not decreasing and a < b:\n decreasing = True\n if increasing and decreasing:\n return True\n</code></pre>\n\n<p>and </p>\n\n<pre><code>def bouncy_zip(number):\n \"\"\"\n tests whether a number is bouncy\n \"\"\"\n digits = str(number)\n increasing = decreasing = False\n for a, b in zip(digits, digits[1::]):\n if not increasing and a > b:\n increasing = True\n if not decreasing and a < b:\n decreasing = True\n if increasing and decreasing:\n return True\n</code></pre>\n\n<p>were faster when the bouncyness was in the beginning of the number, but slower for non-bouncy numbers</p>\n\n<h1><code>find</code></h1>\n\n<ul>\n<li>You have the 0.99 hardcoded. I would pass this on as an argument to the list</li>\n<li>Of the double variables <code>total</code> and <code>start</code>, only 1 is needed </li>\n<li>Instead of the <code>break</code>, just <code>return</code> there</li>\n<li>instead of the <code>while True</code> loop, use <code>itertools.count</code></li>\n<li>no need to shorten <code>bou</code>, you can use <code>bouncy_count</code> or something as a more clear variable name</li>\n<li>You could use the fact that <code>int(True)</code> is <code>1</code> and <code>int(False)</code> is <code>0</code>, \nto replace <code>if bouncy(i): bouncy_count += 1</code> by <code>bouncy_count += bouncy(i)</code></li>\n</ul>\n\n<p>With this result:</p>\n\n<pre><code>def find(fraction = .50):\n \"\"\"Finds the first number where the ratio of bouncy numbers to all umbers is > `fraction`\"\"\"\n bouncy_count = 0\n for i in count(1):\n bouncy_count += bouncy(i)\n if bouncy_count / i > fraction:\n return i\n</code></pre>\n\n<h1>timing</h1>\n\n<p>Instead of using <code>time.time</code>, you can use the <a href=\"https://docs.python.org/3/library/timeit.html?highlight=timeit#module-timeit\" rel=\"nofollow noreferrer\"><code>timeit</code></a> module</p>\n\n<p>for example:</p>\n\n<pre><code>timeit.repeat(\"find_bouncy(.9)\", globals={\"find_bouncy\": find_bouncy}, number = 100)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T16:13:37.777",
"Id": "443131",
"Score": "1",
"body": "The checking conditions in `bouncy_pairwise` can be simplified: `if a > b: increasing = True elif a < b: decreasing = True`. Another alternative is `increasing = increasing or a > b; decreasing = decreasing or a < b`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T14:32:14.053",
"Id": "227577",
"ParentId": "227567",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "227570",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T12:54:04.487",
"Id": "227567",
"Score": "5",
"Tags": [
"python",
"programming-challenge"
],
"Title": "Project Euler problem #112"
}
|
227567
|
<p>I have found the need to schedule a few simple functions in a first-come-first-served way so I developed a small task scheduler based on multiprocessing and I thought it would be a good candidate for my first question here.</p>
<p>I'm open to all kind of comments, regarding style, conventions, possible bugs and other things I'm not considering now. I added some comments for the most sensible mechanism but this is mostly a half-day code.</p>
<pre><code>from multiprocessing import Process
from multiprocessing import JoinableQueue
def worker_process(in_queue, out_queue):
run = True
while run:
# in the queue there should be a Job or None.
# Latter case is the signal that we should stop.
task = in_queue.get()
if task:
task.run()
in_queue.task_done()
# when done, we signal and we put the task id in the output queue
out_queue.put(task.get_id())
else:
run = False
class Scheduler:
def __init__(self, job_done_cb, cb_args=[], N=2):
self.n = N
self.processes = []
self.job_queue = JoinableQueue()
self.done_queue = JoinableQueue()
self.job_done_cb = job_done_cb
self.cb_args = cb_args
for i in range(self.n):
# these workers will get jobs from the queue and give us back the id when done
p = Process(target=worker_process, args=(self.job_queue, self.done_queue))
self.processes.append(p)
# there process will get back the job of the id done and execute the callback
self.cb_process = Process(target=self.on_job_done)
def start(self):
for p in self.processes:
p.start()
self.cb_process.start()
def stop(self):
# add the necessary None to the queue and wait for the processes to be done
# this will make the queue execute the remaining task before finishing
for i in range(self.n):
self.job_queue.put(None)
self.job_queue.close()
for p in self.processes:
p.join()
self.done_queue.put(None)
self.cb_process.join()
def add_task(self, task_id, task, arg_list):
job = Job(task, task_id, arg_list)
self.job_queue.put(job)
def wait_for_idle(self):
self.job_queue.join()
def on_job_done(self):
run = True
while run:
# again, if the id is not None then we should go on waiting for stuff
done = self.done_queue.get()
if done:
self.job_done_cb(self, done, *self.cb_args)
else:
run = False
class Job:
def __init__(self, task, job_id, arg_list):
self.task = task
self.id = job_id
self.arg_list = arg_list
def run(self):
self.task(*self.arg_list)
def get_id(self):
return self.id
</code></pre>
|
[] |
[
{
"body": "<h1>Unused Loop Variables</h1>\n\n<pre><code>for i in range(self.n):\n self.job_queue.put(None)\n</code></pre>\n\n<p>can be written like this</p>\n\n<pre><code>for _ in range(self.n):\n self.job_queue.put(None)\n</code></pre>\n\n<p>and any place where you don't use the loop variable. The <code>_</code> lets you and other programmers know that that variable isn't used and should be ignored.</p>\n\n<h1>Naming</h1>\n\n<p><code>p</code> should be <code>process</code> to be descriptive. While <code>p in self.processes</code> can be obvious, it's good to get in the practice of descriptive variable names.</p>\n\n<h1>Type Hints</h1>\n\n<p>This</p>\n\n<pre><code>def add_task(self, task_id, task, arg_list):\n</code></pre>\n\n<p>can instead be (assuming <code>task</code> is a <code>str</code> and <code>arg_list</code> is a <code>list</code>)</p>\n\n<pre><code>def add_task(self, task_id: int, task: str, arg_list: list) -> None:\n</code></pre>\n\n<p>Using type hints allows you to see/show what types of parameters are accepted, and what type(s) is/are returned from the function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T22:58:04.047",
"Id": "230064",
"ParentId": "227576",
"Score": "2"
}
},
{
"body": "<h2>Termination conditions</h2>\n\n<p>This loop:</p>\n\n<pre><code>run = True\nwhile run:\n # ...\n</code></pre>\n\n<p>should drop the <code>run</code> variable, and where you currently assign it you should just <code>break</code>. Make the loop a <code>while True</code>.</p>\n\n<p>In other words,</p>\n\n<pre><code>while True:\n # in the queue there should be a Job or None.\n # Latter case is the signal that we should stop.\n task = in_queue.get()\n if task:\n task.run()\n in_queue.task_done()\n # when done, we signal and we put the task id in the output queue\n out_queue.put(task.get_id())\n else:\n break\n</code></pre>\n\n<h2>Variable case</h2>\n\n<p>Your parameter <code>N</code> should be <code>n</code>, since it's neither a class nor a constant.</p>\n\n<h2>Keyword arguments</h2>\n\n<p>It's typical to pass both <code>*args</code> and <code>**kwargs</code> to a generic function such as <code>task</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T23:35:20.697",
"Id": "230067",
"ParentId": "227576",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T14:29:57.050",
"Id": "227576",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"multithreading",
"queue"
],
"Title": "TaskScheduler in python"
}
|
227576
|
<p>In another attempt to further my knowledge in the JavaScript language, I've written a chess board generator that will essentially create a chess board with any initial state supplied. This supports the idea of chess game types like fairy chess or series self-mate and puzzle generation alike.</p>
<p>It was a rather fun project, and I'll end up expanding on it further in the future, and perhaps creating an API for it but I can't help but feel like it could use some improvement.</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>// Create and fill the array that holds our pieces.
var board = [];
board.push(["R", "N", "B", "K", "Q", "B", "N", "R"]);
board.push(["P", "P", "P", "P", "P", "P", "P", "P"]);
board.push(["E", "E", "E", "E", "E", "E", "E", "E"]);
board.push(["E", "E", "E", "E", "E", "E", "E", "E"]);
board.push(["E", "E", "E", "E", "E", "E", "E", "E"]);
board.push(["E", "E", "E", "E", "E", "E", "E", "E"]);
board.push(["P", "P", "P", "P", "P", "P", "P", "P"]);
board.push(["R", "N", "B", "K", "Q", "B", "N", "R"]);
// Draw the initial board.
var boardElement = document.getElementById("chess-board");
var rows = "";
for (var x = 0; x < board.length; x++) {
rows += '<div class="row">';
for (var y = 0; y < board[x].length; y++) {
var args = x + ", " + y;
var mouseOver = 'onmouseover="checkSquare(this, ' + args + ')" ';
var mouseOut = 'onmouseout="clearSquare(this, ' + args + ')" ';
var click = 'onclick="clickSquare(this, ' + args + ')" ';
var square = "<div " + mouseOver + mouseOut + click + ">";
var piece = "";
if (board[x][y] != "E")
piece = '<i class="fas fa-chess-';
switch (board[x][y]) {
case "P": piece += "pawn"; break;
case "R": piece += "rook"; break;
case "N": piece += "knight"; break;
case "B": piece += "bishop"; break;
case "K": piece += "king"; break;
case "Q": piece += "queen"; break;
}
if (piece.length > 0){
var shade = "dark";
if (x > 5)
shade = "light";
piece += ' ' + shade + '"></i>';
}
rows += square + piece + '</div>';
}
rows += "</div>";
}
boardElement.innerHTML = rows;
function checkSquare(e, x, y) {}
function clearSquare(e, x, y) {}
function clickSquare(e, x, y) {
if (e)
e.classList.toggle("waiting");
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Board Styles */
.chess-board {
width: 75vh;
min-width: 500px;
height: 75vh;
min-height: 500px;
display: grid;
grid-template-columns: repeat(1, 100%);
grid-template-rows: repeat(8, 12.5%);
place-items: center;
border-radius: 15px;
box-shadow: 0 0 15px #0005;
}
.chess-board > .row {
width: 100%;
height: 100%;
}
.chess-board > .row > div {
display: flex;
align-items: center;
justify-content: center;
width: 12.5%;
height: 100%;
border: none;
transition: 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55) all;
cursor: pointer;
}
.chess-board > .row > div:hover > i { font-size: 7vh; }
.chess-board > .row > div > i {
font-size: 5vh;
text-shadow: 2px 2px 3px #0005;
transition: 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55) all;
}
/* Border Radius */
.chess-board .row:nth-child(1) > div:nth-child(1) { border-top-left-radius: 15px; }
.chess-board .row:nth-child(1) > div:last-of-type { border-top-right-radius: 15px; }
.chess-board .row:last-of-type > div:nth-child(1) { border-bottom-left-radius: 15px; }
.chess-board .row:last-of-type > div:last-of-type { border-bottom-right-radius: 15px; }
.chess-board .row:last-of-type() {
border-bottom-left-radius: 15px;
border-bottom-right-radius: 15px;
}
.chess-board .row:nth-child(1) {
border-top-left-radius: 15px;
border-top-right-radius: 15px;
}
/* Colors */
.chess-board .row:nth-child(odd) > div:nth-child(odd),
.chess-board .row:nth-child(even) > div:nth-child(even) {
background-color: #9995;
}
.chess-board .row:nth-child(odd) > div:nth-child(even),
.chess-board .row:nth-child(even) > div:nth-child(odd) {
background-color: #3335;
}
.chess-board .row > div:hover { border: 5px solid #aafa; }
.chess-board .row > div.invalid:hover { border: 5px solid #f33a; }
.chess-board .row > div.checkmate { background-color: #f33a !important; }
.chess-board .row > div.waiting {
animation: 1.5s border-pulse linear infinite;
}
.chess-board .row > div > i.dark { color: #97f; }
.chess-board .row > div > i.light { color: #f79; }
/* Animations */
@keyframes border-pulse {
0%, 100% { border: 5px solid #5f90; }
50% { border: 5px solid #5f9a; }
}
/* Cursors */
.chess-board .row > div.invalid { cursor: not-allowed; }
/* Title Area */
.display-3 .fa-chess { transform: translateY(-10px); }
.display-3 .flip { transform: translateY(-10px) rotateY(180deg); }
/* Template Overrides */
.primary-content {
display: flex;
flex-direction: column;
align-items: center;
}
.lead { font-size: 25px; }</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" rel="stylesheet"/>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/2940219/PerpetualJ.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<div id="primary-content" class="primary-content">
<h1 class="display-3"><i class="fas fa-chess"></i> Chess <i class="fas fa-chess flip"></i></h1>
<p class="lead">Use the board array in the JavaScript to change the initial state of the board. This is still a WORK IN PROGRESS</p>
<div id="chess-board" class="chess-board"></div>
</div></code></pre>
</div>
</div>
</p>
<p>Some of the things I'm wondering are:</p>
<ul>
<li>Are there any security concerns with the current approach?
<ul>
<li>Focusing on the use of <code>innerHTML</code> here as I believe it could be potentially dangerous.</li>
<li>Should I be creating elements instead of using text based HTML insertion?</li>
</ul></li>
<li>Are there any more-efficient ways of accomplishing this?</li>
<li>Are there any potential gotchas with the direction I took here?</li>
</ul>
<p>As always, additional guidance and comments are more than welcome. Please ensure you supply documentation for anything meant to follow some kind of best practice.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T18:11:25.990",
"Id": "443159",
"Score": "0",
"body": "Can you use ES6?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T18:34:11.037",
"Id": "443164",
"Score": "1",
"body": "@ggorlen I'd have to learn it, but I don't see why not. I run my website on Google Cloud Platform's Compute Engines so I can set it up with whatever I need. :)"
}
] |
[
{
"body": "<blockquote>\n <p>Are there any security concerns with the current approach?</p>\n</blockquote>\n\n<p>No. You never interact with a server or a database. There is no way you could have any security concerns.</p>\n\n<blockquote>\n <p>Focusing on the use of innerHTML here as I believe it could be\n potentially dangerous. Should I be creating elements instead of using\n text based HTML insertion?</p>\n</blockquote>\n\n<p>No it does not matter. Users have access to this already. For example, on this webpage (codereview.stackexchange.com) you can right click an element and edit it. You can even edit the JavaScript. It's all client side. Users can always 'hack' themselves.</p>\n\n<p>I recommend using an ENUM for your board pieces. This will help with readability.</p>\n\n<p>This is a little picky, but I'd use a different variable name for <code>args</code>. Use descriptive names, don't name it <code>args</code> because you use it as an argument for a function. <code>args</code> is also used often inside of a main method in other languages.</p>\n\n<p>Try to avoid <code>magic numbers</code>. Instead declare a static variable at the top. Or At the very least, add a comment describing what the number is.</p>\n\n<pre><code>if (x > 5)\n shade = \"light\";\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T16:38:35.597",
"Id": "443133",
"Score": "1",
"body": "With regards to using an `enum` for the board pieces, should I still consider that approach for just the foundational pieces and then use strings for user defined pieces for things such as fairy chess where you can name your own pieces or should I keep it strings all together to keep it consistent? If this is confusing let me know and I'll try to phrase it better. :) +1 for the great answer!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T16:42:23.660",
"Id": "443134",
"Score": "1",
"body": "In that case I'd say make a class (or anonymous object) for the pieces. Or just give the Enum an additional property. That way 'Knight' stays as 'Knight' even if the user names it something else."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T16:18:15.077",
"Id": "227581",
"ParentId": "227578",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "227581",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T15:01:35.127",
"Id": "227578",
"Score": "7",
"Tags": [
"javascript",
"html",
"css",
"html5",
"chess"
],
"Title": "Generating a chess board with JavaScript"
}
|
227578
|
<p>I have written the following quicksort without using online help. It seems to be fine, but is there anything to improve?</p>
<pre><code>#include<iostream>
using namespace std;
void quicksort(int*, int, int);
void print(int *p, int n)
{
for(int i=0; i < n; ++i)
cout << p[i] << ' ' ;
cout << endl;
}
int main()
{
int arr[] = {10,10,15,15,23,5,55,8,6,0,32,10,100};
int len = sizeof(arr)/sizeof(int);
cout << "Before sort:\n";
print(arr,len);
quicksort(arr,0,len-1);
cout << "After sort:\n";
print(arr,len);
}
void quicksort(int *arr, int start, int end)
{
if(start >= end)
return;
int pivot = arr[end];
int i=start,j=start;
for(;j < end; ++j)
if(arr[j] < pivot)
{
swap(arr[i],arr[j]);
++i;
}
swap(arr[i],arr[end]);
quicksort(arr,0,i-1);
quicksort(arr,i+1,end);
}
</code></pre>
|
[] |
[
{
"body": "<h3>1. Don't use <code>using namespace std;</code></h3>\n\n<ol>\n<li><p>You should place explicit <code>using</code> statements like</p>\n\n<pre><code>using std::cout;\nusing std::swap;\n// etc.\n</code></pre>\n\n<p>instead. </p></li>\n<li>Here's some good argumentation why you shouldn't:<br>\n<a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Why is “using namespace std;” considered bad practice?</a></li>\n</ol>\n\n<h3>2. Don't use recursion</h3>\n\n<p>Using recursive calls limits you to the stack size, and may easily overflow on a large number of array elements.<br>\nYou can use a loop and a <a href=\"https://en.cppreference.com/w/cpp/container/stack\" rel=\"noreferrer\"><code>std::stack<int></code></a> instead:\n - Entering the recursive function can be turned into a <code>push()</code> operation within the loop\n - Returning from the function can be turned in to geting the value via <code>top()</code> and a subsequent <code>pop()</code> operation.</p>\n\n<h3>3. Don't use raw c-style arrays with c++</h3>\n\n<p>Instead of using <code>int arr[]</code> you should use <a href=\"https://en.cppreference.com/w/cpp/container/vector\" rel=\"noreferrer\"><code>std::vector<int></code></a>, or a <a href=\"https://en.cppreference.com/w/cpp/container/array\" rel=\"noreferrer\"><code>std::array<int,N></code></a> where <code>N</code> is a fixed size known at compile time.</p>\n\n<p>Raw arrays have several drawbacks. The worst is that the size cannot longer be determined after they <a href=\"https://stackoverflow.com/questions/1461432/what-is-array-decaying\">decayed to pointers</a> if they're going out of scope.<br>\nAlso raw array's aren't automatically copyable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T04:08:08.110",
"Id": "443199",
"Score": "0",
"body": "Yes. i am aware of errors because of \"using namespace std;\". I never use it in my work code. Can you find any case where this code will fail ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T07:03:25.310",
"Id": "443211",
"Score": "0",
"body": "@KamalPancholi As mentioned with larger input length recursion could fail with stack overflows."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T16:55:26.890",
"Id": "227584",
"ParentId": "227579",
"Score": "6"
}
},
{
"body": "<p>The code is very C-style. It accepts raw arrays. Indexes should not be of type <code>int</code>. Closed intervals are unidiomatic in C++. Since this is C++ code, use iterators and STL containers instead.</p>\n\n<p>It may also be a good idea to randomize the choice of the pivot value to avoid the dead case of already sorted array. This can be done by swapping the last element with another randomly selected element before partitioning.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T09:13:49.273",
"Id": "229016",
"ParentId": "227579",
"Score": "2"
}
},
{
"body": "<p>It's a relatively basic quicksort with no \"fancy features\", so it has the same issues that basic quicksort always has:</p>\n\n<ul>\n<li><p>O(n) space usage. When using recursion, that easily means \"unexpected termination\". When using an explicit stack, it means potentially wasting a ton of memory. The solution is to use recursion (or emulated recursion, with the explicit stack) only for the smallest half of the partition, and loop (tail recursion) for the larger half.</p></li>\n<li><p>O(n²) time in common cases. Picking the last (or first) element as the pivot has bad behavior for common inputs. Picking the middle element is easy and at least a little better, there are more advanced options such as median-of-3 etc. In most cases the O(n²) worst case stays, for example with the famous \"median of 3 killer sequence\", but a rare worst case has less impact than a common worst case.</p></li>\n<li><p>Inefficient partitioning (Lumoto's scheme). Hoare's original partioning scheme on average performs 1/3rd as many swaps. It is more complicated to code, but partitioning is the heart of quicksort: efficient partitioning is what makes quicksort quick.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T10:35:12.107",
"Id": "229018",
"ParentId": "227579",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T15:20:17.637",
"Id": "227579",
"Score": "6",
"Tags": [
"c++",
"sorting",
"reinventing-the-wheel",
"quick-sort"
],
"Title": "Quicksort for ints"
}
|
227579
|
<p>The following script is very slow and I'm not sure why.
The script works so if you copy and paste its a typo in the question. </p>
<pre><code>Sub deleteData()
Dim wb as workbook
Dim ws as worksheet
Dim myCell as range
dim myRange as Range
with Application
.Calculation = xlCalculationManual
.ScreenUpdating = False
end with
Set wb = activeworkbook
set ws = wb.Sheets(1)
set myRange = ws.range("I15845:I64572")
set myCell = ws.range("I15845")
For each myCell in myRange
myCell.Delete
next myCell
with Application
.Calculation = xlCalculationAutomatic
.ScreenUpdating = True
end with
MsgBox "Procedure Complete!"
end sub
</code></pre>
<p>I have also tried</p>
<pre><code>Sub deleteData()
Dim wb as workbook
Dim ws as worksheet
Dim myCell as range
dim myRange as Range
with Application
.Calculation = xlCalculationManual
.ScreenUpdating = False
end with
Set wb = activeworkbook
set ws = wb.Sheets(1)
set myRange = ws.range("I15845:I64572")
myRange.Delete
with Application
.Calculation = xlCalculationAutomatic
.ScreenUpdating = True
end with
MsgBox "Procedure Complete!"
end sub
</code></pre>
<p>I know this is a large range but it should not take hours to complete.</p>
<p>The data in the column is an anchored <code>countif</code>.</p>
<pre><code>=countif($A$1:A1,A1)
</code></pre>
<p>So each cell would be:</p>
<pre><code>=countif($A$1:A1,A1)
=countif($A$1:A2,A2)
=countif($A$1:A3,A3)
.
.
.
=countif($A$1:A10000,A10000)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T19:21:01.880",
"Id": "443167",
"Score": "1",
"body": "The current question title states your concerns about the code, but what we need here is a summary of the *purpose* of the code. Please see [ask] for examples, and [edit] the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T20:04:45.480",
"Id": "443168",
"Score": "2",
"body": "This cannot be the complete code set and we don't have any good context for a review (as @TobySpeight mentions). The only other factor based on what is provided is `Application.EnableEvents=`[`True`|`False`] but still should not take literal hours to complete. Also, providing us with the actual time to complete (still don't believe this should be \"hours\") would be helpful."
}
] |
[
{
"body": "<p><code>COUNTIF()</code> is slow. A few <code>COUNTIF()</code> statements in a worksheet can be okay, but thousands of them will result in a glacial spreadsheet.</p>\n\n<p>Here is a way to replace your <code>COUNTIF()</code> statements:</p>\n\n<ol>\n<li>Sort Column A.</li>\n<li>In Column B, have each cell check if the corresponding cell in column A is equal to the cell above it in column A. If no, put 1 in column B's cell. If yes, set column B's cell equal to 1 + the value in the cell above it in column B.</li>\n<li>In Column C, have each cell check if the corresponding cell in column A is equal to the cell <strong>below</strong> it in column A. If yes, let the cell in column C be an empty string. If no, set column C's cell equal to column B's cell.</li>\n<li>(Optional) In Column D, have each cell check if the corresponding cell in column C is an empty string. If no, set column D's cell equal to column C's cell. If yes, set column D's cell equal to the cell below it in column D.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T00:49:45.180",
"Id": "229283",
"ParentId": "227585",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T17:01:14.823",
"Id": "227585",
"Score": "0",
"Tags": [
"performance",
"vba",
"excel"
],
"Title": "Excel VBA Sub Routine is extremely Slow deleting a Range"
}
|
227585
|
<p>Given that I have a dataset as follows:</p>
<pre><code>{ 1: ['Extremely Tall'], 2: ['Tall'], 3: ['Medium', 'Low'], 4: ['Dwarf'] }
</code></pre>
<p>and I receive a value (e.g. Tall or Medium) I want to determine the associated key. By the way feel free to change the dataset, i.e. it doesn't have to be a json object... so long as:</p>
<pre><code>Medium -> 3
Low -> 3
Tall -> 2
</code></pre>
<p>My solution is below, anyone have a better way of doing it? </p>
<pre><code>const R = require('ramda')
const heightsMap = { 1: ['Extremely Tall'], 2: ['Tall'], 3: ['Medium', 'Low'], 4: ['Dwarf'] }
const height = 'Medium'
const associatedNumber = R.keys(heightsMap).filter(key => heightsMap[key].includes(height))[0]
console.log(associatedNumber)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T17:18:10.280",
"Id": "443143",
"Score": "0",
"body": "why the down vote?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T17:39:57.593",
"Id": "443146",
"Score": "6",
"body": "Welcome to Code Review! I am not the downvoter but I see there is 1 vote to close this question due to lack of context. It would be helpful if you could [edit] your post to explain how the data is used after the code above is used. If you haven't already read it, check out [_How do I ask a good question?_](https://codereview.stackexchange.com/help/how-to-ask)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T18:02:26.670",
"Id": "443156",
"Score": "0",
"body": "well OK.. I'm really not sure what else I could say that would be relevant. I'm going to save the answer to the database but I dont see how that changes the solution"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T07:42:38.110",
"Id": "443322",
"Score": "1",
"body": "Have you heard the joke about the person who asks for directions and is told \"If I wanted to go there, I wouldn't start here\"? More context would help answerers know whether the real solution to propose would be \"Don't store your dataset like that\"."
}
] |
[
{
"body": "<h3>Review</h3>\n\n<p>I'm not a big fan of importing other libraries when a built-in alternative is available.</p>\n\n<blockquote>\n<pre><code>const R = require('ramda')\n</code></pre>\n</blockquote>\n\n<p><code>R.keys</code> could be replaced by <code>Object.keys</code>:</p>\n\n<pre><code>const associatedNumber = Object.keys(heightsMap)\n .filter(key => heightsMap[key]\n .includes(height))[0]\n</code></pre>\n\n<p>Two improvements can be made. First, you're using <code>filter</code> which iterates all elements. This is a pity, since you're only interested in the first item <code>[0]</code>. <code>Find</code> is the method you were looking for. Second, You're traversing keys to perform another lookup <code>heightsMap[key]</code>. This could be done in a single iteration using <code>Object.entries</code>.</p>\n\n<h3>Proposed Rewrite</h3>\n\n<pre><code>const associatedNumber = Object.entries(heightsMap)\n .find(([key, value]) => value.includes(height))[0];\n\nconsole.log(associatedNumber);\n</code></pre>\n\n<p>Note that <code>[0]</code> in the refactored code gets the <code>key</code> of <code>[key, value]</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T17:54:38.047",
"Id": "227590",
"ParentId": "227586",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227590",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T17:12:09.963",
"Id": "227586",
"Score": "1",
"Tags": [
"javascript",
"functional-programming",
"ramda.js"
],
"Title": "Join a JSON object of arrays and reduce down to one key"
}
|
227586
|
<p>I'm training a GRU auto-encoder and my current code is very slow.I believe it's predict_captions function that takes most the time. Any suggestion to optimize this code?</p>
<pre><code>for epoch in xrange(0, 13):
print ("Starting New Epoch: %d" % epoch)
rewards = {
'sample_cider': [],
'sample_context': [],
'sample_reward': [], # actual reward, controlled by beta
'greedy_cider': [],
'greedy_context': [],
'greedy_reward': []
}
order = np.arange(enc_padded_text.shape[0])
np.random.shuffle(order)
enc_padded_text = enc_padded_text[order]
input_text=[input_text[i] for i in order]
dec_text_tensor.data = dec_text_tensor.data[order]
for i in xrange(num_batches):
s = i * BATCH_SIZE
e = (i+1) * BATCH_SIZE
_, enc_pp, dec_pp, enc_lengths = make_packpadded_s2s(s, e, enc_padded_text, dec_text_tensor)
enc.zero_grad()
dec.zero_grad()
hid = enc.initHidden(BATCH_SIZE)
out_enc, hid_enc = enc.forward(enc_pp, hid, enc_lengths)
hid_enc = torch.cat([hid_enc[0,:, :], hid_enc[1,:,:]], dim=1).unsqueeze(0)
gt_dict = dict(zip(_,input_text[s:e]))
sampled_captions, sampled_log_probs=predict_captions(out_enc,hid_enc,enc_pp,'sample')
sampled_dict = dict(zip(_, sampled_captions))
with torch.no_grad():
greedy_captions = predict_captions(out_enc,hid_enc,enc_pp, 'greedy')
greedy_dict = dict(zip(_, greedy_captions))
sample_cider_score, sample_context_score, sample_reward = get_scores(
dec_pp[:,1:], sampled_captions, gt_dict, sampled_dict)
greedy_cider_score, greedy_context_score, greedy_reward = get_scores(
dec_pp[:,1:], greedy_captions, gt_dict, greedy_dict)
# self-critical: score from sampling - score from test time
advantages = torch.Tensor((sample_cider_score - greedy_cider_score).reshape(-1))
# normalize advantages
advantages = ((advantages - advantages.mean()) /
advantages.std() + 1e-9)
if cuda:
advantages = advantages.cuda()
loss = -(advantages *
torch.stack(sampled_log_probs).reshape(-1)).mean()
torch.autograd.set_detect_anomaly(True)
loss.backward()
clip_grad_value_(enc_optim.param_groups[0]['params'], 5.0)
clip_grad_value_(dec_optim.param_groups[0]['params'], 5.0)
enc_optim.step()
dec_optim.step()
rewards['sample_cider'].extend(sample_cider_score)
rewards['sample_context'].extend(sample_context_score)
rewards['sample_reward'].extend(sample_reward)
rewards['greedy_cider'].extend(greedy_cider_score)
rewards['greedy_context'].extend(greedy_context_score)
rewards['greedy_reward'].extend(greedy_reward)
if (b + 1) % 100 == 0:
print('\t[Batch {} running metrics] - R train {:.2f} - R train (greedy): {:.2f}'.format(
b + 1, np.mean(rewards['sample_reward']), np.mean(rewards['greedy_reward'])))
</code></pre>
<p>predict_captions function:</p>
<pre class="lang-py prettyprint-override"><code>def predict_captions(img_features,hid_enc,enc_pp, mode='sample', constrain=False,L=22):
dec_tensor = torch.ones((enc_pp.shape[0]), L+1, dtype=torch.long) * Toks.SOS
global cuda
if cuda:
dec_tensor = dec_tensor.cuda(device=device)
last_enc = hid_enc
if mode == 'beam_search':
return self.beam_search(img_features, state, lstm_states)
predictions = []
log_probs = []
# this should store the index of the first occurrence of <EOS>
# for each sample in the batch
EOS_tracker = np.full(img_features.shape[0], None)
r=dec_tensor[:,0].unsqueeze(1)
for i in range(L):
out_dec, hid_dec, word_logits = dec(r, last_enc, img_features)
out_dec[:, 0, Toks.UNK] = -np.inf # ignore unknowns
l=out_dec[:,0]
chosen = torch.argmax(l,dim=1)
r = chosen.unsqueeze(1)
last_enc = hid_dec
# decoding stuff
probs1 = F.softmax(word_logits, dim=2)
probs=probs1.reshape(128,20004)
if constrain:
# enforce constraint that the same word can't be predicted
# twice in a row. zero-out the probability of previous words
for p, prev_idx in zip(probs, state['prev_word_indeces']):
p[prev_idx] = 0
if mode == 'sample':
idxs = torch.multinomial(probs, 1)
else:
idxs = torch.argmax(probs, dim=1)
if cuda:
idxs = idxs.cpu()
words = [dec_idx_to_word[index] for index in idxs]
predictions.append(np.array(words).reshape(-1))
# get the respective log probability of chosen word
# for each sample in the batch
log_probs.append([lp[i] for (lp, i)
in zip(torch.log(probs), idxs)])
# inefficient but this should be fast enough anyway... ? :(
eos_idxs = (np.array(words)==dec_idx_to_word[2]).nonzero()[0]
for idx in eos_idxs:
if EOS_tracker[idx] is None:
EOS_tracker[idx] = i + 1
# finish loop if they're all done
if len(EOS_tracker[EOS_tracker == None])==0:
break
# build the actual sentences, up until the first occurrence of <EOS>
captions = [
[' '.join(w[:eos_idx])] for (w, eos_idx) in
zip(np.array(predictions).T, EOS_tracker)
]
print captions
# do this only when training. not needed otherwise.
if mode == 'sample':
log_probs = [lp[:eos_idx].sum() for (lp, eos_idx) in zip(np.array(log_probs).T, EOS_tracker)]
return captions, log_probs
return captions
</code></pre>
<p>models:</p>
<pre class="lang-py prettyprint-override"><code>class Encoder_s2s(nn.Module):
def __init__(self, input_size, hidden_size):
super(Encoder_s2s, self).__init__()
assert hidden_size % 2 == 0
self.hidden_size = hidden_size
self.input_size = input_size
self.hidden_init_tensor = torch.zeros(2, 1, self.hidden_size/2, requires_grad=True)
nn.init.normal_(self.hidden_init_tensor, mean=0, std=0.05)
self.hidden_init = torch.nn.Parameter(self.hidden_init_tensor, requires_grad=True)
self.embedding = nn.Embedding(input_size, hidden_size)
self.emb_drop = nn.Dropout(0.2)
self.gru = nn.GRU(hidden_size, hidden_size/2, batch_first=True, bidirectional=True)
self.gru_out_drop = nn.Dropout(0.2)
self.gru_hid_drop = nn.Dropout(0.3)
def forward(self, input, hidden, lengths):
emb = self.emb_drop(self.embedding(input))
#emb = embedded_dropout(self.embedding, input, dropout=0.2 if self.training else 0)
pp = torch.nn.utils.rnn.pack_padded_sequence(emb, lengths, batch_first=True)
out, hidden = self.gru(pp, hidden)
out = torch.nn.utils.rnn.pad_packed_sequence(out, batch_first=True)[0]
out = self.gru_out_drop(out)
hidden = self.gru_hid_drop(hidden)
return out, hidden
def initHidden(self, bs):
return self.hidden_init.expand(2, bs, self.hidden_size/2).contiguous()
class DecoderAttn(nn.Module):
def __init__(self, input_size, hidden_size, output_size, out_bias):
super(DecoderAttn, self).__init__()
self.hidden_size = hidden_size
self.input_size = input_size
self.embedding = nn.Embedding(input_size, hidden_size)
self.emb_drop = nn.Dropout(0.2)
self.gru = nn.GRU(hidden_size, hidden_size, batch_first=True)
self.gru_drop = nn.Dropout(0.2)
self.mlp = nn.Linear(hidden_size*2, output_size)
if out_bias is not None:
out_bias_tensor = torch.tensor(out_bias, requires_grad=False)
self.mlp.bias.data[:] = out_bias_tensor
self.logsoftmax = nn.LogSoftmax(dim=2)
self.att_mlp = nn.Linear(hidden_size, hidden_size, bias=False)
self.attn_softmax = nn.Softmax(dim=2)
def forward(self, input, hidden, encoder_outs):
emb = self.embedding(input)
emb=self.emb_drop(emb)
out, hidden = self.gru(emb, hidden)
out_proj = self.att_mlp(out)
enc_out_perm = encoder_outs.permute(0, 2, 1)
e_exp = torch.bmm(out_proj, enc_out_perm)
attn = self.attn_softmax(e_exp)
ctx = torch.bmm(attn, encoder_outs)
full_ctx = torch.cat([self.gru_drop(out), ctx], dim=2)
out = self.mlp(full_ctx)
out1 = self.logsoftmax(out)
return out1, hidden, out
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T17:51:31.513",
"Id": "443150",
"Score": "0",
"body": "Welcome to Code Review! Have you already tried to find the portion of your code that makes up most of the time?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T17:53:28.573",
"Id": "443151",
"Score": "1",
"body": "Yes I believe it's predict_captions function that takes most the time @AlexV"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T17:56:05.097",
"Id": "443152",
"Score": "0",
"body": "Such information can be vital to help reviewers to give you meaningful feedback. Please add it to your question as well as possibly other efforts you have already made."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T13:35:53.940",
"Id": "455885",
"Score": "3",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T15:30:40.287",
"Id": "455904",
"Score": "1",
"body": "Exactly what are you training it to do?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T17:37:36.063",
"Id": "455928",
"Score": "0",
"body": "To close voters, a generic title is not a reason to close the question; https://codereview.meta.stackexchange.com/questions/9402/the-context-of-lacks-concrete-context-lets-fix-it/9407?noredirect=1#comment20200_9404"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T17:47:26.070",
"Id": "455929",
"Score": "0",
"body": "@pacmaninbw generate sentence using a sequence od words as input"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T19:53:10.443",
"Id": "455951",
"Score": "1",
"body": "Did you leave out any code by chance? This looks incomplete, and reviewing incomplete ML code is unnecessarily hard."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-08T22:48:21.190",
"Id": "456784",
"Score": "0",
"body": "Please don't expect everyone to know what you are talking about. What is a GRU Autoencoder?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T17:27:56.170",
"Id": "227587",
"Score": "2",
"Tags": [
"python",
"performance",
"machine-learning",
"pytorch"
],
"Title": "GRU-Autoencoder training"
}
|
227587
|
<p><a href="https://projecteuler.net/problem=113" rel="nofollow noreferrer">Problem</a> statement:</p>
<blockquote>
<p>Working from left-to-right if no digit is exceeded by the digit to its
left it is called an increasing number; for example, 134468.</p>
<p>Similarly if no digit is exceeded by the digit to its right it is
called a decreasing number; for example, 66420.</p>
<p>We shall call a positive integer that is neither increasing nor
decreasing a "bouncy" number; for example, 155349.</p>
<p>As n increases, the proportion of bouncy numbers below n increases
such that there are only 12951 numbers below one-million that are not
bouncy and only 277032 non-bouncy numbers below <span class="math-container">\$10^{10}\$</span>.</p>
<p>How many numbers below a googol (<span class="math-container">\$10^{100}\$</span>) are not bouncy?</p>
</blockquote>
<p>Code:</p>
<pre><code>import time
from scipy import special
def count_non_bouncy_numbers(n):
'''n - number of digits'''
include_zeroes = scipy.special.comb(10,n,exact=True,repetition=True) - 1
exclude_zeroes = scipy.special.comb(9,n,exact=True,repetition=True)
only_zeroes = include_zeroes - exclude_zeroes
total = only_zeroes + exclude_zeroes*2 - 9
return total
if __name__ == '__main__':
total = 0
for n in range(1,101) : total+= count_non_bouncy_numbers(n)
print(total)
</code></pre>
<hr>
<p>The reasoning behind the code: </p>
<p>The formula I should note here is the combinations with replacement, which is <span class="math-container">\$ {\frac{(q+r-1)!}{r!(q-1)!} }\$</span>. I will denote it as <span class="math-container">\$C(q,r)\$</span> where <span class="math-container">\$q\$</span> represents number of items that can be selected and <span class="math-container">\$r\$</span> numbers of items that <em>are</em> selected.</p>
<p>My function takes an argument <span class="math-container">\$n\$</span>, which represents number of digits, e.g:</p>
<p>If <span class="math-container">\$n = 2\$</span>, then we consider all the numbers in range [10,99]</p>
<p>If <span class="math-container">\$n = 3 \$</span>, then we consider all the numbers in range [100,999]</p>
<p>Step 1. We find all the non-bouncy numbers that contain zeroes. Specifically, for all numbers with <span class="math-container">\$n\$</span> digits, there will be <span class="math-container">\$C(10,n) - C(9,n)\$</span> non-bouncy numbers that contain zeroes in them</p>
<p>Step 2. We find number of strictly increasing non-bouncy numbers with <span class="math-container">\$n\$</span> digits, there are <span class="math-container">\$C(9,n)\$</span> of them. </p>
<p>Step 3. We find number of strictly decreasing non-bouncy numbers with <span class="math-container">\$n\$</span> digits. Since decreasing numbers are just increasing numbers in reverse, we can see that there are <span class="math-container">\$C(9,n)\$</span> of them. </p>
<p>Step 4. We note that numbers such as 111, 33, 555 etc can be considered as strictly decreasing/increasing at the same time, hence we need to remove the overcount. To do so, we subtract <span class="math-container">\$9\$</span>.</p>
<p>Step 5. Add up the results, i.e: <span class="math-container">\$C(10,n) - C(9,n) + C(9,n) - C(9,n) - 9\$</span> , which represents total number of non-bouncy numbers with <span class="math-container">\$n\$</span> digits.</p>
<hr>
<p>What can be improved?</p>
|
[] |
[
{
"body": "<p>Project Euler problems generally can be computed with a calculator or manually.<br>\nSo, take a different approach:</p>\n\n<ol>\n<li><p>For ascending numbers, choose the transitions (digits 0-9; 9 transitions).</p></li>\n<li><p>For descending numbers, choose the transitions (initial zeros, digits 9-0; 10 transitions).</p></li>\n<li><p>Subtract those where initial zeros are followed only by a non-empty string of a single repeated digit (0-9) (1 transition, but the last place cannot be chosen).</p></li>\n<li><p>Subtract the case of only the initial zeros.</p></li>\n</ol>\n\n<p>In the end you have to calculate:</p>\n\n<p><span class=\"math-container\">$$\\binom{100+9}{9} + \\binom{100 + 10}{10} - 10 * \\binom{100}{1} - 1 = \\binom{109}{9} + \\binom{110}{10} - 1001$$</span></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T19:15:25.907",
"Id": "443166",
"Score": "0",
"body": "Wow, that's neat!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T18:13:41.957",
"Id": "227593",
"ParentId": "227588",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T17:40:35.393",
"Id": "227588",
"Score": "4",
"Tags": [
"python",
"programming-challenge",
"combinatorics",
"scipy"
],
"Title": "Counting Bouncy Numbers: Project Euler #113"
}
|
227588
|
<p>I have this simple setup for a .NET Core project which is just a very basic HttpClient usage to do some simple integration tests to a RESTful API. For now the test project remains separated from the main API project, that's why it's built on .NET Core for now, using NUnit as test framework as well. But because of that I have the freedom to change it anytime.</p>
<p>For now, the implementation is very simple, like this:</p>
<pre><code>public static HttpClient _client1;
public static HttpClient _client2;
[OneTimeSetUp]
public void OneTimeSetUp()
{
_client1 = new HttpClient {BaseAddress = new Uri("https://address1.com")};
_client1.DefaultRequestHeaders.Add("API-KEY", "token_here");
_client2 = new HttpClient {BaseAddress = new Uri("https://address2.com")};
_client1.DefaultRequestHeaders.Add("API-KEY", "token_here");
}
//[OneTimeTearDown]
//public void OneTimeTearDown()
//{
//_client1?.Dispose();
//_client2?.Dispose();
//}
</code></pre>
<p>That's the main test class, but considering that later it will become a more robust test suite and it's going to be added on main project, I've found that I can use <code>HttpClientFactory</code> like this, which produces the same test results and I can modelate the services to be added to the API solution later.</p>
<pre><code>public static HttpClient _client1;
public static HttpClient _client2;
[OneTimeSetUp]
public void OneTimeSetUp()
{
var services = new ServiceCollection();
services.AddHttpClient("Client1", client =>
{
client.BaseAddress = new Uri("https://address1.com/");
client.DefaultRequestHeaders.Add("KEY", "token_here");
});
services.AddHttpClient("Client2", client =>
{
client.BaseAddress = new Uri("https://address2.com/");
client.DefaultRequestHeaders.Add("KEY", "token_here");
});
var factory = services.BuildServiceProvider().GetService<IHttpClientFactory>();
_client1 = factory.CreateClient("Client1");
_client2 = factory.CreateClient("Client2");
}
//[OneTimeTearDown]
//public void OneTimeTearDown()
//{
//_client1?.Dispose();
//_client2?.Dispose();
//}
</code></pre>
<p>My main problem is that we have two main API addresses that will be used under production environment and I'm not sure if this implementation is appropriated. Everything works as expected on both scenarios when called on tests...</p>
<pre><code>[TestFixture, Parallelizable(ParallelScope.All)]
public class TestCase : Setup
{
[Test]
public async Task Get()
{
var response = await _client1.GetAsync("v1/Endpoint");
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadAsStringAsync();
Assert.NotNull(response);
Console.WriteLine(JToken.Parse(result));
}
}
</code></pre>
<p>So it will be the same for <code>_client2</code> and in a lot of tests...</p>
<p>As I said, it works as expected on both ways, but since I'm new at this and didn't found much about this kind of integration test separated from the main API reference project, I'm not so sure about how I built it, so any other and more experienced views about it will be very much appreciated.</p>
<p><strong>EDIT:</strong> I had the need to run all the tests in parallel, so I was generating an <code>ObjectDisposedException</code> with the <code>Parallelizable</code> attribute. Removing the <code>OneTimeTearDown</code> with the client disposing calls solved the problem, but I have doubts if that's the correct way to use HttpClient as well, as it still gives the expected results.</p>
|
[] |
[
{
"body": "<p>First of all I would like to say that, in my opinion, testing API in a such way is wrong, because how does such unit test behave when:</p>\n\n<ul>\n<li>developer machine does not have Internet connection?</li>\n<li>developer machine does not have proper certificates?</li>\n<li>machine that run test does not have acces to such domain?</li>\n<li>external API URL changed?</li>\n<li>some new requirements (headers, parameters, body) occure (assume that external API is still under development)?</li>\n<li>external API has Internet/electricity/domain problem?</li>\n</ul>\n\n<p>The answer is simple - it will fail. And it could lead to <a href=\"https://en.wikipedia.org/wiki/Broken_windows_theory\" rel=\"nofollow noreferrer\">BROKEN WINDOWS THEORY</a> which basically means that someone can say \"ok that unit tests does not pass, so we can ignore it\" or even worse: \"(...) add new failing tests!\".</p>\n\n<p>So if you want to test external API you should use some monitoring tool and health check it. If any problem occur - contact with API owner to make him solve the problem.</p>\n\n<p>Secondly, you integrate external API with some kind of version - all responses are in JSON for example. The most important thing is to stub all its possible responses - correct ones with corrupted/correct data, without any data, empty response, timeouts, responses in other formats (HTML) etc. to test whether or not your code works correctly and predictable for all these cases. If API contract will change then new use cases you will add to your integration test.</p>\n\n<p>My proposition is to wrap your communication method (HttpClient) into some kind of Facade, let's name it 'ICommunicatorFacade'. Let the parameters be single your custom Request, and let it return your custom Response type (which wraps what you need from HttpClient).</p>\n\n<pre><code>interface ICommunicatorFacade\n{\n Task<CustomResponse> Get(CustomRequest request);\n}\n</code></pre>\n\n<p>That you can easily stub with <a href=\"https://nsubstitute.github.io/\" rel=\"nofollow noreferrer\">NSubstitute</a> <a href=\"https://github.com/Moq/moq4/wiki/Quickstart\" rel=\"nofollow noreferrer\">Moq</a> and other libraries. Also you can check whether or not your facade received correct paramters and of course how does ICommunicator user (method that invokes Get method) behave for all use cases I mentioned above.</p>\n\n<p>Good luck!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T09:30:35.433",
"Id": "228832",
"ParentId": "227596",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T18:58:16.540",
"Id": "227596",
"Score": "6",
"Tags": [
"c#",
"comparative-review",
"integration-testing",
".net-core",
"nunit"
],
"Title": "Simple HttpClient usage for integration tests in .NET Core"
}
|
227596
|
<p>Utilizing the below relation, I am able to compute the Euler constant to great precision on a single thread quickly and simply.</p>
<p>My process is to compute the natural log via the AGM(utilizing Pi an the Ln(2)), and apply the result to the <a href="https://www.ams.org/journals/mcom/1980-34-149/S0025-5718-1980-0551307-4/home.html" rel="nofollow noreferrer">BMM</a> algorithm.</p>
<p><span class="math-container">\$\gamma=\lim_{n\to\infty}\mathscr{G}_n=\lim_{n\to\infty}\frac{\sum\limits_{k=0}^\infty \left(\frac{n^k}{k!}\right)^2 (H_k-\log\,n)}{\sum\limits_{k=0}^\infty \left(\frac{n^k}{k!}\right)^2}\$</span></p>
<p>where <span class="math-container">\$H_k=\sum\limits_{j=1}^k \frac1{j}\$</span> is a Harmonic number.</p>
<p>This process is much more efficient than my <a href="https://codereview.stackexchange.com/questions/227562/euler-mascheroni-single-thread-speed-improvements">previous post</a>.</p>
<pre><code>import decimal
from tqdm import tqdm
def agm(a, b):
"""Arithmetic Geometric Mean"""
a, b = D(a),D(b)
for x in tqdm(range(prec)):
a, b = (a + b) / 2, (a * b).sqrt()
return a
def pi_agm():
"""Pi via AGM and lemniscate"""
print('Computing Pi...')
a, b, t = 1, D(0.5).sqrt(), 1/D(2)
p, pi, k = 2, 0, 0
while 1:
an = (a+b)/2
b = (a*b).sqrt()
t -= p*(a-an)**2
a, p = an, 2**(k+2)
piold = pi
pi = ((a+b)**2)/(2*t)
k += 1
if pi == piold:
break
return pi
def lnagm(x):
"""Natural log of via AGM"""
if x == D(1):
return 0
if x == D(2):
return lntwo()
m = prec*2
ln2 = lntwo()
decimal.getcontext().prec = m
pi = pi_agm()
print('Computing Ln({0})...'.format(x))
twoprec = (D(2)**(2-m))/x
den = agm(1, twoprec)*2
diff = m*ln2
result = ((pi/den) - diff)
logr = D(str(result)[:m//2])
decimal.getcontext().prec = prec
return logr
def lntwo(): #Fast converging Ln 2
print('Computing Ln(2)...')
def lntwosum(n, d, b):
logsum, logold, e = D(0), D(0), 0
while True:
logold = logsum
logsum += (1/((D(b**e))*((2*e)+1)))
e += 1
if logsum == logold:
return (D(n)/D(d))*logsum
logsum1 = lntwosum(14, 31, 961)
logsum2 = lntwosum(6, 161, 25921)
logsum3 = lntwosum(10, 49, 2401)
ln2 = logsum1 + logsum2 + logsum3
return ln2
def gamma():
n = D(prec)
a = u = -lnagm(n)
b = v = D(1)
i = D(1)
while True:
k = (n/i)**2
a *= k
b *= k
a += (b/i)
if (u+a) == u or (v+b) == v:
break
u += a
v += b
i += 1
return D(str(u/v)[:prec-3])
if __name__ == "__main__":
"""Setting precision plus 5 to accomodate error"""
prec = int(input('Precision: '))+5
decimal.getcontext().prec = prec
D = decimal.Decimal
print(gamma())
</code></pre>
|
[] |
[
{
"body": "<p>The single largest optimization I was able to make was to the logarithms. Once the two terms of a AGM are the same, they will not differ again. Therefore you can be sure you have converged. The argument of oscillating convergence does not apply. </p>\n\n<p>I also noticed that, code aside, y=2^x+8; AGM(1, y) converges the fastest out of the numbers. I don't know the exact Math behind AGM convergence rates but I noticed that.(therefore in the script, put precision as 2^x -1 for ultra fast Ln convergence)</p>\n\n<p>Since this is my own answer, I'm fine with me putting gmpy2 in places to make the computations faster.</p>\n\n<p>I computed 212,143 digits of Gamma in 3.5 hours with the script. Usable precision into the thousands is done in less than breath :) . </p>\n\n<pre><code>import decimal\nfrom tqdm import tqdm\nfrom gmpy2 import mpc\nimport gmpy2\n\ndef agm(a, b):\n \"\"\"Arithmetic Geometric Mean\"\"\"\n a, b = D(a),D(b)\n for i in tqdm(range(prec)):\n a, b = (a + b) / 2, (a * b).sqrt()\n if a == b:\n break\n return a\n\ndef pi_agm():\n \"\"\"Pi via AGM and lemniscate\"\"\"\n print('Computing Pi...')\n a, b, t = 1, D(0.5).sqrt(), 1/D(2)\n p, pi, k = 2, 0, 0\n while 1:\n an = (a+b)/2\n b = (a*b).sqrt()\n t -= p*(a-an)**2\n a, p = an, 2**(k+2)\n piold = pi\n pi = ((a+b)**2)/(2*t)\n k += 1\n if pi == piold:\n break\n return pi\n\ndef lnagm(x): \n \"\"\"Natural log of via AGM\"\"\"\n if x == D(1):\n return 0\n if x == D(2):\n return lntwo()\n m = prec*2\n ln2 = lntwo()\n decimal.getcontext().prec = m\n pi = pi_agm()\n print('Coverging on Ln({0})...'.format(x))\n twoprec = (D(2)**(2-m))/x\n den = agm(1, twoprec)*2\n diff = m*ln2\n result = ((pi/den) - diff)\n logr = D(str(result)[:m//2])\n decimal.getcontext().prec = prec\n return logr\n\ndef lntwo(): \n \"\"\"Fast converging Ln2\"\"\"\n print('Computing Ln(2)...')\n def lntwosum(n, d, b):\n logsum, logold = mpc(0), mpc(0), \n e, n, d = mpc(0), mpc(n), mpc(d)\n while True:\n logold = logsum\n logsum += (1/((b**e)*((2*e)+1)))\n e += 1\n if logsum == logold:\n return (n/d)*logsum\n logsum1 = lntwosum(14, 31, 961)\n logsum2 = lntwosum(6, 161, 25921)\n logsum3 = lntwosum(10, 49, 2401)\n ln2 = logsum1 + logsum2 + logsum3\n return D(str(ln2.real)[:-4])\n\ndef gamma():\n n = D(prec)\n a = u = mpc(str(-lnagm(n)))\n print('Computing Gamma...')\n b = v = mpc(1)\n i = mpc(1)\n while True:\n k = (n/i)**2\n a *= k\n b *= k\n a += (b/i)\n if (u+a) == u or (v+b) == v:\n break\n u += a\n v += b\n i += 1\n return D(str(u/v)[:prec-3])\n\nif __name__ == \"__main__\":\n \"\"\"Setting precision plus 5 to accomodate error\"\"\"\n prec = int(input('Precision: '))+5\n gmpy2.get_context().precision=(prec*4)\n decimal.getcontext().prec = prec\n D = decimal.Decimal\n gam = gamma()\n print(gam)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T18:12:08.593",
"Id": "227680",
"ParentId": "227601",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227680",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T19:58:01.650",
"Id": "227601",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x",
"mathematics",
"numerical-methods"
],
"Title": "Arbitrary precision Euler-Mascheroni constant via a Brent-McMillan algorithm with no math module"
}
|
227601
|
<p>I wrote program that reads and processes xml files submitted by external users. The part of the code in question iterates over xml node's children, appends a dictionary - a future row in a table, and repeats the process for every child and its child and so on.</p>
<p>Exemplary xml node looks like this:</p>
<pre><code>xmlstr = '<Root_Level><Level1><Foo_A>1065106.46</Foo_A><Foo_B>675706.31</Foo_B><Foo_B1>0.00</Foo_B1><Level1_A><Foo_A>23750.00</Foo_A><Foo_B>0.00</Foo_B><Foo_B1>0.00</Foo_B1></Level1_A><Level1_B><Foo_A>1041356.46</Foo_A><Foo_B>675706.31</Foo_B><Foo_B1>0.00</Foo_B1><Level1_B_1><Foo_A>0.00</Foo_A><Foo_B>0.00</Foo_B><Foo_B1>0.00</Foo_B1></Level1_B_1><Level1_B_2><Foo_A>466158.93</Foo_A><Foo_B>59838.40</Foo_B><Foo_B1>0.00</Foo_B1><Level1_B_2_1><Foo_A>0.00</Foo_A><Foo_B>0.00</Foo_B><Foo_B1>0.00</Foo_B1></Level1_B_2_1><Level1_B_2_2><Foo_A>0.00</Foo_A><Foo_B>0.00</Foo_B><Foo_B1>0.00</Foo_B1></Level1_B_2_2></Level1_B_2></Level1_B><Level1_C><Foo_A>0.00</Foo_A><Foo_B>0.00</Foo_B><Foo_B1>0.00</Foo_B1></Level1_C><Level1_D><Foo_A>0.00</Foo_A><Foo_B>0.00</Foo_B><Foo_B1>0.00</Foo_B1></Level1_D></Level1><Level2><Foo_A>1065106.46</Foo_A><Foo_B>675706.31</Foo_B><Foo_B1>0.00</Foo_B1><Level2_A><Foo_A>556001.19</Foo_A><Foo_B>138410.82</Foo_B><Foo_B1>0.00</Foo_B1><Level2_A_1><Foo_A>50000.00</Foo_A><Foo_B>50000.00</Foo_B><Foo_B1>0.00</Foo_B1></Level2_A_1></Level2_A><Level2_B><Foo_A>509105.27</Foo_A><Foo_B>537295.49</Foo_B><Foo_B1>0.00</Foo_B1><Level2_B_1><Foo_A>0.00</Foo_A><Foo_B>0.00</Foo_B><Foo_B1>0.00</Foo_B1></Level2_B_1><Level2_B_2><Foo_A>0.00</Foo_A><Foo_B>0.00</Foo_B><Foo_B1>0.00</Foo_B1></Level2_B_2></Level2_B></Level2></Root_Level>’
</code></pre>
<p>Code I’ve written (brace yourself, it's pretty ugly):</p>
<pre><code># code to help you get started
from lxml import etree
tree = etree.fromstring(xmlstr)
tree.xpath('.')[0].getchildren()
xml_node = tree.xpath('.')[0]
# real use case starts here
table = []
tmp = {}
for b in xml_node:
lvl = 0
tag = b.tag
txt = b.text
table.append(tmp)
tmp = {}
tmp['lbl'] = tag
tmp['lvl'] = lvl
for elem in b.getchildren():
lvl = 1
tag = elem.tag
txt = elem.text
if tag.lower().strip().startswith('foo'):
tmp[tag] = txt
else:
table.append(tmp)
tmp = {}
tmp['lbl'] = tag
tmp['lvl'] = lvl
for el in elem.getchildren():
lvl = 2
tag = el.tag
txt = el.text
if tag.lower().strip().startswith('foo'):
tmp[tag] = txt
else:
table.append(tmp)
tmp = {}
tmp['lbl'] = tag
tmp['lvl'] = lvl
for e in el.getchildren():
lvl = 3
tag = e.tag
txt = e.text
if tag.lower().strip().startswith('foo'):
tmp[tag] = txt
else:
table.append(tmp)
tmp = {}
tmp['lbl'] = tag
tmp['lvl'] = lvl
for e in e.getchildren():
lvl = 4
tag = e.tag
txt = e.text
if tag.lower().strip().startswith('foo'):
tmp[tag] = txt
else:
table.append(tmp)
tmp = {}
tmp['lbl'] = tag
tmp['lvl'] = lvl
for e in e.getchildren():
lvl = 5
tag = e.tag
txt = e.text
if tag.lower().strip().startswith('foo'):
tmp[tag] = txt
else:
table.append(tmp)
tmp = {}
tmp['lbl'] = tag
tmp['lvl'] = lvl
for e in e.getchildren():
lvl = 6
tag = e.tag
txt = e.text
if tag.lower().strip().startswith('foo'):
tmp[tag] = txt
else:
table.append(tmp)
tmp = {}
tmp['lbl'] = tag
tmp['lvl'] = lvl
for e in e.getchildren():
lvl = 7
tag = e.tag
txt = e.text
if tag.lower().strip().startswith('foo'):
tmp[tag] = txt
else:
table.append(tmp)
tmp = {}
tmp['lbl'] = tag
tmp['lvl'] = lvl
if e.getchildren():
raise NotImplementedError
# make_sure_last_row_is_appended
try:
if table[-1]['lbl'] != tag:
table.append(tmp)
except KeyError:
# probably table has only 1 row
table.append(tmp)
# remove_technical_first_row
p = table.pop(0)
</code></pre>
<p>Output looks like this (as it should, there is no leeway regarding its structure):</p>
<pre><code>[ {'lbl': 'Level1', 'lvl': 0, 'Foo_A': '1065106.46', 'Foo_B': '675706.31', 'Foo_B1': '0.00'}, {'lbl': 'Level1_A', 'lvl': 1, 'Foo_A': '23750.00', 'Foo_B': '0.00', 'Foo_B1': '0.00'}, {'lbl': 'Level1_B', 'lvl': 1, 'Foo_A': '1041356.46', 'Foo_B': '675706.31', 'Foo_B1': '0.00'}, {'lbl': 'Level1_B_1', 'lvl': 2, 'Foo_A': '0.00', 'Foo_B': '0.00', 'Foo_B1': '0.00'}, {'lbl': 'Level1_B_2', 'lvl': 2, 'Foo_A': '466158.93', 'Foo_B': '59838.40', 'Foo_B1': '0.00'}, {'lbl': 'Level1_B_2_1', 'lvl': 3, 'Foo_A': '0.00', 'Foo_B': '0.00', 'Foo_B1': '0.00'}, {'lbl': 'Level1_B_2_2', 'lvl': 3, 'Foo_A': '0.00', 'Foo_B': '0.00', 'Foo_B1': '0.00'}, {'lbl': 'Level1_C', 'lvl': 1, 'Foo_A': '0.00', 'Foo_B': '0.00', 'Foo_B1': '0.00'}, {'lbl': 'Level1_D', 'lvl': 1, 'Foo_A': '0.00', 'Foo_B': '0.00', 'Foo_B1': '0.00'}, {'lbl': 'Level2', 'lvl': 0, 'Foo_A': '1065106.46', 'Foo_B': '675706.31', 'Foo_B1': '0.00'}, {'lbl': 'Level2_A', 'lvl': 1, 'Foo_A': '556001.19', 'Foo_B': '138410.82', 'Foo_B1': '0.00'}, {'lbl': 'Level2_A_1', 'lvl': 2, 'Foo_A': '50000.00', 'Foo_B': '50000.00', 'Foo_B1': '0.00'}, {'lbl': 'Level2_B', 'lvl': 1, 'Foo_A': '509105.27', 'Foo_B': '537295.49', 'Foo_B1': '0.00'}, {'lbl': 'Level2_B_1', 'lvl': 2, 'Foo_A': '0.00', 'Foo_B': '0.00', 'Foo_B1': '0.00'}, {'lbl': 'Level2_B_2', 'lvl': 2, 'Foo_A': '0.00', 'Foo_B': '0.00', 'Foo_B1': '0.00'}]
</code></pre>
<p>The main problem with this code is that I don't have control over the input xml, so theoretically it can be more nested than I'll anticipate in my code. So far I wrote 'n'+3 for-loops with 'n' being the maximal nesting level observed in a test sample, but an input xml easily can be more nested that 'n'+3.</p>
<p>What I wrote was partly justified by being in a hurry, but to be honest I don't have an idea how to handle this more elegantly. I went through methods proposed in several articles (for example <a href="https://www.thepythoncorner.com/2017/12/the-art-of-avoiding-nested-code/?source=post_page-----ec8a780089b7----------------------" rel="nofollow noreferrer">this one</a> or <a href="https://medium.com/python-pandemonium/never-write-for-loops-again-91a5a4c84baf" rel="nofollow noreferrer">that one</a>), but nothing came to mind. Maybe this can be done with 'while True...break' statement or getchildren() method hidden in a generator function...</p>
<p>Also, it's important to maintain the data structure, so lxml._Element.iter() method instead of lxml._Element.getchildren() seems a bad idea.</p>
<p>So far performance wasn’t an issue.
At last stage of refactoring process I usually improve variable names and divide code into smallest possible functions with descriptive names as per ‘Clean Code’ methodology, so suggestions in this area while welcomed are secondary to the main problem.</p>
<p>How can I improve my code?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T20:35:19.033",
"Id": "443169",
"Score": "0",
"body": "_\"How can I improve my code?\"_ Do some XSLT procesing before in 1st place."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T20:55:00.670",
"Id": "443171",
"Score": "0",
"body": "Your code doesn't do what the question says it does. Is this because it is not implemented?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T20:56:41.837",
"Id": "443172",
"Score": "0",
"body": "Quick suggestion: get all matching nodes with `tree.xpath(\"//*[starts-with(name(), 'Foo')]\")` and then use `getparent()` to find the height of the node (or perhaps that's possible with XPath too)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T21:02:36.070",
"Id": "443174",
"Score": "0",
"body": "Thanks @ferada, I'll try that. Can I use XPath() instead of xpath()? (see:https://www.ibm.com/developerworks/xml/library/x-hiperfparse/)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T21:04:35.167",
"Id": "443175",
"Score": "0",
"body": "I don't know, I meant XPath the standard, not the method. Seems to work fine for me with `tree.xpath`, but of course you can see if there's a more convenient/fast/... implementation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T21:06:35.247",
"Id": "443176",
"Score": "0",
"body": "@FreezePhoenix, what do you mean? I was trying to convay the goal of re-writing for-loops into something different... Is the title misleading?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T21:30:54.683",
"Id": "443180",
"Score": "0",
"body": "Thanks @πάντα ῥεῖ for your suggestion. Could you elaborate on how would you transform xml via xsl? I’m not proficient in XSLT and it seems to me that I’ll be doing the same only using <xsl:for-each select=””>"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T19:54:29.397",
"Id": "443297",
"Score": "0",
"body": "@PawelKam Your title says it is not using nested for loops - however your code disagrees."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T16:49:19.367",
"Id": "443368",
"Score": "0",
"body": "I edited the title."
}
] |
[
{
"body": "<p>The way to process recursively nested data is with recursively nested code.</p>\n\n<p>I don't know Python, and I would do this in XQuery or XSLT by preference, but the pseudo-code is the same whatever the language:</p>\n\n<pre><code>function deep_process (parent, table, level) {\n for child in parent.children() {\n shallow_process(child, table, level)\n deep_process(child, table, level+1);\n }\n}\n</code></pre>\n\n<p>where shallow_process() is whatever local processing you do at every level. </p>\n\n<p>The key message to take away is that processing recursive data requires recursive code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T21:51:08.027",
"Id": "227605",
"ParentId": "227602",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "227605",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T20:14:42.203",
"Id": "227602",
"Score": "3",
"Tags": [
"python",
"parsing",
"xml",
"iteration",
"lxml"
],
"Title": "Nested for-loops in xml parsing"
}
|
227602
|
<p>I have a ReactJS component that I feel is a little bulky. The component holds the information for an event, and clicking on it shows the description for the event. Clicking the event component again will hide the description. The event component also has a triangle symbol that changes from down to up when the Event component is clicked. When the mouse overs over the Event component it changes from grey to maroon. Below are images of the component expressing this functionality. </p>
<p><a href="https://i.stack.imgur.com/poZ8g.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/poZ8g.png" alt=" Initial state, no clicking or mouse hovering "></a></p>
<p><a href="https://i.stack.imgur.com/veaqu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/veaqu.png" alt="Mouse hovering, changes to maroon. "></a></p>
<p><a href="https://i.stack.imgur.com/QJSTq.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QJSTq.jpg" alt="Event component gets clicked, shows the description. When the Event component gets clicked, the description gets hidden. "></a></p>
<p>The code for the entire Event Component:</p>
<pre><code>import React, { Component } from 'react';
class Event extends Component {
constructor(props) {
super(props);
this.state = { des:false, titleHov: false };
}
showDescription = ( ) => {
if ( this.state.des == true ) {
this.setState({
des:false
});
} else {
this.setState({
des:true
});
}
}
onMouseEnter = () => {
this.setState({
titleHov:true
});
}
onMouseLeave = () => {
this.setState({
titleHov:false
});
}
render() {
var eve = this.props.eve;
var des;
var tUp = '△';
var tDown = '▽';
var AtriangleCLS = 'Atriangle';
if (this.state.des == true) {
AtriangleCLS = 'Atriangle titleHover';
des = (
<div>
<div className = 'eTitle titleHover'
onClick = {this.showDescription}
onMouseEnter={this.onMouseEnter}
onMouseLeave={this.onMouseLeave}>
{eve.title} - {eve.date}
<span className = {AtriangleCLS} > {tUp} </span>
</div>
<div className = "eDescription" >
Start Time: {eve.st} - End Time: {eve.et} <br />
{eve.description}
</div>
</div>
);
} else {
var titleCLS = '';
if (this.state.titleHov == true) {
titleCLS = 'eTitle titleHover';
AtriangleCLS = 'Atriangle titleHover';
} else {
titleCLS = 'eTitle nottitleHover';
AtriangleCLS = 'Atriangle nottitleHover';
}
des = (
<div className = {titleCLS}
onClick = {this.showDescription}
onMouseEnter={this.onMouseEnter}
onMouseLeave={this.onMouseLeave} >
{eve.title} - {eve.date}
<span className = {AtriangleCLS} > {tDown} </span>
</div>
);
}
return (
<li> {des} </li>
);
}
}
export default Event;
</code></pre>
<p>Next CSS used:</p>
<pre><code>#eventslist li {
list-style-type: none;
}
#eventslist .eTitle {
display: block;
margin-top: 1em;
padding: 0.75em;
cursor: pointer;
width: 60%;
min-width: 270px;
}
#eventslist .eDescription {
color: rgb( 77, 0, 38 );
background: rgb(232, 234,240 );
display: block;
padding: 0.75em;
width: 60%;
min-width: 270px;
}
.titleHover {
background: rgb( 77, 0, 38 );
color: rgb(232, 234,240 );
}
.nottitleHover {
color: rgb( 77, 0, 38 );
background: rgb(232, 234,240 );
}
.Atriangle {
padding: 0.2em;
float: right;
margin-left: 1em;
display: block;
font-family: 'consolas';
}
</code></pre>
<p>My concerns are that <code>onMouseEnter</code> and <code>onMouseLeave</code> are inefficient. I'd use CSS hover, but I want the Event component to stay maroon when the description is extended.</p>
<p>I am concerned about my use of the triangle symbol. I would like to know the best way to handle and display Unicode symbols.</p>
<p>My concern for <code>showDescription</code> is that it could be bulky and inefficient.</p>
<p>Interested in any advice. </p>
<p>To see my coding style, these are links to gits for event.js, events.css, and events.js. This isn't finished production code yet, just working code. Where I'm at after I get the component working.</p>
<p><a href="https://gist.github.com/digitaldulphin/dd0826bf09b0aec87e7b7a1bce0b57f7" rel="nofollow noreferrer">Event.js</a></p>
<p><a href="https://gist.github.com/digitaldulphin/d25677244b2fc984da3b8e0bf8739092" rel="nofollow noreferrer">Events.css</a></p>
<p><a href="https://gist.github.com/digitaldulphin/4d757edfddd774c22ef3b6b7511bb393" rel="nofollow noreferrer">Events.js (Parent Component) </a> </p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T22:52:16.323",
"Id": "227607",
"Score": "1",
"Tags": [
"javascript",
"css",
"react.js"
],
"Title": "Using ReactJS. Div changes color on hover. On Click drops down description"
}
|
227607
|
<p>Caeser's cipher code where there are a converter and a game part with user input. The code includes keys (settable and not settable).</p>
<pre><code>import random
def change_letter(original, new_message, key_number, alpha):
for letter in original:
if letter in alpha.lower():
new_message += alpha[(alpha.lower().index(letter) + key_number) % 26].lower()
elif letter in alpha:
new_message += alpha[(alpha.index(letter) + key_number) % 26]
else:
new_message += letter
return new_message
def encipher(the_key, message, inp=True):
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
output_message = ""
if inp:
try:
the_key = int(input('Key? ・ '))
except ValueError:
the_key = input('\nNot valid input ・ ')
while not the_key.isnumeric():
the_key = input('Not valid input ・ ')
output_message = change_letter(message, output_message, int(the_key), alphabet)
return output_message
def convert():
while True:
key = None
type_word = input('\nType your word ・ ')
print('\n{} :: {}'.format(type_word, encipher(key, type_word)))
convert_again = input('\nWould you like to convert again? | Y/N ・ ').upper()
if convert_again == 'Y' or convert_again == 'YES':
continue
break
def play():
while True:
key = random.randint(1, 25)
words = ('WWE', 'Javascript', 'Pythonista', 'Computer Science', 'Eighty-three', 'Event Log', '5K Freestyle')
word = random.choice(words)
question = input('\nWhat is {} of key {} ・ '.format(word, key)).lower()
changed_word = encipher(key, word, inp=False)
if question == changed_word.lower():
print(f'Congratulations! You guessed {changed_word} from {word}')
else:
print(f'Oops! Wrong answer. The word is {changed_word} from {word}')
play_again = input('\nWould you like to play again? | Y/N ・ ')
if play_again.upper() == 'YES' or play_again.upper() == 'Y':
continue
break
def main():
while True:
convert_or_play = input('C to convert, P to play ・ ')
if convert_or_play.upper() == 'C':
convert()
elif convert_or_play.upper() == 'P':
play()
else:
break
print()
if __name__ == '__main__':
main()
</code></pre>
|
[] |
[
{
"body": "<pre><code>def change_letter(original, new_message, key_number, alpha):\n</code></pre>\n\n<ul>\n<li><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.</li>\n</ul>\n\n<p>You should include a docstring indicating what the parameters are and what the function does:</p>\n\n<pre><code>def change_letter(original, new_message, key_number, alpha):\n \"\"\"\n Encode message.\n original: a string (word)\n new_message: empty string\n key_number: int\n alpha: a string containing lowercase alphabet\n \"\"\"\n</code></pre>\n\n<p><strong>unecessary function parameter</strong>: <code>new_message</code></p>\n\n<p>There is no need to bother user with entering an empty string.</p>\n\n<p><strong>string immutability:</strong>:</p>\n\n<pre><code>new_message += alpha[(alpha.lower().index(letter) + key_number) % 26].lower()\n</code></pre>\n\n<p>A string is immutable in Python therefore each time you're adding to a string, you're creating another string instance and this is pretty inefficient, use list comprehension syntax instead.</p>\n\n<p><strong>list comprehension syntax:</strong></p>\n\n<p>You can use list comprehensions to replace this whole function in the following way:</p>\n\n<pre><code>def encode(message: str, shift: int):\n \"\"\"Encode and return message.\"\"\"\nreturn ''.join([chr(ord(char) + shift) for char in message.lower()])\n</code></pre>\n\n<p>the use of ord and chr is very useful in this case since both do not care about whether a character is uppercase, lowercase or digit, they convert everything and they are much more efficient than <code>alpha.lower().index(letter) + key_number) % 26</code> which call .lower() and .index() for each letter in the word.</p>\n\n<pre><code>def encipher(the_key, message, inp=True):\n alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n</code></pre>\n\n<ul>\n<li>same comments regarding docstrings.</li>\n<li>you can use string.ascii_uppercase instead of manually writing the letters with possibility of a slip of hand and the creation of a bug in the case of a missed letter.</li>\n<li><code>if inp:</code> I did not find a single case where inp might be set to False so there is no need for this parameter.</li>\n</ul>\n\n<p>This whole <code>encipher()</code> can be shortened to the following:</p>\n\n<pre><code>def encipher(message, encryption_key=input('Enter key: ')):\n \"\"\"Encipher according to a user given key, return an error if key is not digit.\"\"\"\n while not encryption_key.isdigit():\n encryption_key = input('Invalid input, enter a number: ')\n return encode(message, int(encryption_key))\n</code></pre>\n\n<p><strong>f-strings:</strong> since you're using Python 3, in Python source code, an f-string is a literal string, prefixed with 'f', which contains expressions inside braces. The expressions are replaced with their values.</p>\n\n<pre><code>print('\\n{} :: {}'.format(type_word, encipher(key, type_word)))\n</code></pre>\n\n<p>expression can be written using f-strings in the following way:</p>\n\n<pre><code>print(f\"\\n{type_word} : {encipher(key, type_word)}\")\n</code></pre>\n\n<p>same goes for <code>question = input('\\nWhat is {} of key {} ・ '.format(word, key)).lower()</code></p>\n\n<p>can be written: </p>\n\n<pre><code>question = input(f'What is the translation of {word} using {key} as key? ').lower()\n</code></pre>\n\n<p><strong>Here's a refactored version of the code:</strong></p>\n\n<pre><code>import random\n\n\ndef encode(message: str, shift: int):\n \"\"\"Encode and return message.\"\"\"\n return ''.join([chr(ord(char) + shift) for char in message.lower()])\n\n\ndef encipher():\n \"\"\"Encode message interactively.\"\"\"\n message = input('Enter word/message: ')\n encryption_key = input('Enter key: ')\n while not encryption_key.isdigit():\n key = input('Invalid input, enter a number: ')\n encoded_message = encode(message, int(encryption_key))\n print(f'{message} has been encoded to {encoded_message}')\n re_encode = input(f'Would you like to convert {encoded_message} again? y/n: ').lower()\n while re_encode.lower() not in 'yesno':\n print(f'Invalid input {re_encode}')\n re_encode = input(f'Would you like to convert another word? y/n: ').lower()\n if re_encode in 'no':\n print('Thank you for using Cesar cipher.')\n exit(0)\n if re_encode in 'yes':\n encipher()\n\n\ndef play():\n \"\"\"Play a cipher game.\"\"\"\n key = random.randint(1, 25)\n words = ('WWE', 'Javascript', 'Pythonista', 'Computer Science', 'Eighty-three', 'Event Log', '5K Freestyle')\n word = random.choice(words)\n answer = input(f'What is the translation of {word} using {key} as key? ')\n encoded_word = encode(word, key)\n if answer == encoded_word:\n print(f'Correct guess {encoded_word}')\n if answer != encoded_word:\n print(f'Oops! wrong guess {answer} the correct answer is {encoded_word}')\n replay = input('Would you like to play again? y/n: ')\n while replay not in 'yesno':\n print(f'Invalid input {replay}')\n replay = input('Would you like to play again? y/n: ')\n if replay in 'no':\n print('Thank you for using Cesar cipher.')\n exit(0)\n if replay in 'yes':\n play()\n\n\nif __name__ == '__main__':\n while True:\n game_or_encode = input('Enter e to encode or p to play e/p: ').lower()\n while game_or_encode not in 'ep':\n print(f'Invalid entry {game_or_encode}')\n game_or_encode = input('Enter e to encode or p to play e/p: ').lower()\n if game_or_encode == 'e':\n encipher()\n if game_or_encode == 'p':\n play()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T05:19:44.683",
"Id": "443205",
"Score": "0",
"body": "what does \"''.join([chr(ord(char) + shift) for char in message.lower()])\" explicitly mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T05:27:21.103",
"Id": "443206",
"Score": "1",
"body": "The ord() gets the numerical representation of a character if you add shift then the numerical representation is shifted by the shift value. Then the call to chr() converts a numerical value back to a letter. example: ord('a') = 97, ord('c') = 99 so if you called chr(99) it converts the 99 to its respective letter 'c', the list contains all the converted letters(strings) so a call to join() joins the list into the converted(encoded) word."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T05:28:19.590",
"Id": "443207",
"Score": "1",
"body": "You might want to check this link https://docs.python.org/2/library/functions.html"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T03:09:06.837",
"Id": "227616",
"ParentId": "227611",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T00:48:15.130",
"Id": "227611",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x",
"game",
"caesar-cipher"
],
"Title": "Caesar Cypher guessing game"
}
|
227611
|
<p>I wrote a floating-point multiplication function as an excercise. The program compares its result to the usual hardware multiplication result and for this purpose I use unspecified behavior, but the function itself should be fine. I do get warnings about XOR-ing 1-bit ints but I have no idea why.</p>
<p>I noticed there aren't that many comments in the multiplication function so I wonder what I could put there.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <math.h>
#include <assert.h>
#include <memory.h>
#include <limits.h>
#include <fenv.h>
#include <float.h>
#include <thread>
#include <mutex>
#include <iostream>
#include <random>
int msb( uint64_t v )
{
if(v == 0) return 0;
return 63-__builtin_clzll(v);
}
void roundedShift(uint64_t* a, unsigned int n) {
if(n >= sizeof(uint64_t)*CHAR_BIT) {
// we don't care about rounding if n == 64 because mantissa product is always less than 2^46
*a = 0;
}
uint64_t roundoff = *a - ((*a >> n) << n);
*a >>= n;
if(roundoff*2 > (1ull<<n)
||
(roundoff*2 == (1ull<<n) && (*a)%2 == 1)) {
++(*a);
}
}
struct SoftFloat {
unsigned int mantissa : 23;
unsigned int exponent : 8;
unsigned int sign : 1;
static const SoftFloat nan;
SoftFloat operator *(SoftFloat right) const {
if(exponent == 255 || right.exponent == 255) {
return specialMultiplication(right);
}
uint64_t fullLeftMantissa = (mantissa)+(exponent!=0?(1<<23):0);
uint64_t fullRightMantissa = (right.mantissa)+(right.exponent!=0?(1<<23):0);
uint64_t fullNewMantissa = fullLeftMantissa * fullRightMantissa;
// experiment have shown that operating on biased exponents is faster than
// computing unbiased exponent and then adding bias
short leftNormalBiasedExponent = exponent != 0 ? exponent: 1;
short rightNormalBiasedExponent = right.exponent != 0 ? right.exponent : 1;
short newNormalBiasedExponent = leftNormalBiasedExponent +
rightNormalBiasedExponent - 127 - 23;
int totalShift = 0;
if(newNormalBiasedExponent < 1) {
int diff = -newNormalBiasedExponent + 1;
newNormalBiasedExponent = 1;
totalShift += diff;
}
int implicitBit = msb(fullNewMantissa);
int shift = implicitBit - totalShift - 23;
if(shift >= 0) {
newNormalBiasedExponent += shift;
totalShift += shift;
fullNewMantissa &= ~(1ll << implicitBit);
} else {
newNormalBiasedExponent = 0;
}
roundedShift(&fullNewMantissa, totalShift);
if(fullNewMantissa == (1 << 23)) {
++newNormalBiasedExponent;
fullNewMantissa = 0;
}
if(newNormalBiasedExponent >= 255) {
newNormalBiasedExponent = 255;
fullNewMantissa = 0;
}
return SoftFloat{(uint)fullNewMantissa, (uint)newNormalBiasedExponent, sign ^ right.sign};
// i don't really understan why this return expression gives warning
// narrowing conversion of ‘(((int)((const SoftFloat*)this)->SoftFloat::sign) ^ ((int)right.SoftFloat::sign))’ from ‘int’ to ‘unsigned int’
}
bool isNan() const {
return exponent == 255 && mantissa != 0;
// This is same as (*reinterpret_cast<const unsigned int*>(this) << 1) > 0b11111111000000000000000000000000u,
// but the experiments have shown it doesn't make any difference for speed on my machine.
// Current version does not invoke any UB
}
bool isZero() const {
return exponent == 0 && mantissa == 0;
}
bool isRepresentationEqual(const SoftFloat& right) {
return !memcmp(this, &right, sizeof(SoftFloat));
}
// Correctness testing relies on specific layout of floats and of fields inside SoftFloat, but the multiplication function itself does not
float toHardFloat() const {
float res;
memcpy(&res, this, sizeof(SoftFloat));
return res;
}
static SoftFloat fromOrdinalNumber(const unsigned int& a) {
SoftFloat res;
memcpy(&res, &a, sizeof(SoftFloat));
return res;
}
static SoftFloat fromHardFloat(const float& a) {
SoftFloat res;
memcpy(&res, &a, sizeof(SoftFloat));
return res;
}
private:
SoftFloat specialMultiplication(SoftFloat right) const {
// precondition - at least one of *this, right is either inf, -inf or nan
if(isNan() || right.isNan()) {
return nan;
}
if(isZero() || right.isZero()) {
return nan;
}
return {0, 255, sign ^ right.sign};
}
};
const SoftFloat SoftFloat::nan = {1, 255, 0};
std::mutex coutMutex;
void checkOneMultiplication(SoftFloat left, SoftFloat right) {
SoftFloat softProduct = left*right;
SoftFloat hardProduct = SoftFloat::fromHardFloat(
left.toHardFloat() *
right.toHardFloat());
bool equalRepresentation = softProduct.isRepresentationEqual(hardProduct);
bool bothNan = softProduct.isNan() &&
hardProduct.isNan();
if(!(equalRepresentation || bothNan)) {
std::lock_guard<std::mutex> lock(coutMutex);
std::cerr << "failed\n";
std::cerr << "left operand\t" << left.mantissa << " " << left.exponent << " " << left.sign << " " << left.toHardFloat() << std::endl;
std::cerr << "right operand\t" << right.mantissa << " " << right.exponent << " " << right.sign << " " << right.toHardFloat() << std::endl;
std::cerr << "soft product\t" << softProduct.mantissa << " " << softProduct.exponent << " " << softProduct.sign << " " << softProduct.toHardFloat() << std::endl;
std::cerr << "hard product\t" << hardProduct.mantissa << " " << hardProduct.exponent << " " << hardProduct.sign << " " << hardProduct.toHardFloat() << std::endl;
abort();
}
}
void checkRange(unsigned int start, unsigned int end, int threadNumber) {
// this loop checks multiplication with every one of 2^28 possible floats in given range of representaions. Right operand is pseudorandom but deterministic
std::uniform_int_distribution<unsigned int> distr;
std::mt19937 gen(threadNumber);
for(unsigned int representationNumber = start; representationNumber != end; representationNumber++) {
// can't use < in condition because last block ends with 0
int rigntOperandRepresentationNumber = distr(gen);
SoftFloat leftOperand = SoftFloat::fromOrdinalNumber(representationNumber);
SoftFloat rightOperand = SoftFloat::fromOrdinalNumber(rigntOperandRepresentationNumber);
checkOneMultiplication(leftOperand, rightOperand);
if(representationNumber%0x10000000 == 0 && representationNumber > start) {
std::lock_guard<std::mutex> lock(coutMutex);
std::cout << "thread " << threadNumber << " checked 0x" << std::hex << representationNumber-start << " multiplications" << std::endl;
}
}
}
int main(int argc, char *argv[])
{
static_assert(sizeof(SoftFloat) == sizeof(float));
static_assert(alignof(SoftFloat) == alignof(float), "");
static_assert(sizeof(SoftFloat) == sizeof(int), "");
static_assert(__BYTE_ORDER__ == LITTLE_ENDIAN, "");
// Unfortunately we can't statically check further details of layout of structures
assert(SoftFloat::fromHardFloat(std::numeric_limits<float>::denorm_min()).isRepresentationEqual(SoftFloat{1, 0, 0}));
assert(SoftFloat::fromHardFloat(FLT_MIN).isRepresentationEqual(SoftFloat{0, 1, 0}));
float nonConstant = -1;
assert(SoftFloat::fromHardFloat(nonConstant*0).isRepresentationEqual(SoftFloat{0, 0, 1}));
// Test can't run if any of the above asserts fail
const int threadCount = 4;
fesetround(FE_TONEAREST); // assuming mantissa is rounded to even when there are two nearest
std::thread threads[threadCount-1];
const unsigned int blockSize = UINT32_MAX/4+1;
for(int i = 1; i < threadCount; i++) {
threads[i-1] = std::thread(checkRange, blockSize*i, blockSize*(i+1), i);
}
checkRange(0, blockSize, 0);
SoftFloat specialCases[] = {{0, 0, 0}, // 0
{0, 0, 1}, // -0
{0, 255, 0}, //inf
{0, 255, 1}, //-inf
SoftFloat::nan,
SoftFloat::fromHardFloat(std::nanf("")),
SoftFloat::fromHardFloat(FLT_MIN),
SoftFloat::fromHardFloat(1),
SoftFloat::fromHardFloat(FLT_MAX),
SoftFloat::fromHardFloat(FLT_EPSILON),
SoftFloat::fromHardFloat(std::numeric_limits<float>::denorm_min()),
SoftFloat::fromHardFloat(-FLT_MAX),
SoftFloat::fromHardFloat(FLT_MIN_EXP),
SoftFloat::fromHardFloat(FLT_MIN_10_EXP),
SoftFloat::fromHardFloat(FLT_MAX_EXP),
SoftFloat::fromHardFloat(FLT_MAX_10_EXP)};
int numberOfSpecialCases = sizeof(specialCases)/sizeof(SoftFloat);
for(int i = 0; i < numberOfSpecialCases; i++) {
for(int j = 0; j < numberOfSpecialCases; j++) {
checkOneMultiplication(specialCases[i], specialCases[j]);
}
}
for(int i = 1; i < threadCount; i++) {
threads[i-1].join();
}
std::cout << "checked 0x" << UINT32_MAX + numberOfSpecialCases*numberOfSpecialCases << " multiplications";
return 0;
}
</code></pre>
<p>The program tests multiplication of every possible floating-point number with a random number. This takes a long time to run, so I made it threaded. I also used fancy C++11 RNG stuff to make it deterministic.</p>
<p>The function uses <code>__builtin_clzll</code> which is available on gcc and clang but not on MSVC, I believe.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T01:22:52.757",
"Id": "446286",
"Score": "0",
"body": "What (compiler, OS, standard) are you targeting?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T19:00:59.287",
"Id": "446495",
"Score": "0",
"body": "Let's say gcc, linux, x64"
}
] |
[
{
"body": "<p>Fairly good code overall.</p>\n\n<p>Mostly small stuff below.</p>\n\n<p><strong>Narrowing</strong></p>\n\n<blockquote>\n <p>I do get warnings about XOR-ing 1-bit ints but I have no idea why.</p>\n</blockquote>\n\n<p>Weak compiler.</p>\n\n<p>Perhaps use <code>bool sign : 1;</code></p>\n\n<p><strong>Naked magic numbers</strong></p>\n\n<p>Rather than 23, 127, etc, consider the C-ish</p>\n\n<pre><code>#define MANTISSA_BIT_WIDTH 23\n</code></pre>\n\n<p>or a C++ -ish</p>\n\n<pre><code>const int mantissa_bit_width = 23;\n</code></pre>\n\n<p><strong><code>uint</code>?</strong></p>\n\n<p><code>uint</code> appears non-standard. Perhaps <code>unsigned</code>?</p>\n\n<pre><code>// return SoftFloat{(uint)fullNewMantissa, (uint)newNormalBiasedExponent, sign ^ right.sign};\nreturn SoftFloat{(unsigned)fullNewMantissa, (unsigned)newNormalBiasedExponent, sign ^ right.sign};\n</code></pre>\n\n<hr>\n\n<p>Minor stuff</p>\n\n<p><strong>Portability</strong></p>\n\n<p>Although OP has \"gcc, linux, x64\", little changes would step toward portability without sacrificing efficient emitted code.</p>\n\n<pre><code>// if(fullNewMantissa == (1 << 23)) {\nif(fullNewMantissa == (1ul << 23)) { // `int` could be 16-bit\n\n// fullNewMantissa &= ~(1ll << implicitBit);\nfullNewMantissa &= ~(1ull << implicitBit); // Why mess with signed shifts?\n</code></pre>\n\n<p><strong><code>int</code> vs. <code>short</code></strong></p>\n\n<p>Rarely is <code>short</code> faster/better than <code>int</code> unless one has an array of the type.</p>\n\n<p>Consider</p>\n\n<pre><code>// short leftNormalBiasedExponent, rightNormalBiasedExponent, newNormalBiasedExponent\nint leftNormalBiasedExponent, rightNormalBiasedExponent, newNormalBiasedExponent\n</code></pre>\n\n<p><strong>sizeof type vs sizeof object</strong></p>\n\n<p>Consider the clearer, less maintenance </p>\n\n<pre><code>// return !memcmp(this, &right, sizeof(SoftFloat));\nreturn !memcmp(this, &right, sizeof *this);\n</code></pre>\n\n<p><strong><code>roundedShift()</code></strong></p>\n\n<p>Unclear about <code>roundedShift()</code> correctness. Partly due to lack of comments, partly due to \"it takes time\" to analyze.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T10:26:11.167",
"Id": "447444",
"Score": "2",
"body": "I doubt *weak compiler* - the 1-bit `unsigned` are each promoted to `int` for the XOR, so narrowing to 1-bit `unsigned` warrants a warning. Changing the type to `bool` and using `!=` in place of `^` is a good suggestion, though."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T16:58:32.633",
"Id": "229857",
"ParentId": "227612",
"Score": "4"
}
},
{
"body": "<p>Using the C compatibility headers is questionable in new code:</p>\n\n<blockquote>\n<pre><code>#include <math.h>\n#include <assert.h>\n#include <memory.h>\n#include <limits.h>\n#include <fenv.h>\n#include <float.h>\n</code></pre>\n</blockquote>\n\n<p>I recommend using the C++ versions (<code><cmath></code> etc.) which define their identifiers in the <code>std</code> namespace.</p>\n\n<p>We're missing an include of <code><stdint.h></code> for <code>uint64_t</code> (or better, include <code><cstdint></code> to define <code>std::uint64_t</code>). Do we really need a 64-bit type, or would <code>std::fast_uint64_t</code> be a better choice?</p>\n\n<p>There are many instances of <code>sizeof</code> with a typename argument, which would be clearer with an ordinary expression argument. For example:</p>\n\n<blockquote>\n<pre><code> SoftFloat res;\n memcpy(&res, &a, sizeof(SoftFloat));\n return res;\n</code></pre>\n</blockquote>\n\n<p>Here we can show that we're correctly passing the size of the destination argument:</p>\n\n<pre><code> SoftFloat res;\n std::memcpy(&res, &a, sizeof res);\n return res;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T10:36:49.273",
"Id": "229904",
"ParentId": "227612",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "229857",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T02:10:56.860",
"Id": "227612",
"Score": "7",
"Tags": [
"c++",
"floating-point"
],
"Title": "Software floating-point multiplication"
}
|
227612
|
<p>For learning purpose, I've written a simple lambda calculus interpreter (plus 'Add'). I would like it to be the cleanest and most idiomatic possible.</p>
<p>Bonus question: how would you use <code>deriving (Show)</code> for <code>Val</code>, just having to define <code>show</code> for <code>Fun (Val -> Val)</code>? </p>
<pre><code>-- Lambda calculus interpreter example.
import qualified Data.Map.Lazy as Map
data Val = Num Integer | Fun (Val -> Val) | Wrong
data Term = Cons Integer | Var String | Lam String Term | App Term Term | Add Term Term
type Env = Map.Map String Val
add :: Val -> Val -> Val
add (Num x) (Num y) = Num (x+y)
add _ _ = Wrong
apply :: Val -> Val -> Val
apply (Fun f) v = f v
apply _ _ = Wrong
instance Show Val where
show (Num x) = show x
show (Fun f) = "function"
show Wrong = "Wrong"
interp :: Term -> Env -> Val
interp (Cons x) e = Num x
interp (Var s) e = Map.findWithDefault Wrong s e -- Equivalent to:
-- interp (Var s) e = maybe Wrong id (Map.lookup s e)
interp (Lam s t) e = Fun (\v -> interp t (Map.insert s v e))
interp (App f t) e = apply (interp f e) (interp t e)
interp (Add a b) e = add (interp a e) (interp b e)
expr = App (Lam "x" (Add (Var "x") (Var "x"))) (Add (Cons 10) (Cons 11))
res = interp expr Map.empty
main = putStrLn (show res)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T02:01:05.327",
"Id": "443306",
"Score": "0",
"body": "Someone posted the very similar [Lambda calculus interpreter in Haskell](https://codereview.stackexchange.com/questions/139752/lambda-calculus-interpreter-in-haskell) here on Code Review 3 years ago; unfortunately, it only received a few comments."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T09:40:49.833",
"Id": "443328",
"Score": "0",
"body": "I've seen it, the goal seemed sufficiently different. For instance I don't care about alpha renaming..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T19:47:48.817",
"Id": "444935",
"Score": "0",
"body": "I randomly stumbled upon a syntax tree, similar to the one I recommended, in this paper on monad transformers: https://page.mi.fu-berlin.de/scravy/realworldhaskell/materialien/monad-transformers-step-by-step.pdf -- the author has a constructor that would be `Fun Env String Term` in your case, rather than `Fun (Val -> Val)`."
}
] |
[
{
"body": "<p>I wanted to give a more full answer, but I can't fully commit to it, so here are a few things:</p>\n\n<ul>\n<li><p>Instead of having <code>Wrong</code> built into the result type, you would rather want <code>Maybe Val</code>, or better yet, <code>Either String Val</code> or <code>Either Error val</code>, since there are multiple possible causes for failure.</p></li>\n<li><p>I'm a little skeptical about <code>Fun (Val -> Val)</code>: This seems to serve two purposes:</p>\n\n<ol>\n<li><p>The final result of <code>interp</code> could be a lambda.</p>\n\n<p>Theoretically it must always be, but for a practical purpose, perhaps, you've decided that integers are different from functions. And that if one were to return a value that hasn't reduced to an integer, then rather produce a Haskell function that can resume evaluation later.</p>\n\n<p>The drawback is that you can't further transform the structure hidden away in a <code>Fun (Val -> Val)</code> in the same way as you can with a <code>Term</code>; you can only reduce it further using <code>interp</code>. For example, you can only pretty-print the result if it's an integer, or a failure.</p></li>\n<li><p>As an intermediate representation of a term being evaluated. But since any lambda reduction rule provides another term, <code>Term</code> should be an excellent intermediate representation.</p></li>\n</ol></li>\n<li><p>When you express an intermediate state as <code>Fun (Val -> Val)</code>, it also contains an implicit <code>Env</code>, which is in some sense a reader monad pattern. Typically you might represent this with <code>Control.Monad.Reader</code> instead.</p></li>\n<li><p>I think keeping an <code>Env</code> might be neat - I've seen several examples of people building quite advanced lambda calculus interpreters that do this. But when I first thought how I'd make it myself, I thought of</p>\n\n<pre><code>interp (App (Lam x body) arg) = subst x body arg\ninterp (App (Var x) _arg) = Left (\"Free variable \" ++ show x)\n</code></pre>\n\n<p>since, if I encountered a <code>Var x</code> on the left-hand side of an application, I'd know that it hadn't been substituted by an outer reduction. But I'm not wise enough to say which is better here, that was just my first thought.</p></li>\n<li><p>I'd rename <code>Cons</code> to <code>Num</code> or <code>Int</code>: <code>Cons</code> seems a bit contrived for constant, and <code>Const</code> is a bit vague, since you really mean integer constant. But what constant is there about a lambda term? I mean, theoretically it could also be a function if the interpreter allowed it.</p></li>\n<li><p>If your intermediate representation was <code>Term</code> and not <code>Val</code>, and your interpreter was monadic (e.g. for handling errors) you could merge <code>add</code> into <code>apply</code>, since <code>Add</code> is just a special-case function application:</p>\n\n<pre><code>interp (App (Lam x body) arg) = subst x body arg\ninterp (App (Var x) _arg) = Left (\"Free variable \" ++ show x)\ninterp (Add e1 e2) = add <$> interp e1 <*> interp e2\n\nadd (Int m) (Int n) = return (Int (m + n))\nadd x y = Left (\"Cannot add non-integers \" ++ show x ++ \" and \" ++ show y)\n</code></pre>\n\n<p>Pretty-printing <code>m</code> and <code>n</code> here is possible because <code>Term</code>'s structure is not hidden within a Haskell <code>-></code> function.</p></li>\n<li><p>You have two things that could be expressed in terms of monads: Making <code>Env</code> implicit using a reader monad, and handling errors using <code>Either</code>. This could be expressed as</p>\n\n<pre><code>type Env = Map Var Term\ntype Interpreter = Env -> Term -> Either String Term\n</code></pre>\n\n<p>or rather using <a href=\"http://hackage.haskell.org/package/transformers-0.5.6.2/docs/Control-Monad-Trans-Reader.html\" rel=\"nofollow noreferrer\"><code>Control.Monad.Trans.Reader</code></a>:</p>\n\n<pre><code>type Env = Map Var Term\ntype Interpreter a = ReaderT Env (Either String) a\n</code></pre>\n\n<p>which is <a href=\"http://hackage.haskell.org/package/transformers/docs/src/Control.Monad.Trans.Reader.html#ReaderT\" rel=\"nofollow noreferrer\">equivalent under the hood</a>, but it means you can do stuff like:</p>\n\n<pre><code>interp (Add e1 e2) = add <$> interp e1 <*> interp e2\n</code></pre></li>\n</ul>\n\n<blockquote>\n <p>I don't care about alpha renaming</p>\n</blockquote>\n\n<p>I'm not sure how to interpret this, but the following thought comes to mind:</p>\n\n<p>It is idiomatic to model your data type as close to the domain, so the fact that <code>Lam \"x\" (Var \"y\")</code> passes type-check but can not evaluate (unless there's some kind of initial environment that catches free variables) is a problem. One way to address this I've seen is e.g. <a href=\"https://en.wikipedia.org/wiki/De_Bruijn_index\" rel=\"nofollow noreferrer\">de Bruijn indexing</a> as performed e.g. by <a href=\"https://jameshfisher.com/2018/03/15/a-lambda-calculus-interpreter-in-haskell/\" rel=\"nofollow noreferrer\">James Fisher</a> which is one way to say that he also doesn't care about alpha renaming by never having the need. One could even convert freely between one interpretation with variables and another without, depending on which representation is most convenient for a given purpose.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T10:58:34.990",
"Id": "227775",
"ParentId": "227617",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T04:41:43.343",
"Id": "227617",
"Score": "2",
"Tags": [
"haskell",
"mathematics",
"interpreter"
],
"Title": "Meta-circular interpreter for lambda calculus in Haskell"
}
|
227617
|
<p>For learning purpose, I've written a simple lambda calculus interpreter (plus 'Add'). I would like it to be the cleanest and most idiomatic possible.</p>
<p>Can we make it as neat as the <a href="https://codereview.stackexchange.com/questions/227617/meta-circular-interpreter-for-lambda-calculus-in-haskell">Haskell version</a>?</p>
<pre><code># lambda interpreter example.
# Values: Num, Fun & Wrong.
# Terms: Cons, Var, Lam, App & Add.
class Num:
def __init__(self, v):
self.v = v
def __str__(self):
return str(self.v)
class Fun:
def __init__(self, f):
self.f = f
def __call__(self, *args, **kargs):
return self.f(*args, **kargs)
def __str__(self):
return 'function'
class Wrong:
def __str__(self):
return 'Wrong'
def add(v1, v2):
return Num(v1.v + v2.v)
def apply(v1, v2):
return v1(v2)
class Cons:
def __init__(self, v):
self.v = int(v)
def interp(self, env):
return Num(self.v)
class Var:
def __init__(self, x):
self.x = x
def interp(self, env):
return env[self.x]
class Lam:
def __init__(self, arg, body):
self.arg = arg
self.body = body
def interp(self, env):
def f(v):
env2 = env.copy()
env2[self.arg] = v
return self.body.interp(env2)
return Fun(f)
class App:
def __init__(self, fun, param):
self.fun = fun
self.param = param
def interp(self, env):
return apply(self.fun.interp(env),
self.param.interp(env))
class Add:
def __init__(self, a, b):
self.a = a
self.b = b
def interp(self, env):
return add(self.a.interp(env), self.b.interp(env))
expr = App( Lam('x', Add(Var('x'), Var('x'))),
Add(Cons(10), Cons(11)) )
print(expr.interp({}))
</code></pre>
|
[] |
[
{
"body": "<p>I don't quite know what lambda calculus is (I'm assuming it's a mathematical annotation for what we might call \"purely functional programming\"?), but I'll give this a quick shot.</p>\n\n<p>First, I'd love to have <code>env</code> populate itself if not provided. You really shouldn't have mutable default values for functions, though; the typical practice is to define:</p>\n\n<pre><code>interp(self, env=None):\n env = env or {}\n # ...\n</code></pre>\n\n<p>but that's really bloat'y in this case, so let's use a little inheritance:</p>\n\n<pre><code>class Op:\n def interp(self, env=None):\n return self._interp(env if env is not None else {})\n\n def _interp(self, env):\n raise NotImplementedError()\n\n\nclass Cons(Op):\n def __init__(self, v):\n self.v = int(v)\n\n def _interp(self, env): # update name to \"_interp\"\n return Num(self.v)\n\n# ...\n\nprint(expr.interp()) # Yay for no boilerplate arguments!\n</code></pre>\n\n<p>Now we can just call <code>interp()</code> and the rest handles itself.</p>\n\n<p>The next thing I'd do to make things a bit more concise is to leverage <a href=\"https://docs.python.org/3/library/dataclasses.html\" rel=\"nofollow noreferrer\">Python 3.7's new dataclass feature</a>; while this doesn't seem to remove any lines of code, it's certainly more concise and descriptive, and adds some useful meta-features like allowing our AST objects to be intelligently compared and printed:</p>\n\n<pre><code>from dataclasses import dataclass\n\n# ...\n\n@dataclass\nclass App(Op):\n fun: Lam\n param: Op\n\n def _interp(self, env):\n return self.fun.interp(env)(self.param.interp(env))\n\n\n@dataclass\nclass Add(Op):\n a: Op\n b: Op\n\n def _interp(self, env):\n return add(self.a.interp(env), self.b.interp(env))\n\n# ...\n\nprint(expr)\n# App(fun=Lam(arg='x', body=Add(a=Var(x='x'), b=Var(x='x'))), param=Add(a=Cons(v=10), b=Cons(v=11)))\n</code></pre>\n\n<p>Moving beyond <code>Add</code>, we can start using inheritance to make things clearer and more concise:</p>\n\n<pre><code>@dataclass\nclass BinOp(Op):\n a: Op\n b: Op\n\n @staticmethod\n def _func(v1, v2):\n raise NotImplementedError()\n\n def _interp(self, env):\n return self._func(self.a.interp(env), self.b.interp(env))\n\n\nclass Add(BinOp):\n @staticmethod\n def _func(v1, v2):\n return Num(v1.v + v2.v)\n\n\nclass Sub(BinOp):\n @staticmethod\n def _func(v1, v2):\n return Num(v1.v - v2.v)\n</code></pre>\n\n<p>Some minor nit-pick details to finish off:</p>\n\n<ul>\n<li><p>4-space indentation is more common than 2-space, which can look a bit cramped.</p></li>\n<li><p>I'm not sure if it's typically allowed in lambda calculus, but I'd like to see Lam/functions that can take any number of arguments (I have a working implementation that's pretty clean that I'd be happy to share if you're interested).</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T11:04:00.850",
"Id": "444877",
"Score": "1",
"body": "Thanks for the tips! \nI'm not convinced by the env handling, tough. Too much indirections. Isn't \"Explicit better than implicit\"? :) Here, we really want to say the interpreter needs an environnement, and that this environnement is empty at the beginning.\n\nI'll definitively look at dataclass@. Con: even more \"magic\". Pro: if it becomes idiomatic, it sure can make things clearer.\n\nIn lambda calculus, you handle several arguments by [currying](https://en.wikipedia.org/wiki/Currying). In python: \n>>> m = lambda x: lambda y: x*y\n>>> m(6)(7)\n42"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T11:06:22.913",
"Id": "444878",
"Score": "0",
"body": "That being said, I'am interested in your multi-args implementation!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T22:29:33.630",
"Id": "227815",
"ParentId": "227618",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T05:27:55.623",
"Id": "227618",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"mathematics",
"interpreter"
],
"Title": "Meta-circular interpreter for lambda calculus in Python"
}
|
227618
|
<p>Well this is a basic hangman game in c++ without the classy man getting hanged animation (life is printed instead) </p>
<pre><code>#include <iostream>
#include <cstdlib>
#include <string.h>
#include <time.h>
#include <fstream>
using namespace std;
string previousGuesses; //string to hold previous guesses
class movie {
private:
string name;
int _size;
public:
movie(void);
inline string getName(void) {
return this->name;
}
inline int getSize(void) {
return this->_size;
}
};
movie::movie(void) {
ifstream fin;
fin.open("movies.txt", ios::in);
// int random_integer = rand();
getline(fin, this->name); //currently takes the first line as movie name. Randomising logic will be inserted....any hints??
this->_size = name.size();
fin.close();
}
int numOfSpaces(string name) {
register unsigned counter = 0;
for (register int i = 0; i < name.size(); i++) {
if(name[i] == ' ') {
counter++;
}
}
return counter;
}
bool guessedPreviously(char ch) {
if(previousGuesses.find(ch) != -1) { //if guess is found, return true
return true;
}
previousGuesses += ch;
return false;
}
void print(char name[], int size) {
for (register int i = 0; i < size; i++) {
cout << name[i];
}
cout << endl;
}
int main(int argc, char const* argv[]) {
/*to get name of the movie*/
srand(time(NULL)); //seed for rand();
register int counter = 0; //used to check if the full guess has been finally made though better logic is welcome
register int life = 10; //hold the lives user has
movie m1; //object of movie class
char name[m1.getSize()]; //temp char[] (used to mask/unmask movie name)
char guess; //shall hold user's guess
string _name = m1.getName(); //a variable to store the movie name (needed as m1.getName()[i] surprisingly doesn't work....why??)
for (register int i = 0; i < m1.getSize(); i++) {
/*logic to keep spaces, spaces in the temp char[]*/
if(_name[i] != ' ')
name[i] = '*';
else
name[i] = ' ';
}
while (1) { //runs the game loop
/*User's guess*/
cout << "Enter a guess: ";
cin >> guess;
if(guessedPreviously(guess)) {
cout << "guess already made!!" << endl;
life--;
cout << life << endl;
if (life == 0) {
cout << "game over!!!" << endl;
cout << m1.getName() << endl;
exit(0);
}
continue;
}
cout << endl; //I/O formatting ...... because we need it!!
/*check guess*/
bool check = false; //boolean variable to umm.. not let the else if get unnecessarily executed
for (register int i = 0; i < _name.size(); i++) {
if(_name[i] == guess) {
name[i] = guess; //replaces * in temporary char[] at all places where guess is correct
check = true;
/*To check if the full guess has finally been made!!*/
counter++;
if(counter == (m1.getSize() - numOfSpaces(m1.getName()))) { //m1.getSize() also returns spaces, which are not being guessed
cout << "congrats!! You've won" << endl;
exit(0);
}
}
else if (i == _name.size() - 1 && !check) { //the 'what to do if guess is wrong??' logic
cout << "wrong guess!!" << endl;
life--; //kill the user once XD
cout << "You have " << life << " guesses left!!" << endl;
if (life == 0) {
cout << "game over!!!" << endl;
cout << m1.getName() << endl;
exit(0);
}
}
}
/*unmask*/
print(name, m1.getSize());
}
return 0;
}
</code></pre>
<p>All kinds of improvements are welcome :)</p>
<p>Also how do I make the code case insensitive efficiently??</p>
<p>BTW, the repository is public <a href="https://github.com/d4rk4ng31/cpp-projects" rel="nofollow noreferrer">here</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T07:53:34.223",
"Id": "443215",
"Score": "2",
"body": "I added the tag _game_ which is the generic tag accompanying any specific game tag. You don't see this change at the revision (https://codereview.stackexchange.com/revisions/227619/3) But you do see it at the revision overview (https://codereview.stackexchange.com/posts/227619/revisions)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T08:03:27.870",
"Id": "443218",
"Score": "0",
"body": "No offense taken :) I am surprised to see a revision does not show tag edits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T08:06:42.173",
"Id": "443221",
"Score": "1",
"body": "@Mast I am not sure whether this is as designed or not. But I'm not concerned about it either :) If it's a bug, it's hypo minor :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T08:14:56.993",
"Id": "443223",
"Score": "2",
"body": "Welcome to Code Review! Similar questions are fine on Code Review."
}
] |
[
{
"body": "<p>Welcome to Code Review! Here's some suggestions.</p>\n\n<h1>Overall design</h1>\n\n<p>You defined a class <code>movie</code>. Despite its name, all it does is read a string from the configuration file <code>movies.txt</code>. This is unnecessary — just write a function that reads a string.</p>\n\n<p>The global variable <code>previousGuesses</code> contains the previous guesses. This shows that the game is stateful. This is a good use for classes:</p>\n\n<pre><code>class Hangman_game {\npublic:\n // ...\nprivate:\n std::string word;\n std::string guesses;\n};\n</code></pre>\n\n<p>The <code>numOfSpaces</code> function can be replaced by <code>std::count</code>. The <code>print</code> function is unnecessary. And it is counter-intuitive that <code>guessedPreviously</code> modifies the <code>previousGuesses</code>.</p>\n\n<p>You are using char arrays all over the place. In C++, prefer <code>std::string</code> for actual strings.</p>\n\n<h1>Code</h1>\n\n<blockquote>\n<pre><code>#include <iostream>\n#include <cstdlib>\n#include <string.h>\n#include <time.h>\n#include <fstream>\n</code></pre>\n</blockquote>\n\n<p>Use <code><cstring></code> and <code><ctime></code>. And sort the headers alphabetically:</p>\n\n<pre><code>#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#include <fstream>\n#include <iostream>\n</code></pre>\n\n<blockquote>\n<pre><code>using namespace std;\n</code></pre>\n</blockquote>\n\n<p>Do not use <code>using namespace std;</code>. It is considered <a href=\"https://stackoverflow.com/q/1452721\">bad practice</a> and will cause a lot of problems. For example, you will have some trouble using common identifiers like <code>size</code>.</p>\n\n<blockquote>\n<pre><code>class movie {\n private:\n string name;\n int _size;\n\n public:\n movie(void);\n inline string getName(void) {\n return this->name;\n }\n inline int getSize(void) {\n return this->_size;\n }\n};\n</code></pre>\n</blockquote>\n\n<ol>\n<li><p><code>inline</code> is redundant in a class.</p></li>\n<li><p><code>(void)</code> is C-style and is not recommended in C++. Use <code>()</code> instead.</p></li>\n<li><p><code>this-></code> is unnecessary.</p></li>\n<li><p><code>std::string</code> maintains the size, so <code>_size</code> should be removed.</p></li>\n</ol>\n\n<p><code>public:</code> and <code>private:</code> are usually not indented. And as I said before, this class should not exist at all.</p>\n\n<blockquote>\n<pre><code>movie::movie(void) {\n ifstream fin;\n fin.open(\"movies.txt\", ios::in);\n // int random_integer = rand();\n getline(fin, this->name); //currently takes the first line as movie name. Randomising logic will be inserted....any hints??\n this->_size = name.size();\n fin.close();\n}\n</code></pre>\n</blockquote>\n\n<p>The same thing with compact code:</p>\n\n<pre><code>std::ifstream fin{\"movies.txt\"}; // the default is \"in\"\nstd::getline(fin, name);\n</code></pre>\n\n<p>Also, <code>\"movies.txt\"</code> should not be hardcoded.</p>\n\n<blockquote>\n<pre><code>int numOfSpaces(string name) {\n register unsigned counter = 0;\n for (register int i = 0; i < name.size(); i++) {\n if(name[i] == ' ') {\n counter++;\n }\n }\n return counter;\n}\n</code></pre>\n</blockquote>\n\n<p>The keyword <code>register</code> is completely ignored by the compiler. Also, use</p>\n\n<pre><code>std::count(name.begin(), name.end(), ' ')\n</code></pre>\n\n<p>instead.</p>\n\n<blockquote>\n<pre><code>bool guessedPreviously(char ch) {\n if(previousGuesses.find(ch) != -1) { //if guess is found, return true\n return true;\n }\n previousGuesses += ch;\n return false;\n}\n</code></pre>\n</blockquote>\n\n<p>Use <code>std::string::npos</code> instead of <code>-1</code>. The latter is counter-intuitive and may cause signedness warnings.</p>\n\n<blockquote>\n<pre><code>void print(char name[], int size) {\n for (register int i = 0; i < size; i++) {\n cout << name[i];\n }\n cout << endl;\n}\n</code></pre>\n</blockquote>\n\n<p>You should never be using a <code>char[]</code>, but even if that is the case, use <code>std::cout << std::string_view(name, size) << '\\n';</code>. <a href=\"https://stackoverflow.com/q/213907\">Don't use <code>std::endl</code>.</a></p>\n\n<hr>\n\n<p>The main function is too long and looks chaotic. It should be broken into different functions. And you are using a variable length array which is a non-standard extension and should not be used. <code>std::string</code> should be used instead. And there's quite a few problems. <code>rand</code> is infamous for its low quality and should not be used. Too many variables make the logic hard to understand. Most of the loops should be replaced by standard algorithms. <code>return</code> is better than <code>exit(0)</code>. Use <code>++i</code> instead of <code>i++</code> in a discarded value expression.</p>\n\n<h1>Improved version</h1>\n\n<p>Here's a very rough version in which I fix the aforementioned problems, not tested extensively:</p>\n\n<pre><code>#include <algorithm>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <stdexcept>\n#include <string>\n#include <string_view>\n\nclass Hangman {\npublic:\n Hangman(std::string_view w, int l)\n :word{w}, current(w.size(), '_'), lives{l}\n {\n if (w.find('_') != w.npos) {\n throw std::runtime_error{\"underscore character not supported\"};\n }\n }\n void run();\n\nprivate:\n std::string word;\n std::string current; // the current state (e.g., \"_an_man\")\n int lives; // number of lives left\n\n enum class State {\n none, win, fail\n };\n\n void display();\n State guess();\n};\n\nvoid Hangman::run()\n{\n State state;\n do {\n display();\n state = guess();\n } while (state == State::none);\n\n display();\n if (state == State::win) {\n std::cout << \"Congratulations! You win.\\n\";\n } else {\n std::cout << \"Game over.\\n\"\n << \"The word is \" << std::quoted(word) << '\\n';\n }\n}\n\nvoid Hangman::display()\n{\n std::cout << \"Word: \" << current << \"\\n\"\n \"Lives left: \" << lives << \"\\n\\n\";\n}\n\nauto Hangman::guess() -> State\n{\n std::cout << \"Guess a letter: \";\n\n char c;\n std::cin >> c;\n if (!std::cin) {\n throw std::runtime_error{\"input failure\"};\n }\n\n if (current.find(c) != current.npos) {\n std::cout << \"You have already guessed this letter.\\n\\n\";\n --lives;\n } else if (word.find(c) == word.npos) {\n std::cout << \"Bad guess.\\n\\n\";\n --lives;\n } else {\n for (std::size_t i = 0; i < word.size(); ++i) {\n if (word[i] == c)\n current[i] = c;\n }\n if (word == current)\n return State::win;\n }\n\n if (lives == 0)\n return State::fail;\n else\n return State::none;\n}\n\nint main()\n{\n Hangman game{\"derivative\", 6}; // configuration\n game.run();\n}\n</code></pre>\n\n<p>Example session:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Word: __________\nLives left: 6\n\nGuess a letter: a\nWord: _____a____\nLives left: 6\n\nGuess a letter: b\nBad guess.\n\nWord: _____a____\nLives left: 5\n\nGuess a letter: c\nBad guess.\n\nWord: _____a____\nLives left: 4\n\nGuess a letter: d\nWord: d____a____\nLives left: 4\n\nGuess a letter: e\nWord: de___a___e\nLives left: 4\n\nGuess a letter: f\nBad guess.\n\nWord: de___a___e\nLives left: 3\n\nGuess a letter: g\nBad guess.\n\nWord: de___a___e\nLives left: 2\n\nGuess a letter: h\nBad guess.\n\nWord: de___a___e\nLives left: 1\n\nGuess a letter: i\nWord: de_i_a_i_e\nLives left: 1\n\nGuess a letter: j\nBad guess.\n\nWord: de_i_a_i_e\nLives left: 0\n\nGame over.\nThe word is \"derivative\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T09:09:45.537",
"Id": "443231",
"Score": "1",
"body": "@d4rk4ng31 You are welcome. Essentially, the game needs to keep track of some states (the word, the current guessed letters, lives left), so it is advised to use a class to encapsulate them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T09:15:14.113",
"Id": "443233",
"Score": "1",
"body": "@d4rk4ng31 As I said before, `rand()` is a low-quality RNG and should not be used. C++11 offers the `<random>` header which contains high-quality RNG."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T09:24:20.590",
"Id": "443236",
"Score": "0",
"body": "Also, is there any specific reason for compiler to ignore `register` keyword?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T09:25:32.847",
"Id": "443237",
"Score": "0",
"body": "@d4rk4ng31 Yeah, `<random>` is a big one. You need to construct an engine first (e.g., mt19937) and then use a uniform int distribution to generate an index from, say, 0 to 25."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T09:26:11.387",
"Id": "443238",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/98394/discussion-between-d4rk4ng31-and-l-f)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T09:27:11.843",
"Id": "443239",
"Score": "1",
"body": "@d4rk4ng31 `register` is specified to have no meaning since C++11, and \"poisoned\" since C++17 (i.e., using it is ill-formed)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T16:02:01.743",
"Id": "443457",
"Score": "1",
"body": "@d4rk4ng31 Good optimizing compilers will do a better job of allocating registers than the author (supposedly). Good optimizing compilers may modify the algorithm as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T16:03:34.533",
"Id": "443459",
"Score": "0",
"body": "Alphabetizing includes may not work in all cases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T16:17:58.667",
"Id": "443463",
"Score": "0",
"body": "Oh!! But does it work at least in C (still) ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T01:44:17.693",
"Id": "443508",
"Score": "1",
"body": "@d4rk4ng31I Yeah, it still works in C11 AFAIK, but please note that the notion of \"register\" doesn't exist in the C or C++ standards, so it exists merely as a recommendation to the implementation. The recommendation isn't always respected, anyway - the implementation is free to put a non-`register` variable in registers, and free to put a `register` variable outside registers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T07:32:05.907",
"Id": "443524",
"Score": "0",
"body": "One more thing. I have never seen this syntax. What does `auto Hangman::guess() -> State` do?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T08:14:44.447",
"Id": "443537",
"Score": "0",
"body": "@d4rk4ng31 It’s called the “trailing return type” `auto f() -> T` is equivalent to `T f()`"
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T08:42:04.783",
"Id": "227625",
"ParentId": "227619",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "227625",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T05:52:39.297",
"Id": "227619",
"Score": "6",
"Tags": [
"c++",
"game",
"hangman"
],
"Title": "CLI Hangman game in C++"
}
|
227619
|
<p>I made an implementation of atoi (ascii to integer) in Python a while ago for fun, and I'd like to know what I could do to improve it.</p>
<hr>
<pre><code>class CannotConvertToInteger(Exception):
"""A non-numeric character was present in the string passed to atoi"""
pass
def atoi(string : str) -> int:
sign = multiplier = 1
val = 0
if string[0] == '-':
string = string[1:]
sign = -1
elif string[0] == '+':
string = string[1:]
for i in string[::-1]:
code = ord(i)
try:
if ((code > 57) or (code < 48)):
raise CannotConvertToInteger
else:
val += (code - 48) * multiplier
multiplier *= 10
except CannotConvertToInteger:
return print('Cannot convert string to an integer!')
return (val * sign)
test_string = input('Enter an optionally signed integer: ')
result = atoi(test_string)
if result:
print('It was a valid int! atoi() returned:', result)
else:
print('It was an invalid int! atoi() returned:', result)
input()
</code></pre>
<hr>
<p>One specific question I have is if it's bad practice to return a print call, as a way to print an error and simultaneously return from the function? I did that so that I could print the error and return <code>None</code> on the same line.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T11:54:02.913",
"Id": "443335",
"Score": "1",
"body": "Your program reports \"invalid integer\" if you input `0`. (Note: this is not a problem in your `atoi` function, but rather in the testing code below the function)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T17:41:04.733",
"Id": "443376",
"Score": "0",
"body": "@marcelm I can’t believe I forgot to test for that but thanks for pointing that out!"
}
] |
[
{
"body": "<ul>\n<li><p>Python already has an exception that denotes that the value you passed is inappropriate somehow. It is <a href=\"https://docs.python.org/3/library/exceptions.html#ValueError\" rel=\"noreferrer\"><code>ValueError</code></a>, which is what the built-in <a href=\"https://docs.python.org/3/library/functions.html#int\" rel=\"noreferrer\"><code>int</code></a> also raises if a wrong string is passed.</p>\n\n<p>In addition, defining a nice readable error which you can raise, only to catch it directly within the function and to return <code>None</code> (the output of <code>print</code>) and print to the terminal is not ideal. Just let the exception rise to the caller of the function, it should be their problem if the function is used in a bad way (which you are telling them all about with that exception).</p></li>\n<li><p>You should avoid magic constants. What are <code>57</code> and <code>48</code>? Either give them names and use compound comparisons:</p>\n\n<pre><code>zero = ord(\"0\")\nnine = ord(\"9\")\n\nif not zero <= code <= nine:\n ...\n</code></pre>\n\n<p>Or, maybe even better, write a <code>isdigit</code> function:</p>\n\n<pre><code>def isdigit(s):\n return s in set(\"0123456789\")\n</code></pre>\n\n<p>Which can be slightly sped up by using the standard library <a href=\"https://docs.python.org/3/library/string.html\" rel=\"noreferrer\"><code>string</code></a> module:</p>\n\n<pre><code>from string import digits\n\nDIGITS = set(digits)\n\ndef isdigit(s):\n return s in DIGITS\n</code></pre>\n\n<p>Incidentally, don't shadow the standard library <code>string</code> module, just call the input <code>s</code> or <code>x</code>, as <code>int</code> does.</p>\n\n<p>Note that there are also <a href=\"https://docs.python.org/3/library/stdtypes.html#str.isdigit\" rel=\"noreferrer\"><code>str.isdigit</code></a>, but this unfortunately also returns true for unicode digits, such as all of <code>¹²³⁴⁵⁶⁷⁸⁹⁰</code>. Only with a whitelist can you fully control what counts as a digit in your case.</p></li>\n<li><p>Instead of iterating over the string and directly calling <code>ord</code>, you can use <a href=\"https://docs.python.org/3/library/functions.html#map\" rel=\"noreferrer\"><code>map</code></a> (and <a href=\"https://docs.python.org/3/library/functions.html#reversed\" rel=\"noreferrer\"><code>reversed</code></a>):</p>\n\n<pre><code>for code in map(ord, reversed(string)):\n ...\n</code></pre>\n\n<p>You could also iterate over <code>multiplier</code> (or rather its exponent) at the same time using <a href=\"https://docs.python.org/3/library/functions.html#enumerate\" rel=\"noreferrer\"><code>enumerate</code></a>:</p>\n\n<pre><code>for exponent, code in enumerate(map(ord, reversed(string))):\n ...\n value += (code - zero) * 10 ** exponent\n</code></pre></li>\n<li><p>Actually directly manipulating ASCII values is not the most robust (although it works). Instead you could just make a dictionary that maps strings to integer values:</p>\n\n<pre><code>VALUES = {c: d for d, c in enumerate(DIGITS)}\n</code></pre></li>\n<li><p>Using <code>string[0]</code> to check for a sign character can fail if the empty string is passed. Instead you can use <a href=\"https://docs.python.org/3/library/stdtypes.html#str.startswith\" rel=\"noreferrer\"><code>str.startswith(\"+\")</code></a> or even <code>str.startswith((\"+\", \"-\"))</code>. This will just return <code>False</code> for an empty string.</p></li>\n<li><p>With all this done, your function can actually easily be extended to arbitrary bases (but let's stick to maximum base 36, like <code>int</code>, i.e. all digits and lowercase letters):</p>\n\n<pre><code>DIGITS = string.digits + string.ascii_lowercase\nVALUES = {c: d for d, c in enumerate(DIGITS)}\n\ndef isdigit(s, base=10):\n return s in DIGITS[:base]\n\ndef atoi(x : str, base : int = 10):\n if not 2 <= base <= 36:\n raise ValueError(\"Only 2 <= base <= 36 currently supported\")\n sign = 1\n if x.startswith((\"+\", \"-\")):\n if x[0] == \"-\":\n sign = -1\n x = x[1:]\n value = 0\n for exp, c in enumerate(reversed(x)):\n if c not in VALUES or VALUES[c] >= base:\n raise ValueError(f\"{c} is not a valid digit in base {base}\")\n value += VALUES[c] * base ** exp\n return sign * value\n</code></pre>\n\n<p>This works, as demonstrated below:</p>\n\n<pre><code>atoi(\"12345\")\n# 12345\natoi(\"+12345\")\n# 12345\natoi(\"-12345\")\n# -12345\natoi(\"12345\", base=6)\n# 1865\natoi(\"12345\", base=5)\n# ValueError: 5 is not a valid digit in base 5\natoi(\"101010\", base=2)\n# 42\natoi(\"1234567890abcdef\", base=16)\n# 1311768467294899695\natoi(\"1234567890abcdefghijklmnopqrstuvwxyz\", base=36)\n# 3126485650002806059265235559620383787531710118313327355\natoi(\"\")\n# 0\natoi(\"111\", base=1)\n# ValueError: Only 2 <= base <= 36 currently supported\natoi(\"Az\", base=62)\n# ValueError: Only 2 <= base <= 36 currently supported\n</code></pre></li>\n<li><p>You should surround your calling code with a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to allow importing from this module from another script without the user input/output being run:</p>\n\n<pre><code>if __name__ == \"__main__\":\n x = input('Enter an optionally signed integer: ')\n try:\n print('It was a valid int! atoi() returned:', atoi(x))\n except ValueError:\n print('It was an invalid int!)\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T08:06:21.717",
"Id": "443220",
"Score": "3",
"body": "Damn! I thought about your first two bullet points literally the first second I looked at this, but then forgot to include it in my answer ;-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T08:03:01.007",
"Id": "227622",
"ParentId": "227620",
"Score": "11"
}
},
{
"body": "<h1>Error handling</h1>\n\n<blockquote>\n <p>One specific question I have is if it's bad practice to return a print\n call, as a way to print an error and simultaneously return from the\n function? I did that so that I could print the error and return None\n on the same line.</p>\n</blockquote>\n\n<p>That is unconventional to say the least. By catching the exception internally and print it to the console you take away the ability to handle exceptions in calling code. You should raise an exception if an error occured that cannot be handled by the function itself to give the caller the possibility to decide how to handle this. Also, ask yourself: What is the advantage of your chosen approach? Is</p>\n\n<blockquote>\n<pre><code>result = atoi(test_string)\nif result:\n print('It was a valid int! atoi() returned:', result)\nelse:\n print('It was an invalid int! atoi() returned:', result)\n</code></pre>\n</blockquote>\n\n<p>really any better than, for example:</p>\n\n<pre><code>try:\n result = atoi(test_string)\n print('It was a valid int! atoi() returned:', result)\nexcept CannotConvertToInteger:\n print('It was an invalid int!)\n</code></pre>\n\n<h1>The code itself</h1>\n\n<ul>\n<li>The function would profit from some blank lines to seperate logical blocks.</li>\n<li><code>string[::-1]</code> actually creates a copy, since strings are immutable. You can avoid that by using <code>reversed(string)</code>, which is perfectly fine for your use-case since you only want the single digits, not the whole thing reversed.</li>\n<li><p>This convoluted structure</p>\n\n<blockquote>\n<pre><code>try:\n if ((code > 57) or (code < 48)):\n raise CannotConvertToInteger\n else:\n val += (code - 48) * multiplier\n multiplier *= 10\nexcept CannotConvertToInteger:\n return print('Cannot convert string to an integer!')\n</code></pre>\n</blockquote>\n\n<p>is the price you pay for the way you chose to handle your error cases. As said above, removing the <code>try: ... catch ...:</code> is the favorable approach here.</p></li>\n<li><p><a href=\"https://codereview.stackexchange.com/users/98493/\">@Graipher</a>'s <a href=\"https://codereview.stackexchange.com/a/227622/\">answer</a> has more good points about using built-in exceptions and avoiding magical numbers, that I almost immediately thought about when writing this up, but then forgot in the process.</p></li>\n<li><p>Almost as a side note: you don't need parens around conditions in Python. Most people only ever use them if the conditions get very long and need to spread over multiple lines. The same goes for the return value. Here the parens are even more unnecessary.</p></li>\n<li>You should have a look at the official <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">Style Guide for Python Code</a> (often just called PEP8). The recommendations most relevant to your code would be to use 4 spaces per indentation level and avoid multiple initializations per source line. The meta-site for Code Review also has a nice <a href=\"https://codereview.meta.stackexchange.com/a/5252/92478\">list of tools</a> that can help you check this automatically.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T16:48:56.847",
"Id": "443276",
"Score": "2",
"body": "Even though I didn’t choose your answer, it’s still a really good answer and I very much appreciate the time and thought you put into it. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T08:04:40.837",
"Id": "227623",
"ParentId": "227620",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "227622",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T06:22:54.717",
"Id": "227620",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"reinventing-the-wheel",
"error-handling"
],
"Title": "Python implementation of atoi"
}
|
227620
|
<p><a href="https://projecteuler.net/problem=114" rel="nofollow noreferrer">Problem statement</a> (For more detailed description (including pictures), please, visit the link):</p>
<blockquote>
<p>A row measuring seven units in length has red blocks with a minimum
length of three units placed on it, such that any two red blocks
(which are allowed to be different lengths) are separated by at least
one grey square. There are exactly seventeen ways of doing this.</p>
<p>How many ways can a row measuring fifty units in length be filled?</p>
</blockquote>
<p>Code:</p>
<pre><code>from scipy import special
import time
import itertools
def partitionfunc(n,k,l=3):
'''n is the integer to partition, k is the
length of partitions, l is the min partition element size'''
if k < 1:
return 0
if k == 1:
if n >= l:
yield (n,)
return 0
for i in range(l,n+1):
for result in partitionfunc(n-i,k-1,i):
yield (i,)+result
def valid_partitions(p):
total = p
count = 0 #Max. number of tiles that can be placed on a row.
while True:
count += 1
total -=3
if total <= 3:
break
total-=1
'''Find all the valid partitions with length [1,count] that can be placed on the row with length p'''
data = []
for k in range(1,count+1):
min_part = k*3
for n in range(min_part,p+1):
Allowed = []
LIST = list(partitionfunc(n,k))
for b in LIST:
if sum(b) + (len(b)-1) <= p:
Allowed.append(b)
data+= Allowed
return data
def count_permutations(array):
'''Counts how many possible permutations are there for the particular partition'''
get_unique_elements = set(array)
total_length = len(array)
lengths = [array.count(x) for x in get_unique_elements]
answer = 1
for b in lengths:
answer*= special.comb(total_length, b)
total_length-= b
return answer
def calculate_ways(m,n):
return special.comb(n-m+1,n-2*m+1)
def final(w):
total_variations = 0
data = valid_partitions(w)
for q in data:
m = len(q)
remain = w - sum(q) - m + 1
n = 2*m -1 + remain
total_variations+= calculate_ways(m,n)*count_permutations(q)
return int(total_variations+1)
if __name__ == '__main__':
start = time.time()
print('Answer: {}'.format(final(50)))
print(time.time()-start)
</code></pre>
<p>I'll explain the reasoning behind the code using example provided by the Euler:</p>
<p><strong>Step 1</strong></p>
<p>First, we find maximum number of tiles that can be placed on the row with length 7. At most only 2 tiles can be placed, hence number equals 2 (call this number <strong>count</strong>).</p>
<p>Then we iterate through [1,<strong>count</strong>] and and find all the valid partitions of the number seven:</p>
<p>In our case:</p>
<p>1 tile: (3), (4), (5), (6), (7) (The reason we omit (1) and (2) is because minimum length of red tile is 3)</p>
<p>2 tiles: (3, 3) (Note, that although (3,4) is a partition of 7 too, but it won't work in our case, because it is specified that there must be <em>at least 1 tile gap</em> between two red tiles.</p>
<p><strong>Step 2.</strong></p>
<p>For each partition obtained in step 1, we calculate number of ways the partition can be placed on the row.</p>
<p>For example:</p>
<p>(5) Represents 1 tile with length 5. There are 3 ways to place such tile.</p>
<p>(3,3) Represents 2 tiles both with length 3. There is 1 way to place them on the row.</p>
<p>When we add up the numbers, we end up with 16. We need to add 1, because (I'm curious why) the row that doesn't contain <em>any</em> red tiles is a valid case too. The final answer is 17.</p>
<hr>
<p>I believe that there are <em>a lot</em> of things that can be improved. I'm glad to hear any suggestions!</p>
<p>P.S The problem I would like to specifically point out is the variable/function names. I believe there is a possibility to make them way <em>more</em> descriptive/clear then they are now.</p>
|
[] |
[
{
"body": "<p>Firstly, I have to admit to not doing too much in the way of thinking up better variable names; in part because the algorithm was a little hard to follow without solving the problem myself.</p>\n\n<p>The spacing is all over the place: I'm not a PEP 8 purist but you have -= with a space before on one line, with a space after on another, and neither on a third. I fixed all the things my IDE complained about, including a redundant import of itertools.</p>\n\n<pre><code> LIST = list(partitionfunc(n,k))\n for b in LIST:\n ...\n</code></pre>\n\n<p>Writing LIST to not shadow the builtin list is evil but it's also unecessary: you don't need to listify the generator to iterate over it. That becomes:</p>\n\n<pre><code> for b in partition(n, k):\n ...\n</code></pre>\n\n<p>I changed the partition from tuples to lists, since I thought that was more natural in Python for an homogenous sequence of arbitrary length.</p>\n\n<p>There is a loop in valid_partitions:</p>\n\n<pre><code>count = 0 #Max. number of tiles that can be placed on a row.\nwhile True:\n count += 1\n total -=3\n if total <= 3:\n break\n total-=1\n</code></pre>\n\n<p>I replaced this with:</p>\n\n<pre><code>max_tiles = (p + 1) // 4\n</code></pre>\n\n<p>I made valid_partitions a generator, and lost some temporary variables like 'data'. I also changed the range() to start from 1 as the comment suggests.</p>\n\n<p>There is a little logic in the function final that I felt was doing too much, so moved it into calculate_ways()</p>\n\n<pre><code>for q in data:\n m = len(q)\n remain = w - sum(q) - m + 1\n n = 2*m -1 + remain\n total_variations+= calculate_ways(m,n)*count_permutations(q)\n</code></pre>\n\n<p>final() became:</p>\n\n<pre><code>def total_variations(w):\n return sum(calculate_ways(q, w) * count_permutations(q) for q in valid_partitions(w)) + 1\n</code></pre>\n\n<p>Mayble the one liner is a little <em>too</em> dense, and one should keep the for loop.</p>\n\n<p>calculate_ways() is now a bit opaque and could probably use tidying but at least it's all in one place now.</p>\n\n<p>I added MIN_SIZE = 3. It's probably overkill to pass 3 around as a parameter but probably worth flagging as a magic number.</p>\n\n<pre><code>from scipy import special\nimport time\n\nMIN_SIZE = 3\n\n\ndef partition(n, k, min=MIN_SIZE):\n \"\"\"n is the integer to partition, k is the\n length of partitions, min is the min partition element size\"\"\"\n if k == 1:\n if n >= min:\n yield [n]\n return 0\n for i in range(min, n+1):\n for result in partition(n - i, k - 1, i):\n yield [i] + result\n\n\ndef valid_partitions(p):\n \"\"\"Find all the valid partitions with length [1,max_tiles] that can be placed on the row with length p\"\"\"\n max_tiles = (p + 1) // 4\n for k in range(1, max_tiles+1):\n min_part = k * MIN_SIZE\n for n in range(min_part, p+1):\n for b in partition(n, k):\n if sum(b) + (len(b)-1) <= p:\n yield b\n\n\ndef count_permutations(array):\n \"\"\"Counts how many possible permutations are there for the particular partition\"\"\"\n get_unique_elements = set(array)\n lengths = [array.count(x) for x in get_unique_elements]\n total_length = len(array)\n answer = 1\n for b in lengths:\n answer *= special.comb(total_length, b, exact=True)\n total_length -= b\n return answer\n\n\ndef calculate_ways(q, w):\n m = len(q)\n remain = w - sum(q) - m + 1\n n = 2*m - 1 + remain\n return special.comb(n - m + 1, n - 2*m + 1, exact=True)\n\n\ndef total_variations(w):\n return sum(calculate_ways(q, w) * count_permutations(q) \n\nif __name__ == '__main__':\n start = time.time()\n print('Answer: {}'.format(total_variations(50)))\n print(time.time()-start)\n</code></pre>\n\n<p>As always with Project Euler, there may be some deep mathematical insight that can optimise the algorithm. And there still are a lot of single letter variables; it's a start, though. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T21:49:09.940",
"Id": "443301",
"Score": "0",
"body": "I'm not sure how deep it is, but there's definitely a mathematical insight which makes the algorithm both faster (linear time, assuming constant-time arithmetic operations) and a whole lot easier to understand. However, that's by the by. Great first review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T06:50:56.573",
"Id": "443312",
"Score": "0",
"body": "@richardb Great review, thank you!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T20:22:21.390",
"Id": "227641",
"ParentId": "227624",
"Score": "4"
}
},
{
"body": "<p>Here is a better algorithm to solve the problem.</p>\n\n<p>Let <span class=\"math-container\">\\$c(n, m)\\$</span> be the number of ways to cover <span class=\"math-container\">\\$n\\$</span> units with red blocks of minimum length <span class=\"math-container\">\\$m\\$</span>. Let <span class=\"math-container\">\\$c_r(n, m)\\$</span> and <span class=\"math-container\">\\$c_b(n, m)\\$</span> be the respective number of covers that ends with a red or black unit. We have\n<span class=\"math-container\">$$\nc(n, m) = c_r(n, m) + c_b(n, m)\\label{f1}\\tag{1}\n$$</span></p>\n\n<p>Since any length-<span class=\"math-container\">\\$(n-1)\\$</span> cover can be extended with a black unit to yield a length <span class=\"math-container\">\\$n\\$</span> cover, we have\n<span class=\"math-container\">$$\nc_b(n,m)=c(n-1,m)\\label{f2}\\tag{2}\n$$</span></p>\n\n<p>For any length-<span class=\"math-container\">\\$n\\$</span> cover that ends with a red unit, it either extends a red-ending, length-<span class=\"math-container\">\\$(n-1)\\$</span> cover, or adds a length-<span class=\"math-container\">\\$m\\$</span> red block to a black-ending, length-<span class=\"math-container\">\\$(n-m)\\$</span> cover. Therefore\n<span class=\"math-container\">$$\n\\begin{eqnarray}\nc_r(n,m) & = & c_r(n-1,m)+c_b(n-m,m) \\\\\n & = & c(n - 1, m) - c_b(n - 1, m) + c_b(n - m, m) \\\\\n & = & c(n - 1, m) - c(n - 2, m) + c(n - m - 1, m) \\label{f3}\\tag{3}\n\\end{eqnarray}\n$$</span></p>\n\n<p>Substituting (\\ref{f2}) and (\\ref{f3}) into (\\ref{f1}) yields:\n<span class=\"math-container\">$$\nc(n, m) = 2 \\cdot c(n - 1, m) - c(n - 2, m) + c(n - m - 1, m) \\label{f4} \\tag{4}\n$$</span></p>\n\n<p>The sequence <span class=\"math-container\">\\$\\{c(i, m)\\}_{i=0}^n\\$</span> can now be generated from the linear recurrence (\\ref{f4}) with initial values <span class=\"math-container\">\\$c(-1,m)=c(0,m)=\\ldots=c(m-1,m)=1\\$</span>.</p>\n\n<p>While a linear algorithm solves the original problem with ease, it is not efficient enough to solve <a href=\"https://www.hackerrank.com/contests/projecteuler/challenges/euler114/problem\" rel=\"nofollow noreferrer\">the extended version</a> where the input <span class=\"math-container\">\\$n\\$</span> can go up to <span class=\"math-container\">\\$10^{18}\\$</span>. To speed up computation using the linear recurrence, we define a length-<span class=\"math-container\">\\$(m+1)\\$</span> column vector\n<span class=\"math-container\">$$\nC_i=\n\\begin{pmatrix}\nc(i+m,m) & c(i+m-1,m) & \\ldots & c(i,m)\n\\end{pmatrix} ^T\n$$</span>\nand a <span class=\"math-container\">\\$(m+1)\\times (m+1)\\$</span> coefficient matrix\n<span class=\"math-container\">$$\nA=\n\\begin{pmatrix}\n2 & -1 & 0 & \\cdots & 0 & 1 \\\\\n1 & 0 & 0 & \\cdots & 0 & 0 \\\\\n0 & 1 & 0 & \\cdots & 0 & 0 \\\\\n0 & 0 & 1 & \\cdots & 0 & 0 \\\\\n\\vdots & \\vdots & \\vdots & \\ddots & \\vdots & \\vdots \\\\\n0 & 0 & 0 & \\cdots & 1 & 0 \\\\\n\\end{pmatrix}\n$$</span>\nThen we can see <span class=\"math-container\">\\$C_i=AC_{i-1}=\\ldots=A^{i+1}C_{-1}\\$</span>, where \n<span class=\"math-container\">\\$\nC_{-1}=\n\\begin{pmatrix}\n1 & 1 & \\ldots & 1\n\\end{pmatrix} ^T\n\\$</span>. Therefore <span class=\"math-container\">\\$c(n,m)\\$</span> can be obtained by extracting the first element of \n<span class=\"math-container\">$$C_{n-m}=A^{n-m+1}C_{-1}$$</span>\nSince the power operation can be computed in <span class=\"math-container\">\\$\\Theta(\\log(n-m+1))\\$</span> matrix multiplications and the multiplication time complexity is <span class=\"math-container\">\\$O(m^3)\\$</span>, the entire algorithm is <span class=\"math-container\">\\$O(m^3\\log(n-m))\\$</span> which is sufficient to solve the extended problem.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T16:18:45.853",
"Id": "227671",
"ParentId": "227624",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227641",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T08:23:35.657",
"Id": "227624",
"Score": "2",
"Tags": [
"python",
"programming-challenge",
"combinatorics"
],
"Title": "Counting block combinations I: Project Euler 114"
}
|
227624
|
<p>I have decent experience in programming before (mostly C++), but I am very, very, very new to Python, and I decided to try out Project Euler as an exercise. Here's the description of <a href="https://projecteuler.net/problem=1" rel="nofollow noreferrer">Problem 1</a>:</p>
<blockquote>
<p>If we list all the natural numbers below 10 that are multiples of 3 or
5, we get 3, 5, 6 and 9. The sum of these multiples is 23.</p>
<p>Find the sum of all the multiples of 3 or 5 below 1000.</p>
</blockquote>
<p>Here's my solution:</p>
<pre><code>sum = 0
for n in range(0, 1000):
if n % 3 == 0 or n % 5 == 0:
sum += n
print(sum)
</code></pre>
<p>The program works fine. What I want to get from a code review:</p>
<ul>
<li><p>whether I did anything non-Pythonic;</p></li>
<li><p>whether I did anything outdated;</p></li>
<li><p>whether I did anything against the PEP 8;</p></li>
<li><p>whether there's a better way of doing this;</p></li>
<li><p>...</p></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T11:52:44.780",
"Id": "443251",
"Score": "0",
"body": "Oops, I got a downvote in 40 seconds :( Did I do something wrong?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T13:51:16.720",
"Id": "445784",
"Score": "0",
"body": "hint: the sum of 1.to x is (x*(x+1))/2. I'm pretty sure there's a way to use it here too"
}
] |
[
{
"body": "<p>The keyword <code>sum</code> is a built in function and you shouldn't name variables from within the reserved keywords.</p>\n\n<p>Here's a list of the most common used keywords which you shouldn't be naming any of your variables: </p>\n\n<p>[False, class, finally, is, return, None, continue, for, lambda, try, True, def, from, nonlocal, while, and, del, global, not, with, as, elif, if or, yield, assert, else, import, pass, break, except, in, raise]</p>\n\n<p>And for the built-in functions check <a href=\"https://www.programiz.com/python-programming/methods/built-in\" rel=\"nofollow noreferrer\">https://www.programiz.com/python-programming/methods/built-in</a></p>\n\n<pre><code>for n in range(0, 1000):\n</code></pre>\n\n<p>Can be written <code>for n in range(1000):</code></p>\n\n<p>The <code>range()</code> function as well as the whole Python is zero-indexed.</p>\n\n<p>You might also want to use comprehension syntax (which is much more efficient than explicit loops) and enclose it inside a function like this:</p>\n\n<pre><code>def get_multiples(upper_bound):\n \"\"\"Return sum of multiples of 3 and multiples of 5 within specified range.\"\"\"\n return sum(number for number in range(upper_bound) if not number % 3 or not number % 5)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T12:40:17.797",
"Id": "443259",
"Score": "1",
"body": "Thank you for the review! I'll definitely avoid the reserved identifiers in the future."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T12:56:22.187",
"Id": "443260",
"Score": "0",
"body": "How did you come up with the list of predefined identifiers? Its sorting order looks totally random, which makes it hard to read and learn."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T12:57:24.110",
"Id": "443261",
"Score": "1",
"body": "And by the way, predefined identifiers are different from keywords."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T12:58:54.537",
"Id": "443263",
"Score": "4",
"body": "The function name `get_multiples` sounds as if it returned a sequence, but it doesn't. The function should better be called `sum_of_multiples`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T13:02:50.653",
"Id": "443264",
"Score": "2",
"body": "Using the `not` operator on numbers is confusing, at least for me. The code more clearly expresses its intention by saying `number % 3 == 0`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T17:24:08.733",
"Id": "443280",
"Score": "1",
"body": "`sum` is a built-in function but not a keyword. Bulit-ins can be overriden while assignments to keywords would result in syntax errors."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T12:35:13.297",
"Id": "227630",
"ParentId": "227628",
"Score": "4"
}
},
{
"body": "<p>The problem can be solved using math formulas, which will lead to an O(1) solution. But here I show another way to implement it, which is more efficient than a naive loop:</p>\n\n<pre><code>def sum_multiples(n):\n return sum(range(0, n, 3)) + sum(range(0, n, 5)) - sum(range(0, n, 3*5))\n</code></pre>\n\n<p>Or alternatively,</p>\n\n<pre><code>def sum_multiples(n):\n numbers = range(n)\n return sum(numbers[::3]) + sum(numbers[::5]) - sum(numbers[::3*5])\n</code></pre>\n\n<p>By the way, on the <a href=\"https://www.hackerrank.com/contests/projecteuler/challenges\" rel=\"nofollow noreferrer\">HackerRank website</a>, the original problems are modified to require handling a wide range of inputs. You can run your solutions (with appropriate input / output added) on various provided test cases to verify the correctness under a time constraint.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T01:40:06.457",
"Id": "443304",
"Score": "0",
"body": "Yeah, I am tempted to type in something like `3*(333*332/2) + 5*(200*199/2) - 15*(67*66/2)` into my calculator and see the result ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T01:48:18.370",
"Id": "443305",
"Score": "0",
"body": "You could go to [the website](https://www.hackerrank.com/contests/projecteuler/challenges/euler001/problem) and try to implement that O(1) solution yourself :) You need that to pass all the test cases because the input can be up to `10^9` so a linear solution would result in timeouts."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T18:04:46.330",
"Id": "227636",
"ParentId": "227628",
"Score": "4"
}
},
{
"body": "<p>Welcome to Python!</p>\n\n<blockquote>\n <p>\"Project Euler exists to encourage, challenge, and develop the skills and enjoyment of anyone with an interest in the fascinating world of mathematics.\"</p>\n</blockquote>\n\n<p>Like you, I went to Project Euler when I was learning Python as yet another language for my toolbox. Unfortunately, Project Euler is primarily a mathematics challenge site, not a programming challenge site. The emphasis is on solving the problem and getting the right answer; not on programming skills. More over, the site asks that you <strong>not</strong> post your solution, which really discourages you from getting feedback on your programming skills, and proper best practices for the language. So while you can get problems that you can actually try writing code to solve the problem for, you’re still discouraged from getting feedback on your approach. Not exactly an ideal site for learning a new language on.</p>\n\n<p>Still, you have violated their request and posted your solution, so let’s try and give you some useful feedback.</p>\n\n<h2>Write Functions</h2>\n\n<p>You’ve got two sets of data to try your solution on. The first being the “example” data in the problem itself; the second being the dataset you are being asked to solve. If you’re going to do something twice, write a function:</p>\n\n<pre><code>def sum_of_multiples_of_3_or_5_below(limit):\n total = 0\n for n in range(0, limit):\n if n % 3 == 0 or n % 5 == 0:\n total += n\n return total\n</code></pre>\n\n<p>Then you can test your function with the example data, as well as solve the problem:</p>\n\n<pre><code>assert sum_of_multiples_of_3_or_5_below(10) == 23\n\nanswer = sum_of_multiples_of_3_or_5_below(1000)\nprint(f\"sum of all multiples of 3 or 5 below 1000 is {answer}\")\n</code></pre>\n\n<p>This gives you confidence in your solution. Usually the example data is fairly trivial, so the time needed to solve the problem twice isn’t noticeably increased.</p>\n\n<h2>Use a <code>__main__</code> guard</h2>\n\n<p>Now that we have a function, it is possible to import this “module” into another program to reuse the function. Except, it runs that pesky code at the bottom, generating unexpected output. Using a <code>__main__</code> guard, the code will only execute when we run this script, not when this scripted is imported:</p>\n\n<pre><code>if __name__ == '__main__':\n assert sum_of_multiples_of_3_or_5_below(10) == 23\n\n answer = sum_of_multiples_of_3_or_5_below(1000)\n print(f\"sum of all multiples of 3 or 5 below 1000 is {answer}\") \n</code></pre>\n\n<h2>Generalization</h2>\n\n<p>This function is still perhaps too specific. Why just below a <code>limit</code>. Why just multiples of <code>3</code> or <code>5</code>? We can generalize things a wee bit, and maybe actually increase the possibility of reusing the function elsewhere. And perhaps more importantly, explore the capabilities of Python.</p>\n\n<p>First, instead of passing in the limit, let’s pass in the <code>range</code>.</p>\n\n<pre><code>def sum_of_multiples_of_3_or_5_in(iterable):\n total = 0\n for n in iterable:\n if n % 3 == 0 or n % 5 == 0:\n total += n\n return total\n\nif __name__ == '__main__':\n assert sum_of_multiples_of_3_or_5_in(range(0, 10)) == 23\n\n answer = sum_of_multiples_of_3_or_5_in(range(0, 1000))\n print(f\"sum of all multiples of 3 or 5 below 1000 is {answer}\") \n</code></pre>\n\n<p><code>range</code> is a first class object in Python. It can be passed as an argument. So now you can easily compute the sum of the multiples of 3 or 5 in <code>range(1000, 2000)</code>.</p>\n\n<p>Or ... any <code>iterable</code> object, actually, such as lists.</p>\n\n<pre><code>print(sum_of_multiples_of_3_or_5_in([10, 12, 15, 17, 18, 19, 20])\n</code></pre>\n\n<p>How about those multiples? Let’s make them more general:</p>\n\n<pre><code>def sum_of_multiples_in(iterable, m1, m2):\n total = 0\n for n in iterable:\n if n % m1 == 0 or n % m2 == 0:\n total += n\n return total\n\nif __name__ == '__main__':\n m1 = 3\n m2 = 5\n assert sum_of_multiples_in(range(0, 10), m1, m2) == 23\n\n answer = sum_of_multiples_in(range(0, 1000), m1, m2)\n print(f\"sum of all multiples of {m1} or {m2} below 1000 is {answer}\") \n</code></pre>\n\n<p>You had a formula for computing the answer before. Sum of multiples of 3, plus sum of multiples of 5, minus sum of multiples of 15. Now it is harder, because <code>m1</code> could be a multiple of <code>m2</code> or vis versa. More cases to check for. But the above works just fine regardless of whether <code>m1</code> and <code>m2</code> are mutually prime or not.</p>\n\n<h2><code>any</code></h2>\n\n<p>Why only multiples of 2 numbers? Why not multiples of <code>3</code>, <code>5</code> or <code>7</code>? Passing yet another argument to the function seems wrong, because we’ll then need another function for 4 multiples, and yet another for 5 multiples. Let’s instead pass a list.</p>\n\n<pre><code>def sum_of_multiples_in(iterable, multiples):\n total = 0\n for n in iterable:\n for m in multiples:\n if n % m == 0:\n total += n\n break\n return total\n</code></pre>\n\n<p>That’s a good start. For each value of <code>n</code>, we start looping of the multiples, and if we find one, we add <code>n</code> to <code>total</code> and break out of the inner loop, to continue with the next <code>n</code> value.</p>\n\n<p>But we can make it clearer. We want to know if <code>n</code> is a multiple of <code>any</code> of the multiples. Python has an <code>any()</code> function, which is true of any of the terms is true:</p>\n\n<pre><code>def sum_of_multiples_in(iterable, multiples):\n total = 0\n for n in iterable:\n if any(n % m == 0 for m in multiples)\n total += n\n return total\n</code></pre>\n\n<p>There is also an <code>all(...)</code> function which returns true only if <strong>all</strong> of the terms are true. Not needed here, but good to have in your back pocket.</p>\n\n<h2><code>sum</code></h2>\n\n<p>Now that we have a loop, an accumulator, and a filter condition, we can combine the three into a single <code>sum()</code> operation:</p>\n\n<pre><code>def sum_of_multiples_in(iterable, multiples):\n return sum(n for n in iterable if any(n % m == 0 for m in multiples))\n</code></pre>\n\n<h2>Variable arguments</h2>\n\n<p>Using our above function, we have to pass in a <code>list</code> of multiples:</p>\n\n<pre><code>assert sum_of_multiples_in(range(0, 10), [3, 5]) == 23\n</code></pre>\n\n<p>It may be desirable to get rid of that explicit list <code>[3, 5]</code>, and just pass in the arguments <code>3, 5</code> like we did earlier. We can do this by using a variable argument list syntax.</p>\n\n<pre><code>def sum_of_multiples_in(iterable, *multiples):\n return sum(n for n in iterable if any(n % m == 0 for m in multiples))\n\nassert sum_of_multiples_in(range(0, 10), 3, 5) == 23\n</code></pre>\n\n<p>After all explicit arguments (<code>iterable</code> in this case), all remaining (non-keyword) arguments are rolled up into one list and assigned to the <code>*args</code> argument ... named <code>multiples</code> in this case.</p>\n\n<h2><code>\"\"\"Docstrings\"\"\"</code></h2>\n\n<p>Comments are used to describe the code to someone reading the source code. Doc-strings are used to describe how to use the code you’ve written, without the user needing to read your code. Various tools exist to extract the doc-strings, and turn them into webpages, PDF documents and so on. The simplest is Python’s built-in <code>help()</code> command.</p>\n\n<pre><code>\"\"\"\nA collection of functions for solving problems from Project Euler.\n(Currently, only Problem 1)\n\"\"\"\n\ndef sum_of_multiples_in(iterable, *multiples):\n \"\"\"\n From a list of numbers, return the sum of those numbers which\n are a multiple of one or more of the remaining arguments.\n \"\"\"\n\n return sum(n for n in iterable if any(n % m == 0 for m in multiples))\n\nif __name__ == '__main__':\n m1 = 3\n m2 = 5\n assert sum_of_multiples_in(range(0, 10), m1, m2) == 23\n\n answer = sum_of_multiples_in(range(0, 1000), m1, m2)\n print(f\"sum of all multiples of {m1} or {m2} below 1000 is {answer}\") \n</code></pre>\n\n<p>A doc string is a string appearing at the top of a module, class, and/or function. It can be a single quoted string (<code>\"docstring\"</code> or <code>'docstring'</code>) or a triple quoted string (<code>\"\"\"docstring\"\"\"</code> or <code>'''docstring'''</code>). Triple quoted strings are typically used since they can span multiple lines and can contain quotes without needing escaping.</p>\n\n<p>Save the file as <code>pe1.py</code>, then from a Python interpreter, type:</p>\n\n<pre><code>>>> import pe1\n>>> help(pe1)\n</code></pre>\n\n<p>to see your help documentation.</p>\n\n<h2>Type Hints</h2>\n\n<p>Coming from C++, you will be used to a more “type safe” environment. Python’s fast and loose rules for type safety may be a wee bit difficult to get used too. Fortunately (or unfortunately), Python 3.6 and later allows you to specify “type hints”. These do <strong>absolutely nothing</strong> ... at least, as far as the Python interpreter is concerned. They can be read by static analysis tools, which can reason about them and ensure variables are being used in their intended fashion. If used for nothing else, they can provide additional “documentation” about the types of arguments for functions, and the return type of the function.</p>\n\n<pre><code>def sum_of_multiples_in(iterable: int, *multiples: int) -> int:\n ...\n</code></pre>\n\n<p>You can use type hints on local variables as well:</p>\n\n<pre><code> total: int = 0\n</code></pre>\n\n<hr>\n\n<p>Hope this jump starts your exploration of Python. And once again, welcome to Python!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T09:59:16.993",
"Id": "444719",
"Score": "0",
"body": "Thank you so much for investing the time to write such a detailed review! I learned quite a few new things. Some of this may be a bit advanced for me at this moment, so it's probably beneficial for me to reread this maybe a month later I guess :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T00:03:45.457",
"Id": "444809",
"Score": "0",
"body": "You’re welcome. Feel free to ask questions in a month. :-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T07:23:18.670",
"Id": "228827",
"ParentId": "227628",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "228827",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T11:51:25.373",
"Id": "227628",
"Score": "4",
"Tags": [
"python",
"beginner",
"python-3.x",
"programming-challenge"
],
"Title": "(Project Euler #1) Find the sum of all the multiples of 3 or 5 below 1000"
}
|
227628
|
<h2>Description</h2>
<blockquote>
<p>An immutable keyed set is a readonly collection of elements without
duplicates or null values having each of the elements linked to
exactly one key.</p>
</blockquote>
<h3>Example</h3>
<blockquote>
<p>This simple <a href="https://en.wikipedia.org/wiki/Exact_cover#Representations" rel="nofollow noreferrer">example of an Exact Cover</a> solution has a constraint
set <span class="math-container">\$\{ 1,2,3,4,5,6,7 \}\$</span> covered by candidates <span class="math-container">\$\{ B,D,F \}\$</span>.</p>
<ul>
<li><span class="math-container">\$B: \{ 1,4 \}\$</span> </li>
<li><span class="math-container">\$D: \{ 3,5,6 \}\$</span> </li>
<li><span class="math-container">\$F: \{ 2,7 \}\$</span></li>
</ul>
</blockquote>
<p>This could be presented as an immutable keyed set. What's imperative is that each of the constraints <span class="math-container">\$X\$</span> only has 1 matching candidate <span class="math-container">\$S\$</span>.</p>
<p><a href="https://i.stack.imgur.com/aPBpW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aPBpW.png" alt="enter image description here"></a></p>
<h3>Usage</h3>
<pre><code>[TestMethod]
public void Usage()
{
IReadOnlyKeyedSet<char, int> set = new ImmutableKeyedSet<char, int>(Data());
var sb = new StringBuilder();
foreach (var entry in set)
{
sb.AppendLine($"{entry.Key}: {string.Join(",", entry)}");
}
var rendered = sb.ToString();
// B: 1,4
// D: 3,5,6
// F: 2,7
}
private static IEnumerable<KeyValuePair<char, IEnumerable<int>>> Data()
{
yield return new KeyValuePair<char, IEnumerable<int>>('B', new[] { 1, 4 });
yield return new KeyValuePair<char, IEnumerable<int>>('D', new[] { 3, 5, 6 });
yield return new KeyValuePair<char, IEnumerable<int>>('F', new[] { 2, 7 });
}
</code></pre>
<p>The purpose is to guard against an invalid set. </p>
<pre><code>private static IEnumerable<KeyValuePair<char, IEnumerable<int>>> Data()
{
yield return new KeyValuePair<char, IEnumerable<int>>('B', new[] { 1, 2, 4 });
yield return new KeyValuePair<char, IEnumerable<int>>('D', new[] { 3, 5, 6 });
yield return new KeyValuePair<char, IEnumerable<int>>('F', new[] { 2, 7 });
}
</code></pre>
<p>The above should throw:</p>
<pre><code>"Duplicate value 2 on key F and B"
</code></pre>
<hr>
<h2>Code</h2>
<p>Interface <code>IReadOnlyKeyedSet<TKey, TElement></code></p>
<pre><code>public interface IReadOnlyKeyedSet<TKey, TElement> : ILookup<TKey, TElement>
{
IEqualityComparer<TKey> KeyComparer { get; }
IEqualityComparer<TElement> ElementComparer { get; }
bool ContainsValue(TElement value);
bool TryGetValues(TKey key, out IEnumerable<TElement> values);
bool TryGetKey(TElement value, out TKey key);
}
</code></pre>
<p>Implementation <code>ImmutableKeyedSet<TKey, TElement></code></p>
<pre><code>public class ImmutableKeyedSet<TKey, TElement> : IReadOnlyKeyedSet<TKey, TElement>
{
private readonly Dictionary<TKey, Bucket> buckets;
private readonly Dictionary<TElement, TKey> elements;
public ImmutableKeyedSet(
IEnumerable<KeyValuePair<TKey, IEnumerable<TElement>>> keyedSet,
IEqualityComparer<TKey> keyComparer = null,
IEqualityComparer<TElement> elementComparer = null)
{
KeyComparer = keyComparer ?? EqualityComparer<TKey>.Default;
ElementComparer = elementComparer ?? EqualityComparer<TElement>.Default;
buckets = new Dictionary<TKey, Bucket>(KeyComparer);
elements = new Dictionary<TElement, TKey>(ElementComparer);
Set(keyedSet ?? throw new ArgumentNullException(nameof(keyedSet)));
}
public IEqualityComparer<TKey> KeyComparer { get; }
public IEqualityComparer<TElement> ElementComparer { get; }
public IEnumerable<TElement> this[TKey key] => buckets[key];
public int Count => buckets.Count;
public bool Contains(TKey key) => buckets.ContainsKey(key);
public bool ContainsValue(TElement value) => elements.ContainsKey(value);
public IEnumerator<IGrouping<TKey, TElement>> GetEnumerator()
=> buckets.Values.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public bool TryGetValues(TKey key, out IEnumerable<TElement> values)
{
var bucket = FindBucketByKey(key);
values = bucket == null ? default : bucket.Values;
return bucket != null;
}
public bool TryGetKey(TElement value, out TKey key)
{
var bucket = FindBucketByValue(value);
key = bucket == null ? default : bucket.Key;
return bucket != null;
}
private Bucket FindBucketByValue(TElement value)
{
if (elements.TryGetValue(value, out var key))
{
return buckets[key];
}
return null;
}
private Bucket FindBucketByKey(TKey key)
{
if (buckets.TryGetValue(key, out var bucket))
{
return bucket;
}
return null;
}
private void Set(IEnumerable<KeyValuePair<TKey, IEnumerable<TElement>>> keyedSet)
{
foreach (var entry in keyedSet)
{
var key = entry.Key;
if (key == null) throw new ArgumentException("Key must be set");
var bucket = FindBucketByKey(key);
if (bucket != null)
{
throw new InvalidOperationException($"Duplicate key {key}");
}
bucket = new Bucket(key);
if (entry.Value == null) throw new ArgumentException("Value must be set");
var values = new HashSet<TElement>(entry.Value);
foreach (var value in values)
{
if (value == null) throw new ArgumentException(
"Value must not contain null");
var valueBucket = FindBucketByValue(value);
if (valueBucket != null)
{
throw new InvalidOperationException(
$"Duplicate value {value} on key {key} and {valueBucket.Key}");
}
bucket.Values.Add(value);
}
buckets.Add(key, bucket);
foreach (var value in values)
{
elements.Add(value, key);
}
}
}
class Bucket : IGrouping<TKey, TElement>
{
public TKey Key { get; }
public IEnumerator<TElement> GetEnumerator() => Values.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
internal ICollection<TElement> Values { get; }
internal Bucket(TKey key)
{
Key = key;
Values = new List<TElement>();
}
}
}
</code></pre>
<hr>
<h2>Questions</h2>
<ul>
<li>Is this a useful type of collection?</li>
<li>Is this collection implementing immutability correctly?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T12:25:34.970",
"Id": "443256",
"Score": "1",
"body": "What's the concrete purpose / context to use that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T12:27:01.607",
"Id": "443257",
"Score": "0",
"body": "@πάνταῥεῖ Any situation that requires a unique set of values, where the values are linked to a key. The way I would use it today, is to store the results of an Exact Cover Problem solution, to verify the solution is a correct keyed set."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T14:42:19.837",
"Id": "443274",
"Score": "1",
"body": "I think the `Contains` method should be renamed `ContainsKey` since (1) it calls `buckets.ContainsKey` and (2) there is also a `ContainsValue` method so the rename adds clarity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T14:50:29.880",
"Id": "443275",
"Score": "0",
"body": "@RickDavin You are right, that would take away any ambiguity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T21:08:42.287",
"Id": "443300",
"Score": "1",
"body": "@RickDavin Unfortunately, _Contains_ is part of the _ILookup_ interface I'm implementing."
}
] |
[
{
"body": "<p>Just a couple of thoughts</p>\n\n<ul>\n<li><code>FindBucketByKey</code> and <code>FindBucketByValue</code> should be implemented as <code>TryGetSomething</code> because you already are doing this anyway internally and what is most important, it would save you from a ton of <code>null</code>-checks all over the place. Nobody likes them.</li>\n<li><code>Set</code> should be called <code>Initialize</code></li>\n<li>This one is funny:\n\n<ul>\n<li><code>if (x == null)</code> + <code>throw</code> means do not use <code>{}</code> whereas </li>\n<li><code>if (x != null)</code> + <code>throw</code> means use <code>{}</code> ;-)</li>\n</ul></li>\n<li>You should not initialize <code>values</code> with <code>= new HashSet<TElement>(entry.Value);</code> as this could change their order. Groupings don't do this so this behavior would be unexpected. You are also not using any other features of a <code>HashSet</code> as I find using <code>Distict</code> would be more appropriate and would maintain the order of values.</li>\n<li><code>Bucket</code> would be easier to use and implement if it was derived from <code>List<T></code>.</li>\n<li><p>Use more linq. You know I like linq so I when I see how <code>Set</code> is implemented I feel the same way as <a href=\"https://codereview.stackexchange.com/users/39858/visualmelon\">@VisualMelon</a> when he sees tuples :-P. This is how I imagine this method doing its main job:</p>\n\n<pre><code>var result =\n from x in Data()\n from y in x.Value\n group x.Key by y into g\n select g;\n</code></pre>\n\n<p>This would give you groups for each element where you later could check whether any of the groups contains more than one element. With that, you could identify <strong>all</strong> duplicates and not only the first two and of course the implementation would become much simpler too. This would also be a lot more helpful as with multiple bugs you would need to run the code multiple time to discover every one of them.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T06:51:58.873",
"Id": "443314",
"Score": "0",
"body": "I didn't even notice my subconscious (consistent :p) handling of parenthesis there o_O"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T06:58:36.077",
"Id": "443315",
"Score": "0",
"body": "Do you think this class could be useful as API or is it too specific for my use case?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T07:00:40.847",
"Id": "443316",
"Score": "1",
"body": "@dfhwze I think this is quite useful... for example it could be used as a command identifier and the values as its aliases or tags. Or in any other use case where there is a name and some aliases/tags. I've had a lot of them recently so I think I'll borrow form it."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T06:45:38.860",
"Id": "227652",
"ParentId": "227629",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "227652",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T12:15:41.520",
"Id": "227629",
"Score": "4",
"Tags": [
"c#",
"api",
"hash-map",
"set",
"immutability"
],
"Title": "Immutable Keyed Set"
}
|
227629
|
<p>(See the <a href="https://codereview.stackexchange.com/questions/227519/fast-algorithms-in-javascript-for-shortest-path-queries-in-directed-unweighted-g">previous iteration</a>.)</p>
<p>Now I have reworked my pathfinder program, and I ended up with this:</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-html lang-html prettyprint-override"><code><html>
<body>
<div id="output">
</div>
<script>
function NodeSet() {
this.array = [];
}
NodeSet.prototype.clear = function() {
this.array = [];
}
NodeSet.prototype.add = function(node) {
this.array[node.id] = node;
}
NodeSet.prototype.includes = function(node) {
return this.array[node.id] !== undefined;
}
NodeSet.prototype.size = function() {
return this.array.length;
}
function Node(id) {
this.id = id;
this.children = [];
this.parents = [];
}
Node.prototype.toString = function() {
return "[Node " + this.id + "]";
}
function nodeEq(nodeA, nodeB) {
return nodeA.id === nodeB.id;
}
function connect(tail, head) {
tail.children.push(head);
head.parents.push(tail);
}
function BuildPath(sourceNode, meetingNode, backwardStack) {
let path = BidirectionalIterativeDeepeningDepthFirstSearch(sourceNode,
meetingNode);
path.splice(-1, 1);
path.push(...backwardStack);
return path;
}
function DepthLimitedSearchForward(node, depth, frontier) {
if (depth === 0) {
frontier.add(node);
return;
}
node.children.forEach(function(child) {
DepthLimitedSearchForward(child, depth - 1, frontier);
});
}
function DepthLimitedSearchBackward(node, depth, backwardStack, frontier) {
backwardStack.unshift(node);
if (depth === 0) {
if (frontier.includes(node)) {
return node;
}
backwardStack.shift();
return null;
}
for (var i = 0; i !== node.parents.length; i++) {
let parent = node.parents[i];
let meetingNode = DepthLimitedSearchBackward(parent, depth - 1, backwardStack, frontier);
if (meetingNode !== null) {
return meetingNode;
}
}
backwardStack.shift();
return null;
}
function BidirectionalIterativeDeepeningDepthFirstSearch(sourceNode,
targetNode) {
if (sourceNode.id === targetNode.id) {
return [sourceNode];
}
let frontier = new NodeSet();
let backwardStack = [];
let depth = 0;
while (true) {
DepthLimitedSearchForward(sourceNode, depth, frontier);
for (var i = 0; i < 2; i++) {
let meetingNode = DepthLimitedSearchBackward(targetNode,
depth + i,
backwardStack,
frontier);
if (meetingNode !== null) {
return BuildPath(sourceNode,
meetingNode,
backwardStack);
}
backwardStack = [];
}
frontier.clear();
depth++;
}
}
function DequeNode(elem) {
this.next = undefined;
this.elem = elem;
}
function Deque() {
this.head = undefined;
this.tail = undefined;
this.size = 0;
}
Deque.prototype.shift = function() {
let ret = this.head.elem;
this.head = this.head.next;
this.size--;
return ret;
}
Deque.prototype.push = function(elem) {
let newNode = new DequeNode(elem);
if (this.head) {
this.tail.next = newNode;
} else {
this.head = newNode;
}
this.size++;
this.tail = newNode;
}
Deque.prototype.length = function() {
return this.size;
}
Deque.prototype.front = function() {
return this.head.elem;
}
let NULL = "NULL";
function tracebackPath(touchNode, parentsA, parentsB) {
let path = [];
let current = touchNode;
while (current != NULL) {
path.push(current);
current = parentsA.get(current);
}
path.reverse();
if (parentsB) {
current = parentsB.get(touchNode);
while (current != NULL) {
path.push(current);
current = parentsB.get(current);
}
}
return path;
}
function NodeMap() {
this.array = [];
this.size = 0;
}
NodeMap.prototype.put = function(key, value) {
if (this.array[key.id] === undefined) {
this.array[key.id] = value;
this.size++;
}
}
NodeMap.prototype.get = function(key) {
return this.array[key.id];
}
NodeMap.prototype.containsKey = function(key) {
return this.array[key.id] !== undefined;
}
NodeMap.prototype.length = function() {
return this.size;
}
function BidirectionalBreadthFirstSearch(s, t) {
let queueA = new Deque();
let queueB = new Deque();
let parentsA = new NodeMap();
let parentsB = new NodeMap();
let distanceA = new NodeMap();
let distanceB = new NodeMap();
queueA.push(s);
queueB.push(t);
parentsA.put(s, NULL);
parentsB.put(t, NULL);
distanceA.put(s, 0);
distanceB.put(t, 0);
let bestCost = 1000 * 1000 * 1000;
let touchNode = undefined;
while (queueA.length() > 0 && queueB.length() > 0) {
let distA = distanceA.get(queueA.front());
let distB = distanceB.get(queueB.front());
if (touchNode && bestCost < distA + distB) {
return tracebackPath(touchNode,
parentsA,
parentsB);
}
if (distanceA.length() < distanceB.length()) {
let current = queueA.shift();
for (let i = 0; i < current.children.length; i++) {
let child = current.children[i];
if (!distanceA.containsKey(child)) {
distanceA.put(child, distanceA.get(current) + 1);
parentsA.put(child, current);
queueA.push(child);
if (distanceB.containsKey(child)
&&
bestCost > distanceA.get(child) + distanceB.get(child)) {
bestCost = distanceA.get(child) + distanceB.get(child);
touchNode = child;
}
}
}
} else {
let current = queueB.shift();
for (let i = 0; i < current.parents.length; i++) {
let parent = current.parents[i];
if (!distanceB.containsKey(parent)) {
distanceB.put(parent, distanceB.get(current) + 1);
parentsB.put(parent, current);
queueB.push(parent);
if (distanceA.containsKey(parent)
&&
bestCost > distanceA.get(parent) + distanceB.get(parent)) {
bestCost = distanceA.get(parent) + distanceB.get(parent);
touchNode = parent;
}
}
}
}
}
return [];
}
function BreadthFirstSearch(source, target) {
let queue = new Deque();
let parents = new NodeMap();
queue.push(source);
parents.put(source, NULL);
while (queue.length() > 0) {
let current = queue.shift();
if (current.id === target.id) {
return tracebackPath(current, parents, undefined);
}
for (let i = 0; i < current.children.length; i++) {
let child = current.children[i];
if (!parents.containsKey(child)) {
parents.put(child, current);
queue.push(child);
}
}
}
return [];
}
function createGraph(nodes, arcs) {
let graph = [];
for (var id = 0; id < nodes; id++) {
graph.push(new Node(id));
}
for (var i = 0; i < arcs; i++) {
let tailIndex = Math.floor(Math.random() * nodes);
let headIndex = Math.floor(Math.random() * nodes);
connect(graph[tailIndex], graph[headIndex]);
}
return graph;
}
let outputDiv = document.getElementById("output");
const NODES = 1000000;
const ARCS = 5000000;
const graph = createGraph(NODES, ARCS);
let sourceIndex = Math.floor(Math.random() * NODES);
let targetIndex = Math.floor(Math.random() * NODES);
let sourceNode = graph[sourceIndex];
let targetNode = graph[targetIndex];
console.log("Source node: " + sourceNode);
console.log("Target node: " + targetNode);
outputDiv.innerHTML += "Source node: " + sourceNode + "<br>" +
"Target node: " + targetNode + "<br>";
outputDiv.innerHTML += "<br>BIDDFS:";
var startTime = new Date().getMilliseconds();
var path = BidirectionalIterativeDeepeningDepthFirstSearch(sourceNode,
targetNode);
var endTime = new Date().getMilliseconds();
var num = 1;
for (var i = 0; i < path.length; i++) {
let node = path[i];
outputDiv.innerHTML += "<br>" + num + ": " + node;
console.log(num++ + ": " + node);
}
let duration = endTime - startTime;
console.log("Duration: " + duration + " ms.");
outputDiv.innerHTML += "<br>Duration: " + duration + " ms.";
outputDiv.innerHTML += "<br><br>Bidirectional BFS:";
startTime = new Date().getMilliseconds();
var path2 = BidirectionalBreadthFirstSearch(sourceNode,
targetNode);
endTime = new Date().getMilliseconds();
duration = endTime - startTime;
num = 1;
for (var i = 0; i < path2.length; i++) {
let node = path2[i];
outputDiv.innerHTML += "<br>" + num + ": " + node;
console.log(num++ + ": " + node);
}
console.log("Duration: " + (endTime - startTime) + " ms.");
outputDiv.innerHTML += "<br>Duration: " + duration + " ms.";
outputDiv.innerHTML += "<br><br>BFS:";
startTime = new Date().getMilliseconds();
var path3 = BreadthFirstSearch(sourceNode,
targetNode);
endTime = new Date().getMilliseconds();
duration = endTime - startTime;
num = 1;
for (var i = 0; i < path3.length; i++) {
let node = path3[i];
outputDiv.innerHTML += "<br>" + num + ": " + node;
console.log(num++ + ": " + node);
}
console.log("Duration: " + duration + " ms.");
outputDiv.innerHTML += "<br>Duration: " + duration + " ms.";
</script>
</body>
</html></code></pre>
</div>
</div>
</p>
<p><strong>Example output</strong></p>
<pre><code>Source node: [Node 437100]
Target node: [Node 368960]
BIDDFS:
1: [Node 437100]
2: [Node 815624]
3: [Node 858313]
4: [Node 506296]
5: [Node 956880]
6: [Node 172071]
7: [Node 406177]
8: [Node 443935]
9: [Node 250512]
10: [Node 368960]
Duration: 5 ms.
Bidirectional BFS:
1: [Node 437100]
2: [Node 815624]
3: [Node 858313]
4: [Node 506296]
5: [Node 956880]
6: [Node 172071]
7: [Node 406177]
8: [Node 443935]
9: [Node 250512]
10: [Node 368960]
Duration: 20 ms.
BFS:
1: [Node 437100]
2: [Node 815624]
3: [Node 966613]
4: [Node 62273]
5: [Node 951283]
6: [Node 238369]
7: [Node 436275]
8: [Node 327303]
9: [Node 818069]
10: [Node 368960]
Duration: 652 ms.
</code></pre>
<p><strong>Critique request</strong></p>
<p>Please tell me anything that comes to mind.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T17:40:19.310",
"Id": "443283",
"Score": "0",
"body": "Is function _BidirectionalIterativeDeepeningDepthFirstSearch_ declared correctly, it seems odd to me?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T16:14:56.043",
"Id": "227633",
"Score": "2",
"Tags": [
"javascript",
"algorithm",
"comparative-review",
"pathfinding"
],
"Title": "Fast algorithms in Javascript for shortest path queries in directed unweighted graphs - follow-up"
}
|
227633
|
<p>I've created a Java class for Android that connects to a FTP server (using the <code>FTPClient</code> library from <code>commons-net-3.6</code>) and uploads a file that is stored on an Android device. The code of the class is the following:</p>
<hr>
<pre><code>public class FTPHandler{
private String HOST = "ipftpserver";
private String USERNAME = "mylogin";
private String PASSWORD = "mypassword";
private int PORT = portnumber;
FTPClient mFTPClient = new FTPClient();
private boolean ftpConnect() {
boolean ftpConnected;
for (int i = 0; i <= 10; i++) {
try {
mFTPClient.connect(HOST, PORT);
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
boolean status = mFTPClient.login(USERNAME, PASSWORD);
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
mFTPClient.enterLocalPassiveMode();
return status;
}
Thread.sleep(400);
} catch (Exception e) {
Log.d("TAG", "Error: could not connect to host " + HOST);
}
}
return false;
}
private boolean ftpDisconnect() {
try {
mFTPClient.logout();
mFTPClient.disconnect();
return true;
} catch (Exception e) {
Log.d("TAG", "Error occurred while disconnecting from ftp server.");
}
return false;
}
public void uploadToFTP(String localPath, String remotePath) {
Thread t = new Thread(new Runnable() {
public void run() {
try {
if (ftpConnect()) {
File remoteFile = new File(remotePath);
String remoteFileName = remoteFile.getName();
// check if remote file exists
boolean fileExists = false;
InputStream inputStream = mFTPClient.retrieveFileStream("/tmp/." + remoteFileName);
int returnCode = mFTPClient.getReplyCode();
if (inputStream == null || returnCode == 550) {
fileExists = false;
} else {
fileExists = true;
}
if (inputStream != null) {
inputStream.close();
}
// delete remote file if it exists
if (fileExists) {
mFTPClient.deleteFile("/tmp/." + remoteFileName);
}
ftpDisconnect(); // I don't know why I need to close and open the connection again here, if I don't the new file won't be uploaded after deleting the repeated old file on the server
ftpConnect();
// upload file to server
boolean status = false;
FileInputStream localStreamObject = new FileInputStream(localPath);
File remoteFileObject = new File("/tmp/." + remoteFileName);
String remoteDirectory = remoteFileObject.getParent();
if (mFTPClient.changeWorkingDirectory(remoteDirectory)) {
status = mFTPClient.storeFile("/tmp/." + remoteFileName, localStreamObject);
mFTPClient.rename("/tmp/." + remoteFileName, remotePath);
}
localStreamObject.close();
System.err.println(status);
}
} catch (Exception e) {
System.err.println("uploadToFTP: error uploading fle");
}
ftpDisconnect();
}
});
t.start();
}
}
</code></pre>
<hr>
<p>Basically, I have three methods:</p>
<ul>
<li><p><code>ftpConnect()</code>, connects to the FTP server</p></li>
<li><p><code>ftpDisconnect()</code>, closes the connection to the FTP server </p></li>
<li><p><code>uploadToFTP(String localPath, String remotePath)</code>, uploads a
file to the FTP server, I made it in a way that it mimics the
command line <code>mv</code> command. So I just need to give the local path and
the server path in order to transfer a file to it. Also, I first
upload it to the <code>/temp</code> folder and after finishing the upload I move
the file location on the server (just so I know that in the moment
that the file was moved to the <code>remotePath</code> I'm 100% sure that the
upload has finished its streaming of data).</p></li>
</ul>
<p>This code works fine for its purpose... But I'd like some advice on how to make it better. I'm managing the permissions outside the <code>FTPHandler</code> class and I'm not so sure if the way that I've created the thread (on Android I'm obligated to run internet interactions as threads) is the best way of doing it (In a good practice perspective would it be better creating the thread outside my <code>FTPClass</code>?). Any ideas about how to improve this code or alternative ways of doing the same thing more efficiently?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T19:50:15.697",
"Id": "227639",
"Score": "2",
"Tags": [
"java",
"android",
"ftp"
],
"Title": "Upload to FTP method for Android that mimics the command line mv"
}
|
227639
|
<p>I've created a component that validates an email address.</p>
<p>It works, but since I'm new to hooks I would like some validation of what I've done before I let what I've done loose on the rest of the components I'm creating.</p>
<p>In particular I'm concerned I'm not managing the state correctly, it seems verbose, and I've got a lot of variables I am tracking.</p>
<p>If anyone has any pointers on the Fade Component as well I'd appreciate them.</p>
<p>I still need to handle errors back from useQuery too, I realise.</p>
<p>And of course, I don't know what I don't know, so feel free to point me in the right direction.</p>
<p>Thank you!</p>
<pre><code>import React, { useState } from 'react'
import { InputAdornment, Typography } from '@material-ui/core'
import Fade from '@material-ui/core/Fade'
import CircularProgress from '@material-ui/core/CircularProgress'
import { MdCheckCircle } from 'react-icons/md'
import { ErrorMessage } from 'formik'
import TextField from 'Components/TextField'
import { string } from 'yup'
import { useAsyncFn } from 'react-use'
import { useApolloClient } from '@apollo/react-hooks'
import { FIND_BY_IDENTIFIER } from 'Queries/FindByIdentifier.query'
import { not } from 'ramda'
const schema = string()
.ensure()
.required('Oops, email is required')
.email('Oops, check your email format')
const LoginInstead = () => { return (<div>Would you like to login instead?</div>) }
function FormEmailAsync ({
name,
email,
handleChange,
label,
setFieldError,
setFieldTouched,
onBlurred,
...rest
}) {
const [emailValid, setValidEmail] = useState('')
const client = useApolloClient()
const [loading, setLoading] = useState(false)
const [error, setError] = useState(false)
const [emailPresent, setEmailPresent] = useState(false)
//eslint-disable-next-line no-unused-vars
const [theState, asyncFunc] = useAsyncFn(async value => {
const returnedSchema = await schema.validate(value)
if (returnedSchema !== value) { return returnedSchema }
setLoading(true)
const { data } = await client.query({
query: FIND_BY_IDENTIFIER,
variables: { identifier: value },
context: { uri: process.env.REACT_APP_GRAPHQL_PUBLIC_API }
})
setValidEmail(not(data.findByIdentifier.present))
setEmailPresent(data.findByIdentifier.present)
setLoading(false)
return value
}, [])
const onBlurFunc = async (name, email) => {
setFieldTouched(name)
let returnFromAsync = await asyncFunc(email)
if (returnFromAsync === email) {
onBlurred(returnFromAsync)
} else {
setError(true)
setFieldError(name, returnFromAsync.message)
}
}
const onChangeFunc = (evt) => {
setValidEmail(null)
setEmailPresent(false)
setError(false)
handleChange(evt)
}
return (
<div>
<TextField
error={error}
name={name}
variant='outlined'
value={email}
placeholder={'email@example.com'}
onChange={evt => onChangeFunc(evt)}
label={label}
onBlur={event => onBlurFunc(name, event.target.value)}
InputProps={{
endAdornment: (
<InputAdornment position='end'>
<Fade
in={loading}
style={{
transitionDelay: loading ? '800ms' : '0ms'
}}
unmountOnExit
>
<CircularProgress size={16} />
</Fade>
{ emailValid === true &&
<Fade
in={emailValid}
>
<MdCheckCircle
color='green'
data-testid={'success'}
size={16}
/>
</Fade> }
</InputAdornment>
)
}}
{...rest}
/>
{ emailPresent ? LoginInstead() :
<ErrorMessage
name='email'
render={msg => <Typography color='error'>{msg}</Typography> }
/>}
</div>
)
}
export default FormEmailAsync
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>While hooks are amazing, there is no point in using them when your function component becomes overly complex. Better to just create a class component.</p>\n\n<p>Some reasons why switching to a class component is better:</p>\n\n<ol>\n<li>Defining functions within your functions will cause those variables to be redefined after each re-render which is a waste of efficiency and performance</li>\n<li>Destructuring too many variables from your <code>useState</code> makes it exceedingly hard to maintain in the future and hard to read</li>\n</ol>\n\n<p>The general rule of thumb is that <code>class components</code> are \"smart components\" and <code>function components</code> are \"dummy components\". Reason why is that class components have a state and handle logic while \"dummy components\" are simply there to create views.</p>\n\n<p>I would recommend creating a class component handling your validation, and simplifying your render method by creating \"dummy components\" with simple hook usage (so that they stay <em>dumb</em>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T01:49:42.680",
"Id": "444673",
"Score": "0",
"body": "Thanks for your review. I've spent quite some time on this hooks implementation so understandably I'm not keen to move to a class implementation. I do see some value though in creating more components to handle the \"dumb\" aspects. Perhaps a class might drop out of that."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T11:22:59.867",
"Id": "227718",
"ParentId": "227643",
"Score": "2"
}
},
{
"body": "<p>I feel your component <strong>mixes a lot of <a href=\"https://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">concerns</a></strong>: API requests and responses, form field validations and error display, and presentational concerns such as styling and animations.</p>\n\n<p>In my opinion, a React component works best if it concerns itself either:</p>\n\n<ul>\n<li>with <strong>one concern</strong> only (API <em>or</em> validation <em>or</em> presentation)</li>\n<li>with the <strong>coordination of multiple components</strong></li>\n</ul>\n\n<p>I think your component (and by extension, your codebase) could profit from splitting this component into multiple components or hooks that each address one of the issues. You already apply hooks very well and I don't see a problem with that – no need to switch back to class components. Hooks can even help you better with <strong>extracting logic</strong> that is not bound to a specific level in the component hierarchy, such as repeating tasks like API requests and validations.</p>\n\n<p>Since you're thinking about \"unleashing\" this on the rest of your codebase, this is a perfect moment to think about which aspects of the component you want to reuse and how you want to use these tools, informing <strong>the design of your components</strong>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T01:54:41.130",
"Id": "444674",
"Score": "0",
"body": "Yes, I think extracting some of the components will \"dry\" things up and make it easier to understand what is going on. I shall try extracting the logic as you suggest into separate components and see how this looks. Thank you. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T13:34:25.587",
"Id": "227721",
"ParentId": "227643",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T23:03:36.067",
"Id": "227643",
"Score": "3",
"Tags": [
"javascript",
"react.js"
],
"Title": "Async Data Validation with Hooks"
}
|
227643
|
<p>I'm trying to teach myself streaming and lambda expressions. Here's the scenario: I have a collection of 10 Thing objects each containing an int[] of 3 random number. I've written code to print out the largest number in each Thing.</p>
<p>I've already written two statements and an accompanying method that print the result I want, however the code is pretty ropey... improvements and suggestions would be greatly appreciated.</p>
<pre><code>import java.util.Random;
public class Thing {
private Random r = new Random();
private int a = r.nextInt(), b = r.nextInt(), c = r.nextInt();
public int[] getCollectionOfInts() {
return collectionOfInts;
}
private int[] collectionOfInts = new int[]{a, b, c};
}//end of class
//main in separate driver class
public static void main(String[] args) {
Thing[] things = new Thing[10];
int a=0,b=0,c=0;
for (int x =0;x<10;x++){
things[x] = new Thing();
for (int y=0;y<things[x].getCollectionOfInts().length;y++)
{
if(y==0)
a = things[x].getCollectionOfInts()[y];
if(y==1)
b = things[x].getCollectionOfInts()[y];
if(y==2)
c = things[x].getCollectionOfInts()[y];
}
//print 3 numbers in each Thing object
System.out.println(x+": "+a+", "+b+", "+c);
}
System.out.println();
//compare each number and print out largest... too many ternaries
Stream.of(things).forEach(Thing->System.out.println(Stream.of(Thing.getCollectionOfInts()).mapToInt(z->z[0]>z[1]&&z[0]>z[2]?z[0]:z[1]>z[2]?z[1]:z[2]).reduce((x,y)->x+y).getAsInt()));
System.out.println();
//improper use of .max() or .mapToInt(...)?
Stream.of(things).forEach(Thing->System.out.println(Stream.of(Thing.getCollectionOfInts()).mapToInt(x->maxInt(x)).max().getAsInt()));
}
public static int maxInt(int[] x) {
int max=x[0];
for (int y:x) {
if(y>max)
max = y;
}
return max;
}
</code></pre>
<p>I get the expected results for both streams, but I'm still unhappy with how I get there!</p>
|
[] |
[
{
"body": "<p><strong>Advice 1: code packaging</strong></p>\n\n<p>I suggest you put your <code>Thing</code> related code into a package. That way you may practice industrial level programming:</p>\n\n<pre><code>package net.tnm;\n</code></pre>\n\n<p>Note that the above package name is just an example. Usually, is should be reversed domain name of your company. (For example, <code>package com.oracle.xxx</code> where <code>xxx</code> is the project name.)</p>\n\n<p><strong>Advice 2: code layout</strong>\nYou have this:</p>\n\n<pre><code>private int a = r.nextInt(), b = r.nextInt(), c = r.nextInt();\n</code></pre>\n\n<p>I would suggest</p>\n\n<pre><code>private final int a = r.nextInt(), \n b = r.nextInt(), \n c = r.nextInt();\n</code></pre>\n\n<p><strong>Advice 3: declaring immutable fields final</strong></p>\n\n<p>Once again:</p>\n\n<pre><code>private final int a = r.nextInt(), \n b = r.nextInt(), \n c = r.nextInt();\n</code></pre>\n\n<p><strong>Advice 4: spaces around binary operators</strong></p>\n\n<p>A <em>binary operator</em> is an operator that that takes <strong>two</strong> operands. You often write, for example, <code>y=0</code>, when the coding conventions dictate <code>y = 0</code>.</p>\n\n<p><strong>Advice 5: bracing</strong></p>\n\n<p>You have <code>\n for (int x =0;x<10;x++){</code></p>\n\n<p>when you should write </p>\n\n<pre><code> for (int x =0;x<10;x++) {\n ^\n space\n</code></pre>\n\n<p>Also,</p>\n\n<pre><code>for (int y=0;y<things[x].getCollectionOfInts().length;y++)\n{\n</code></pre>\n\n<p>is C/C++ style. In Java, it is customary to write </p>\n\n<pre><code>for (int y=0;y<things[x].getCollectionOfInts().length;y++) { \n</code></pre>\n\n<p><strong>Advice 6: lambdas</strong></p>\n\n<pre><code>Stream.of(things).forEach(Thing->System...\n</code></pre>\n\n<p>Since <code>Thing</code> is a variable in that context and not a type, I would rename it to <code>thing</code>.</p>\n\n<p><strong>Advice 7: max of three</strong></p>\n\n<p>You have this:</p>\n\n<pre><code>z -> z[0] > z[1] && z[0] > z[2] ? z[0] : z[1] > z[2] ? z[1] : z[2]\n</code></pre>\n\n<p>A shorter way of writing the same is </p>\n\n<pre><code>z -> Math.max(z[0], Math.max(z[1], z[2]))\n</code></pre>\n\n<p><strong>Advice 8: maxInt</strong></p>\n\n<p>You can write it as </p>\n\n<pre><code>public static int maxInt(int[] x) {\n int max = Integer.MIN_VALUE;\n\n for (int i : x) {\n max = Math.max(max, i);\n }\n\n return max;\n}\n</code></pre>\n\n<p><strong>Advice 9: redundant <code>if</code> statements</strong></p>\n\n<pre><code>if(y==0)\n a = things[x].getCollectionOfInts()[y];\nif(y==1)\n b = things[x].getCollectionOfInts()[y];\nif(y==2)\n c = things[x].getCollectionOfInts()[y];\n</code></pre>\n\n<p>Only one of those <code>if</code> statements will be executed yet all the condition will be checked. Basically, you can do this:</p>\n\n<pre><code>if (y == 0) { \n a = ...\n} else if (y == 1) {\n b = ...\n} else {\n c = ...\n}\n</code></pre>\n\n<p><strong>Advice 10: naked <code>if</code> statements</strong></p>\n\n<p>Once again, you have</p>\n\n<pre><code>if (y==0)\n a = things[x].getCollectionOfInts()[y];\n</code></pre>\n\n<p>More idiomatic Java is this:</p>\n\n<pre><code>if (y == 0) {\n a = ...\n}\n</code></pre>\n\n<p>(Note the braces.)</p>\n\n<p><strong>Summa summarum</strong></p>\n\n<p>I had this in mind:</p>\n\n<p><strong>Thing.java</strong></p>\n\n<pre><code>package net.tnm;\n\nimport java.util.Random;\n\npublic class Thing {\n\n private final Random r = new Random();\n private final int a = r.nextInt(), \n b = r.nextInt(), \n c = r.nextInt();\n\n private int[] collectionOfInts = new int[]{a, b, c};\n\n public int[] getCollectionOfInts() {\n return collectionOfInts;\n }\n}\n</code></pre>\n\n<p><strong>Driver.java</strong></p>\n\n<pre><code>package net.tnm;\n\nimport java.util.stream.Stream;\n\npublic class Driver {\n\n public static void main(String[] args) {\n Thing[] things = new Thing[10];\n int a = 0, b = 0, c = 0;\n\n for (int x = 0; x < 10; x++) {\n things[x] = new Thing();\n\n for (int y = 0; y < things[x].getCollectionOfInts().length; y++) {\n switch (y) {\n case 0:\n a = things[x].getCollectionOfInts()[0];\n break;\n\n case 1:\n b = things[x].getCollectionOfInts()[1];\n break;\n\n case 2:\n c = things[x].getCollectionOfInts()[2];\n break;\n }\n }\n\n //print 3 numbers in each Thing object\n System.out.println(x + \": \" + a + \", \" + b + \", \" + c);\n }\n\n System.out.println();\n\n Stream.of(things)\n .forEach(thing -> System.out.println(\n Stream.of(thing.getCollectionOfInts())\n .mapToInt(z -> Math.max(z[0], Math.max(z[1], z[2])))\n .reduce((x, y) -> x + y)\n .getAsInt()\n )\n );\n\n System.out.println();\n\n Stream.of(things)\n .forEach(thing -> System.out.println(\n Stream.of(thing.getCollectionOfInts())\n .mapToInt(x -> maxInt(x))\n .max()\n .getAsInt()));\n\n }\n\n public static int maxInt(int[] x) {\n int max = Integer.MIN_VALUE;\n\n for (int i : x) {\n max = Math.max(max, i);\n }\n\n return max;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T06:50:06.450",
"Id": "443310",
"Score": "1",
"body": "Your answer is missing explanations for many of your suggestions. Remember that the OP is a beginner. +++ Why would `net.tnm` be an appropriate package name? +++ In idiomatic Java code, there's no reason to write your own `max` helper function. +++ The `switch` is completely useless and can be replaced by 3 simple variable assignments, it's a pattern that often appears in beginner code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T06:15:07.480",
"Id": "227650",
"ParentId": "227644",
"Score": "1"
}
},
{
"body": "<p>The first thing about your code are the two lines inside your class <code>Thing</code>:</p>\n\n<pre><code>private Random r = new Random();\nprivate int a = r.nextInt(), b = r.nextInt(), c = r.nextInt();\n</code></pre>\n\n<p>If Random r is used just to initialize the array and not in other methods inside the class , it is better to use it in the costructor of the class :</p>\n\n<pre><code>public Thing() {\n Random r = new Random();\n this.arr = new int[] {r.nextInt(), r.nextInt(), r.nextInt()};\n}\n</code></pre>\n\n<p>You can check I initialize directy here the array of ints instead of defining variables a, b, c.\nA good thing is also override the String method to print the internal state of a object:</p>\n\n<pre><code>@Override\npublic String toString() {\n return Arrays.toString(arr);\n}\n</code></pre>\n\n<p>Now you can print the state of your <code>Thing</code> object in this way:</p>\n\n<pre><code>for (int i = 0;i < 10; ++i){\n things[i] = new Thing();\n //print 3 numbers in each Thing object\n System.out.println(i + \": \" + things[i]);\n}\n</code></pre>\n\n<p>Your iterations with <code>Stream</code> are ok, but instead of use <code>Stream</code> because you are working with <code>int</code> values you can use instead <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html\" rel=\"nofollow noreferrer\">IntStream</a> simplifyng the code:</p>\n\n<pre><code>Stream.of(things).forEach(t -> System.out.println(Arrays.stream(t.getArr()).max().getAsInt()));\n</code></pre>\n\n<p>Below the code of class <code>Thing</code> including all my modifies:</p>\n\n<pre><code>package codereview;\n\nimport java.util.Arrays;\nimport java.util.Random;\nimport java.util.stream.Stream;\n\npublic class Thing {\n\n private int[] arr;\n\n public Thing() {\n Random r = new Random();\n this.arr = new int[] {r.nextInt(), r.nextInt(), r.nextInt()};\n }\n\n public int[] getArr() {\n return arr;\n }\n\n @Override\n public String toString() {\n return Arrays.toString(arr);\n }\n\n\n public static void main(String[] args) {\n Thing[] things = new Thing[10];\n for (int i = 0;i <10; ++i){\n things[i] = new Thing();\n //print 3 numbers in each Thing object\n System.out.println(i + \": \" + things[i]);\n }\n System.out.println();\n Stream.of(things).forEach(t -> System.out.println(Arrays.stream(t.getArr()).max().getAsInt()));\n } \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T17:55:14.293",
"Id": "443642",
"Score": "0",
"body": "Your code could benefit from being formatted consistently by an IDE. Apart from that, it's nice and simple. I also refactored the OP's code and reached very similar code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T20:48:07.197",
"Id": "443661",
"Score": "0",
"body": "@RolandIllig Thanks, I'm still messing when I copy code from IDE here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T22:02:04.310",
"Id": "443667",
"Score": "0",
"body": "There's a simple recipe against messed up code: just forget about the 4 spaces of indentation and surround the code by `~~~`. That's much easier to get right."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T08:49:58.470",
"Id": "444712",
"Score": "0",
"body": "@RolandIllig I didn't know this, I apply it in the next answers."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T15:57:06.433",
"Id": "227670",
"ParentId": "227644",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T23:04:46.970",
"Id": "227644",
"Score": "6",
"Tags": [
"java",
"beginner",
"stream",
"lambda"
],
"Title": "Printing the max of groups of three random ints"
}
|
227644
|
<p>I have this hosted services which garbs the data from the API and save it in the database. But before saving it checks if the data already exists in the DB if not it creates the new row and if it already exists it compares <code>updated_at</code> from new data with DB if they are equal it ignores it if not it updates it.</p>
<p>Additionally, I have this <code>deleted_at</code> check where it needs to compare existing data with new data from API, my current logic for this process is as below but I'm sure there will be another approach to this.</p>
<p>This hosted services works just fine for me but sometimes (once or twice a day) I'm getting <code>Timeout error</code> at <code>deleted_at</code> logic.</p>
<p>I need it to be reviewed and looking for some inputs on efficiency on my overall code and how can I do this in a better way. </p>
<pre><code>public class DisasteRecoveryServices : DelegatingHandler, IHostedService
{
public IConfiguration Configuration { get; }
protected IMemoryCache _cache;
private Timer _timer;
public IHttpClientFactory _clientFactory;
protected HttpClient _client_DR;
private readonly IServiceScopeFactory _scopeFactory;
public DisasteRecoveryServices(IConfiguration configuration, IMemoryCache memoryCache, IHttpClientFactory clientFactory, IServiceScopeFactory scopeFactory)
{
Configuration = configuration;
_cache = memoryCache;
_clientFactory = clientFactory;
_scopeFactory = scopeFactory;
// NamedClients foreach Env.
_client_DR = _clientFactory.CreateClient("DisasteRecoveryEnv");
}
public Task StartAsync(CancellationToken cancellationToken)
{
_timer = new Timer(GetAccessToken, null, 0, 3300000);
// Thread.Sleep(2000);
_timer = new Timer(Heartbeat, null, 1000, 1000);
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
//Timer does not have a stop.
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public async Task<Token> GetToken(Uri authenticationUrl, Dictionary<string, string> authenticationCredentials)
{
HttpClient client = new HttpClient();
FormUrlEncodedContent content = new FormUrlEncodedContent(authenticationCredentials);
HttpResponseMessage response = await client.PostAsync(authenticationUrl, content);
if (response.StatusCode != System.Net.HttpStatusCode.OK)
{
string message = String.Format("POST failed. Received HTTP {0}", response.StatusCode);
throw new ApplicationException(message);
}
string responseString = await response.Content.ReadAsStringAsync();
Token token = JsonConvert.DeserializeObject<Token>(responseString);
return token;
}
private void GetAccessToken(object state)
{
Dictionary<string, string> authenticationCredentials_np = Configuration.GetSection("DisasteRecoveryEnvironment:Credentials").GetChildren().Select(x => new KeyValuePair<string, string>(x.Key, x.Value)).ToDictionary(x => x.Key, x => x.Value);
Token token_dr = GetToken(new Uri(Configuration["DisasteRecoveryEnvironment:URL"]), authenticationCredentials_np).Result;
_client_DR.DefaultRequestHeaders.Add("Authorization", $"Bearer {token_dr.AccessToken}");
}
public void Heartbeat(object state)
{
// Discard the result
_ = GetOrg();
_ = GetSpace();
_ = GetApps();
}
public async Task GetOrg()
{
var request = new HttpRequestMessage(HttpMethod.Get, "organizations");
var response = await _client_DR.SendAsync(request);
var json = await response.Content.ReadAsStringAsync();
OrganizationsClass.OrgsRootObject model = JsonConvert.DeserializeObject<OrganizationsClass.OrgsRootObject>(json);
using (var scope = _scopeFactory.CreateScope())
{
var _DBcontext = scope.ServiceProvider.GetRequiredService<DBContexts>();
foreach (var item in model.resources)
{
var g = Guid.Parse(item.guid);
var x = _DBcontext.Organizations.FirstOrDefault(o => o.OrgGuid == g);
if (x == null)
{
_DBcontext.Organizations.Add(new Organizations
{
OrgGuid = g,
Name = item.name,
CreatedAt = item.created_at,
UpdatedAt = item.updated_at,
Timestamp = DateTime.Now,
Foundation = 5
});
}
else if (x.UpdatedAt != item.updated_at)
{
x.CreatedAt = item.created_at;
x.UpdatedAt = item.updated_at;
x.Timestamp = DateTime.Now;
}
}
await _DBcontext.SaveChangesAsync();
}
}
public async Task GetSpace()
{
var request = new HttpRequestMessage(HttpMethod.Get, "spaces");
var response = await _client_DR.SendAsync(request);
var json = await response.Content.ReadAsStringAsync();
SpacesClass.SpaceRootObject model = JsonConvert.DeserializeObject<SpacesClass.SpaceRootObject>(json);
using (var scope = _scopeFactory.CreateScope())
{
var _DBcontext = scope.ServiceProvider.GetRequiredService<DBContexts>();
foreach (var item in model.resources)
{
var g = Guid.Parse(item.guid);
var x = _DBcontext.Spaces.FirstOrDefault(o => o.SpaceGuid == g);
if (x == null)
{
_DBcontext.Spaces.Add(new Spaces
{
SpaceGuid = Guid.Parse(item.guid),
Name = item.name,
CreatedAt = item.created_at,
UpdatedAt = item.updated_at,
OrgGuid = Guid.Parse(item.relationships.organization.data.guid),
Foundation = 5,
Timestamp = DateTime.Now
});
}
else if (x.UpdatedAt != item.updated_at)
{
x.CreatedAt = item.created_at;
x.UpdatedAt = item.updated_at;
x.Timestamp = DateTime.Now;
}
}
await _DBcontext.SaveChangesAsync();
}
}
public async Task GetApps()
{
var request = new HttpRequestMessage(HttpMethod.Get, "apps?per_page=200");
var response = await _client_DR.SendAsync(request);
var json = await response.Content.ReadAsStringAsync();
AppsClass.AppsRootobject model = JsonConvert.DeserializeObject<AppsClass.AppsRootobject>(json);
using (var scope = _scopeFactory.CreateScope())
{
var _DBcontext = scope.ServiceProvider.GetRequiredService<DBContexts>();
foreach (var item in model.resources)
{
var g = Guid.Parse(item.guid);
var x = _DBcontext.Apps.FirstOrDefault(o => o.AppGuid == g);
if (x == null)
{
_DBcontext.Apps.Add(new Apps
{
AppGuid = Guid.Parse(item.guid),
Name = item.name,
State = item.state,
CreatedAt = item.created_at,
UpdatedAt = item.updated_at,
SpaceGuid = Guid.Parse(item.relationships.space.data.guid),
Foundation = 5,
Timestamp = DateTime.Now
});
}
else if (x.UpdatedAt != item.updated_at)
{
x.State = item.state;
x.CreatedAt = item.created_at;
x.UpdatedAt = item.updated_at;
x.Timestamp = DateTime.Now;
}
}
var guids = model.resources.Select(r => Guid.Parse(r.guid));
var apps = _DBcontext.Apps.Where(o => guids.Contains(o.AppGuid) == false && o.Foundation == 5 && o.DeletedAt == null);
foreach (var app in apps)
{
app.DeletedAt = DateTime.Now;
}
await _DBcontext.SaveChangesAsync();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T07:34:41.063",
"Id": "443321",
"Score": "1",
"body": "where does that underscore variable come from in _Heartbeat_?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T11:07:05.143",
"Id": "443330",
"Score": "0",
"body": "From here https://github.com/davidfowl/AspNetCoreDiagnosticScenarios/blob/master/AsyncGuidance.md#timer-callbacks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T12:10:33.157",
"Id": "443336",
"Score": "0",
"body": "awesome thanks: https://docs.microsoft.com/en-us/dotnet/csharp/discards"
}
] |
[
{
"body": "<p>Interesting problem, hard to solve with so Little information but perhaps test if you're data management is not as efficient as you hope or you might even have a locking issue on the database where you're blocking yourself.</p>\n\n<p>Normally what I would do in a situation like this is the following. </p>\n\n<ol>\n<li><p>Have the webservice write the data in a staging table and return as efficient as possible.</p></li>\n<li><p>use a stored procedure to process the data on the server, Ideally use a Merge statement if you need to do update, insert and deletes.</p></li>\n</ol>\n\n<p>I am guessing that your dbcontext is getting to much data in memory an that this causes to much server side processing. Have a look at <a href=\"https://stackoverflow.com/questions/52257431/best-way-to-handle-large-data-in-entity-framework\">this</a> post if you have large volumes. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T06:58:57.987",
"Id": "227704",
"ParentId": "227645",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T00:35:17.150",
"Id": "227645",
"Score": "2",
"Tags": [
"c#",
".net",
"asp.net",
"asp.net-core",
".net-core"
],
"Title": "Hosted service which perform CRUD operations in high update environment"
}
|
227645
|
<p>I wrote a function to calculate the change due from a transaction. It also prints the number of twenties, tens, fives, ones, and coins required to meet the amount. I am looking for suggestions for a more simplified and pythonic approach.</p>
<pre><code>def change_return(cost,paid):
change = round(paid-cost,2)
print(f'Change due: {change}')
change_dict = {}
if change > 0:
twenties = change // 20.00
change_dict['Twenties'] = twenties
change -= 20.00 * twenties
tens = change // 10.00
change_dict['Tens'] = tens
change -= 10.00 * tens
fives = change // 5.00
change_dict['Fives'] = fives
change -= 5.00 * fives
ones = change // 1.00
change_dict['Ones'] = ones
change -= 1.00 * ones
quarters = change // 0.25
change_dict['Quarters'] = quarters
change -= 0.25 * quarters
dimes = change // 0.10
change_dict['Dimes'] = dimes
change -= 0.10 * dimes
nickels = change // 0.05
change_dict['Nickels'] = nickels
change -= 0.05 * nickels
pennies = change // 0.01
change_dict['Pennies'] = pennies
change -= 0.01 * pennies
else:
print('Insufficient funds')
for key,value in change_dict.items():
if value > 0:
print(key + ': ' + str(value))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T06:50:16.307",
"Id": "443311",
"Score": "3",
"body": "I don't have time for a full review, but wanted to mention that the general change making problem (use the smallest number of coins of provided denominations to make some sum) isn't correctly solved by always using the largest available coin. It works for standard US coins, but consider the case if some strange currency had 20, 9 and 1 and you want 37. Four 9s and a 1 is better than a 20, a 9 and eight 1s."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T06:51:26.913",
"Id": "443313",
"Score": "0",
"body": "I don't know whether you care about hypothetical other currency or are just thinking about dollars at the moment."
}
] |
[
{
"body": "<p>I would clean it up by separating my declarations from my code. With the below code, it becomes immediately clear to the reader that you are working with the various denominations of US currency. I have to work to figure it out in your code. Also, this lends itself to using other currency. I could define a different denominations variable to work with different currencies without changing my code at all. </p>\n\n<pre><code>from collections import namedtuple\n\nDenomination = namedtuple('Denomination', 'name value')\ndenominations = [\n Denomination(\"Twenties\", 20.00),\n Denomination(\"Tens\", 10.00),\n Denomination(\"Fives\", 5.00),\n Denomination(\"Ones\", 1.00),\n Denomination(\"Quarters\", 0.25),\n Denomination(\"Dimes\", 0.10),\n Denomination(\"Nickles\", 0.05),\n Denomination(\"Pennies\", 0.01)\n]\n\n\ndef change_return(cost, paid):\n change = round(paid-cost,2)\n print(f'Change due: {change}')\n\n if change > 0:\n for d in denominations:\n used = change // d.value\n if used > 0:\n print(d.name + \": \" + str(d.value))\n change -= d.value * used\n\n else:\n print('Insufficient funds')\n\n\nif __name__ == '__main__':\n change_return(30, 75.13)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T15:32:20.077",
"Id": "443359",
"Score": "5",
"body": "The poor person that gives exactly the right amount to the cashier/program. They are told that they have insufficient funds (it should probably be `elif change < 0`)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T03:26:35.067",
"Id": "227647",
"ParentId": "227646",
"Score": "5"
}
},
{
"body": "<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 to give you some insights on how to write a Pythonic style code.</p>\n\n<pre><code>def change_return(cost,paid):\n</code></pre>\n\n<ul>\n<li><p><strong>Docstrings:</strong> Python Docstring is the documentation string which is string literal, and it occurs in the class, module, function or method definition, and it is written as a first statement. Docstrings are accessible from the doc attribute for any of the Python object and also with the built-in help() function can come in handy. You should include a docstrings to your functions explaining what they do and what they return: </p>\n\n<pre><code>def calculate_total_change(cost, paid):\n \"\"\"Calculate change and return total\"\"\"\n # code\n</code></pre></li>\n<li><p><strong>f-Strings</strong> PEP 498 introduced 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 and this facilitates the insertion of variables in strings.</p>\n\n<pre><code>print(key + ': ' + str(value))\n</code></pre>\n\n<p>can be written:</p>\n\n<pre><code>print(f'{key}: {value}')\n</code></pre></li>\n<li><p><strong>Blank lines:</strong> Too much blank lines in your function: </p></li>\n</ul>\n\n<p><strong>PEP008:</strong> Surround top-level function and class definitions with two blank lines.\nMethod definitions inside a class are surrounded by a single blank line.\nExtra blank lines may be used <strong>(sparingly)</strong> to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations).\nUse blank lines in functions, sparingly, to indicate logical sections.</p>\n\n<h1>Code</h1>\n\n<ul>\n<li><p><strong>A function should return</strong> a function usually returns something instead of printing. </p>\n\n<pre><code>else:\n print('Insufficient funds')\n\n for key,value in change_dict.items():\n if value > 0:\n print(key + ': ' + str(value))\n</code></pre></li>\n</ul>\n\n<p><strong>You might do the following instead:</strong></p>\n\n<pre><code>return change_dict\n</code></pre>\n\n<p>Then use <code>if __name__ == '__main__':</code> guard at the end of your script which allows other modules to import your module without running the whole script like this:</p>\n\n<pre><code>if __name__ == '__main__': \n change = change_return(15, 20)\n if change:\n for unit, value in change.items():\n print(f'{value}: {unit}')\n if not change:\n print('Amount paid is exact.')\n</code></pre>\n\n<p><strong>Here's a refactored version of your code:</strong></p>\n\n<pre><code>from fractions import Fraction\n\n\ndef calculate_total_change(cost, paid):\n \"\"\"\n cost: a float/int representing the total cost.\n paid: a float/int representing amount paid\n return: Total change (dictionary).\n \"\"\"\n units = [('Twenties', 20), ('Tens', 10), ('Fives', 5), ('Ones', 1), ('Quarters', Fraction(1 / 4)),\n ('Dimes', Fraction(1 / 10)), ('Nickels', Fraction(5 / 100)), ('Pennies', Fraction(1 / 100))]\n total_change = {unit[0]: 0 for unit in units}\n if cost > paid:\n raise ValueError(f'Insufficient amount {paid} for cost {cost}.')\n if cost == paid:\n print('No change.')\n return {}\n if cost < paid:\n change = paid - cost\n if change:\n for unit in units:\n while change - unit[1] >= 0:\n total_change[unit[0]] += 1\n change -= unit[1]\n return total_change\n\n\nif __name__ == '__main__':\n change = calculate_total_change(15, 22.5)\n if change:\n for unit, value in change.items():\n print(f'{unit}: {value}')\n else:\n print('Amount exact')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T06:48:33.353",
"Id": "443515",
"Score": "1",
"body": "Is there a reason you use Fraction over Decimal? Also, your return value is inconsistent - if someone pays the exact amount you return an integer instead of a dict, which will break your loop in `if __name__ == \"__main__\"`. I think it would be more consistent to return an empty dict there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T06:52:06.110",
"Id": "443516",
"Score": "0",
"body": "thanks for pointing this out, I'll edit the code and there is no specific reason for choosing Fraction over Decimal, I guess both would do the same job, I'm more familiar with Fraction that's all and why returning a zero will break the loop?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T07:00:31.933",
"Id": "443519",
"Score": "0",
"body": "I think returning a zero would be inconsistent with what is indicated in the docstring however, it won't break the loop because both a zero and the empty dict have the same boolean value (False)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T07:14:30.223",
"Id": "443522",
"Score": "0",
"body": "Oh, right, didn't see that `if change:`. However, perhaps someone will use the function somewhere else - and having to check it would be a pain in that case."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T03:29:24.523",
"Id": "227648",
"ParentId": "227646",
"Score": "6"
}
},
{
"body": "<p>You have a lot of repeating code (<code>x = change // y</code>).\nTo fix this, you can use the following function:</p>\n\n<hr>\n\n<pre><code>def get_denomination(change, denom):\n num_of_denom = change // denom\n return (num_of_denom, change - (num_of_denom * denom))\n# New use-case\ntwenties, change = get_denomination(change, 20.00)\n</code></pre>\n\n<hr>\n\n<p>And, to avoid calculating the amount of every denomination in the case that <code>change</code> reaches zero before the end of your conditional block:</p>\n\n<hr>\n\n<pre><code>def change_return(cost,paid):\n\n change = round(paid-cost,2)\n print(f'Change due: {change}')\n\n change_dict = {}\n denominations = [20, 10, 5, 1, 0.25, 0.1, 0.05, 0.01]\n titles = ['Twenties', 'Tens', 'Fives', 'Ones', 'Quarters', 'Dimes',\n 'Nickels', 'Pennies']\n\n for index, denomination in enumerate(denominations):\n num_denom, change = get_denomination(change, denomination)\n change_dict[titles[index]] = num_denom\n if change == 0:\n break\n\n if change < 0:\n print('Insufficient funds')\n\nfor key,value in change_dict.items():\n if value > 0:\n print(key + ': ' + str(value))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T06:53:24.467",
"Id": "443518",
"Score": "0",
"body": "Why are you re-implementing the divmod() builtin? Also, it will be a bit better if you `zip(titles, denominations)` instead of enumerate + indexing."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T03:33:44.137",
"Id": "227649",
"ParentId": "227646",
"Score": "5"
}
},
{
"body": "<p>Firstly, when working with monetary values, to avoid <a href=\"https://docs.python.org/3/tutorial/floatingpoint.html\" rel=\"nofollow noreferrer\">floating-point-number-related issues</a> (you can try calling <code>change_return(1, 1.15)</code> in your solution to see it), it is more common to either (1) use cent as the unit and store all values as integers; or (2) use the <a href=\"https://docs.python.org/3/library/decimal.html\" rel=\"nofollow noreferrer\"><code>Decimal</code></a> class.</p>\n\n<p>Secondly, the repetition in the code can be avoided. The currencies can be stored and iterated over one by one in a for loop. A simple approach to store all kinds of currencies is to use a list as others have shown. Another option is to use <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\">enumerations</a>.</p>\n\n<p>Thirdly, the logic could be simplified a bit by using the modulo operation <code>change % denom</code> to calculate <code>change - change // denom * denom</code>.</p>\n\n<p>Following is refactored code:</p>\n\n<pre><code>from enum import Enum\nfrom decimal import Decimal\n\nclass Currency(Enum):\n TWENTY = \"20.00\", \"Twenties\"\n TEN = \"10.00\", \"Tens\"\n FIVE = \"5.00\", \"Fives\"\n ONE = \"1.00\", \"Ones\"\n # more ...\n PENNY = \"0.01\", \"Pennies\"\n\n def __init__(self, denomination, print_name):\n self.denomination = Decimal(denomination)\n self.print_name = print_name\n\ndef change_return(cost, paid):\n cost = Decimal(cost) \n paid = Decimal(paid)\n\n change = paid - cost\n change_dict = {} # Before Python 3.6 dictionaries do not preserve order so a sorting may be needed before printing\n\n if change < 0:\n return None # Better to raise an exception if performance is not a major concern\n\n # Better to do rounding here rather than before calculating the change\n # round() could also be used here, quantize() offers more rounding options, if needed\n precision = Decimal(\"0.01\")\n change = change.quantize(precision)\n\n # Note that the iteration order follows the declaration order in the Currency Enum,\n # therefore currencies should be declared in descending order of their denominations\n # to yield the desired outcome\n for cur in Currency:\n currency_cnt, change = divmod(change, cur.denomination) # divmod(a, b) returns a tuple (a // b, a % b)\n if currency_cnt: # Same as currency_cnt != 0\n change_dict[cur] = currency_cnt\n return change_dict\n\nif __name__ == \"__main__\":\n changes = change_return(\"30\", \"86.13\")\n if changes is None:\n print('Insufficient funds')\n else:\n for cur, count in changes.items():\n print(f\"{cur.print_name:<9}: {count}\") # Format output using format strings\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T00:34:26.877",
"Id": "443400",
"Score": "0",
"body": "Good call out on `Decimal` or using `int`s and nice use of `Enum`. You could use a `dict` but you would have to `sorted()` the iterator unless you want to rely on Py3.6+ having ordered dictionaries. You don't really need the `else` after a `return`. I would be tempted to `raise ValueError('Insufficient Funds')` vs `return None`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T01:23:09.667",
"Id": "443401",
"Score": "0",
"body": "@AChampion Thanks for the comment. A few points: 1. It does rely on ordered dictionaries. A comment is added. I considered to return a list of tuples but eventually kept the dictionary just in case a lookup is needed on that. 2. I agree with you in this case but be aware that sometimes an explicit `else` can [improve readablity](https://blog.mozilla.org/nnethercote/2009/08/31/no-else-after-return-considered-harmful/). 3. I was also tempted to raise an error but eventually hold it back because of the potential performance overhead of handling exceptions and not knowing the full requirement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T14:25:04.787",
"Id": "443444",
"Score": "0",
"body": "I'm loving the divmod use. Perhaps add a note about the fact that the iteration order of `for cur in Currency`is dependent on the declaration order in the `Currency` Enum? This is a gotcha in progressing code development here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T14:42:26.807",
"Id": "443448",
"Score": "0",
"body": "@JaccovanDorp Thanks. A comment about that is added."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T08:01:48.677",
"Id": "227653",
"ParentId": "227646",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T02:32:07.250",
"Id": "227646",
"Score": "9",
"Tags": [
"python",
"change-making-problem"
],
"Title": "Change-due function"
}
|
227646
|
<p>I have a exercise where I have to write a Stack class with the push and pop methods. The code compiles and works as it should. Are there better practices to use in my code? Is there something I should avoid doing?</p>
<pre><code>public class Stack {
private final int INCREMENTSIZE = 1024;
Integer position = 0;
int[] list = null;
public Stack(){
list = new int[INCREMENTSIZE];
}
public void push(Integer i) {
if(position == list.length) {
list = Arrays.copyOf(list, list.length + INCREMENTSIZE);
}
list[position++] = i;
}
public Integer pop(){
return list[--position];
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T20:59:44.450",
"Id": "443394",
"Score": "6",
"body": "Your stack grows and never shrinks..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T04:21:08.083",
"Id": "443403",
"Score": "2",
"body": "class Stack extends LinkedList<Integer> {}\n\nOught to pass all your tests. No responsibility taken for your marks, but I'd give you 100% as an employee for not reinventing a very old wheel."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T05:46:31.923",
"Id": "443409",
"Score": "7",
"body": "@Rich Except that extending linked list allows the stack's contract to be broken. It would be usable only as a strictly class private data structure, at which point having a separate name for it makes no sense at all. I would reject that merge request."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T09:44:52.720",
"Id": "443547",
"Score": "0",
"body": "@TorbenPutkonen: All contracts can be broken by someone determined enough to do so. (For example, if your nice and well-behaved Stack class isn't `final`, someone could extend it and make the subclass do whatever they want. Or there's always reflection.) But I do agree that renaming a perfectly ordinary LinkedList into something else is pointless. (For that matter, using LinkedList for anything is usually a poor choice anyway — at least 99% of the time ArrayList is just as good or better.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T06:04:15.170",
"Id": "444828",
"Score": "0",
"body": "@IlmariKaronen That's a bit useless hair splitting. Every contract can be broken via security flaws. Point is wheter breaking the contract is by design or by \"malicious\" use."
}
] |
[
{
"body": "<p>This looks good, However I suggest you properly indent the code.</p>\n\n<p><strong>Further suggestions:</strong></p>\n\n<p>I would change following</p>\n\n<blockquote>\n<pre><code>private final int INCREMENTSIZE = 1024;\n</code></pre>\n</blockquote>\n\n<p>to </p>\n\n<pre><code>private static final int INCREMENTSIZE = 1024;\n</code></pre>\n\n<p>Since you are not changing this in the constructor (to a new value) we might as well make it unique for the whole class.</p>\n\n<p>I would change following </p>\n\n<blockquote>\n<pre><code>Integer position = 0;\n</code></pre>\n</blockquote>\n\n<p>to </p>\n\n<pre><code>private int position = 0;\n</code></pre>\n\n<p>There is no reason to have an <code>Integer</code> when <code>int</code> will do. We can also make it <code>private</code>.</p>\n\n<p>For <code>push</code> and <code>pop</code> functions you can also use <code>int</code>'s instead of <code>Integer</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T08:58:19.213",
"Id": "227656",
"ParentId": "227655",
"Score": "12"
}
},
{
"body": "<p>Your class is small and does what you said it should, that's good.<br />\nHowever, there are a few things you could do better.</p>\n<h3>1. <a href=\"https://stackoverflow.com/questions/39004292/why-do-we-prefer-primitives-to-boxed-primitives-in-java\">Use primitive types unless the boxed ones are specifically needed</a>:</h3>\n<p>You are using the <code>Integer</code> type for counting the position and storing/returning data. If you actually used the fact, that it could be <code>null</code>, this would be acceptable use. However, any instance of <code>null</code> would break your code here. You are storing your integers in an <code>int[]</code>, a primitive integer array. This leads to unboxing and a <code>null</code> reference will break your code.<br />\nA position of <code>null</code> (not zero <code>0</code>) also isn't making any sense in the context of your class.</p>\n<p>Use <code>int</code> instead of <code>Integer</code> unless you actually need <code>null</code> references.</p>\n<h3>2. <a href=\"https://stackoverflow.com/questions/17393736/why-it-is-recommended-to-declare-instance-variables-as-private\">Reduce the visibility of member fields</a></h3>\n<p>Other classes inside the same package as your class typically don't need access to your internal array. Make that array <code>private</code>.</p>\n<h3>3. Think about what you want to store in your stack.</h3>\n<p>Currently your stack only allows storing primitive <code>int</code>s. Maybe think about storing any type of data using generics. Extending your current class wouldn't be difficult.</p>\n<p>Other than that: Your code is concise, not too complicated and serves its purpose. Think about formatting the code using your IDE's formatter and add comments and documentation to your code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T09:05:26.267",
"Id": "227658",
"ParentId": "227655",
"Score": "11"
}
},
{
"body": "<p>Your class is good (for me I would rename the variable <code>list</code> as <code>arr</code>), but you should consider case where you call <code>pop</code> on an empty stack. In this case your method could throw an exception like the code below:</p>\n\n<pre><code>public Integer pop(){\n if (position == 0) throw new RuntimeException(\"Empty Stack\");\n return list[--position];\n}\n</code></pre>\n\n<p>You can check from Java documentation that <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/Stack.html#pop()\" rel=\"noreferrer\">Stack pop()</a> throws <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/EmptyStackException.html\" rel=\"noreferrer\">EmptyStackException</a>, subclass of <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/RuntimeException.html\" rel=\"noreferrer\">RuntimeException</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T16:38:38.393",
"Id": "443366",
"Score": "0",
"body": "_INCREMENTSIZE_ is an unfortunate name for a full stack :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T16:50:40.550",
"Id": "443369",
"Score": "1",
"body": "@dfhwze lol, I realized now there is plenty of double meanings in my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T16:57:48.923",
"Id": "443371",
"Score": "4",
"body": "There is no sich thing as a Full stack in the original code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T18:43:29.777",
"Id": "443384",
"Score": "1",
"body": "You need to remove the first line of your `push` method (as @eckes is suggesting). Please note what the `push` method is doing in the original code and you will see why. Cheers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T19:27:26.057",
"Id": "443386",
"Score": "0",
"body": "The general idea of this answer, that one should make sure to handle edge cases like popping from an empty stack, is valid and worth pointing out. The specific advice and code you've suggested has several errors, however, and you appear not to have understood what the code you quoted and modified actually does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T19:46:21.913",
"Id": "443390",
"Score": "0",
"body": "given _if (position == INCREMENTSIZE)_ throws and _list.length >= INCREMENTSIZE_ the next condition _if(position == list.length)_ never yields _true_ why not remove that part from the code altogether?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T16:33:57.997",
"Id": "227672",
"ParentId": "227655",
"Score": "6"
}
},
{
"body": "<p>Other answers correctly point out that using primitive types and not mixing them with Objects (=<code>int</code> instead of <code>Integer</code>), reducing visibility wherever possible (=adding <code>private</code> modifier to <code>position</code> and <code>list</code>) and preventing popping from empty stack are good practices. There are a few more subtleties which can be improved:</p>\n\n<ol>\n<li>Rename <code>INCREMENTSIZE</code> to <code>INCREMENT_SIZE</code>. It's customary, when naming constants using full caps, to separate words with underscores.</li>\n<li>Consider growing a stack by multiplying current size and start small, e.g. instead having new size be current+increment, make it current*factor, where factor can be 1.5 or 2, or even decreased as the stack grows. If you're implementing a general purpose stack, you don't know how small or large the user will want it to be—incrementing by a constant might be an overkill or too small, while starting small and growing it in multiples will conserve memory if user needs a small stack, and will grow it in large enough increments later on if user needs to store many elements. The two approaches can be mixed and fine-tuned for best performance.</li>\n<li>Consider generifying the stack class so it can be a stack of anything, not just Integers. It's a small cost, but can be of large benefit.</li>\n<li>If you do store arbitrarily typed objects, beware of memory leaks! The <code>pop</code> function as it stands won't free memory if a user decides to empty the stack. It's a merely unconservative approach when dealing with primitives or small, usually pooled <code>Integer</code>s. It can be a real problem when storing something heavyweight—your stack will keep a reference to something which the user has popped and prevent the garbage collector from collecting it (also see Effective Java 3rd ed., Item 7). To prevent this, when popping an element, set the value of the popped element in array to <code>null</code>; additionally when a considerable proportion of the array is empty, deallocate a portion of it (e.g. using the <code>Arrays.copyOf</code> with a smaller second argument).</li>\n<li>Guard against overflows. At some point, <code>list.length + INCREMENTSIZE</code> will overflow, and you'll get <code>NegativeArraySizeException</code> from <code>Arrays#copyOf</code>. Unfortunately, you can't have arrays which are indexed by <code>long</code>s, so best you can do is use <code>Integer.MAX_VALUE</code> as the new size, and throw an exception (e.g. <code>IllegalStateException</code> with a helpful message) if the caller wants to add more items to stack after it's grown to MAX_VALUE. You can see how <code>ArrayDeque#grow(int)</code> and <code>ArrayDeque#newCapacity(int, int)</code> are implemented by OpenJDK <a href=\"https://github.com/AdoptOpenJDK/openjdk-jdk11/blob/master/src/java.base/share/classes/java/util/ArrayDeque.java#L141\" rel=\"noreferrer\">here</a>.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T05:30:10.020",
"Id": "443407",
"Score": "4",
"body": "To add to your point 2: the factor approach is asymptotically faster. As written in OP using a fixed increment, `push` is O(n). Using a factor like you've described makes it *amortized* O(1)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T19:36:17.490",
"Id": "227686",
"ParentId": "227655",
"Score": "18"
}
},
{
"body": "<p>In addition to what other's have said:</p>\n\n<p>Your constant-increment growth scheme causes <code>push</code> operations to be amortized <code>O(n)</code>. You should grow by a constant factor, as <code>ArrayList</code> does (1.5x, if I recall correctly). Even better, just don't use a primitive array at all, and use <code>ArrayList</code> instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T22:24:08.430",
"Id": "227693",
"ParentId": "227655",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T08:32:59.763",
"Id": "227655",
"Score": "13",
"Tags": [
"java",
"reinventing-the-wheel",
"stack"
],
"Title": "Stack class in Java 8"
}
|
227655
|
<p>This is a follow up to this code and I still did not get the feedback on the drawing functions</p>
<p><a href="https://codereview.stackexchange.com/questions/227363/maze-generator-in-python-gif-animator-custom-colors-sizes">Maze generator in Python- Gif animator-Custom colors/sizes</a></p>
<p>The code generates custom color and size mazes with optional generation of either a single full maze image or an animated GIF for the maze being created. 6 algorithms were implemented so far which are presented with examples below and more algorithms will be added to this code, awaiting your suggestions for improvements and feedback for the overall code specially the drawing functions.</p>
<p>Code works perfectly fine however my main concern is how to improve the drawing functions <code>_make_grid_image()</code>, <code>produce_maze_image()</code> and <code>produce_maze_visualization()</code> in terms of drawing accuracy, I want the paint-re paint procedure to be accurate using any given line width or size given that unless I change variables inside the body of the functions each time I change the width/size of the maze, I would get a pixelated image(and this is due to the absence of some method adjusting the drawing coordinates(and I do this manually each time I decide to change line width or the general size of the maze generated) I want something that automates the adjustment each to prevent a manual adjustment or getting pixelated images without changing the structure of the code. If you have any questions about the code, feel free to ask and I included some GIFs and description for the algorithms used so far. Take your time examining the code and I apologize if it's a bit long I'm constantly trying to eliminate repetition/redundancy as well as possible. </p>
<p><strong><em>Algorithms implemented so far:</em></strong></p>
<p><strong>1. Binary Tree Algorithm Description:</strong></p>
<p>Binary Tree Maze Generator is one of the very rareful algorithms with the ability to generate a perfect maze without keeping any state at all: it is an exact memoryless Maze generation algorithm with no limit to the size of Maze you can create. It can build the entire maze by looking at each cell independently. This is the most straightforward and fastest algorithm possible.</p>
<p><strong>Maze generated examples (25 % average dead ends):</strong></p>
<p><a href="https://i.stack.imgur.com/5rM0r.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5rM0r.gif" alt="Binary Tree - 50 x 50 Black & white"></a>
<a href="https://i.stack.imgur.com/Xwxif.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Xwxif.gif" alt="Binary Tree - 50 x 50 Blue & Yellow"></a>
<a href="https://i.stack.imgur.com/TMAcj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TMAcj.png" alt="Binary Tree - 50 x 50"></a></p>
<p><strong>2. Sidewinder Algorithm Description:</strong></p>
<p>Sidewinder Maze Generator is very similar to the Binary Tree algorithm, and only slightly more complicated. Furthermore, the Sidewinder algorithm only needs to consider the current row, and therefore can be used to generate infinitely large mazes (like the Binary Tree).While binary tree mazes have two of its four sides being one long passage, Sidewinder mazes have just one long passage.</p>
<p><strong>Maze generated examples: (28% average dead ends)</strong></p>
<p><a href="https://i.stack.imgur.com/tImNh.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tImNh.gif" alt="Sidewinder - 50 x 50 Black and White"></a>
<a href="https://i.stack.imgur.com/ziQcD.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ziQcD.gif" alt="Sidewinder = 50 x 50 Black and Gold"></a>
<a href="https://i.stack.imgur.com/jljHG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jljHG.png" alt="Sidewinder 50 x 50"></a></p>
<p><strong>3.Aldous Broder Algorithm Description:</strong></p>
<p>The Aldous-Broder algorithm is an algorithm for generating uniform spanning trees of a graph. Uniform Spanning Tree means "a maze generated in such a way that it was randomly selected from a list of every possible maze to be generated.</p>
<p><strong>Maze generated examples: (29% average dead ends)</strong></p>
<p><a href="https://i.stack.imgur.com/dYLc7.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dYLc7.gif" alt="Aldous Broder - 50 x 50 Black and White"></a>
<a href="https://i.stack.imgur.com/hDtai.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hDtai.gif" alt="Aldous Broder - 50 x 50 Dark Green and Turquoise"></a>
<a href="https://i.stack.imgur.com/6lmnb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6lmnb.png" alt="Aldous Broder - 50 x 50"></a></p>
<p><strong>4.Wilson Algorithm Description:</strong></p>
<p>Wilson’s algorithm uses loop-erased random walks to generate a uniform spanning tree — an unbiased sample of all possible spanning trees. Most other maze generation algorithms do not have this beautiful property (similar to Aldous Broder but more efficient)</p>
<p><strong>Maze generated examples: (30% average dead ends)</strong></p>
<p><a href="https://i.stack.imgur.com/jnSaI.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jnSaI.gif" alt="Wilson - 50 x 50 Black and White"></a>
<a href="https://i.stack.imgur.com/xLYPU.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xLYPU.gif" alt="Wilson - 50 x 50 Dark Blue and Pink"></a>
<a href="https://i.stack.imgur.com/MedeG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MedeG.png" alt="Wilson - 50 x 50"></a></p>
<p><strong>5.Recursive Backtracker Algorithm Description:</strong></p>
<p>The Recursive Backtracker Algorithm is probably the most widely used algorithm for maze generation. It has an implementation that many programmers can relate with (Recursive Backtracking).</p>
<p>*** Note: for efficiency, no recursion was used in the implementation, only backtracking.</p>
<p><strong>Maze generated examples: (10% average dead ends)</strong></p>
<p><a href="https://i.stack.imgur.com/pmzSZ.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pmzSZ.gif" alt="Recursive Backtracker - 50 x 50 Black and White"></a>
<a href="https://i.stack.imgur.com/Svoi4.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Svoi4.gif" alt="Recursive Backtracker - 50 x 50 Purple and white"></a>
<a href="https://i.stack.imgur.com/RYutB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RYutB.png" alt="Recursive Backtracker - 50 x 50"></a></p>
<p><strong>6.Hunt And Kill Algorithm Description:</strong></p>
<p>Works similarly to recursive backtracking algorithm, without the backtracking part.</p>
<p><strong>Maze generated examples: (10% average dead ends)</strong></p>
<p><a href="https://i.stack.imgur.com/K8QuG.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/K8QuG.gif" alt="Hunt And Kill - 50 x 50 Black and White"></a>
<a href="https://i.stack.imgur.com/C5wZQ.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C5wZQ.gif" alt="Hunt And Kill - 50 x 50 Red and Cyan"></a>
<a href="https://i.stack.imgur.com/lSlrB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lSlrB.png" alt="Hunt And Kill - 50 x 50"></a></p>
<pre><code>#!/usr/bin/env python
from PIL import Image, ImageDraw
from time import perf_counter
import random
import os
import glob
import imageio
import shutil
class Cell:
"""Create grid cell."""
def __init__(self, row_index, column_index, rows, columns):
"""
Initiate 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 is_linked(self, other):
"""Return True if 2 cells are linked."""
return other in self.linked_cells
def __str__(self):
"""Cell display."""
return f'Cell{self.coordinates()}'
def __repr__(self):
"""Cell representation."""
return f'Cell{self.coordinates()}'
class Maze:
"""
Generate a maze using different algorithms:
- Binary Tree Algorithm.
- Sidewinder Algorithm.
- Aldous-Broder Algorithm.
- Wilson Algorithm.
- Hunt And Kill Algorithm.
- Recursive Backtracker Algorithm.
"""
def __init__(self, rows, columns, width, height, line_width=5, line_color='black', background_color='white'):
"""
Initiate 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 = '/Users/emadboctor/Desktop/New code folder September 7 2019/Mazes for programmers/Maze test/'
# self.path = input('Enter path to folder to save maze creation GIF: ').rstrip()
self.configurations = {
'b': self._binary_tree_configuration(),
's': self._side_winder_configuration(),
'ab': self._aldous_broder_configuration(),
'w': self._wilson_configuration(),
'hk': self._hunt_and_kill_configuration(),
'rb': self._recursive_back_tracker_configuration()
}
self.algorithm_names = {'b': 'BINARY TREE', 's': 'SIDEWINDER', 'ab': 'ALDOUS BRODER', 'w': 'WILSON',
'hk': 'HUNT AND KILL', 'rb': 'RECURSIVE BACKTRACKER'}
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.height, 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 _get_dead_ends(self, maze):
"""
maze: A 2D list containing finished maze configuration.
Return dead end cells in current maze configuration.
"""
return {cell for row in maze for cell in row if len(cell.linked_cells) == 1 and
str(cell) != str(maze[-1][-1])}
def _binary_tree_configuration(self):
"""Return binary tree maze configuration."""
maze_cells = self._create_maze_cells()
modified_cells = []
for row in range(self.rows):
for column in range(self.columns):
current_cell = maze_cells[row][column]
north, south, east, west = current_cell.neighbors(maze_cells)
to_link = random.choice('nw')
if not north and not west:
continue
if to_link == 'n' and north:
current_cell.link(north, maze_cells)
modified_cells.append((current_cell, north))
if to_link == 'w' and west:
current_cell.link(west, maze_cells)
modified_cells.append((current_cell, west))
if to_link == 'n' and not north:
current_cell.link(west, maze_cells)
modified_cells.append((current_cell, west))
if to_link == 'w' and not west:
current_cell.link(north, maze_cells)
modified_cells.append((current_cell, north))
dead_ends = self._get_dead_ends(maze_cells)
return modified_cells, dead_ends
def _side_winder_configuration(self):
"""Return sidewinder algorithm maze configuration."""
maze_cells = self._create_maze_cells()
checked_cells = []
modified_cells = []
for row in range(self.rows):
for column in range(self.columns):
current_cell = maze_cells[row][column]
north, south, east, west = current_cell.neighbors(maze_cells)
if row == 0 and east:
east_cell = maze_cells[row][column + 1]
current_cell.link(east_cell, maze_cells)
modified_cells.append((current_cell, east_cell))
if row != 0:
checked_cells.append(current_cell)
to_link = random.choice('ne')
if to_link == 'e' and east:
east_cell = maze_cells[row][column + 1]
current_cell.link(east_cell, maze_cells)
modified_cells.append((current_cell, east_cell))
if to_link == 'n' or (to_link == 'e' and not east):
random_cell = random.choice(checked_cells)
checked_cells.clear()
random_cell_coordinates = random_cell.coordinates()
random_cell_north_neighbor = maze_cells[random_cell_coordinates[0] - 1][
random_cell_coordinates[1]]
random_cell.link(random_cell_north_neighbor, maze_cells)
modified_cells.append((random_cell, random_cell_north_neighbor))
dead_ends = self._get_dead_ends(maze_cells)
return modified_cells, dead_ends
def _aldous_broder_configuration(self):
"""Return Aldous Broder algorithm maze configuration."""
maze_cells = self._create_maze_cells()
modified_cells = []
starting_cell = maze_cells[random.choice(range(self.rows))][random.choice(range(self.columns))]
visited = set()
run = [starting_cell]
while len(visited) < self.rows * self.columns:
current_cell = run[-1]
visited.add(current_cell)
random_neighbor = random.choice([
neighbor for neighbor in current_cell.neighbors(maze_cells) if neighbor])
if random_neighbor not in visited:
visited.add(random_neighbor)
run.append(random_neighbor)
current_cell.link(random_neighbor, maze_cells)
modified_cells.append((current_cell, random_neighbor))
if random_neighbor in visited:
run.clear()
run.append(random_neighbor)
dead_ends = self._get_dead_ends(maze_cells)
return modified_cells, dead_ends
def _wilson_configuration(self):
"""Return Wilson algorithm maze configuration."""
maze_cells = self._create_maze_cells()
unvisited = {cell for row in maze_cells for cell in row}
starting_cell = random.choice(list(unvisited))
unvisited.remove(starting_cell)
visited = {starting_cell}
path = [random.choice(list(unvisited))]
unvisited.remove(path[-1])
modified_cells = []
while unvisited:
current_cell = path[-1]
new_cell = random.choice([neighbor for neighbor in current_cell.neighbors(maze_cells) if neighbor])
if new_cell in path and new_cell not in visited:
to_erase_from = path.index(new_cell)
del path[to_erase_from + 1:]
if new_cell in visited:
for cell in path:
visited.add(cell)
if cell in unvisited:
unvisited.remove(cell)
path.append(new_cell)
for index in range(len(path) - 1):
path[index].link(path[index + 1], maze_cells)
modified_cells.append((path[index], path[index + 1]))
path.clear()
if unvisited:
path.append(random.choice(list(unvisited)))
if new_cell not in path and new_cell not in visited:
path.append(new_cell)
dead_ends = self._get_dead_ends(maze_cells)
return modified_cells, dead_ends
def _hunt_and_kill_configuration(self):
"""Return hunt and kill algorithm maze configuration."""
maze_cells = self._create_maze_cells()
unvisited = [cell for row in maze_cells for cell in row]
starting_cell = random.choice(list(unvisited))
visited = [starting_cell]
unvisited.remove(starting_cell)
run = [starting_cell]
modified_cells = []
while unvisited:
current_cell = run[-1]
valid_neighbors = [neighbor for neighbor in current_cell.neighbors(maze_cells) if neighbor in unvisited]
if valid_neighbors:
next_cell = random.choice(valid_neighbors)
current_cell.link(next_cell, maze_cells)
modified_cells.append((current_cell, next_cell))
visited.append(next_cell)
unvisited.remove(next_cell)
run.append(next_cell)
if not valid_neighbors:
for cell in unvisited:
valid_neighbors = [neighbor for neighbor in cell.neighbors(maze_cells) if neighbor in visited]
if valid_neighbors:
choice = random.choice(valid_neighbors)
cell.link(choice, maze_cells)
modified_cells.append((cell, choice))
unvisited.remove(cell)
visited.append(cell)
run.append(cell)
break
dead_ends = self._get_dead_ends(maze_cells)
return modified_cells, dead_ends
def _recursive_back_tracker_configuration(self):
"""Return recursive backtracker maze configuration."""
maze_cells = self._create_maze_cells()
unvisited = [cell for row in maze_cells for cell in row]
starting_cell = random.choice(unvisited)
unvisited.remove(starting_cell)
run = [starting_cell]
modified = []
while run:
current_cell = run[-1]
valid_neighbors = [neighbor for neighbor in current_cell.neighbors(maze_cells) if neighbor in unvisited]
if valid_neighbors:
next_cell = random.choice(valid_neighbors)
current_cell.link(next_cell, maze_cells)
modified.append((current_cell, next_cell))
unvisited.remove(next_cell)
run.append(next_cell)
if not valid_neighbors:
run.pop()
dead_ends = self._get_dead_ends(maze_cells)
return modified, dead_ends
def produce_maze_image(self, configuration):
"""
configuration: a string representing the algorithm:
'b': Binary Tree Algorithm.
's': Sidewinder Algorithm.
'ab': Aldous Broder Algorithm.
'w': Wilson Algorithm.
'hk': Hunt And Kill Algorithm.
'rb': Recursive Backtracker Algorithm.
Return maze image according to specified configuration.
"""
if configuration not in self.configurations:
raise ValueError(f'Invalid configuration {configuration}')
cells, dead_ends = self.configurations[configuration]
maze = self._make_grid_image()
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)
number_of_dead_ends = len(dead_ends)
total_cells = self.rows * self.columns
dead_end_percentage = 100 * (number_of_dead_ends / total_cells)
print(f'{round(dead_end_percentage, 2)}% dead ends: {number_of_dead_ends} out of {total_cells} cells.')
return maze
def produce_maze_visualization(self, frame_speed, configuration):
"""
** NOTE: Works on Unix systems only.
Create a GIF for maze being created by respective specified configuration.
frame_speed: speed in ms.
configuration: a string representing the algorithm:
'b': Binary Tree Algorithm.
's': Sidewinder Algorithm.
'ab': Aldous Broder Algorithm.
'w': Wilson Algorithm.
'hk': Hunt And Kill Algorithm.
'rb': Recursive Backtracker Algorithm.
"""
if configuration not in self.configurations:
raise ValueError(f'Invalid configuration {configuration}')
print('GIF creation started ...')
os.chdir(self.path)
maze_image = self._make_grid_image()
cells, dead_ends = self.configurations[configuration]
count = 0
for cell1, cell2 in cells:
cell1_coordinates = cell1.coordinates()
cell2_coordinates = cell2.coordinates()
if cell1_coordinates[0] == cell2_coordinates[0]:
column = min(cell1_coordinates[1], cell2_coordinates[1])
x0 = (column + 1) * self.cell_width
row = cell1_coordinates[0]
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_image).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_image).line(y_end, self.line_color, self.line_width)
maze_image.save(self.path + str(count) + '.png', 'png')
count += 1
# Remove horizontal walls
if cell1_coordinates[1] == cell2_coordinates[1]:
column = cell1_coordinates[1]
x0 = column * self.cell_width + self.line_width - 2
row = min(cell1_coordinates[0], cell2_coordinates[0])
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_image).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_image).line(x_end, self.line_color, self.line_width)
maze_image.save(self.path + str(count) + '.png', 'png')
count += 1
maze_name = ' '.join(
[self.algorithm_names[configuration], str(self.rows), 'x', str(self.columns), self.background_color,
'x', self.line_color, 'maze', str(random.randint(10 ** 6, 10 ** 8))]
)
os.mkdir(maze_name)
for file in os.listdir(self.path):
if file.endswith('.png'):
shutil.move(file, maze_name)
os.chdir(maze_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(maze_name) + '.gif', frames, 'GIF', duration=frame_speed)
print(f'Creation of {self.algorithm_names[configuration]} {count} frames GIF successful.')
number_of_dead_ends = len(dead_ends)
total_cells = self.rows * self.columns
dead_end_percentage = (number_of_dead_ends / total_cells) * 100
print(f'{round(dead_end_percentage, 2)}% dead ends: {number_of_dead_ends} out of {total_cells} cells.')
if __name__ == '__main__':
start_time = perf_counter()
the_test1 = Maze(50, 100, 1000, 500)
the_test1.produce_maze_image('rb').show()
end_time = perf_counter()
print(f'Time: {end_time - start_time} seconds.')
</code></pre>
|
[] |
[
{
"body": "<p>This is a tip I make a lot, but if you have a collection that's simply tracking \"membership\", and you don't care about order, you should consider using a Set over a List.</p>\n\n<p>I think this is the case for <code>cell.linked_cells</code>. The only thing you ever do with <code>cell.linked_cells</code> is do <code>in</code> membership tests, and add and remove from it.</p>\n\n<p>Make the following changes:</p>\n\n<ul>\n<li><p>Initialize it as <code>self.linked_cells = set()</code> (Python doesn't have an empty set literal unfortunately)</p></li>\n<li><p>Change all <code>append</code>s to <code>add</code>s, and leave the <code>remove</code>s as-is.</p></li>\n</ul>\n\n<p>This has the potential for speed gains. After these changes, <code>in</code> and <code>remove</code> will no longer linear; they'll now run in effectively constant time.</p>\n\n<hr>\n\n<p><code>is_linked</code> doesn't appear to ever be used.</p>\n\n<hr>\n\n<p>Conditions like <code>if row_index >= rows or row_index < 0:</code> can make use of Python's \"comparison chaining\":</p>\n\n<pre><code>if not 0 <= row_index < rows:\n</code></pre>\n\n<p>It depends on if you think the negation hurts readability or not.</p>\n\n<hr>\n\n<p>I think in <code>neighbors</code> you should make the fact that <code>north</code> and similar variables are tuples more obvious.</p>\n\n<pre><code>north = (self.row - 1, self.column)\n</code></pre>\n\n<p>I think the explicitness of the parenthesis makes it clearer.</p>\n\n<p>And I find it confusing how you're reassigning <code>north</code> and other such variables to <code>0</code>. You're using <code>north</code>, for example, to represent both the tuple of coordinates, <em>and</em> as a flag to indicate whether or not the associated condition was True. You also appear to be using <code>0</code> to mean <code>False</code>. This isn't C! Be explicit about what your intentions are.</p>\n\n<p>My issue with the variables being used like this is, for example, the <em>type</em> of <code>north</code> will depend on whether or not <code>north[0] < 0</code> is <code>True</code>. Having a variable conditionally have one type or another is asking for trouble when those types don't share a usable superclass. What if you forget that the type can change and add a line like</p>\n\n<pre><code>some_var = north[0] - south[0]\n</code></pre>\n\n<p>(Dumb example, I don't know why you'd need to do this). Now, this will cause exceptions at runtime dependent on if the previous condition was <code>True</code> or not. Or say you were wanting to print out <code>north[0]</code> for debugging purposes. Now an unrelated error is being thrown, and the information you wanted to see was overwritten by <code>north = 0</code>.</p>\n\n<p>To remedy this, I'd:</p>\n\n<ul>\n<li><p>Create a <em>separate</em> flag variable to track whether or not <code>north[0] < 0</code> was True so <code>north</code> isn't being used for two separate, unrelated purposes. You could also probably refactor it a bit and make use of an <code>else</code> to get rid of the need for a flag altogether. That may add some nesting though.</p></li>\n<li><p>Use <code>False</code> instead of <code>0</code> so it's clear what the intent is.</p></li>\n</ul>\n\n<hr>\n\n<p><code>link</code> is fairly large even though it isn't doing much. The majority of the method is pre-condition checks to make sure the data is correct, and I think that's muddying the purpose of the method a bit.</p>\n\n<p>I'd split that up:</p>\n\n<pre><code>def _link_precondition_check(self, other, grid):\n if self in other.linked_cells or other in self.linked_cells:\n raise ValueError(f'{self} and {other} are already connected.')\n if self.columns != other.columns or self.rows != other.rows:\n raise ValueError('Cannot connect cells in different grids.')\n if self not in other.neighbors(grid) or other not in self.neighbors(grid):\n raise ValueError(f'{self} and {other} are not neighbors and cannot be connected.')\n if not isinstance(other, Cell):\n raise TypeError(f'Cannot link Cell to {type(other)}.')\n\ndef link(self, other, grid):\n \"\"\"Link 2 unconnected cells.\"\"\"\n self._link_precondition_check(other, grid)\n\n self.linked_cells.append(other)\n other.linked_cells.append(self)\n</code></pre>\n\n<p>I'll also point out, you're doing a type check at the end there. Whether or not this is necessary is debatable, but if you do want to have type safety, I would make use of <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">Type Hints</a>. Yes, Python does have support for weak static typing! I've been making <em>extensive</em> use of them lately, and they've helped me avoid dumb mistakes.</p>\n\n<p>You could make the following changes:</p>\n\n<pre><code>from __future__ import annotations # Needed until later versions so classes can reference themselves in type checks\nfrom typing import List\n\n# A grid is a List of List of Cells\ndef _link_precondition_check(self, other: Cell, grid: List[List[Cell]]):\n . . .\n\ndef link(self, other: Cell, grid: List[List[Cell]]):\n . . .\n</code></pre>\n\n<p>I'll note, you can also make type aliases so you don't need to write <code>List[List[Cell]]</code> over and over:</p>\n\n<pre><code>Grid = List[List[Cell]]\n</code></pre>\n\n<p>Unfortunately, I can't see a good way of declaring this anywhere since it needs to be inside of <code>Cell</code> (so that <code>Cell</code> exists otherwise <code>List[List[Cell]]</code> won't make sense), but can't be declared as a class attribute. Oddly enough, I've never run into this limitation before.</p>\n\n<p>Now you don't need <code>instanceof</code> type checks because a good IDE will catch mistakes before the code even runs!</p>\n\n<p>I'd recommend playing around with type hints though. They can help the IDE give you better auto-complete suggestions (since it'll have a better idea of what types it's dealing with), and will allow it to catch you mistakes like it would if Python was statically typed (although it isn't as competent as a good compiler for a statically-typed languages unfortunately).</p>\n\n<hr>\n\n<hr>\n\n<p>I'd keep going, but I gotta get to work here. Good luck!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T15:24:01.280",
"Id": "443358",
"Score": "0",
"body": "Thank you for taking the time, to go through this."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T15:11:15.833",
"Id": "227666",
"ParentId": "227660",
"Score": "14"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T11:32:29.237",
"Id": "227660",
"Score": "14",
"Tags": [
"python",
"python-3.x",
"image",
"animation"
],
"Title": "Maze generator & animator in Python"
}
|
227660
|
<p>By hashing together various online tutorials I've constructed my first MVVM application that lets users <a href="https://rachel53461.wordpress.com/2011/12/18/navigation-with-mvvm-2/" rel="nofollow noreferrer">navigate between "tabs"</a> and a "tab" (ColorList_Tab) that performs basic list functions such as adding, editing, deleting and saving colors. </p>
<p><a href="https://i.stack.imgur.com/l6ETH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l6ETH.png" alt="Application running"></a></p>
<p>A new tab can be addded by adding a new data context to the <code>MainWindow</code> resources and then adding the viewmodel to <code>PageViewModels</code> list in the <code>MainWindowViewModel</code>. This tab will then be represented by its <code>Icon</code> property from inheriting from <code>IPageViewModel</code>.</p>
<p><code>ColorList_Tab</code> supports adding, editing, deleting and saving colors to a text file in a Json format. Two textboxes are used to input the color name and hex, add and edit mode can be switched between by clicking on the <code>AddSwitchCommand</code> and <code>EditSwitchCommand</code> buttons. The execute command then executes the selected mode. Edit and delete will perform the function upon the currently selected item in the <code>Color</code> List, with every change being saved to a text file in Json form. <code>SampleColorCommand</code> sets the <code>InputHexString</code> to the color of cursor on screen.</p>
<p>Besides general critique and corrections, I was hoping a few of my questions could be addressed:</p>
<ol>
<li><p>Is <code>MainWindowViewModel</code> a good way of implementing navigation in MVVM?</p></li>
<li><p>Currently my App.Xaml.Cs is unused however I've seen <a href="https://rachel53461.wordpress.com/2011/05/08/simplemvvmexample/" rel="nofollow noreferrer">examples</a> where it is used to bind the viewmodel, which should I use?</p></li>
<li><p>Have I correctly placed the <code>AddColorItem</code>, <code>EditColorItem</code> and <code>DeleteColorItem</code> methods in the Model?</p></li>
<li><p>Should <code>ColorClass</code> use try and catch to create the brush or should an if else statement be used with a regex check on the hex code?</p></li>
</ol>
<p>MainWindow:</p>
<pre class="lang-xml prettyprint-override"><code><Window x:Class="MVVM_Color_Utilities.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:local="clr-namespace:MVVM_Color_Utilities"
mc:Ignorable="d"
xmlns:ViewModel ="clr-namespace:MVVM_Color_Utilities.ViewModel"
xmlns:ColorList="clr-namespace:MVVM_Color_Utilities.ColorsList_Tab"
Title="MainWindow" Height="600" Width="1000"
WindowStartupLocation="CenterScreen" Background="LightGray"
WindowStyle="None" AllowsTransparency="True">
<Window.DataContext>
<ViewModel:MainWindowViewModel/>
</Window.DataContext>
<Window.Resources>
<DataTemplate DataType="{x:Type ColorList:ColorListViewModel}">
<ColorList:ColorListView/>
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="70"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="70"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Rectangle Grid.Column="1" Fill="{StaticResource BurgundyBrush}" />
<Rectangle Grid.RowSpan="2" Fill="{StaticResource CyanTerracottaBrush}" Margin="0,0,-0.5,0"/>
<ItemsControl Grid.Row="1" ItemsSource="{Binding PageViewModels}" HorizontalAlignment="Stretch">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Height="70"
Command="{Binding DataContext.ChangePageCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
CommandParameter="{Binding }">
<materialDesign:PackIcon Kind="{Binding Icon}" Height="30" Width="30" />
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Rectangle Grid.Column="1" Fill="{StaticResource BurgundyBrush}" Name="DragWindow" MouseDown="DragWindow_MouseDown"/>
<ContentControl Grid.Column="1" Grid.RowSpan="2" Content="{Binding CurrentPageViewModel}" />
<!--#region Window Controls-->
<StackPanel Grid.Column="1" Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Top" Height="30" x:Name="Stack" Margin="7,0,0,0">
<!--Minimise-->
<Button Click="MinimizeWindowButton_Click" x:Name="MinimizeWindowButton">
<materialDesign:PackIcon Kind="Remove" Background="{x:Null}" BorderBrush="{x:Null}"/>
</Button>
<!--Toggle Window State-->
<Button Click="ChangeWindowState_Click" x:Name="ChangeWindowState" >
<materialDesign:PackIcon Kind="CropSquare" Background="{x:Null}" BorderBrush="{x:Null}"/>
</Button>
<!--Close Window-->
<Button Click="CloseWindow_Click" Height="Auto" x:Name="CloseWindow" >
<materialDesign:PackIcon Kind="Close" Background="{x:Null}" BorderBrush="{x:Null}"/>
</Button>
</StackPanel>
<!--#endregion-->
</Grid>
</Window>
</code></pre>
<p>MainWindowViewModel:</p>
<pre class="lang-cs prettyprint-override"><code>using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using MVVM_Color_Utilities.ViewModel.Helper_Classes;
namespace MVVM_Color_Utilities.ViewModel
{
public class MainWindowViewModel : ObservableObject
{
#region Fields
private ICommand _changePageCommand;
private IPageViewModel _currentPageViewModel;
private List<IPageViewModel> _pageViewModels;
#endregion
#region Constructors
public MainWindowViewModel()
{
PageViewModels.Add(new ColorsList_Tab.ColorListViewModel());
//PageViewModels.Add(new ImageQuantizer_Tab.ImageQuantizerViewModel());
CurrentPageViewModel = PageViewModels[0];
}
#endregion
public ICommand ChangePageCommand
{
get
{
if (_changePageCommand == null)
{
_changePageCommand = new RelayCommand(
p => ChangeViewModel((IPageViewModel)p),
p => p is IPageViewModel);
}
return _changePageCommand;
}
}
public List<IPageViewModel> PageViewModels
{
get
{
if (_pageViewModels == null)
_pageViewModels = new List<IPageViewModel>();
return _pageViewModels;
}
}
public IPageViewModel CurrentPageViewModel
{
get
{
return _currentPageViewModel;
}
set
{
if (_currentPageViewModel != value)
{
_currentPageViewModel = value;
OnPropertyChanged("CurrentPageViewModel");
}
}
}
private void ChangeViewModel(IPageViewModel viewModel)
{
if (!PageViewModels.Contains(viewModel))
{
PageViewModels.Add(viewModel);
}
CurrentPageViewModel = PageViewModels
.FirstOrDefault(vm => vm == viewModel);
}
}
}
</code></pre>
<p>IPageViewModel Interface
(Sets the icon for each viewmodel for display in the main window):</p>
<pre class="lang-cs prettyprint-override"><code>using MaterialDesignThemes.Wpf;
namespace MVVM_Color_Utilities.ViewModel.Helper_Classes
{
public interface IPageViewModel
{
PackIconKind Icon { get; }
}
}
</code></pre>
<p>ColorList_Tab View:</p>
<pre class="lang-xml prettyprint-override"><code><UserControl x:Class="MVVM_Color_Utilities.ColorsList_Tab.ColorListView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:MVVM_Color_Utilities.ColorsList_Tab"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
mc:Ignorable="d"
>
<UserControl.InputBindings>
<KeyBinding Key="Enter" Command="{Binding ExecuteCommand}"/>
<KeyBinding Modifiers="Ctrl" Key="D" Command="{Binding DeleteItem}"/>
<KeyBinding Modifiers="Ctrl" Key="A" Command="{Binding AddSwitchCommand}"/>
<KeyBinding Modifiers="Ctrl" Key="E" Command="{Binding EditSwitchCommand}"/>
<KeyBinding Modifiers="Ctrl" Key="Q" Command="{Binding SampleColorCommand}"/>
</UserControl.InputBindings>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="70"/>
<RowDefinition Height="50"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Width="270" HorizontalAlignment="Left">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<!--This changes the "background" of the buttons as setting the background of buttons
while using material design causes an ugly shadow effect-->
<Rectangle Grid.Column="0" >
<Rectangle.Style>
<Style TargetType="Rectangle">
<Setter Property="Fill" Value="{StaticResource BurgundyBrush}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding AddingModeBool}" Value="True">
<Setter Property="Fill" Value="{StaticResource BurgundyLightBrush}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Rectangle.Style>
</Rectangle>
<Rectangle Grid.Column="1">
<Rectangle.Style>
<Style TargetType="Rectangle">
<Setter Property="Fill" Value="{StaticResource BurgundyLightBrush}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding AddingModeBool}" Value="True">
<Setter Property="Fill" Value="{StaticResource BurgundyBrush}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Rectangle.Style>
</Rectangle>
<Button Grid.Column="0" Command="{Binding Path=AddSwitchCommand}">
<materialDesign:PackIcon Kind="Add"/>
</Button>
<Button Grid.Column="1" Command="{Binding Path=EditSwitchCommand}" >
<materialDesign:PackIcon Kind="Edit" />
</Button>
<Button Grid.Column="2" Command="{Binding Path=DeleteItem}">
<materialDesign:PackIcon Kind="Delete" VerticalAlignment="Center"/>
</Button>
</Grid>
<!--#region ListBox Header-->
<Grid Grid.Row="1" Background="{StaticResource BurgundyLightBrush}" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.8*"/>
<ColumnDefinition Width="1.5*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="0.7*"/>
<ColumnDefinition Width="1.2*"/>
</Grid.ColumnDefinitions>
<Grid.Resources>
<Style TargetType="TextBox">
<Setter Property="Background" Value="{StaticResource BurgundyFaintBrush}"/>
<Setter Property="Height" Value="20"/>
</Style>
</Grid.Resources>
<Rectangle Height="18" Width="60" Fill="White"/>
<Rectangle Height="18" Width="60" Fill="{Binding IndicatorBrush}" Stroke="Gray" StrokeThickness="0.4"/>
<TextBox Grid.Column="1" Width="160" Text="{Binding InputName, UpdateSourceTrigger=PropertyChanged}" />
<TextBox Grid.Column="2" Width="80" Text="{Binding InputHex, UpdateSourceTrigger=PropertyChanged}"/>
<Button Grid.Column="4" Command="{Binding Path=SampleColorCommand}">
<materialDesign:PackIcon Kind="Colorize" Width="40"/>
</Button>
<Button Grid.Column="5" Command="{Binding Path=ExecuteCommand}">
<materialDesign:PackIcon Kind="done" Width="100"/>
</Button>
</Grid>
<!--#endregion-->
<!--#region ListBox-->
<ListBox Grid.Row="2" ItemsSource="{Binding ColorListSource}" SelectedIndex="{Binding SelectedItemIndex}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem" BasedOn="{StaticResource {x:Type ListBoxItem}}">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Style.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsSelected" Value="true"/>
<Condition Property="Selector.IsSelectionActive" Value="true"/>
</MultiTrigger.Conditions>
<Setter Property="Background" Value="Gray"/>
</MultiTrigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid
>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.8*"/>
<ColumnDefinition Width="1.5*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="0.7*"/>
<ColumnDefinition Width="1.2*"/>
</Grid.ColumnDefinitions>
<Rectangle Height="18" Width="60" Fill="{Binding SampleBrush}" Stroke="Gray" StrokeThickness="0.4"/>
<TextBlock Text="{Binding Name}" Width="160" Grid.Column="1"/>
<TextBlock Text="{Binding Hex}" Width="70" Grid.Column="2"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<!--#endregion-->
</Grid>
</UserControl>
</code></pre>
<p>ColorList_Tab ViewModel:</p>
<pre class="lang-cs prettyprint-override"><code>using System.Collections.ObjectModel;
using MVVM_Color_Utilities.ViewModel.Helper_Classes;
using MaterialDesignThemes.Wpf;
using System.Windows.Media;
using System.Windows.Input;
using MVVM_Color_Utilities.Helpers;
using System.Text.RegularExpressions;
namespace MVVM_Color_Utilities.ColorsList_Tab
{
class ColorListViewModel : ObservableObject, IPageViewModel
{
private readonly ColorListModel model = new ColorListModel();
private Regex _hexReg = new Regex("^#([0-9a-fA-F]{0,8})?$"); //"^#(?:(?:[0-9a-fA-F]{3}){1,2}|(?:[0-9a-fA-F]{4}){1,2})$"
private bool _addingModeBool = true;
private int _selectedItemIndex;
private string _inputNameString;
private string _inputHexString;
private SolidColorBrush _inputBrush = Brushes.
private ICommand _addSwitchCommand;
private ICommand _editSwitchCommand;
private ICommand _executeCommand;
private ICommand _sampleColorCommand;
private ICommand _deleteItemCommand;
public ColorListViewModel()
{
SelectedItemIndex = 0;
}
public SolidColorBrush IndicatorBrush
{
get
{
return _inputBrush;
}
set
{
_inputBrush = value;
OnPropertyChanged("IndicatorBrush");
}
}
public string InputName
{
get
{
return _inputNameString;
}
set
{
_inputNameString = value;
OnPropertyChanged("InputName");
}
}
public string InputHex
{
get
{
return _inputHexString;
}
set
{
if (_hexReg.IsMatch(value)||value=="")//Only allows valid hex charcters ie start with # and the 1-9a-f
{
_inputHexString = value;
OnPropertyChanged("InputHex");
}
try
{
//Sets indicator to the new color
IndicatorBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString(value));
}
catch { }
}
}
public PackIconKind Icon => PackIconKind.Palette;
public bool AddingModeBool
{
get
{
return _addingModeBool;
}
set
{
_addingModeBool = value;
OnPropertyChanged("AddingModeBool");
}
}
public ObservableCollection<ColorClass> ColorListSource
{
get
{
return model.ColorClassList;
}
}
public int SelectedItemIndex
{
get
{
if (_selectedItemIndex >= ColorListSource.Count && ColorListSource.Count != 0)
{
_selectedItemIndex = ColorListSource.Count - 1;
}
return _selectedItemIndex;
}
set
{
_selectedItemIndex= MathUtils.Clamp(0, ColorListSource.Count - 1, value);
if (ColorListSource.Count > 0)
{
InputHex = ColorListSource[_selectedItemIndex].Hex;
InputName = ColorListSource[_selectedItemIndex].Name;
}
else
{
InputHex = "";
InputName = "";
}
OnPropertyChanged("SelectedItemIndex");
}
}
public ICommand AddSwitchCommand
{
get
{
if (_addSwitchCommand == null)
{
_addSwitchCommand = new RelayCommand(param => AddSwitchMethod());
}
return _addSwitchCommand;
}
}
public ICommand EditSwitchCommand
{
get
{
if(_editSwitchCommand == null)
{
_editSwitchCommand = new RelayCommand(param => EditSwitchMethod());
}
return _editSwitchCommand;
}
}
public ICommand ExecuteCommand
{
get
{
if (_executeCommand == null)
{
_executeCommand = new RelayCommand(param => ExecuteMethod());
}
return _executeCommand;
}
}
public ICommand SampleColorCommand
{
get
{
if (_sampleColorCommand == null)
{
_sampleColorCommand = new RelayCommand(param => SampleColorMethod());
}
return _sampleColorCommand;
}
}
public ICommand DeleteItem
{
get
{
if (_deleteItemCommand == null)
{
_deleteItemCommand = new RelayCommand(param => DeleteItemMethod());
}
return _deleteItemCommand;
}
}
void AddSwitchMethod()
{
AddingModeBool = true;
}
void EditSwitchMethod()
{
AddingModeBool = false;
}
void ExecuteMethod()
{
if (AddingModeBool)
AddNewItemMethod();
else
EditItemMethod();
}
void AddNewItemMethod()
{
model.AddColorItem(SelectedItemIndex, InputHex, InputName);
SelectedItemIndex = 0;
}
void EditItemMethod()
{
model.EditColorItem(SelectedItemIndex, InputHex, InputName);
}
void DeleteItemMethod()
{
model.DeleteColorItem(SelectedItemIndex);
}
void SampleColorMethod()
{
Color color = ColorUtils.GetCursorColor();
InputHex = $"#{color.R:X2}{color.G:X2}{color.B:X2}";
}
}
}
</code></pre>
<p>Observable Objects (not my code)</p>
<pre class="lang-cs prettyprint-override"><code>using System.ComponentModel;
namespace MVVM_Color_Utilities.ViewModel.Helper_Classes
{
public abstract class ObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (PropertyChanged != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
</code></pre>
<p><a href="https://rachel53461.wordpress.com/2011/12/18/navigation-with-mvvm-2/" rel="nofollow noreferrer">RelayCommand (not my code)</a>
:</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Diagnostics;
using System.Windows.Input;
namespace MVVM_Color_Utilities.ViewModel.Helper_Classes
{
public class RelayCommand : ICommand
{
#region Fields
readonly Action<object> _execute;
readonly Predicate<object> _canExecute;
#endregion // Fields
#region Constructors
public RelayCommand(Action<object> execute)
: this(execute, null)
{
}
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
{
throw new ArgumentNullException("execute");
}
_execute = execute;
_canExecute = canExecute;
}
#endregion // Constructors
#region ICommand Members
[DebuggerStepThrough]
public bool CanExecute(object parameters)
{
return _canExecute == null ? true : _canExecute(parameters);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameters)
{
_execute(parameters);
}
#endregion // ICommand Members
}
}
</code></pre>
<p>ColorList_Tab Model:</p>
<pre class="lang-cs prettyprint-override"><code>using System.IO;
using System.Collections.ObjectModel;
using System.Windows.Media;
using Newtonsoft.Json;
namespace MVVM_Color_Utilities.ColorsList_Tab
{
public class ColorListModel
{
#region Fields
private readonly static string projectPath = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName; //Get Path of ColorItems file
private readonly static string colorsFilePath = projectPath + "/Resources/ColorItemsList.txt";
#endregion
#region Properties
public ObservableCollection<ColorClass> ColorClassList { get; }
=JsonConvert.DeserializeObject<ObservableCollection<ColorClass>>(File.ReadAllText(colorsFilePath));
public int NextID
{
get
{
return ColorClassList.Count > 0 ? ColorClassList[0].ID + 1 : 0;
}
}
#endregion
#region Methods
private void SaveColorsList()
{
try
{
File.WriteAllText(colorsFilePath, JsonConvert.SerializeObject(ColorClassList));
}
catch { }
}
public void AddColorItem(int index,string hexString, string nameString)
{
if(ColorClassList.Count > index || ColorClassList.Count==0)
{
ColorClassList.Insert(0, new ColorClass(NextID, hexString, nameString));
SaveColorsList();
}
}
public void EditColorItem(int index,string hexString, string nameString)
{
if (ColorClassList.Count > index && ColorClassList.Count > 0)
{
ColorClassList[index] = new ColorClass(NextID, hexString, nameString);
SaveColorsList();
}
}
public void DeleteColorItem(int index)
{
if (ColorClassList.Count > index &&ColorClassList.Count>0)
{
ColorClassList.RemoveAt(index);
SaveColorsList();
}
}
#endregion
}
}
</code></pre>
<p>ColorClass:</p>
<pre class="lang-cs prettyprint-override"><code> public class ColorClass
{
public ColorClass(int id, string hex, string name)
{
ID = id;
Name = name;
Hex = hex;
}
public int ID { get; set; }
public string Hex { get; set; }
public string Name { get; set; }
public SolidColorBrush SampleBrush
{
get
{
Color color;
try
{
color = (Color)ColorConverter.ConvertFromString(Hex);
}
catch//Invalid hex defaults to white.
{
color = (Color)ColorConverter.ConvertFromString("#FFFF");
Hex = "#FFFF";
}
return new SolidColorBrush(color);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T15:50:18.357",
"Id": "443360",
"Score": "0",
"body": "Do you happen to have this on GitHub too?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T15:58:50.100",
"Id": "443361",
"Score": "1",
"body": "Yes, however it does have two additional unfinished tabs. https://github.com/TimothyMakkison/MVVM-Color-Utilities . Sorry for the long question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T16:03:19.250",
"Id": "443362",
"Score": "1",
"body": "Don't worry about the length, the question is great and as a matter of fact I wanted to fork it ;-]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T16:46:52.697",
"Id": "443367",
"Score": "0",
"body": "I'd have to read up again about WPF lifetime management of Pages through different strategies of navigation. Memory leaks are lurking everywhere (in general, don't know about OP)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T16:54:24.783",
"Id": "443370",
"Score": "2",
"body": "Is _RelayCommand_ your code or picked from the internet? It's ok to use third-party classes, it's just so we know whether we should review that class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T17:25:02.467",
"Id": "443373",
"Score": "0",
"body": "Good catch @dfhwze both ObservableObject and [RelayCommand](https://rachel53461.wordpress.com/2011/05/08/simplemvvmexample/) are from the internet. I'll update the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T17:31:06.167",
"Id": "443374",
"Score": "1",
"body": "I did review these 2 classes to challenge you that maybe creating your own classes would be a better idea than using these standard snippet classes."
}
] |
[
{
"body": "<h3>Preface</h3>\n\n<p>There is a lot to review. This review is focused on the parts that are not related to the View or ViewModel.</p>\n\n<p><em>Note: You have also edited the question concurrently with me making this review to state ObservableObject and RelayCommand are third-party classes. That's fine by me, since I still wanted to point out to you you shouldn't just copy these classes from internet and use them without any changes or proper consideration.</em></p>\n\n<hr>\n\n<h2>ColorListModel</h2>\n\n<p>You cannot reuse this class in scenarios where the paths are different than below. Also, when changing paths, you'd have to update this code with it. Consider reading these paths from a settings or configuration file.</p>\n\n<blockquote>\n<pre><code>private readonly static string projectPath \n = Directory.GetParent(Directory.GetCurrentDirectory())...\nprivate readonly static string colorsFilePath \n = projectPath + \"/Resources/ColorItemsList.txt\";\n</code></pre>\n</blockquote>\n\n<p>Consider using the lazy pattern to load properties on first demand to avoid unnecessary resources when not required: property <code>ColorClassList</code>.</p>\n\n<p><code>SaveColorsList</code> swallows all exceptions. At least log something or return a <code>bool</code> in sandbox mode if you don't like this method to throw exceptions.</p>\n\n<p><code>AddColorItem</code>, <code>EditColorItem</code> and <code>DeleteColorItem</code> only execute when the index is in bounds. The caller does not get feedback about out-of-bounds. Throw an exception or return a <code>bool</code> to let caller handle edge cases. Furthermore, <code>AddColorItem</code> does not use <code>index</code> as it stores on index <code>0</code> instead. Is this as designed?</p>\n\n<hr>\n\n<p><em>(third-party code)</em></p>\n\n<h2>ObservableObject</h2>\n\n<p>This class is a design decision that I would challenge. It provides insufficient context to be a good candidate for a base class for other classes. I put it in the list of classes as <code>ComparableBase</code>, <code>EquatableBase</code>, <code>DisposableBase</code>. Think about whether a common base clase is really helpful here.</p>\n\n<p>In addition, this class provides a public event <code>PropertyChanged</code> but never disposes it. Even if the WPF framework is able to subscribe and unsubscribe correctly from it, your own code-behind and other application logic is also allowed to subscribe. Classes that provide events should in my opinion always implement <code>IDisposable</code>.</p>\n\n<h2>RelayCommand</h2>\n\n<p>This is a famous allround command. I think it originates from Telerik, but several other variants are out there as well (<code>DelegateCommand</code> for instance). I would mention the use of third-party code in a question so we know how to review it.</p>\n\n<p>This pattern with <code>Action<object> execute</code> is contravariant, but since <code>object</code> is the deepest base class, it's not that useful. For instance, you cannot exchange <code>execute</code> with an <code>Action<string></code>. For this reason, consider creating also a <code>RelayCommand<T></code> that accepts <code>Action<T> execute</code>. This class is more usable for code-behind and other application logic.</p>\n\n<p>The <code>predicate</code> parameter should be made optional. You might also like to create an <code>AsyncRelayCommand<T></code> with a composite <code>CancelCommand</code> (<a href=\"https://github.com/StephenCleary/Mvvm.Async/issues/3\" rel=\"nofollow noreferrer\">Example</a>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T17:28:04.393",
"Id": "227677",
"ParentId": "227661",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "227677",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T13:42:45.377",
"Id": "227661",
"Score": "6",
"Tags": [
"c#",
"wpf",
"mvvm"
],
"Title": "WPF MVVM ColorLister with navigation"
}
|
227661
|
<p>It's a simple range function that works like python range and it is only a syntactic sugar for the usual for loop</p>
<p>if we want to operate on numbers in the range from 1 to 10 (1 ... 9) we use this code :</p>
<pre><code>for (int i = 0; i < 10; ++i) { ... }
</code></pre>
<p>but c++ 11 came with the for range loops in which this code :</p>
<pre><code>for (auto i : array) {...}
</code></pre>
<p>will be expanded to something like this :</p>
<pre><code>for (auto begin = array.begin(), auto end = array.end(); begin != end; ++begin) {auto i = *begin; ... }
</code></pre>
<p>the iterators are just wrappers for the pointers</p>
<p>so to make use of this feature and loop in a range of numbers we need to do somethings :</p>
<ul>
<li><p>make i and end (the pointers) some integral type (int, short, long, ...) instead</p></li>
<li><p>and we should check if the start value is smaller than the final value because in the new for expression the test is for non equality not for less than or more than . it is this because this syntax is used to operate on the elements of the containers where we want to access the elements that we know they start at begin and end marks that the previous element was the final</p></li>
</ul>
<p>so this is my implementation :
I implemented two types of range functions</p>
<ul>
<li><p>one for c++ 11 using iterators like counters</p></li>
<li><p>the second is for c++ 20 using the new generator and coroutines</p></li>
</ul>
<p>both can be called lazy range because we don't get the whole numbers at one time (e.g in a vector) but the first is much faster because the compiler will expand it to a usual for loop and there is nothing to do with synchronize objects like promise, mutexes and condition variables</p>
<pre><code>template <class T>
class range_iterator
{
private:
T ptr;
template <typename> friend class range_iterator;
public:
constexpr range_iterator() : ptr(0) {}
range_iterator(const range_iterator&) = default;
explicit range_iterator(T p) : ptr(p) {}
template <class U>
constexpr range_iterator(const range_iterator<U>& other) : ptr(other.ptr) {}
range_iterator& operator=(const range_iterator&) = default;
template <class U>
constexpr range_iterator& operator=(const range_iterator<U>& other) { ptr = other.ptr; return *this; }
constexpr range_iterator& operator++() { ++ptr; return *this; }
constexpr range_iterator operator++(int) { range_iterator old_iter(ptr); ++ptr; return old_iter; }
constexpr range_iterator& operator--() { --ptr; return *this; }
constexpr range_iterator& operator--(int) { range_iterator old_iter(ptr); --ptr; return old_iter; }
T operator*() const { return ptr; }
constexpr bool operator==(const range_iterator& other) const { return ptr == other.ptr; }
constexpr bool operator!=(const range_iterator& other) const { return ptr != other.ptr; }
template <class U>
constexpr bool operator==(const range_iterator<U>& other) const { return ptr == other.ptr; }
template <class U>
constexpr bool operator!=(const range_iterator<U>& other) const { return ptr != other.ptr; }
constexpr range_iterator operator+(const range_iterator& other) { return range_iterator(ptr + other.ptr); }
constexpr range_iterator& operator+=(const range_iterator& other) { ptr += other.ptr; return *this; }
constexpr range_iterator operator-(const range_iterator& other) { return range_iterator(ptr - other.ptr); }
constexpr range_iterator& operator-=(const range_iterator& other) { ptr -= other.ptr; return *this; }
template <class U>
constexpr range_iterator operator+(const range_iterator<U>& other) { return range_iterator(ptr + other.ptr); }
template <class U>
constexpr range_iterator& operator+=(const range_iterator<U>& other) { ptr += other.ptr; return *this; }
template <class U>
constexpr range_iterator operator-(const range_iterator<U>& other) { return range_iterator(ptr - other.ptr); }
template <class U>
constexpr range_iterator& operator-=(const range_iterator<U>& other) { ptr -= other.ptr; return *this; }
explicit operator T() const { return ptr; }
void swap(range_iterator& rhs)
{
T temp_ptr = ptr;
ptr = rhs.ptr;
rhs.ptr = temp_ptr;
}
};
template <class T1, class T2>
class range_step_iterator
{
template <typename, typename> friend class range_step_iterator;
private:
T1 ptr;
T2 step;
public:
constexpr range_step_iterator() : ptr(0), step(1) {}
range_step_iterator(const range_step_iterator&) = default;
explicit range_step_iterator(T1 p, T2 s) : ptr(p), step(s) {}
template <class U1, class U2>
constexpr range_step_iterator(const range_step_iterator<U1, U2>& other) : ptr(other.ptr), step(other.step) {}
range_step_iterator& operator=(const range_step_iterator&) = default;
template <class U1, class U2>
constexpr range_step_iterator& operator=(const range_step_iterator<U1, U2>& other) { ptr = other.ptr; step = other.step; return *this; }
constexpr range_step_iterator& operator++() { ptr += step;; return *this; }
constexpr range_step_iterator operator++(int) { range_step_iterator old_iter(ptr, step); ptr += step; return old_iter; }
constexpr range_step_iterator& operator--() { ptr -= step; return *this; }
constexpr range_step_iterator& operator--(int) { range_step_iterator old_iter(ptr, step); ptr -= step; return old_iter; }
T1 operator*() const { return ptr; }
constexpr bool operator==(const range_step_iterator& other) const { return ptr == other.ptr; }
constexpr bool operator!=(const range_step_iterator& other) const { return ptr != other.ptr; }
template <class U1, class U2>
constexpr bool operator==(const range_step_iterator<U1, U2>& other) const { return ptr == other.ptr; }
template <class U1, class U2>
constexpr bool operator!=(const range_step_iterator<U1, U2>& other) const { return ptr != other.ptr; }
constexpr bool operator==(T1 other) const { return ptr == other; }
constexpr bool operator!=(T1 other) const { return ptr != other; }
constexpr range_step_iterator operator+(const range_step_iterator& other) const { return range_step_iterator(ptr + other.ptr, step); }
constexpr range_step_iterator& operator+=(const range_step_iterator& other) { ptr += other.ptr; return *this; }
constexpr range_step_iterator operator-(const range_step_iterator& other) const { return range_step_iterator(ptr - other.ptr, step); }
constexpr range_step_iterator& operator-=(const range_step_iterator& other) { ptr -= other.ptr; return *this; }
template <class U1, class U2>
constexpr range_step_iterator operator+(const range_step_iterator<U1, U2>& other) const { return range_step_iterator(ptr + other.ptr); }
template <class U1, class U2>
constexpr range_step_iterator& operator+=(const range_step_iterator<U1, U2>& other) { ptr += other.ptr; return *this; }
template <class U1, class U2>
constexpr range_step_iterator operator-(const range_step_iterator<U1, U2>& other) const { return range_step_iterator(ptr - other.ptr); }
template <class U1, class U2>
constexpr range_step_iterator& operator-=(const range_step_iterator<U1, U2>& other) { ptr -= other.ptr; return *this; }
explicit operator T1() const { return ptr; }
void swap(range_step_iterator& rhs)
{
T1 temp_ptr = ptr;
T2 temp_step = step;
ptr = rhs.ptr;
step = rhs.step;
rhs.ptr = temp_ptr;
rhs.step = temp_step;
}
template <class U1, class U2>
void swap(range_step_iterator<U1, U2>& rhs)
{
T1 temp_ptr = ptr;
T2 temp_step = step;
ptr = rhs.ptr;
step = rhs.step;
rhs.ptr = temp_ptr;
rhs.step = temp_step;
}
};
namespace std
{
template <class T>
void swap(range_iterator<T>& lhs, range_iterator<T>& rhs)
{
lhs.swap(rhs);
}
template <class T1, class T2, class U1, class U2>
void swap(range_step_iterator<T1, T2>& lhs, range_step_iterator<U1, U2>& rhs)
{
lhs.swap(rhs);
}
template <class T>
void swap(reverse_range_iterator<T>& lhs, reverse_range_iterator<T>& rhs)
{
lhs.swap(rhs);
}
};
template <class T1, class T2>
class range_1_step
{
static_assert(std::is_integral_v<T1> && std::is_integral_v<T2>, "T1 and T2 must be an integral type");
private:
range_iterator<T1> from_iter;
range_iterator<T2> to_iter;
public:
constexpr range_1_step(T1 from, T2 to) : from_iter(from), to_iter(to) { if (from >= to) from_iter = to_iter; }
constexpr range_iterator<T1> begin() const { return range_iterator<T1>(from_iter); }
constexpr range_iterator<T2> end() const { return range_iterator<T2>(to_iter); }
constexpr bool empty() const { return from_iter == to_iter; }
constexpr T1 size() const { return T1(to_iter - from_iter); }
};
template <class T1, class T2, class T3>
class range_step
{
static_assert(std::is_integral_v<T1> && std::is_integral_v<T2> && std::is_integral_v<T3>, "T1 and T2 and T3 must be an integral type");
using iterator = typename range_step_iterator<T1, T3>;
iterator from_iter;
iterator to_iter;
public:
constexpr range_step(T1 from, T2 to, T3 step) : from_iter(from, step), to_iter(to, step)
{
if (!step)
throw std::runtime_error("step can't be zero");
if ((from > to && step > 0) || (from < to && step < 0)) from_iter = to_iter;
}
constexpr iterator begin() const { return from_iter; }
constexpr iterator end() const { return to_iter; }
constexpr bool empty() const { return from_iter == to_iter; }
constexpr T1 size() const { return T1(to_iter - from_iter); }
};
template <class T1, class T2, class T3>
auto range(T1 from, T2 to, T3 step)
{
return range_step(from, to, step);
}
template <class T1, class T2>
auto range(T1 from, T2 to)
{
return range_1_step(from, to);
}
template <class T>
auto range(T to)
{
return range_1_step((T)0, to);
}
template <class T1, class T2 = T1, class T3 = T1>
std::experimental::generator<T1> lazy_range(T1 from, T2 to, T3 step)
{
for (; from < to; from += step)
co_yield from;
}
template <class T1, class T2 = T1>
std::experimental::generator<T1> lazy_range(T1 from, T2 to)
{
for (; from < to; ++from)
co_yield from;
}
template <class T>
std::experimental::generator<T> lazy_range(T to)
{
for (T i = 0; i < to; ++i)
co_yield i;
}
</code></pre>
<p>usage example :</p>
<pre><code>int main()
{
auto print_duration = [](long long nano_dur)
{
std::cout << "[*] it took " << nano_dur << " nano => " << nano_dur / 1000 << " micro => "
<< nano_dur / 1000000 << " milli => " << nano_dur / 1000000000 << " sec" << endl;
};
const unsigned long long iterations = 100000;
unsigned long long sub = 0;
std::chrono::time_point t1 = std::chrono::high_resolution_clock::now();
for (auto i : range(iterations))
sub += i;
std::chrono::time_point t2 = std::chrono::high_resolution_clock::now();
auto dur = t2 - t1;
print_duration(dur.count());
t1 = std::chrono::high_resolution_clock::now();
for (auto i : lazy_range(iterations))
sub += i;
t2 = std::chrono::high_resolution_clock::now();
auto dur2 = t2 - t1;
print_duration(dur2.count());
if (dur2 > dur)
cout << "coroutine is slower " << endl;
else
cout << "coroutine is faster" << endl;
}
</code></pre>
<p>from this sample the range function is much much faster than lazy range function but the gap goes some small if I use the variable sub because in the above code the compiler may have optimized the whole loop in the first case but it couldn't in the second , but the difference is still much big</p>
<p>some missing points :</p>
<ul>
<li><p>the result type in the iteration is only the first type given to the function , so one should take care of the type he is using</p></li>
<li><p>I couldn't reverse the the range with the same behavior of other containers because range(0, 10) gives : (0 ... 9) but reverse_range(0, 10) gives (10 ... 1) using the reverse iterators that I'm working on</p></li>
</ul>
<p>this is because the compiler converts :</p>
<pre><code>for (int i = 0; i != 10; ++i) {}
</code></pre>
<p>to :</p>
<pre><code>for (int i = 10; i != 0; --i) {}
</code></pre>
<p>so the second is not the reverse of the first but I think it isn't very bad anyway</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T18:10:42.577",
"Id": "443381",
"Score": "0",
"body": "It is more likely that the compiler converts it to `for (int i = 11; --i; )` since most computers have a decrement and test instruction."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T18:11:45.703",
"Id": "443382",
"Score": "0",
"body": "What kind of review are you asking for specifically?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T18:55:38.127",
"Id": "443385",
"Score": "0",
"body": "I am not sure . I wrote the code and wanted to share it so someone code benefit from it or build something upon it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T10:34:54.790",
"Id": "444726",
"Score": "0",
"body": "@dev65 your question is accumulating close votes because it is unclear what you are asking: if you could add a paragraph to the answer discussing the context in which you would use these, and explaining whether you want a comparative review or a general review of both methods then that should help. (Note: be sure to put such information in the answer rather than in comments: comments have a habit of disappearing and not everyone will read them)"
}
] |
[
{
"body": "<p>This is undefined behavior:</p>\n\n<pre><code>namespace std\n{\n template <class T>\n void swap(range_iterator<T>& lhs, range_iterator<T>& rhs)\n {\n lhs.swap(rhs);\n }\n\n template <class T1, class T2, class U1, class U2>\n void swap(range_step_iterator<T1, T2>& lhs, range_step_iterator<U1, U2>& rhs)\n {\n lhs.swap(rhs);\n }\n\n template <class T>\n void swap(reverse_range_iterator<T>& lhs, reverse_range_iterator<T>& rhs)\n {\n lhs.swap(rhs);\n }\n\n};\n</code></pre>\n\n<p>You should never overload <code>swap</code> in the <code>std</code> namespace. Instead, the <code>swap</code> should be overloaded in the same namespace as the type to be swapped. This allows correct usage of <code>swap</code> to find the version with ADL.</p>\n\n<p>This is wrong:</p>\n\n<pre><code>void swap(range_iterator& rhs)\n{\n T temp_ptr = ptr;\n ptr = rhs.ptr;\n rhs.ptr = temp_ptr;\n}\n</code></pre>\n\n<p>it should be</p>\n\n<pre><code>using std::swap;\nswap(ptr, rhs.ptr);\n</code></pre>\n\n<p>instead. Same for the other <code>swap</code> functions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T04:31:01.040",
"Id": "229046",
"ParentId": "227663",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T14:13:46.403",
"Id": "227663",
"Score": "1",
"Tags": [
"c++",
"iterator",
"c++17"
],
"Title": "c++ python like range function to use in for loops"
}
|
227663
|
<p>The following class is set of functions I use for web development(examples below) and I was wondering how to structure it. </p>
<p>Examples:</p>
<pre><code>//Checking if user isn't admin so that he can access login page
$helper = new Base();
if ($helper->is_admin()) {
$helper->location("index.php");
}
//Encoding output to prevent XSS
$html = "<script>alert("XSS")</script>";
echo "<h1>". $helper->clean_html($html) ."</h1>";
//Redirect to another webpage and exit
$helper->location("error.php");
</code></pre>
<p>Is having just one class for all simple functions the correct way?</p>
<pre><code><?php
class Base
{
public function __construct()
{
session_start();
}
public function location($dir = "index.php")
{
header("Location: ".$dir);
exit();
}
public function is_logged_in() {
return (isset($_SESSION['logged_in']) && $_SESSION['logged_in']);
}
public function is_admin() {
return (isset($_SESSION['admin']) && $_SESSION['admin']);
}
/*
* Clean functions para prevenir XSS
*/
public function clean_html($html) {
return htmlspecialchars($html, ENT_QUOTES, 'utf-8');
}
public function clean_json($json) {
return json_encode($json, JSON_HEX_QUOT|JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS);
}
/*
* Check functions
*/
public function check_token($token, $dir)
{
if ($token != $_SESSION["csrf_token"]) {
$this->location($dir);
}
}
public function check_login($dir)
{
if (!$this->is_logged_in()) {
$this->location($dir);
}
}
public function check_admin($dir)
{
if (!$this->is_admin()) {
$this->location($dir);
}
}
public function check_input($required, $erro)
{
foreach ($required as $field) {
if (!empty($_POST[$field])) {
$this->location($erro);
}
}
}
}
</code></pre>
<p>Or since the check functions build on previous functions should I structure it the following way:<br>
Base class:</p>
<pre><code><?php
class Base
{
public function __construct()
{
session_start();
}
public function location($dir = "index.php")
{
header("Location: ".$dir);
exit();
}
public function is_logged_in() {
return (isset($_SESSION['logged_in']) && $_SESSION['logged_in']);
}
public function is_admin() {
return (isset($_SESSION['admin']) && $_SESSION['admin']);
}
/*
* Clean functions para prevenir XSS
*/
public function clean_html($html) {
return htmlspecialchars($html, ENT_QUOTES, 'utf-8');
}
public function clean_json($json) {
return json_encode($json, JSON_HEX_QUOT|JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS);
}
}
</code></pre>
<p>And<br>
Helper class:</p>
<pre><code><?php
class Helper extends Base
{
protected $base;
public function __construct()
{
$this->base = new Base;
}
public function check_token($token, $dir)
{
if ($token != $_SESSION["csrf_token"]) {
$this->base->location($dir);
}
}
public function check_login($dir)
{
if (!$this->base->is_logged_in()) {
$this->base->location($dir);
}
}
public function check_admin($dir)
{
if (!$this->base->is_admin()) {
$this->base->location($dir);
}
}
public function check_input($required, $erro)
{
foreach ($required as $field) {
if (!empty($_POST[$field])) {
$this->base->location($erro);
}
}
}
}
</code></pre>
<p>Second Version made after reading the comments
What can I do to improve it further</p>
<p>Base:</p>
<pre><code>/*
* Miscellaneous functions
*/
class Base
{
public static function location($dir = "index.php")
{
header("Location: ".$dir);
exit();
}
public static function check_input($required, $error)
{
foreach ($required as $field) {
if (empty($_POST[$field])) {
Base::location($error);
}
}
}
}
</code></pre>
<p>Session:</p>
<pre><code>/*
* Session handling class
*/
class Session
{
public function __construct()
{
session_start();
}
public function initialize_user_session($admin, $user_id) {
$_SESSION["admin"] = $admin;
$_SESSION["loggedIn"] = true;
$_SESSION["user_id"] = $user_id;
$_SESSION["csrf_token"] = bin2hex(random_bytes(32));
}
public function logout(){
session_destroy();
exit();
}
public function is_logged_in() {
return (!empty($_SESSION['logged_in']));
}
public function is_admin() {
return (!empty($_SESSION['admin']));
}
/*
* Check functions
*/
public function check_token($token, $dir)
{
if ($token != $_SESSION["csrf_token"]) {
Base::location($dir);
}
}
public function check_login($dir)
{
if (empty($_SESSION['logged_in'])) {
Base::location($dir);
}
}
public function check_admin($dir)
{
if (empty($_SESSION['admin'])) {
Base::location($dir);
}
}
}
</code></pre>
<p>Inpu_Encoding:</p>
<pre><code>/*
* Functions to prevent XSS
*/
class Input_Encoding
{
public static function clean_html($html) {
return htmlspecialchars($html, ENT_QUOTES, 'utf-8');
}
public static function clean_json($json) {
return json_encode($json, JSON_HEX_QUOT|JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T14:42:48.833",
"Id": "443353",
"Score": "3",
"body": "Where is the function `session_start()` defined? Is this working code, or is it hypothetical? We can only review working code on code review. Hypothetical questions are off-topic and may be closed. Please see our guidelines at https://codereview.stackexchange.com/help/dont-ask and https://codereview.stackexchange.com/help/how-to-ask."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T15:06:11.203",
"Id": "443356",
"Score": "5",
"body": "Both versions work. session_start() is php standart function https://www.php.net/manual/en/function.session-start.php"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T19:36:19.490",
"Id": "443389",
"Score": "0",
"body": "I thought a class would be more organized and systematized way of keeping my code clean and functional"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T14:45:59.013",
"Id": "443449",
"Score": "2",
"body": "The title and perhaps the first paragraph should tell us what the code is used for rather than asking the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T17:15:04.673",
"Id": "443629",
"Score": "2",
"body": "Is this better @200_success @pacmaninbw?"
}
] |
[
{
"body": "<p>If you let me to be frank, this is not a class but rather a ratatouille - that is a random collection of functions. </p>\n\n<p>I do understand your idea and a chain of thoughts and in a way you are trying to do the right thing - to achieve the main goal of every programmer - to reduce the amount of code written. And it's for the good you started with OOP.</p>\n\n<p>However, there are common pitfalls on this road, and you didn't miss any of them.</p>\n\n<p>Ironically, the most natural part of OOP - inheritance - should be avoided as much as possible. It's a very dangerous practice that will lead to spaghetti code despite being OOP. </p>\n\n<p>Instead, the first OOP rule you should learn and implement is the Single responsibility principle. As soon as you grasp it, you will see that your lass is an Irish stew consisting of every task your program is about to perform. This is not OOP.</p>\n\n<p>Although I understand your intention to have helper methods in all your classes, it is not an excuse for having such a mess. But there is a solution called \"composition over inheritance\". If you need some service, it has to be <em>injected</em> in your class, not inherited from a parent.</p>\n\n<p>So, now I can tell that you started to move into the right direction. But still such a decomposition you did already is not enough:</p>\n\n<ul>\n<li>There are functions related to processing the user input - they should go into a distinct class</li>\n<li>There are functions related to user user authorization - they should go into a distinct class</li>\n<li>There are functions related to HTML/JSON output - they should go into a distinct class</li>\n</ul>\n\n<p>In the end there will be no Base class but several other classes each related to its particular niche. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T16:55:40.710",
"Id": "443618",
"Score": "0",
"body": "How do I inject a method? Declaring it a `public static function`?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T13:54:04.030",
"Id": "227723",
"ParentId": "227664",
"Score": "7"
}
},
{
"body": "<blockquote>\n <p>Or since the check functions build on previous functions should I structure it the following way</p>\n</blockquote>\n\n<p>This is not a case that makes you go for inheritance. You should go for inheritance to solve the problem of \"repeating same properties in more than 1 class\", for example, you have 2 classes <code>Lion</code> and <code>Cheetah</code></p>\n\n<pre><code>class Lion{\n protected $speed;\n protected $age;\n protected $home;\n protected $sex;\n protected $preferredPrey;\n\n protected $maneColor;\n} \n\nclass Cheetah{\n protected $speed;\n protected $age;\n protected $home;\n protected $sex;\n protected $preferredPrey;\n\n protected $eyeStripesThickness;\n} \n</code></pre>\n\n<p>Instead of doing that you go with this:</p>\n\n<pre><code>class Predator{\n protected $speed;\n protected $age;\n protected $home;\n protected $sex;\n protected $preferredPrey;\n} \nclass Lion extends Predator{\n protected $maneColor;\n}\nclass Cheetah extends Predator{\n protected $eyeStripesThickness;\n}\n</code></pre>\n\n<p>As you see, this solved the problem of repeating the same properties in the classes, and of course to repeat the same <strong>changes</strong> you made to a property that is shared between the <code>Lion</code> and <code>Cheetah</code>, now if you need to add, remove, change a property between <code>Lion</code> and <code>Cheetah</code> do it in only 1 place i.e. \"The parent class\". That makes your code <em>crazy</em>-easier to maintain and organized. Think of:</p>\n\n<pre><code>Animal\nAnimal>Predator\nAnimal>prey\nAnimal>marine\nAnimal>Predator>Lion\nAnimal>Predator>Cheetah\nAnimal>prey>gazelle\nAnimal>prey>Goat\nAnimal>marine>Dolphin\n</code></pre>\n\n<h3>Back to your question, <code>Base</code> or <code>Base</code> and <code>Helper</code> ?</h3>\n\n<p>Do you have, or will have another Class that will extend <code>Base</code> other than <code>Helper</code>? I guess \"no\" , so there is no need for this <code>Helper</code> class.</p>\n\n<h3>Other notes on the code</h3>\n\n<ul>\n<li><p>As said by the earlier answer this is just a class that groups some function that you need to use in your projects to reduce your coding (your own framework), it has no properties, just a group of random functions.</p></li>\n<li><p>The functions that don't need the object, better to be <strong>static</strong>, so you can call them without creating the object and calling it's <code>__construct</code> function, for example <code>location</code>, <code>clean_html</code> , <code>clean_json</code> all don't depend on the object, so make them static so you can call them without creating the object - e.g.</p>\n\n<pre><code>public static function clean_html($html) {\n return htmlspecialchars($html, ENT_QUOTES, 'utf-8');\n}\n</code></pre></li>\n<li><p>This</p>\n\n<pre><code>isset($_SESSION['admin']) && $_SESSION['admin'])\n</code></pre>\n\n<p>can be replaced with this</p>\n\n<pre><code>!empty($_SESSION['admin'])\n</code></pre></li>\n<li><p>The class is using <code>$_SESSION['admin']</code> and <code>$_SESSION['logged_in']</code> but it doesn't set them. It's better to also include functions that set these variables in this class, so the maintainer of your class in the future (you or someone else) can edit the class without depending on the outside world of the class, make it self-contained and ask yourself </p>\n\n<blockquote>\n <p>\"If I edited this class later will I have to go <strong>outside</strong> the class to check something ?\"</p>\n</blockquote></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T15:22:10.947",
"Id": "443594",
"Score": "0",
"body": "Amazing answer, I'm just learning and this helped a lot I'll post a improved version later. About `isset($_SESSION['admin']) && $_SESSION['admin'])` I guess you are right but isn't `!empty($_SESSION['admin'])` the same as `$_SESSION['admin']` and if so shouldn't I use the latter?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T15:25:19.393",
"Id": "443596",
"Score": "1",
"body": "If you did `if ($_SESSION['admin']){..}` directly you can get Undefined index warning, but `if (!empty($_SESSION['admin']))` checks if the variables **is set** and not empty, so you never get Undefined index warnings."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T15:41:44.677",
"Id": "227732",
"ParentId": "227664",
"Score": "4"
}
},
{
"body": "<p>Here is another thing I noticed about your code:</p>\n\n<p>If $helper is not the admin, you did not specify what will happen so I suggest that you modify it like this:</p>\n\n<pre><code>if($helper->is_admin()) {\n go to admin panel\n} else {\n go to normal user panel\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-27T06:57:09.513",
"Id": "455363",
"Score": "2",
"body": "Welcome to Code Review! Based on the implementation of `Base::location()` (which redirects and calls `exit`) the code is basically setup in an if/else pattern, where the `else` case redirects to `error.php`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-27T02:34:07.917",
"Id": "233037",
"ParentId": "227664",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T14:34:53.173",
"Id": "227664",
"Score": "5",
"Tags": [
"php",
"object-oriented",
"comparative-review"
],
"Title": "PHP classes with functions used for building a web application"
}
|
227664
|
<p>I have completed this mockup eCommerce app using pure Vanilla Javascript. This version can add product into shopping cart and automatically calculate the order summary in the shopping cart. It can also delete one item and all items in the shopping cart.</p>
<p>Certain function like checkout,payment,login,update quantity in cart are not included. </p>
<p>Known bugs are duplicate item will be still added when you add same product into cart. </p>
<p>Appreciate all comments and code review especially on Javascript and coding style and best practices. Thanks a lot in advance.</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>// Bugs
// 1. If a product already added into shopping cart, and add again.
// there will be duplicate.
var productList = [
{ id: 101, product: "Logitech Mouse", unitprice: 45.0 },
{ id: 102, product: "Logitech Keyboard", unitprice: 50.0 },
{ id: 103, product: "HP Mouse", unitprice: 35.0 },
{ id: 104, product: "HP Keyboard", unitprice: 32.0 },
{ id: 105, product: "Microsoft Mouse", unitprice: 43.0 },
{ id: 106, product: "Microsoft Keyboard", unitprice: 39.0 }
];
var cart = [];
const createCartHTMLElements = object => {
// Check type
if (typeof object !== "object") return false;
// Start our HTML
var html =
"<table><tbody><tr>\
<td>Product</td>\
<td>Price</td>\
<td>Unit</td>\
<td>Total</td>\
<td></td></tr>";
// Loop through members of the object
object.forEach(function(item) {
html += `<tr><td>${item.product}</td>\
<td>${item.unitprice.toFixed(2)}</td>\
<td><button>+</button>${item.quantity}<button>-</button></td>\
<td>${item.total.toFixed(2)}</td>\
<td><i class="fa fa-remove del" data-id="${item.id}"></i></td>\
</tr>`;
});
// Finish the table:
html += "</tbody></table>";
// Return the table
return html;
};
document.getElementById("clearAll").addEventListener(
"click",
function() {
document.getElementById("shoppingCart").innerHTML = "";
cart.length = 0;
document.getElementById("clearAll").style.display = "none";
document.getElementById("summary").style.display = "none";
updateOrderSummary();
},
false
);
// false means preventdefault.
// sometimes by default, it will trigger other thing
const populateProducts = arrOfObjects => {
// Start our HTML
var html = "";
// Loop through members of the object
arrOfObjects.forEach(function(item) {
html += `<div class="column"><div class="card">\
<h2>${item.product}</h2>
<p class="price">RM ${item.unitprice.toFixed(2)}</p>
<p><button class=AddToCart data-id="${
item.id
}">Add to Cart</button></p>\
</div></div>`;
});
return html;
};
const updateOrderSummary = () => {
//if (cart.length > 0) {
document.getElementById("totalItem").innerHTML = cart.length + " item";
const subTotal = cart
.reduce(function(acc, obj) {
return acc + obj.total;
}, 0)
.toFixed(2);
const shippingFee = 10;
document.getElementById("subTotal").innerHTML = subTotal;
document.getElementById("shippingFee").innerHTML = shippingFee.toFixed(2);
document.getElementById("total").innerHTML = (
parseInt(subTotal) + shippingFee
).toFixed(2);
//}
};
window.addEventListener("load", function() {
document.getElementById("shoppingCartContainer").style.display = "none";
window.setTimeout(function() {}, 1000); // prevent flickering
document.getElementById("productRow").innerHTML = populateProducts(
productList
);
var addToCart = document.getElementsByClassName("AddToCart");
Array.prototype.forEach.call(addToCart, function(element) {
element.addEventListener("click", function() {
debugger;
// Filter the selected "AddToCart" product from the ProductList list object.
// And push the selected single product into shopping cart list object.
productList.filter(prod => {
if (prod.id == element.dataset.id) {
prod.quantity = 1;
prod.total = prod.unitprice;
cart.push(prod);
document.getElementById(
"shoppingCart"
).innerHTML = createCartHTMLElements(cart);
CreateDeleteEventListener();
document.getElementById("clearAll").style.display = "block";
document.getElementById("summary").style.display = "block";
updateOrderSummary();
return;
}
});
});
});
function CreateDeleteEventListener() {
var del = document.getElementsByClassName("del");
Array.prototype.forEach.call(del, function(element) {
element.addEventListener("click", function() {
debugger;
console.log(element.dataset.id);
cart = cart.filter(function(el) {
return el.id != element.dataset.id;
});
if (cart.length === 0) {
document.getElementById("shoppingCart").innerHTML = "";
debugger;
document.getElementById("clearAll").style.display = "none";
document.getElementById("summary").style.display = "none";
}
updateOrderSummary();
element.closest("tr").remove();
});
});
}
});
document.getElementById("cartIcon").addEventListener("click", function() {
var x = document.getElementById("shoppingCartContainer");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.card {
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
margin: auto;
text-align: center;
font-family: arial;
width: 18em;
}
.price {
color: grey;
font-size: 1.5em;
}
.card button {
border: none;
outline: 0;
padding: 12px;
color: white;
background-color: #000;
text-align: center;
cursor: pointer;
width: 100%;
font-size: 1em;
}
.card button:hover {
opacity: 0.7;
}
.some-page-wrapper {
margin: 15px;
}
.summaryDetails {
width: 100px;
text-align: right;
}
#productRow {
display: flex;
flex-wrap: wrap;
}
.column {
flex: 1;
margin-top: 12px;
}
@media (max-width: 1333px) {
.column {
flex-basis: 33.33%;
}
}
@media (max-width: 1073px) {
.column {
flex-basis: 33.33%;
}
}
@media (max-width: 815px) {
.column {
flex-basis: 50%;
}
}
@media (max-width: 555px) {
.column {
flex-basis: 100%;
}
}
#header {
width: 100%;
display: flex;
justify-content: space-between;
height: 50px;
}
#left,
#right {
width: 30%;
padding: 10px;
}
#right {
text-align: right;
}
#main {
max-width: 1000px;
border: 1px solid black;
margin: 0 auto;
position: relative;
}
#shoppingCartContainer {
width: 300px;
background-color: lightyellow;
border: 1px solid silver;
margin-left: auto;
position: absolute;
top: 50px;
right: 0;
padding: 10px;
}
.fa-shopping-cart {
font-size: 36px;
color: blue;
cursor: pointer;
}
.fa-remove {
font-size: 24px;
color: red;
cursor: pointer;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
/>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div id="main">
<div id="header">
<div id="left">Login as Joe Doe, <a href="">Logout</a></div>
<div id="right">
<i id="cartIcon" class="fa fa-shopping-cart"></i>
</div>
</div>
<hr />
<div class="some-page-wrapper">
<div id="productRow"></div>
</div>
<div id="shoppingCartContainer">
<div id="shoppingCart"></div>
<button id="clearAll">Clear Cart</button>
<div id="summary">
<hr />
<h3>Order Summary</h3>
<table>
<tr>
<td>Subtotal (<span id="totalItem"></span>)</td>
<td class="summaryDetails"><span id="subTotal"></span></td>
</tr>
<tr>
<td>Shipping Fee</td>
<td class="summaryDetails"><span id="shippingFee"></span></td>
</tr>
<tr>
<td>Total</td>
<td class="summaryDetails"><span id="total"></span></td>
</tr>
</table>
<button>Proceed to checkout</button>
</div>
</div>
</div>
</body>
</html>
<script src="app.js"></script></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T07:27:19.653",
"Id": "443415",
"Score": "3",
"body": "@Toby Speight This question is attracting close votes because there are known bugs in it. Code should be working as intended in order to be on-topic for this site. On the other hand, if you hadn't mentioned the bugs, there would be no issue. You are being honest, I give you that. This is the best meta post I could find (https://codereview.meta.stackexchange.com/a/8581/200620)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T19:25:04.013",
"Id": "443484",
"Score": "1",
"body": "Rolled back to a previous edit; the fix to having bugs isn't to not tell us, its to resolve the bugs and edit the question. If the bug is not actually a bug (e.g. a feature that you have left out of scope for your current version), then you should clarify that instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T02:08:39.927",
"Id": "443511",
"Score": "0",
"body": "I have fixed the bug. Should I update it or create a new post?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T11:25:49.260",
"Id": "444728",
"Score": "1",
"body": "It's better to edit and make an off-topic question on-topic than to have two questions, one of which needs to be closed and deleted."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T15:18:35.560",
"Id": "227667",
"Score": "1",
"Tags": [
"javascript",
"html",
"css"
],
"Title": "eCommerce Mockup App in Vanilla Javascript"
}
|
227667
|
<p>I have made a little game in JS. Are there any remarks? The game asks a question through the console and accepts the answer through prompt. If the answer is correct you'll get points. To stop the game you need to write <em>exit</em>.</p>
<p>These are the game rules: </p>
<blockquote>
<p>Let's build a fun quiz game in the console!</p>
<ol>
<li><p>Build a function constructor called Question to describe a question. A question should include:<br>
a) question itself<br>
b) the answers from which the player can choose the correct one (choose an adequate data structure here, array, object, etc.)<br>
c) correct answer (I would use a number for this)</p></li>
<li><p>Create a couple of questions using the constructor</p></li>
<li><p>Store them all inside an array</p></li>
<li><p>Select one random question and log it on the console, together with the possible answers (each question should have a number) (Hint: write
a method for the Question objects for this task).</p></li>
<li><p>Use the 'prompt' function to ask the user for the correct answer. The user should input the number of the correct answer such as you
displayed it on Task 4.</p></li>
<li><p>Check if the answer is correct and print to the console whether the answer is correct ot nor (Hint: write another method for this).</p></li>
<li><p>Suppose this code would be a plugin for other programmers to use in their code. So make sure that all your code is private and doesn't
interfere with the other programmers code (Hint: we learned a special
technique to do exactly that).</p></li>
<li><p>After you display the result, display the next random question, so that the game never ends (Hint: write a function for this and call it
right after displaying the result)</p></li>
<li><p>Be careful: after Task 8, the game literally never ends. So include the option to quit the game if the user writes 'exit' instead of the
answer. In this case, DON'T call the function from task 8.</p></li>
<li><p>Track the user's score to make the game more fun! So each time an answer is correct, add 1 point to the score (Hint: I'm going to use
the power of closures for this, but you don't have to, just do this
with the tools you feel more comfortable at this point).</p></li>
<li><p>Display the score in the console. Use yet another method for this.</p></li>
</ol>
</blockquote>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var Question = function(question , answer1 , answer2, answer3 , correctAnswer) {
this.question = question;
this.answer1 = answer1;
this.answer2 = answer2;
this.answer3 = answer3;
this.correctAnswer = correctAnswer;
this.askQuestion = function() {
console.log(this.question);
console.log(this.answer1);
console.log(this.answer2);
console.log(this.answer3);
}
this.chekQuestion = function(){
var answerQuestion = prompt('Answer the question');
console.log(answerQuestion);
if (answerQuestion == this.correctAnswer ){
console.log(answerQuestion + '--- is correct answer');
scorePlayer ++;
console.log("Your score is ---" + scorePlayer);
initGame()
} else if (answerQuestion == "exit"){
alert('game is stopped');
}else {
console.log(answerQuestion + '--- wrong answer')
console.log("Your score is ---" + scorePlayer);
initGame()
}
}
}
var authorOfCourseQuestion = new Question('Who is an author of course?', '0:John' ,'1:Jane' ,'2:Jonas', '2');
var whatIsJS = new Question('What is JS for you?', '0:fun' ,'1:boring' ,'2:not interesting', '0');
var whatIsAFunctionInJS = new Question('What a function in JS?', '0:string' ,'1:obj' ,'2:number', '1');
var arrayQuestions = [authorOfCourseQuestion , whatIsJS , whatIsAFunctionInJS ];
var scorePlayer = 0;
function initGame() {
var randomNumber = Math.floor(Math.random()*3);
arrayQuestions[randomNumber].askQuestion();
arrayQuestions[randomNumber].chekQuestion();
}
initGame();</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Section 5: Advanced JavaScript: Objects and Functions</title>
</head>
<body>
<h1>Section 5: Advanced JavaScript: Objects and Functions</h1>
<script src="script.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>Your layout is all over the place. Sometimes, you indent by 8 spaces, sometimes by 4. Sometimes, you have whitespace around <code>else</code> on both sides, sometimes only on the right. Sometimes, you have whitespace around <code>,</code> on both sides, sometimes only on the right. Sometimes, you have one space before and after an operator, sometimes none, sometimes, you have two spaces after an operator. Be consistent!</p>\n\n<p>Consistency is important, because if you express the same thing in two different ways, a reader of the code will think that you wanted to express two different things, and they will waste time wondering what the difference is.</p>\n\n<p>You have empty lines to break your code up into logical units, but they are in weird places, such as before an <code>else</code> or before a closing curly brace.</p>\n\n<p>Sometimes, you use semicolon, sometimes you don't.</p>\n\n<p>You should be consistent and follow a fixed set of rules. Ideally, you should use an automated tool to format your code, so that you don't have to make those decisions at all.</p>\n\n<p>For example, <code>jslint</code> with default settings detects 3 errors and then stops and doesn't even parse the whole file, <code>jshint</code> with the default settings detects 6 errors, and <code>eslint</code> with some reasonable settings detects a whopping 63 errors and 14 warnings. With <em>my</em> settings, the numbers are even worse: 20 errors for <code>jshint</code> and 155(!!!) for <code>eslint</code>. You should always use a linter and make sure that your code is lint-clean.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T16:52:02.880",
"Id": "227674",
"ParentId": "227668",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227674",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T15:33:49.120",
"Id": "227668",
"Score": "1",
"Tags": [
"javascript",
"quiz"
],
"Title": "Browser quiz game"
}
|
227668
|
<p>I'm trying out a new editor (CLion) and I decided to try an old well known programming problem. I also decided to try out C99 rather than C89.</p>
<p>This program calculates the nth term of the <a href="https://www.mathsisfun.com/numbers/fibonacci-sequence.html" rel="nofollow noreferrer">Fibonacci Sequence</a> where the value of the current term is the sum of the 2 previous terms. The first 4 terms are 0, 1, 1, 2. The upper limit applied in the program is the 91st term, on my computer using <code>long long</code> the term value goes negative at 93rd term.</p>
<p>All Comments and observations are appreciated. I'm especially interested in performance, function and variable names and suggestions about how I can increase the range of terms using integers. I know I can use doubles but that may incur floating point errors at some point. As far as performance goes, the program has a nice small memory signature (0.5% of the system memory) speed is where I would be worried.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
static const int MinimumTerm = 0;
static const int MaximumTerm = 91;
static const int MaxTries = 3;
static const int inputFailure = -1;
static int getTermCount()
{
char *fmtstr = "Please enter an integer value between %d and %d\n";
printf(fmtstr, MinimumTerm, MaximumTerm);
int term = 0;
int count = 0;
do
{
scanf("%d", &term);
if (count < MaxTries)
{
if (term < MinimumTerm || term > MaximumTerm)
{
fprintf(stderr, fmtstr, MinimumTerm, MaximumTerm);
}
}
else
{
return inputFailure;
}
count++;
} while (term < MinimumTerm || term > MaximumTerm);
return term;
}
static long long getNthFibonacciTerm(int term)
{
int termCount = 2;
long long prevValue = 0;
long long nthValue = 1;
switch (term)
{
case 0: return 0;
case 1: return 1;
}
while (termCount < term)
{
long long newValue = prevValue + nthValue;
prevValue = nthValue;
nthValue = newValue;
termCount++;
}
return nthValue;
}
int main()
{
int term = getTermCount();
if (term < MinimumTerm)
{
fprintf(stderr, "Invalid Input\n");
return EXIT_FAILURE;
}
printf("The %d term of the Fibonacci Sequence is %lld\n", term, getNthFibonacciTerm(term));
return EXIT_SUCCESS;
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>A few points about improving code</p>\n\n<ul>\n<li>It seems that your naming convention for constants is to use a capitalized identifier. If so, that should be applied consistently for all constants including <code>inputFailure</code>.</li>\n<li>The loop in the function <code>getTermCount</code> can be simplified. A for-loop is clearer IMO.</li>\n<li>The output of <code>getNthFibonacciTerm</code> is actually off by one term (assuming the sequence starts with 0 at index 0). It outputs <code>1</code> for input <code>3</code>. The conditional checks before the loop could also be avoided to simplify the code.</li>\n<li>Since the Fibonacci sequence is non-negative, the output could use an unsigned integer to allow slightly larger inputs.</li>\n</ul></li>\n<li><p>About input range: since the output exceeds the limit of <code>unsigned long long</code> when the input is over 93, I do not see how it can be accurately represented unless you try to implement representations of big integers yourself in C.</p></li>\n<li><p>About performance: there are several <span class=\"math-container\">\\$\\Theta(\\log n)\\$</span> algorithms for computing Fibonacci numbers for a given input <span class=\"math-container\">\\$n\\$</span>. If you want that, <a href=\"https://www.geeksforgeeks.org/program-for-nth-fibonacci-number/\" rel=\"nofollow noreferrer\">here</a> is a list of all algorithms.</p></li>\n</ol>\n\n<p>Here is an improved version:</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n\nstatic const int MinimumTerm = 0;\nstatic const int MaximumTerm = 93;\nstatic const int MaxTries = 3;\nstatic const int InputFailure = -1;\n\nstatic int getTermCount()\n{\n const char *fmtstr = \"Please enter an integer value between %d and %d\\n\";\n\n for (int count = 0; count < MaxTries; count++)\n {\n int term;\n\n printf(fmtstr, MinimumTerm, MaximumTerm); // IMO it is fine to just output to stdout before all attempts fail\n scanf(\"%d\", &term);\n if (term >= MinimumTerm && term <= MaximumTerm)\n {\n return term;\n }\n }\n\n return InputFailure;\n}\n\nstatic unsigned long long getNthFibonacciTerm(int term)\n{\n unsigned long long nthValue = 0;\n unsigned long long nextValue = 1; // (n+1)th value, you may find a better name for that\n\n for (int termCount = 0; termCount < term; termCount++)\n {\n unsigned long long newValue = nthValue + nextValue;\n nthValue = nextValue;\n nextValue = newValue;\n }\n\n return nthValue;\n}\n\nint main()\n{\n int term = getTermCount();\n if (term == InputFailure)\n {\n fprintf(stderr, \"Invalid Input\\n\");\n return EXIT_FAILURE;\n }\n\n printf(\"The %d term of the Fibonacci Sequence is %llu\\n\", term, getNthFibonacciTerm(term));\n return EXIT_SUCCESS;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T14:54:07.830",
"Id": "443450",
"Score": "0",
"body": "Thanks for the link to the list of algorithms, I appear to be using a variant of one of them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T14:56:32.527",
"Id": "443451",
"Score": "0",
"body": "Just FYI, on code review providing an alternate solution generally lowers the score you receive in an answer. You did a good job on the observations that start your answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T15:08:54.097",
"Id": "443452",
"Score": "1",
"body": "@pacmaninbw I am relatively new here. I wonder what qualifies as \"an alternate solution\"? Providing a brand new algorithm definitely qualifies. What about small variations that simplify the code logic (like I do here)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T15:22:04.077",
"Id": "443453",
"Score": "2",
"body": "You can provide code that enhances your comments for certain points, such as naming conventions for the constants. Providing a full updated version of the code in the question goes too far. If I was a student that posted the code for my homework or a take home test your answer is definitely too much. Someone might take exception to to the `if` control construct that returns the term from the input because it isn't using a best practice such as always adding braces around the `return term`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T15:28:34.563",
"Id": "443455",
"Score": "0",
"body": "@pacmaninbw Thanks for the clarification. I've added the braces by the way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T16:09:27.607",
"Id": "443460",
"Score": "0",
"body": "Unfortunately, I have seen many occasions an alternative solution got more votes than a thorough review without suggested alternative."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T16:20:30.163",
"Id": "443464",
"Score": "0",
"body": "You might want to look at the discussion in the 2nd Monitor. https://chat.stackexchange.com/rooms/8595/the-2nd-monitor"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T19:51:40.660",
"Id": "227688",
"ParentId": "227678",
"Score": "4"
}
},
{
"body": "<p>Suggest using <code>uint64_t</code> (from the header file: <code>stdint.h</code>) rather than <code>long long</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T22:58:16.457",
"Id": "443398",
"Score": "1",
"body": "Or, for an even greater range, try whether your compiler defines `uint128_t`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T14:10:16.170",
"Id": "443442",
"Score": "0",
"body": "@RolandIllig Apparently my compiler and header file don't include uint128_t."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T22:06:02.673",
"Id": "227692",
"ParentId": "227678",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227688",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T17:49:02.933",
"Id": "227678",
"Score": "2",
"Tags": [
"performance",
"c",
"fibonacci-sequence",
"c99"
],
"Title": "Get the Nth Term in the Fibonacci Sequence"
}
|
227678
|
<p><a href="https://leetcode.com/problems/merge-k-sorted-lists/" rel="nofollow noreferrer">https://leetcode.com/problems/merge-k-sorted-lists/</a></p>
<blockquote>
<p>Merge k sorted linked lists and return it as one sorted list. Analyze
and describe its complexity.</p>
<pre><code>Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
</code></pre>
</blockquote>
<pre><code>using System.Collections.Generic;
using Heap;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LinkedListQuestions
{/// <summary>
/// https://leetcode.com/problems/merge-k-sorted-lists/
/// </summary>
[TestClass]
public class MergeKSortedLists
{
[TestMethod]
public void LeetCodeExample()
{
ListNode l1 = new ListNode(1);
l1.next = new ListNode(4);
l1.next.next = new ListNode(5);
ListNode l2 = new ListNode(1);
l2.next = new ListNode(3);
l2.next.next = new ListNode(4);
ListNode l3 = new ListNode(2);
l3.next = new ListNode(6);
ListNode[] arr = new ListNode[] { l1, l2, l3 };
ListNode res = MergeKSortedListsTest.MergeKLists(arr);
}
}
public class MergeKSortedListsTest
{
public static ListNode MergeKLists(ListNode[] lists)
{
if (lists == null || lists.Length == 0)
{
return null;
}
MinHeap<ListNode> heap = new MinHeap<ListNode>(new ListNodeComparer());
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
foreach (ListNode node in lists)
{
if (node != null)
{
heap.Add(node);
}
}
while (heap.Count > 0)
{
tail.next = heap.ExtractDominating();
tail = tail.next;
if (tail.next != null)
{
heap.Add(tail.next);
}
}
return dummy.next;
}
public class ListNodeComparer : Comparer<ListNode>
{
public override int Compare(ListNode o1, ListNode o2)
{
if (o1.val < o2.val)
return -1;
else if (o1.val == o2.val)
return 0;
else
return 1;
}
}
}
}
</code></pre>
<p>you do not need to review the MinHeap code!</p>
<pre><code> public abstract class Heap<T> : IEnumerable<T>
{
//capacity of the Queue
private const int InitialCapacity = 0;
private int _capacity = InitialCapacity;
//items in the queue
private T[] _heap = new T[InitialCapacity];
//last item in the queue
private int _tail = 0;
//when growing the queue you multiply by Growfactor
private const int GrowFactor = 2;
// if the min size is 0 you grow the queue size by at least Min grow
private const int MinGrow = 1;
//how to compare the keys
protected Comparer<T> Comparer { get; private set; }
//store how many Items are in the queue
public int Count { get { return _tail; } }
//shows the current capacity of the queue
public int Capacity { get { return _capacity; } }
//this function is used in BubbleUp and in GetDominating
protected abstract bool Dominates(T x, T y);
protected Heap() : this(Comparer<T>.Default)
{
}
protected Heap(Comparer<T> comparer) : this(Enumerable.Empty<T>(), comparer)
{
}
protected Heap(IEnumerable<T> collection) : this(collection, Comparer<T>.Default)
{
}
protected Heap(IEnumerable<T> collection, Comparer<T> comparer)
{
if (collection == null)
{
throw new ArgumentNullException("collection");
}
if (comparer == null)
{
throw new ArgumentNullException("comparer");
}
Comparer = comparer;
foreach (var item in collection)
{
if (Count > Capacity)
{
Grow();
}
_heap[_tail++] = item;
}
for (int i = 0; i < Parent(_tail - 1); i++)
{
BubbleDown(i);
}
}
public void Add(T item)
{
if (Count == Capacity)
{
Grow();
}
_heap[_tail++] = item;
BubbleUp(_tail - 1);
}
//when adding a new item we bubble the item from tail-1 up to its'
//correct position
private void BubbleUp(int i)
{
if (i == 0 || Dominates(_heap[Parent(i)], _heap[i]))
{
return; //correct domination (or root)
}
Swap(i, Parent(i));
BubbleUp(Parent(i));
}
// when adding new items into the queue from the CTOR
// we bubble them down
private void BubbleDown(int i)
{
int dominatingNode = Dominating(i);
if (dominatingNode == i)
{
return;
}
Swap(i,dominatingNode);
BubbleDown(dominatingNode);
}
public T GetMin()
{
if (Count == 0)
{
throw new InvalidOperationException("Heap is empty");
}
return _heap[0];
}
private void Swap(int i, int j)
{
T tmp = _heap[i];
_heap[i] = _heap[j];
_heap[j] = tmp;
}
public static int Parent(int i)
{
return (i + 1) / 2 - 1;
}
private void Grow()
{
int newCapcity = _capacity * GrowFactor + MinGrow;
var newHeap = new T[newCapcity];
Array.Copy(_heap, newHeap, _capacity);
_heap = newHeap;
_capacity = newCapcity;
}
//return from 0 up to Count
public IEnumerator<T> GetEnumerator()
{
return _heap.Take(Count).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
//when we bubble down, when building the queue from a list in the CTOR
// we need to understand who is dominating i, and we swap them,
// and call bubbleDown again
private int Dominating(int i)
{
int dominatingNode = i;
dominatingNode = GetDominating(YoungChild(i), dominatingNode);
dominatingNode = GetDominating(OldChild(i), dominatingNode);
return dominatingNode;
}
private int GetDominating(int newNode, int dominatingNode)
{
if (newNode < _tail && !Dominates(_heap[dominatingNode], _heap[newNode]))
{
return newNode;
}
else
{
return dominatingNode;
}
}
private static int YoungChild(int i)
{
return 2 * (i + 1) - 1;
}
private static int OldChild(int i)
{
return YoungChild(i) + 1;
}
public T ExtractDominating()
{
if (Count == 0) throw new InvalidOperationException("Heap is empty");
T ret = _heap[0];
_tail--;
Swap(_tail, 0);
BubbleDown(0);
return ret;
}
}
public class MinHeap<T> : Heap<T>
{
public MinHeap()
: this(Comparer<T>.Default)
{
}
public MinHeap(Comparer<T> comparer)
: base(comparer)
{
}
public MinHeap(IEnumerable<T> collection) : base(collection)
{
}
public MinHeap(IEnumerable<T> collection, Comparer<T> comparer)
: base(collection, comparer)
{
}
protected override bool Dominates(T x, T y)
{
return Comparer.Compare(x, y) <= 0;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>One thing I don't like is, that you merge \"in place\" - that is: the input linked lists change as a side effect. I would expect them to be untouched by the method. Consider to make a new linked list as the result.</p>\n\n<hr>\n\n<p>As a micro optimization you could probably spare a couple of ticks, if the input lists contain a lot of duplicate values, by iterate to the first node with a greater value in the second loop:</p>\n\n<pre><code> while (heap.Count > 0)\n {\n ListNode node = heap.ExtractDominating();\n tail.next = node;\n\n while (node.next != null && node.val == node.next.val)\n {\n node = node.next;\n }\n\n if (node.next != null)\n {\n heap.Add(node.next);\n }\n tail = node;\n\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T15:18:43.503",
"Id": "227729",
"ParentId": "227683",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "227729",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T19:13:58.733",
"Id": "227683",
"Score": "4",
"Tags": [
"c#",
"programming-challenge",
"linked-list",
"mergesort",
"heap"
],
"Title": "LeetCode: Merge k sorted lists C#"
}
|
227683
|
<p>I recently learned about backpropagation online and tried to implement it. I am not sure I have it correct yet. I am confused and would love a second pair of eyes on this code. Please help me understand how I can improve this and if this is even correct.</p>
<p><strong>Implementation</strong>:</p>
<pre class="lang-py prettyprint-override"><code>"""
Artificial Neural Network
"""
import numpy as np
def sigmoid(x, derivative=False):
output = 1 / (1 + np.exp(-x))
if derivative:
return output * (1 - output)
return output
def tanh(x, derivative=False):
output = 2 * sigmoid(2 * x) - 1
if derivative:
return 1 - output ** 2
return output
class Layer:
def __init__(self, num_input, num_output, activation_fn=tanh):
# num_rows = num_input, num_cols = num_output
self.weights = activation_fn(np.random.rand(num_input, num_output))
self.bias = activation_fn(np.random.rand(1, num_output))
self.activation_fn = activation_fn
self.raw = None
self.activated = None
self.input_data = None
def __str__(self):
return "Weights:\n" + str(self.weights) + "\nBias:\n" + str(self.bias)
def output(self, x):
self.input_data = x
self.raw = np.dot(x, self.weights) + self.bias
self.activated = self.activation_fn(self.raw)
return self.activated
def output_der(self):
return self.activation_fn(self.activated, derivative=True)
class NeuralNetwork:
def __init__(self, layers, eta=0.1):
if len(layers) < 2:
raise Exception("Layers needs to have input and output")
self.layers = self.init_layers(layers)
self.eta = eta
def __str__(self):
s = ""
for i, l in enumerate(self.layers):
s += "Layer {}.\n{}\n\n".format(i, str(l))
s += "--------------"
return s
def init_layers(self, layers):
ann = []
i = 0
while i < len(layers) - 1:
ann.append(Layer(layers[i], layers[i + 1]))
i += 1
return ann
def train(self, dataset, times=45):
# item[0] = input
# item[1] = label
# backpropagation is an online algorithm (one example at a time)
for i in range(times):
error = 0
output = 0
for item in dataset:
output = self.forward(np.array(item[0]))
# loss_at_output_layer = -(label - output)
self.backward(output - item[1])
error += (item[1] - output) ** 2
print(error)
def hot_encode(self, output):
top = max(output)
for i in range(len(output)):
output[i] = 0 if output[i] != top else 1
return output
def test(self, dataset):
accuracy = 0
for item in dataset:
output = self.forward(np.array(item[0]))
if np.array_equal(self.hot_encode(output[0]), item[1]):
accuracy += 1
print("Accuracy: {}\n".format(accuracy / len(dataset)))
def forward(self, item):
x = item
for l in self.layers:
x = l.output(x)
return x
def backward(self, loss):
# delta_i = error * Δoutput_i
deltas = []
for l in reversed(self.layers):
deltas.append(np.multiply(loss, l.output_der()))
loss = np.dot(deltas[-1], l.weights.T)
l.weights -= self.eta * np.multiply(deltas[-1], l.weights)
l.bias -= self.eta * deltas[-1]
#---------------------------------------------------------------------#
"""
Driver Code
"""
def normalize(data):
return (2 * (data - min(data)) / (max(data) - min(data))) - 1
def get_dataset(filename):
with open(filename, "r") as f:
raw = {}
for line in f:
line_data = line.split(",")
feature = normalize(np.array(list(map(float, line_data[:-1]))))
if line_data[-1] in raw:
raw[line_data[-1]].append(feature)
else:
raw[line_data[-1]] = [feature]
hot_encoding = {}
for i, label in enumerate(raw):
hot_encoding[label] = np.zeros(len(raw))
hot_encoding[label][i] = 1
dataset = []
for label in raw:
for feature in raw[label]:
dataset.append([feature, hot_encoding[label]])
return dataset
if __name__ == "__main__":
classifier = NeuralNetwork([4, 3], eta=0.01)
print("{}\n".format(classifier))
dataset = get_dataset("./iris.data")
np.random.shuffle(dataset)
print(dataset)
split_ratio = int(2 * len(dataset) / 3)
classifier.train(dataset[:split_ratio], times=50)
classifier.test(dataset[split_ratio:])
print("{}\n".format(classifier))
</code></pre>
<p>I am trying to test it on the <a href="https://archive.ics.uci.edu/ml/datasets/iris" rel="nofollow noreferrer">Iris dataset</a> but it doesn't converge. I have tried the following architectures:</p>
<ul>
<li>4 Input, 3 * 3 Hidden, 3 Output (Hot encoded)</li>
<li>4 '' , 3 '' , 3 ''</li>
<li>4 '' , 5 '' , 3 ''</li>
</ul>
<p>Please help me identify how to improve the algorithm, representation, and code quality. Please let me know how to improve this question to help you better answer this as well! Thank you so much!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T19:28:59.777",
"Id": "443387",
"Score": "5",
"body": "_Please help me understand how I can improve this and if this is even correct._ This site is for reviewing working code. The author should understand the code. I am not sure this is the case here. Visit our help center for more info: https://codereview.stackexchange.com/help/on-topic."
}
] |
[
{
"body": "<h3>Coding Style</h3>\n\n<p>First, I'm not a code reviewer. Your code seems to be OK though. There are some basic coding conventions in writing Python scripts, such as variable naming, commenting, docstring, and such, which I don't go through it, since I'm learning myself, and you can find it <a href=\"https://docs.python.org/3/\" rel=\"nofollow noreferrer\">here</a>. </p>\n\n<h3>Implementation</h3>\n\n<p>There are a few things that hold a basic ANN not to properly converge such as: </p>\n\n<ul>\n<li><p>IRIS dataset is a pretty small dataset, to start with; which normally one uses some 70% of a dataset for training, if supervised (which is the case here), and the rest for validation.</p></li>\n<li><p>It is difficult for me to go through your mathematical debugging, but it might be a reason that the math might have some problems and the network doesn't converge. To make sure, you can test it step by step (Neuron by Neuron maybe, if you will) with a very simple training and testing dataset, much simpler than IRIS, to see if there might be some bugs. </p></li>\n<li><p>If there is no bug, the architecture of ANN is another thing that would impact the convergence. I guess you might not need three layers of hiddens, and one hidden layer with maybe 10 to 30 neurons might be just OK for IRIS. Sometimes, adding too many neurons would trap the network into mathematical local minima dilemma. You might want to make sure that the Input and Output layers have the exact correct number of neurons according to the dataset. </p></li>\n<li><p>There might be some related tutorials to implement ANNs from scratch, wouldn't be such a bad idea to look them up. Maybe, something with a <code>Neuron</code> class. </p></li>\n</ul>\n\n<h3>Integration</h3>\n\n<p>You can also apply some already built-in modules to do that, such with KNN in this case, which I'm pretty sure you know:</p>\n\n<pre><code>from sklearn import neighbors, datasets, preprocessing\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\n\niris = datasets.load_iris() \nX, y = iris.data[:, :], iris.target\n\nXtrain, Xtest, y_train, y_test = train_test_split(X, y)\nscaler = preprocessing.StandardScaler().fit(Xtrain)\nXtrain = scaler.transform(Xtrain)\nXtest = scaler.transform(Xtest)\n\nknn = neighbors.KNeighborsClassifier(n_neighbors=4)\nknn.fit(Xtrain, y_train)\ny_pred = knn.predict(Xtest)\n\nprint(accuracy_score(y_test, y_pred))\nprint(classification_report(y_test, y_pred))\nprint(confusion_matrix(y_test, y_pred))\n</code></pre>\n\n<h3>Output</h3>\n\n<pre><code>0.8947368421052632\n precision recall f1-score support\n\n 0 1.00 1.00 1.00 13\n 1 0.79 0.92 0.85 12\n 2 0.91 0.77 0.83 13\n\n accuracy 0.89 38\n macro avg 0.90 0.90 0.89 38\nweighted avg 0.90 0.89 0.89 38\n\n[[13 0 0]\n [ 0 11 1]\n [ 0 3 10]]\n</code></pre>\n\n<h3>Overall</h3>\n\n<p>I think it is great that you are trying to implement a ANN from scratch. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T19:45:12.503",
"Id": "227687",
"ParentId": "227684",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T19:24:06.207",
"Id": "227684",
"Score": "-1",
"Tags": [
"python",
"beginner",
"python-3.x",
"machine-learning",
"neural-network"
],
"Title": "Python ANN Implementation"
}
|
227684
|
<p><a href="https://leetcode.com/problems/minimum-cost-to-merge-stones/" rel="nofollow noreferrer">This is a LeetCode Problem</a></p>
<blockquote>
<p>You have a pile of stones presented as an array. On each turn you must merge <strong>k</strong> consecutive piles of stones, starting from any pile you wish. You must continue merging piles until you are left with one pile only. You must do this with minimum overall cost, where the cost is the sum of the ongoing cost plus the sum of all the piles being merged</p>
<p>If this isn't possible, return -1. If this is possible, return the minimum overall cost</p>
</blockquote>
<p><strong>Example</strong></p>
<blockquote>
<p>If k = 2 and the stones = [3,2,4,1] </p>
<p><em>Round 1</em>: Merge stones 3 and 2 => Cost = <strong>5</strong>, stones = [5, 4, 1]</p>
<p><em>Round 2</em>: Merge stones 4 and 1 => Cost = <strong>5</strong> + (4+1) = <strong>10</strong>, stones = [5, 5]</p>
<p><em>Round 3</em>: Merge the piles 5 and 5 => Cost <strong>10</strong> + (5+5)= 20, stones = [10]</p>
<p><strong>The minimum overall cost is 20</strong></p>
</blockquote>
<p>My code is below. It runs into issues for large piles of stones such as </p>
<blockquote>
<p>stones = [29, 59, 31, 7, 51, 99, 47, 40, 24, 20, 98, 41, 42, 81, 92, 55]</p>
<p>k = 2</p>
</blockquote>
<p>How do I improve this code to quickly calculate the answer for large piles of stones?</p>
<p>Thank you</p>
<pre><code>def helper(stones, k, count, min_count):
# Basecase - if only one pile of stones, set minimum count to lowest value of current minimum and new minimum
if len(stones) == 1:
min_count = min(count, min_count)
return min_count
# Set last index
last_index = len(stones) - k + 1
for start in range(last_index):
new_count = count + sum(stones[start:start + k])
merged_count = sum(stones[start:start + k])
new_list = stones[:start] + [merged_count] + stones[start + k:]
min_count = helper(new_list, k, new_count, min_count)
return min_count
def merge_stones(stones, k):
lng = len(stones)
# Verify if solution is possible
if lng < k or (lng - 1) % (k - 1) != 0:
return -1
# Calculate solution
minimum = helper(stones, k, 0, 99999999)
# Return solution
return minimum
if __name__ == "__main__":
stones = [3, 2, 4, 1]
k = 2
print(merge_stones(stones, k))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T21:37:49.743",
"Id": "443395",
"Score": "0",
"body": "What sort of the issues it rans into?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T22:14:18.633",
"Id": "443397",
"Score": "0",
"body": "It takes for ever to deal with long lists. I suspect it calculates the correct answer as it calculates all of LeetCode's shorter test-samples correctly. My understanding is the code speeds up with dynamic programming (memoisation) but I don't know how to implement it here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T23:02:06.967",
"Id": "443399",
"Score": "3",
"body": "Several DP solutions are posted in the discussion board on LeetCode."
}
] |
[
{
"body": "<p>Without even doing anything clever regarding the algorithm, this:</p>\n\n<pre><code> new_count = count + sum(stones[start:start + k])\n merged_count = sum(stones[start:start + k])\n</code></pre>\n\n<p>can be cleaned up as</p>\n\n<pre><code> merged_count = sum(stones[start:start + k])\n new_count = merged_count + count\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T03:28:00.257",
"Id": "227756",
"ParentId": "227685",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T19:33:19.317",
"Id": "227685",
"Score": "2",
"Tags": [
"python",
"performance",
"algorithm",
"python-3.x",
"programming-challenge"
],
"Title": "LeetCode - Merging piles of stones"
}
|
227685
|
<p>I am working on setting up automated build and deploy jobs in jenkins for a php based project. I would like some feedback on my Jenkinsfile. Specifically regarding the parallelization, the (in my opinion) huge usage of <code>sh</code> and the best practices regarding the site configuration (would a bunch of included files be better?).</p>
<pre><code>#!groovy
//TODO: SSH-steps? https://jenkins.io/blog/2019/02/06/ssh-steps-for-jenkins-pipeline/
//TODO: move some stuff to shared library for ease of use https://jenkins.io/doc/book/pipeline/shared-libraries/
node{
switch (env.BRANCH_NAME) {
case "Production":
echo "Production is not yet implemented"
//DEPLOY_DIR = ""
//SITE_TITLE = ""
//SITE_NAME = ""
//SITE_FQDN = ""
//DEFAULT_FROM_EMAIL = ""
//SESSION_NAME = ""
//MYSQL_HOSTNAME = ""
//MYSQL_DB_NAME = ""
//MYSQL_USERNAME = ""
//MYSQL_PASSWORD = ""
//SSH_SERVER_NAME = ""
//SSH_USERNAME = ""
break
case "Development":
case "development":
DEPLOY_DIR = "/var/www/somesite_dev"
SITE_TITLE = "blablabla"
SITE_NAME = "blablabla.dev.mydomain.dk"
SITE_FQDN = "blablabla.dev.mydomain.dk"
DEFAULT_FROM_EMAIL = "dev@mydaomain.dk"
SESSION_NAME = "TestSession"
MYSQL_HOSTNAME = "localhost"
MYSQL_DB_NAME = "somedb"
MYSQL_USERNAME = "uname"
MYSQL_PASSWORD = "p@sswørd" //TODO Move to Jenkins credential management
SSH_SERVER_NAME = "ssh.mydomain.dk"
SSH_USERNAME = "jenkins"
break
case "Test":
DEPLOY_DIR = "/var/www/somesite_test"
SITE_TITLE = "blablabla"
SITE_NAME = "blablabla.test.mydomain.dk"
SITE_FQDN = "blablabla.test.mydomain.dk"
DEFAULT_FROM_EMAIL = "test@mydaomain.dk"
SESSION_NAME = "DevSession"
MYSQL_HOSTNAME = "localhost"
MYSQL_DB_NAME = "somedb"
MYSQL_USERNAME = "uname"
MYSQL_PASSWORD = "p@sswørd" //TODO Move to Jenkins credential management
SSH_SERVER_NAME = "ssh.mydomain.dk"
SSH_USERNAME = "jenkins"
break
default:
echo "$BRANCH_NAME Does not yet have a configuration."
break
}
}
pipeline {
agent any
environment {
SOURCE_DIR="${WORKSPACE}/src"
BACKUP_FNAME="/tmp/BACKUP-${SITE_NAME}-${(new java.text.SimpleDateFormat("yyyy-MM-dd-HHmm")).format((new Date()))}.tar.gz"
}
triggers {
bitbucketPush()
pollSCM('') // empty cron expression string
}
stages {
stage ('Staging'){
environment {
TEMPLATE_FILE="globals.template.inc.php"
CONFIG_FILE="globals.inc.php"
}
steps {
echo "Cleanup build artifacts"
//remove build folder
sh 'rm -R -f ${WORKSPACE}/build'
echo "Prepare for build"
//re-create folders
sh 'mkdir ${WORKSPACE}/build ${WORKSPACE}/build/api ${WORKSPACE}/build/coverage ${WORKSPACE}/build/logs ${WORKSPACE}/build/pdepend ${WORKSPACE}/build/phpdox'
echo "Running composer"
sh "composer install -o -d ${SOURCE_DIR}"
echo "Building config file ${SOURCE_DIR}/${CONFIG_FILE}"
script {
def inptext = readFile file: "${SOURCE_DIR}/${TEMPLATE_FILE}"
//save deploydate
def deployDate = (new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm")).format((new Date()))
inptext = inptext.replaceAll(~/¤SITE_TITLE¤/, "${SITE_TITLE}")
inptext = inptext.replaceAll(~/¤SITE_NAME¤/, "${SITE_NAME}")
inptext = inptext.replaceAll(~/¤SITE_FQDN¤/, "${SITE_FQDN}")
inptext = inptext.replaceAll(~/¤DEFAULT_FROM_EMAIL¤/, "${DEFAULT_FROM_EMAIL}")
inptext = inptext.replaceAll(~/¤SESSION_NAME¤/, "${SESSION_NAME}")
inptext = inptext.replaceAll(~/¤MYSQL_HOSTNAME¤/, "${MYSQL_HOSTNAME}")
inptext = inptext.replaceAll(~/¤MYSQL_DB_NAME¤/, "${MYSQL_DB_NAME}")
inptext = inptext.replaceAll(~/¤MYSQL_USERNAME¤/, "${MYSQL_USERNAME}")
inptext = inptext.replaceAll(~/¤MYSQL_PASSWORD¤/, "${MYSQL_PASSWORD}")
inptext = inptext.replaceAll(~/¤DEPLOY_DATE¤/, "${deployDate}")
inptext = inptext.replaceAll(~/¤GIT_BRANCH¤/, "${env.GIT_BRANCH}")
inptext = inptext.replaceAll(~/¤GIT_COMMIT¤/, "${env.GIT_COMMIT}")
//inptext = inptext.replaceAll(~/¤GIT_TAG¤/, "${sh(returnStdout: true, script: "git -C . describe --tags").trim()}")
writeFile file: "${SOURCE_DIR}/${CONFIG_FILE}", text: inptext
}
}
}
stage ('Testing, Static Analysis & documenting'){
parallel {
stage ("Count LOC"){
steps {
// echo "Running Lint"
// sh "find . -path ./src/vendor -prune -o -type f -name '*.php' -print0 | xargs -0 -n1 -P4 php -l -n | (! grep -v \"No syntax errors detected\" )"
echo "Running phploc"
sh "./src/vendor/phploc/phploc/phploc --exclude=./src/vendor --no-interaction --quiet --log-csv=./build/logs/loc.csv src tests"
echo "Running sloc"
sh "sloccount --duplicates --wide --details . > ./build/logs/sloccount.sc 2>/dev/null"
}
}
stage ("Copy-Paste Detection"){
steps{
echo "Running copy-paste detection"
sh "./src/vendor/sebastian/phpcpd/phpcpd --fuzzy . --exclude src/vendor --log-pmd ./build/logs/phpcpd.xml || true"
}
}
stage ("Mess Detection"){
steps{
echo "Running mess detection on code"
sh "./src/vendor/phpmd/phpmd/src/bin/phpmd src xml phpmd_ruleset.xml --reportfile ./build/logs/phpmd_code.xml --exclude vendor,build --ignore-violations-on-exit --suffixes php"
//echo "Running mess detection on tests"
//sh "./src/vendor/phpmd/phpmd/src/bin/phpmd tests xml codesize,cleancode,unusedcode,naming --reportfile ./build/logs/phpmd_tests.xml --suffixes php"
}
}
stage ("Testing"){
steps{
echo "Running PHPUnit w/o code coverage"
sh "./src/vendor/phpunit/phpunit/phpunit --configuration phpunit-quick.xml"
}
}
//echo "Running PHP Codesniffer"
//sh "phpcs --report=checkstyle --report-file=./build/logs/checkstyle.xml --standard=PSR2 --extensions=php --ignore=autoload.php ./src ./tests"
//TODO: phpdox
// TODO: set up reporting
// https://wiki.jenkins.io/display/JENKINS/Plot+Plugin
// https://stackoverflow.com/a/48001251/1725871
}
}
stage ("Deploy") {
environment {
SSH_TUNNEL_PORT=3309
}
parallel {
stage ("Deploy code") {
agent any
steps {
echo "Deploying via SSH on ${SSH_SERVER_NAME}:${DEPLOY_DIR}"
//TODO: rename backup file
sh "ssh ${SSH_USERNAME}@${SSH_SERVER_NAME} tar -cvpzf ${BACKUP_FNAME} ${DEPLOY_DIR}/* "
sh "ssh ${SSH_USERNAME}@${SSH_SERVER_NAME} rm -R -f ${DEPLOY_DIR}/*"
sh "scp -rpC ${SOURCE_DIR}/* ${SSH_USERNAME}@${SSH_SERVER_NAME}:${DEPLOY_DIR}"
//TODO: delete backup on success
}
}
stage ("Deploy DB changes") {
agent any //liquibase
steps {
echo "Create SSH tunnel"
sh "ssh -M -S deploy-control-socket -fnNT -L ${SSH_TUNNEL_PORT}:localhost:3306 ${SSH_USERNAME}@${SSH_SERVER_NAME}"
echo "Check tunnel"
sh "ssh -S deploy-control-socket -O check ${SSH_USERNAME}@${SSH_SERVER_NAME}"
echo "Sync liquibase"
sh "liquibase --driver=com.mysql.cj.jdbc.Driver --changeLogFile=${WORKSPACE}/resources/database/db.changelog-1.1.xml --url=\"jdbc:mysql://127.0.0.1:${SSH_TUNNEL_PORT}/${MYSQL_DB_NAME}?autoReconnect=true&useSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC\" --username=${MYSQL_USERNAME} --password=${MYSQL_PASSWORD} update"
echo "Close SSH tunnel to ${SSH_SERVER_NAME}"
sh "ssh -S deploy-control-socket -O exit ${SSH_USERNAME}@${SSH_SERVER_NAME}"
}
}
}
}
}
post {
always {
//archiveArtifacts artifacts: 'build/libs/**/*.jar', fingerprint: true
junit "build/logs/junit.xml"
sloccountPublish encoding: '', pattern: ''
// warnings-ng https://github.com/jenkinsci/warnings-ng-plugin/blob/master/doc/Documentation.md
recordIssues enabledForFailure: true, tool: cpd(pattern: 'build/logs/phpcpd.xml')
recordIssues enabledForFailure: true, tool: pmdParser(pattern: 'build/logs/phpmd_code.xml')
}
//https://jenkins.io/doc/pipeline/tour/post/
success {
echo 'Successful build. Well done'
}
unstable {
echo 'Unstable Build. Check test cases'
}
failure {
echo 'I failed :('
}
changed {
echo 'Things were different before...'
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T01:32:32.983",
"Id": "443402",
"Score": "1",
"body": "I don't know enough about these technologies to help you, but I think people would receive your question better if you could be a little more specific, considering the amount of code there is to go through."
}
] |
[
{
"body": "<p>I have found an inherent flaw in the backup and copy part. Namely </p>\n\n<pre><code>sh \"ssh ${SSH_USERNAME}@${SSH_SERVER_NAME} tar -cvpzf ${BACKUP_FNAME} ${DEPLOY_DIR}/*\"\nsh \"ssh ${SSH_USERNAME}@${SSH_SERVER_NAME} rm -R -f ${DEPLOY_DIR}/*\"\n</code></pre>\n\n<p>Which both exand the asterisk on the local mashine, and <a href=\"https://stackoverflow.com/questions/22222838/shell-script-calling-ssh-how-to-interpret-wildcard-on-remote-server\">https://stackoverflow.com/questions/22222838/shell-script-calling-ssh-how-to-interpret-wildcard-on-remote-server</a> </p>\n\n<p>The solution for tar is simple: </p>\n\n<pre><code>sh \"ssh ${SSH_USERNAME}@${SSH_SERVER_NAME} tar -cvpzf ${BACKUP_FNAME} ${DEPLOY_DIR}\"\n</code></pre>\n\n<p>The solution for rm is more difficult.\nI have considered the <a href=\"https://wiki.jenkins.io/display/JENKINS/SSH+Steps+Plugin\" rel=\"nofollow noreferrer\">ssh steps plugin</a>, but I would like some more surety of whether it would work before I try it...</p>\n\n<p>Right now I am looking into <code>rsync</code> with the <code>--DELETE</code> flag set.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T19:26:01.660",
"Id": "229475",
"ParentId": "227689",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T20:00:09.563",
"Id": "227689",
"Score": "2",
"Tags": [
"php",
"groovy"
],
"Title": "Jenkins Declarative pipeline for multi-branch pipleline"
}
|
227689
|
<p>I wrote a program that converts a hex-encoded string to base64. It's my solution to the <a href="https://cryptopals.com/sets/1/challenges/1" rel="noreferrer">first</a> of the Cryptopals challenges.</p>
<p>My main concerns are:</p>
<ul>
<li>Portability. I don't want to rely on implementation-specific or non-standard behavior.</li>
<li>Reusability. I wrote a function to get bytes from hex and one to get base64 from bytes (rather than going straight from hex to base64), because I will probably need them for other challenges.</li>
<li>Readability.</li>
<li>Testability.</li>
</ul>
<pre><code>/* Convert hex to base64.
*
* This program takes as an argument a hex string, which it converts to base64
* and then prints to stdout.
*/
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* A bytestring represents a string of (8-bit) bytes.
*
* Even if CHAR_BIT > 8, byte values are always in the range [0, 255].
*/
typedef struct {
size_t size;
unsigned char *data;
} bytestring;
static const char *const HEX_DIGITS = "0123456789abcdef";
static const char *const BASE64_DIGITS =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static const char BASE64_PADDING = '=';
/* Print a usage message to stderr.
*/
static void print_usage(int argc, const char *argv[])
{
const char *name = "s1e1.exe";
if (argc >= 1) {
name = argv[0];
}
fprintf(stderr, "Usage: %s hex\n", name);
}
/* Return the value represented by a hexadecimal digit.
*
* `digit` must be a valid hexadecimal digit.
*/
static unsigned char hex_value(char digit)
{
return (unsigned char) (strchr(HEX_DIGITS, digit) - HEX_DIGITS);
}
/* Convert a hex string to a bytestring and return true on success.
*
* On success, the bytestring data must be freed by the caller.
*/
static bool bytes_from_hex(const char *hex, bytestring *bytes_ptr)
{
size_t num_digits = 0;
for (const char *ptr = hex; *ptr != '\0'; ptr++) {
if (strchr(HEX_DIGITS, *ptr) == NULL) {
fprintf(stderr, "Invalid hex digit: %c\n", *ptr);
return false;
}
num_digits++;
}
if (num_digits % 2 == 1) {
fprintf(stderr, "Error: odd number of hex digits\n");
return false;
}
bytes_ptr->size = num_digits / 2;
if ((bytes_ptr->data = malloc(bytes_ptr->size)) == NULL) {
fprintf(stderr, "Error: couldn't allocate memory for bytes\n");
return false;
}
for (size_t i = 0; i < bytes_ptr->size; i++) {
unsigned char value_a = hex_value(hex[2*i + 0]);
unsigned char value_b = hex_value(hex[2*i + 1]);
bytes_ptr->data[i] = (unsigned char) (value_a << 4 | value_b);
}
return true;
}
/* Convert a bytestring to base64 and return true on success.
*
* On success, the base64 string must be freed by the caller.
*/
static bool base64_from_bytes(bytestring bytes, char **base64_ptr)
{
size_t num_triplets = (bytes.size + 2) / 3;
size_t buffer_size = 4 * num_triplets + 1;
if ((*base64_ptr = malloc(buffer_size)) == NULL) {
fprintf(stderr, "Error: couldn't allocate memory for base64\n");
return false;
}
for (size_t i = 0; i < num_triplets; i++) {
uint_fast32_t byte_a = bytes.data[3*i + 0];
uint_fast32_t byte_b = 3*i + 1 < bytes.size ? bytes.data[3*i + 1] : 0;
uint_fast32_t byte_c = 3*i + 2 < bytes.size ? bytes.data[3*i + 2] : 0;
uint_fast32_t value = byte_a << 16 | byte_b << 8 | byte_c;
unsigned char mask = (1 << 6) - 1;
(*base64_ptr)[4*i + 0] = BASE64_DIGITS[value >> 18 & mask];
(*base64_ptr)[4*i + 1] = BASE64_DIGITS[value >> 12 & mask];
(*base64_ptr)[4*i + 2] = BASE64_DIGITS[value >> 6 & mask];
(*base64_ptr)[4*i + 3] = BASE64_DIGITS[value >> 0 & mask];
if (3*i + 1 >= bytes.size) {
(*base64_ptr)[4*i + 2] = BASE64_PADDING;
}
if (3*i + 2 >= bytes.size) {
(*base64_ptr)[4*i + 3] = BASE64_PADDING;
}
}
(*base64_ptr)[buffer_size - 1] = '\0';
return true;
}
/* Convert a hex string to base64 and return true on success.
*
* On success, the base64 string must be freed by the caller.
*/
static bool base64_from_hex(const char *hex, char **base64_ptr)
{
bytestring bytes;
if (!bytes_from_hex(hex, &bytes)) {
return false;
}
bool success = base64_from_bytes(bytes, base64_ptr);
free(bytes.data);
return success;
}
/* Print the base64 representation of a hex string and return true on success.
*/
static bool print_base64(const char *hex)
{
char *base64;
if (!base64_from_hex(hex, &base64)) {
return false;
}
bool success = puts(base64) != EOF;
free(base64);
return success;
}
/* Print the base64 representation of the hex string given as an argument.
*/
int main(int argc, const char *argv[])
{
if (argc != 2) {
print_usage(argc, argv);
return EXIT_FAILURE;
}
if (!print_base64(argv[1])) {
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T09:13:03.160",
"Id": "443420",
"Score": "0",
"body": "Why are you placing digits at the end of `BASE64_DIGITS` instead of at the very beginning? It makes more sense to me to represent base 64 as \"hex and then some\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T17:19:39.413",
"Id": "443468",
"Score": "0",
"body": "@Lundin This order of digits is how [Base64](https://en.wikipedia.org/wiki/Base64) is typically defined (don't ask me why). Thanks for your review!"
}
] |
[
{
"body": "<p>Overall the code is fairly easy to read and I don't spot any portability issues.</p>\n<p>Program design</p>\n<ul>\n<li><p>The module handling the allocation should also clean up after itself. If transferring this to a proper multi-file program, you would have a lib with a header/code pair like base64.h + base64.c. If there exists a function in base64.c that calls malloc, there should also be a function in that file responsible for clean-up. Returning pointers to dynamic memory to a caller outside the code is bad practice - it breaks private encapsulation and leads to memory leaks. Best practice by far is to let the handler deal with the allocation, if possible.</p>\n</li>\n<li><p>Similarly, you should not expose internals of such a dynamic-allocated struct to the caller. The struct could be made opaque and all access to it could be restricted to setters/getters.</p>\n</li>\n<li><p>Mixing error handling with algorithms isn't a good idea. Rather than printing errors inside the functions dealing with the algorithms, you should return an error code. Meaning you'll have to swap the bool return type for an enum or struct.</p>\n</li>\n</ul>\n<p>Performance</p>\n<ul>\n<li><p>Your struct member <code>data</code> should be replaced with a "flexible array member". This allows you to allocate the whole struct in one chunk of memory, which gives better cache performance and quicker look-ups. (Also gives less heap fragmentation)</p>\n</li>\n<li><p>Your <code>HEX_DIGITS</code> lookups with strchr could probably be optimized by calling <code>isxdigit</code> instead. Although that function isn't case-sensitive. Otherwise you can roll it out yourself by first checking if a character is in range of '0'-'9' or 'A'-'F' then use table lookups from there. It would be faster overall.</p>\n</li>\n<li><p>As a rule of thumb, never pass structs by value, always pass them by reference.</p>\n</li>\n<li><p>It might be possible to branch-optimize the code quite a bit, but I didn't look at that since you mention portability, and branch optimizations only makes sense for architectures with branch prediction and instruction cache.</p>\n</li>\n</ul>\n<p>Best practice and style</p>\n<ul>\n<li><p>Avoid assignment inside control statements. It is hard to read and might cause unintentional side-effects. Lines such as <code>if ((*base64_ptr = malloc(buffer_size)) == NULL)</code> should be split in two, one for the malloc call and one for the check against NULL.</p>\n</li>\n<li><p>To avoid the more complex syntax involved with a <code>char**</code>, you should use a local <code>char*</code>. For example <code>char* p64 = malloc(...); ... p64[n] = ...; ... *bae64_ptr = p64; return true; }//end of function</code></p>\n</li>\n<li><p>Replace "magic number" integer constants with named constants when possible. It isn't obvious what all those digits are for and you don't use comments explaining where you got them from.</p>\n</li>\n<li><p><code>HEX_DIGITS</code> and <code>BASE64_DIGITS</code> should be arrays. Makes the code easier to read, enables the use of <code>sizeof</code> and requires ever so slightly less memory. Example:</p>\n<pre><code> static const char HEX_DIGITS[] = "0123456789abcdef";\n</code></pre>\n</li>\n</ul>\n<p>Safety/security</p>\n<ul>\n<li><p>In a real application you would need to sanitize input more when dealing with command line arguments. You can't really know the length of the string passed. The simplest form of doing this would be to look for a null terminator in argv[1] until you reach to a certain max size, then have the program close with an error message if the input is too large. <code>strchr(HEX_DIGITS, digit) - HEX_DIGITS</code> is for example not guaranteed to be 255 or less, which is a vulnerability.</p>\n<p>Also, strchr will return NULL if the digit isn't found, in which case your program will crash.</p>\n</li>\n<li><p>You should make a habit out of appending a <code>u</code> suffic to all integer constants involed in bitwise artimetic. Constants like <code>1</code> is of type signed <code>int</code> and therefore potentially dangerous in various ways.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T15:28:13.693",
"Id": "443454",
"Score": "1",
"body": "nice in depth review."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T10:42:47.097",
"Id": "227717",
"ParentId": "227690",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "227717",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T20:16:55.670",
"Id": "227690",
"Score": "5",
"Tags": [
"c",
"programming-challenge",
"strings",
"c99",
"base64"
],
"Title": "Convert a hex string to base64"
}
|
227690
|
<p>This asks the user for the file name and the number of lines they want to remove. It then stores each line into a vector. A dynamic array is used to hold the random line numbers (generated by random generator) and the corresponding element in the vector is deleted. This vector is then copied to a new file named "temp.txt" where each element is its own line.</p>
<p>Questions:</p>
<ul>
<li>What can I improve to make this code for efficient? i.e. Better methods to perform this task? </li>
<li>What should I not use and should change (for example any bad habits)?</li>
<li>What did I use that is good and should keep it as a habit?</li>
<li>Are there any exceptions I can use to ensure code?</li>
</ul>
<p>Warnings I received:</p>
<blockquote>
<ol>
<li>Warning C26495 Variable 'LineEditor::array' is uninitialized. Always initialize a member variable (type.6). for LineEditor().</li>
<li>Avoid unnamed objects with custom construction and destruction (es.84). for getFileName() in void removeLines().</li>
</ol>
</blockquote>
<pre><code>#include <iostream>
#include <string>
#include <fstream>
#include <random>
#include <ctime>
#include <cstring>
#include <vector>
#include <algorithm>
#include <iterator>
template<typename T>
void writeTo(const std::string& filename, std::vector<T>& v)
{
std::ofstream fstream(filename);
if (!fstream)
exit(1);
std::copy(v.begin(), v.end(), std::ostream_iterator<T>(fstream, "\n"));
fstream.close();
}
class LineEditor
{
std::vector<std::string> buf;
std::string fileName;
int noOfLines{ 0 };
int* array;
public:
LineEditor()
{
}
~LineEditor()
{
std::cout << "\"" << fileName << "\"" << " " << noOfLines << " lines removed.\n";
delete[] array;
}
void removeLines()
{
getFileName();
TotalLinesToRemove();
std::ifstream fileIn;
std::string line;
int lineCounter{ 0 };
int* array = new int[noOfLines];
fileIn.open(fileName);
if (!fileIn)
{
std::cerr << fileName << " can not be opened." << std::endl;
exit(1);
}
while (fileIn.is_open())
{
while (std::getline(fileIn, line))
{
lineCounter++;
buf.push_back(line);
}
for (int i{ 0 }; i < noOfLines; ++i)
{
array[i] = getRandomNumber(0, lineCounter - 1);
buf.erase(buf.begin() + (array[i]));
--lineCounter;
}
writeTo("temp.txt", buf);
fileIn.close();
}
}
private:
std::string getFileName()
{
std::cout << "Enter name of text file: ";
std::cin >> fileName;
return fileName;
}
int TotalLinesToRemove()
{
std::cout << "Enter the number of lines to remove: ";
std::cin >> noOfLines;
return noOfLines;
}
int getRandomNumber(int min, int max)
{
std::mt19937 seed{ static_cast<std::mt19937::result_type>(std::time(nullptr)) };
std::uniform_int_distribution<> rand(min, max);
return rand(seed);
}
};
int main()
{
LineEditor file;
file.removeLines();
return 0;
}
</code></pre>
<p>I am fairly beginner to intermediate at C++ and want to improve. </p>
|
[] |
[
{
"body": "<p>Since <code>writeTo</code> does not modify <code>v</code>, it should take that parameter as a const reference (<code>const std:::vector<T>&v</code>).</p>\n\n<p>In <code>LineEditor</code>, the constructor doesn't initialize <code>ary</code>, so if you construct a LineEditor object and destroy it without calling <code>removeLines</code> (or if that function returns, possibly by an exception, before you allocate the memory) you'll delete an uninitialized pointer. Those problems can be avoided by using <code>std::vector<int></code> instead of a raw int pointer. And since <code>ary</code> is only used within one function (other than deleting the allocated memory), it shouldn't be a class member but should be a local variable within the function.</p>\n\n<p>The <code>removeLines</code> function is doing several things. It asks for a couple of inputs, then opens the file and removes the lines. This can be split into two (or more) functions, one to ask for input and another to do the actual removal. <code>while (fileIn.is_open())</code> can be an <code>if</code> instead since it will be true only once, if at all.</p>\n\n<p>What will happen if the user wants to delete more lines than the file contains?</p>\n\n<p>Deleting lines like you do can be inefficient because <code>erase</code> will move all the entries in the vector after the deleted entry. If you need to process larger files or deleting a large portion of the lines you may want to use a method that will only move the lines that are not deleted once, although doing that can introduce other problems to avoid.</p>\n\n<p>And then there's <code>getRandomNumber</code>. The proper way to use the random number generator is to only create the engine (<code>seed</code>) <em>once</em>. Since the seed is recreated on every function call (a time consuming process), probably within a very small time frame, the value returned by <code>std::time</code> is very likely to be the same, resulting in the same generated random number. Although the returned number will be different with how you're using it (since the range is different every time), this is still bad practice. Common solutions to this are to either have a static local variable with the engine, or (preferably) make <code>seed</code> a member of the class, so every instantiation of the class will have its own engine that is only created once. The distribution object (<code>rand</code>) should remain a local since it can be different on every call.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T02:40:20.660",
"Id": "227697",
"ParentId": "227691",
"Score": "1"
}
},
{
"body": "<h3>Use the <strike>force</strike> library Luke!</h3>\n\n<p>Your code does use <code>std::vector</code>, but for reasons I don't understand, it also uses <code>new</code> to allocate a manually managed dynamic array as well. You don't seem to gain anything from this, so I'd advise using <code>std::vector</code> throughout.</p>\n\n<p>I'd also look at the standard library's algorithms. Some of them (e.g., <code>std::remove_copy_if</code>) could be put to excellent use for this task.</p>\n\n<h3>Avoid <code>std::endl</code></h3>\n\n<p><code>std::endl</code> not only writes a new-line to a stream (which is what you usually want) but also flushes the stream (which you usually don't want). If you do that very often, it can slow a program significantly.</p>\n\n<p>In your case, you using it when writing to <code>std::cerr</code>, which automatically flushes in any case, so the flushing done by <code>std::endl</code> is unnecessary in any case.</p>\n\n<h3>Random generator seeding</h3>\n\n<p>When you're using <code><random></code> (a good idea) the generally accepted way of seeding a generator is by using <code>std::random_device</code>. This is usually a truly random device (e.g., reading from <code>/dev/random</code>) so it normally does a substantially better job of seeding than using the system time.</p>\n\n<p>As @1201ProgramAlarm already pointed out, you normally want to seed a generator exactly once, then just generate numbers from it.</p>\n\n<p>Unfortunately, doing a good job of seeding a random number generator is a somewhat nontrivial task. I posted some code that demonstrates what I believe is one reasonable possibility in <a href=\"https://codereview.stackexchange.com/a/187677/489\">a previous answer</a>. The short summary is that regardless of whether you use <code>time(nullptr)</code> or <code>std::random_device</code>, if you only use a 32-bit seed, you're limiting yourself to only <span class=\"math-container\">\\$2^{32}-1\\$</span> possible sequences that you can generate, which is a huge limitation compared to the full capabilities of MT19377.</p>\n\n<h3>Single Responsibility Principle</h3>\n\n<p>It seems to me that your <code>LineEditor</code> does more than I'd like a single class to do. For most practical purpose, the entire program is embodied in that one class. That doesn't strike me as entirely ideal. I'd rather see individual pieces responsible for the individual parts of doing the job.</p>\n\n<p>This also fits better with having clearly defined layers of abstraction. For example, you might have one layer that deals with the file name, and a separate one that deals with the actual content of the file.</p>\n\n<h3>Convenient Interface</h3>\n\n<p>For most uses, I'd rather run the program something like <code>removeLines foo.txt 10</code>, rather than doing <code>removeLines</code>, then having to separately walk through a questionairre (so to speak) to tell it the name of the file and number of lines to remove. Of course, depending on the situation, that might be better as something like <code>removeLines -f foo.txt -n 10</code> (especially if this were part of a larger program that might have more/other command line arguments as well.</p>\n\n<p>If you are going to ask questions interactively, I'd ask for the filename first, then read in the file, then ask for the number of lines to remove. This will allow you to check how many lines you've actually read, which (in turn) you can use to advise the user as to the maximum number of lines they can have removed (e.g., \"Please enter the number of lines to remove (1-723): \").</p>\n\n<h3>Constructor Definition</h3>\n\n<p>You've currently defined your constructor with no member initializer list and nothing in the body. It's not clear what you're hoping to accomplish by defining it explicitly rather than just accepting what the compiler would define if you didn't define one at all. Until/unless your ctor will actually accomplish something, it's probably better not to define it explicitly.</p>\n\n<h3>Possible Code</h3>\n\n<pre><code>#include <iostream>\n#include <vector>\n#include <string>\n#include <set>\n#include <fstream>\n#include <iterator>\n#include \"rand.h\"\n\nstruct InputSpec {\n std::string filename;\n std::size_t count;\n\n InputSpec(int argc, char **argv) { \n if (argc != 3)\n throw std::runtime_error(\"Usage: removeLines <filename> <count>\");\n\n filename = argv[1];\n count = std::atoi(argv[2]);\n\n if (count == 0)\n throw std::runtime_error(\"numbers of lines to remove can't equal 0\");\n }\n};\n\nint main(int argc, char **argv) { \n InputSpec input{argc, argv};\n\n std::ifstream infile(input.filename);\n std::vector<std::string> lines; \n std::string line;\n while (std::getline(infile, line))\n lines.push_back(line);\n\n int maxLines = std::min(input.count, lines.size());\n\n generator g(maxLines);\n std::set<int> removals;\n\n while (removals.size() < maxLines)\n removals.insert(g());\n\n int current_line = 0;\n std::remove_copy_if(lines.begin(), lines.end(), \n std::ostream_iterator<std::string>(std::cout, \"\\n\"),\n [&](std::string const &) { return removals.find(++current_line) != removals.end(); });\n}\n</code></pre>\n\n<p>Note that for the moment, this presumes that the number of lines to be removed from the file is small compared to the number of lines in the file. If there's a significant chance that won't be true, you may want to see the selection algorithm in yet another <a href=\"https://stackoverflow.com/a/2394292/179910\">old answer</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T05:16:46.963",
"Id": "227757",
"ParentId": "227691",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T20:26:08.190",
"Id": "227691",
"Score": "4",
"Tags": [
"c++",
"object-oriented",
"c++11",
"file"
],
"Title": "Random line remover from file"
}
|
227691
|
<p>I wrote a simple Torrent file parser. The following program accepts a file and builds a Torrent structure based on the contents on the file. If the file is invalid, the app crashes (as intended).</p>
<p>It's my first time writing anything >50 lines in rust, so I'm looking for improvements :)</p>
<hr>
<pre><code>use std::collections::BTreeMap;
use bencode::{Bencode, Encoder};
use bencode::util::ByteString;
#[derive(Default, Debug)]
pub struct Torrent {
announce: String,
announce_list: Vec<String>,
name: String,
comment: String,
multi_file: bool,
piece_length: i32,
length: i64,
creation_date: String,
total_size: i32,
}
impl Torrent {
pub fn new() -> Self {
return Torrent {
..Default::default()
};
}
pub fn populate_from_bencode(&mut self, b: Bencode) -> Bencode {
if let Bencode::Dict(dict) = b {
dict.into_iter().for_each(|(s, b)| {
if s.as_slice() == b"announce" {
self.announce = extract_string(b).unwrap_or_else(|| panic!("unable to extract announce"));
} else if s.as_slice() == b"name" {
self.name = extract_string(b).unwrap_or_else(|| panic!("unable to extract name"));
} else if s.as_slice() == b"pieces" {} else if s.as_slice() == b"comment" {
self.comment = extract_string(b).unwrap_or_else(|| panic!("unable to extract comment"));
} else if s.as_slice() == b"creation-date" {
self.creation_date = extract_string(b).unwrap_or_else(|| panic!("unable to extract creation-date"));
} else if s.as_slice() == b"info" {
self.populate_from_bencode(b);
} else if s.as_slice() == b"length" {
if let Bencode::Number(length) = self.populate_from_bencode(b) {
self.length = length;
}
} else if s.as_slice() == b"announce-list" {
if let Bencode::List(x) = self.populate_from_bencode(b) {
self.announce_list = x.into_iter()
.map(|x| extract_list(x).unwrap_or_else(|| panic!("list")))
.flatten()
.map(|x| extract_string(x).unwrap_or_else(|| panic!("unable to extract string")))
.collect();
}
}
});
return Bencode::Empty;
} else {
return b;
}
}
}
fn extract_list(b: Bencode) -> Option<Vec<Bencode>> {
if let Bencode::List(s) = b {
return Some(s);
}
return None;
}
fn extract_pieces(b: Bencode) -> Option<Vec<u8>> {
if let Bencode::ByteString(x) = b {
return Some(x);
}
return None;
}
fn extract_string(b: Bencode) -> Option<String> {
if let Bencode::ByteString(s) = b {
return Some(String::from_utf8_lossy(&s).to_string());
}
return None;
}
//decoder.rs
use std::fs::File;
use std::io::Read;
use bencode::Bencode;
use crate::torrent;
use crate::torrent::Torrent;
pub fn decode_file_into_torrent(path: &'static str) -> Result<Torrent, Box<dyn std::error::Error>> {
let mut file = File::open(path)?;
let v = file.bytes().map(|x| x.unwrap()).collect::<Vec<u8>>();
let bencode = bencode::from_vec(v).unwrap();
let mut t = Torrent::new();
t.populate_from_bencode(bencode);
Ok(t)
}
#[cfg(test)]
mod tests {
use crate::decoder;
use super::*;
#[test]
fn test_parser() {
let t = decoder::decode_file_into_torrent("src/test.torrent");
assert!(t.is_ok());
}
}
</code></pre>
<p>EDIT: Fighting with the compiler and debugging this been an absolute nightmare :( </p>
|
[] |
[
{
"body": "<p>For deserialization, its a lost easier if you use serde. Then you can do something like this:</p>\n\n<pre><code>use serde_derive::Deserialize;\n\n// the Deserialize derive is provided by serde, it causes the code\n// to be generated that is needed for deserialization\n#[derive(Default, Debug, Deserialize)]\n// this tells serde you want to use kebab-case, which is \n// with dashes instead of underscores for field names\n#[serde(rename_all = \"kebab-case\")]\n// this tells serde to default values to the empty case if not provided\n#[serde(default)]\npub struct Torrent {\n announce: String,\n announce_list: Vec<Vec<String>>,\n name: String,\n comment: String,\n multi_file: bool,\n piece_length: i32,\n length: i64,\n creation_date: String,\n total_size: i32,\n}\n</code></pre>\n\n<p>Then you can read a torrent into this struct with:</p>\n\n<pre><code>let torrent :Torrent = serde_bencode::from_bytes(&v).unwrap();\n</code></pre>\n\n<p>But let's ignore that for a moment, and look through your code:</p>\n\n<pre><code>impl Torrent {\n pub fn new() -> Self {\n return Torrent {\n ..Default::default()\n };\n }\n</code></pre>\n\n<p>You don't need the explicit return statement. If you leave the semicolon off of the last statement in a function, the expression of that statement will be returned. Further, you don't use to unpack the Default::default() into the Torrent. Default::default() will already return a torrent. So this function could be written</p>\n\n<pre><code>pub fn new() -> Self {\n Default::default()\n}\n</code></pre>\n\n<p>Moving on</p>\n\n<pre><code>pub fn populate_from_bencode(&mut self, b: Bencode) -> Bencode {\n</code></pre>\n\n<p>It is unusual that you would modify an object based on the input. Instead, you typically return a new object based on the bencode input. It also odd that you would return the Bencode. You ignore this output in any case, so its unclear why you are doing this.</p>\n\n<pre><code> if let Bencode::Dict(dict) = b {\n dict.into_iter().for_each(|(s, b)| {\n</code></pre>\n\n<p>I would do <code>for (s,b) in dict {</code> instead. In my mind, it is easier to follow standard for loops rather than doing a for_each. </p>\n\n<pre><code> if s.as_slice() == b\"announce\" {\n</code></pre>\n\n<p>Rather then having a repeated if statement like this, use <code>match</code> </p>\n\n<pre><code> self.announce = extract_string(b).unwrap_or_else(|| panic!(\"unable to extract announce\"));\n</code></pre>\n\n<p><code>Option</code> has an expect method, which takes a string and panics if the option is none. However, if you are going to panic anyways, why not panic inside extract_string?</p>\n\n<pre><code> } else if s.as_slice() == b\"length\" {\n if let Bencode::Number(length) = self.populate_from_bencode(b) {\n self.length = length;\n }\n</code></pre>\n\n<p>In this case, you ignore a non-numeric length. This suspicous, I'd almost certainly rather get an error then silently failing to load length.</p>\n\n<pre><code>pub fn decode_file_into_torrent(path: &'static str) -> Result<Torrent, Box<dyn std::error::Error>> {\n</code></pre>\n\n<p>Why are you taking a &'static str. It would seem that this function doesn't have take a str that lasts for the whole lifetime of your application. Further, I prefer to take the std::path::Path and friends types for parameters that are actually paths.</p>\n\n<pre><code> let mut file = File::open(path)?;\n</code></pre>\n\n<p>Why, in this one case, are you returning an error instead of panicking?</p>\n\n<pre><code> let v = file.bytes().map(|x| x.unwrap()).collect::<Vec<u8>>();\n</code></pre>\n\n<p>Firstly, you can do the following:</p>\n\n<pre><code> let v = file.bytes().collect::<Result<Vec<u8>, _>>();\n</code></pre>\n\n<p>Rust knows how to construct a result of vec from iterator over results.</p>\n\n<p>Secondly, there is a specific method for reading the rest of the file</p>\n\n<pre><code> let mut v = Vec::new();\n file.read_to_end(&mut v).unwrap();\n</code></pre>\n\n<p>Third, this a function that reads the whole file into bytes from just the path</p>\n\n<pre><code> let v = std::fs::read(path)?;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T06:28:19.183",
"Id": "227703",
"ParentId": "227694",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-08T23:02:14.990",
"Id": "227694",
"Score": "6",
"Tags": [
"beginner",
"parsing",
"rust"
],
"Title": "Rust Torrent Parser"
}
|
227694
|
<p>One of the things that has been really exciting me in c++20 is <code>std::bind_front</code>. Using placeholders with <code>std::bind</code> and <code>boost::bind</code> has really bothered me and the code looked messier and messier with each call to bind. It was bad enough for me to decide to enable <code>-std=c++2a</code> and pray that I wouldn't have to fix the code in the future if something gets changed.</p>
<p>I was messing around with parameter pack recursion when I realized I could make a <code>std::bind_front</code> alternative that would work in c++17. If I removed the <code>std::invoke</code> it would even work in c++11.</p>
<p>It even seems to compile faster than my standard library's implementation.</p>
<hr>
<pre><code>//#include <utility>
//#include <functional>
//of course this would go into some kind of namespace
template <class F, class A>
struct _bind_obj {
F originalFunc;
A arg;
template <class... Args>
inline auto operator()(Args&&... a){
return std::invoke(originalFunc, arg, std::forward<Args>(a)...);
}
_bind_obj(F &&_originalFunc, A &&_arg) :
originalFunc(std::forward<F>(_originalFunc)),
arg(std::forward<A>(_arg)){
}
};
template <class F, class A>
auto bind_front(F &&func, A &&arg){
return _bind_obj<F, A>(
std::forward<F>(func),
std::forward<A>(arg)
);
}
template <class F, class FirstA, class... A>
auto bind_front(F &&func, FirstA &&firstA, A&&... a){
return bind_front(
bind_front(
std::forward<F>(func),
std::forward<FirstA>(firstA)
),
std::forward<A>(a)...
);
}
</code></pre>
<hr>
<p>So what do you think? Are there some cases in <code>std::bind_front</code> that I missed? Are there any optimizations I should make?</p>
|
[] |
[
{
"body": "<p><code>bind_front</code> can (and should) be made <code>constexpr</code>.</p>\n\n<p>The callable object and the bound arguments need to be decayed per the standard.</p>\n\n<p>You can store all arguments in a tuple instead of generating nested wrappers:</p>\n\n<pre><code>template <class FD, class... Args>\nclass bind_obj {\n // ...\n FD func;\n std::tuple<Args...> args;\n};\n</code></pre>\n\n<p>and then call</p>\n\n<pre><code>std::apply(func, args, std::forward<A>(call_args)...)\n</code></pre>\n\n<p>(which internally calls <code>invoke</code>.)</p>\n\n<p>Otherwise, nice code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T18:56:14.773",
"Id": "445316",
"Score": "0",
"body": "Thanks! I see an improvement in compile time and executable size with constexpr. Out of curiosity, what are the advantages of using `std::apply` and tuples over nested wrappers?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T09:59:49.737",
"Id": "445385",
"Score": "1",
"body": "@user233009 You are welcome. With nested wrappers, the compiler has to instantiate the template multiple times (`n` instantiations of `bind_obj` for `n` args) and there are multiple function calls (think of `f1(f2(f3(f4(f5, a5), a4), a3), a2), a1)` ... scary) whereas `std::apply` simply expands the template parameter pack, resulting a single function call (`f(a1, a2, a3, a4, a5)`). That should explain the reduction in both compile time and executable size."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T08:46:49.443",
"Id": "229015",
"ParentId": "227695",
"Score": "5"
}
},
{
"body": "<blockquote>\n <p>Are there some cases in <code>std::bind_front</code> that I missed?</p>\n</blockquote>\n\n<p>There are several significant differences between <code>std::bind_front</code>'s behavior and your implementations.</p>\n\n<hr />\n\n<p>First, your implementation unconditionally returns a value. But what if the callable in question returned a reference? The behavior is just incorrect.</p>\n\n<hr />\n\n<p>Second, <code>std::bind_front</code> is SFINAE-friendly but yours is not. That is, I can check to see if I can invoke the result with a certain set of arguments. Here is a silly example demonstrating this:</p>\n\n<pre><code>auto f = [](int i, int j) { return i + j; };\nauto g = std::bind_front(f, 1);\nauto g2 = your::bind_front(f, 1);\n\n// this is ok, static assertion doesn't trigger\nstatic_assert(!std::is_invocable_v<decltype(g), int, int>);\n\n// this is a compile error\nstatic_assert(!std::is_invocable_v<decltype(g2), int, int>);\n</code></pre>\n\n<p>Basically, asking the question \"Can I call you with two <code>int</code>s?\" leads to an instantiation failure outside of the immediate context, and will always be a hard error.</p>\n\n<p>You can fix this and the reference issue described above by specified the correct return type instead of <code>auto</code>:</p>\n\n<pre><code>template <class... Args>\ninline std::invoke_result_t<F&, A, Args...> operator()(Args&&... a) { ... }\n</code></pre>\n\n<hr />\n\n<p>Third, you're capturing your arguments differently. Consider:</p>\n\n<pre><code>std::string s = \"Hello\";\nauto f = [](std::string const& s, int i) { return s[i]; }\n\nauto g = std::bind_front(f, s);\nauto g2 = your::bind_front(f, s);\ns = \"Goodbye\";\n\nassert(g(0) == 'H'); // ok\nassert(g2(0) == 'H'); // fails\n</code></pre>\n\n<p><code>std::bind_front</code> owns everything. You keep references to all the lvalues. The way the standard library works is if you want to capture by reference, you use <code>std::ref</code>.</p>\n\n<p>Basically, this:</p>\n\n<pre><code>template <class F, class A>\nauto bind_front(F &&func, A &&arg){\n return _bind_obj<F, A>(\n std::forward<F>(func),\n std::forward<A>(arg)\n );\n}\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>template <class F, class A>\nauto bind_front(F &&func, A &&arg){\n return _bind_obj<std::decay_t<F>, std::decay_t<A>>(\n std::forward<F>(func),\n std::forward<A>(arg)\n );\n}\n</code></pre>\n\n<hr />\n\n<p>Fourth, your result is <em>only</em> invocable on a non-<code>const</code> object. But if the callable I'm <code>bind_front()</code>-ing has a <code>const</code> <code>operator()</code>, I should be able to invoke it as <code>const</code> too right?</p>\n\n<p>The same can be said for ref-qualifiers: if I have a function object with <code>&</code>- and <code>&&-</code>qualified overloads, <code>bind_front</code> should respect that.</p>\n\n<p>The solution is actually to write four overloads of <code>operator()</code>:</p>\n\n<pre><code>template <class... Args>\ninline std::invoke_result_t<F&, A, Args...> operator()(Args&&... a) &;\n\ntemplate <class... Args>\ninline std::invoke_result_t<F const&, A, Args...> operator()(Args&&... a) const&;\n\ntemplate <class... Args>\ninline std::invoke_result_t<F, A, Args...> operator()(Args&&... a) &&;\n\ntemplate <class... Args>\ninline std::invoke_result_t<F const, A, Args...> operator()(Args&&... a) const &&;\n</code></pre>\n\n<p>Note that I'm also adjusting the type of <code>F</code> in the type trait, and be sure to move the callable in the rvalue cases.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T18:58:31.187",
"Id": "229338",
"ParentId": "227695",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "229015",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T00:22:57.017",
"Id": "227695",
"Score": "9",
"Tags": [
"c++",
"performance",
"functional-programming",
"reinventing-the-wheel",
"template-meta-programming"
],
"Title": "c++17 compatible std::bind_front alternative"
}
|
227695
|
<p>I hava a question similiar with <a href="https://stackoverflow.com/questions/54605295/merging-k-sorted-lists-in-python3-problem-with-trade-off-between-memory-and-tim">mege in Python</a> but I am trying to write Java code.
Here is my code:
The input is: The first line - a number of arrays (k); Each next line - the first number is the array size, next numbers are elements.</p>
<p>Max k is 1024. Max array size is 10*k. All numbers between 0 and 100. Memory limit - 10MB, time limit - 1s. Recommended complexity is k ⋅ log(k) ⋅ n, where n is an array length.</p>
<p>Example input:</p>
<pre><code>4
6 2 26 64 88 96 96
4 8 20 65 86
7 1 4 16 42 58 61 69
1 84
</code></pre>
<p>Example output:</p>
<pre><code>1 2 4 8 16 20 26 42 58 61 64 65 69 84 86 88 96 96
</code></pre>
<p>I get memory limit errors.
I use System.gc() to clear the memory but I recieve timeout error</p>
<p>Here is my code:</p>
<pre><code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TaskFSolution {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int k = Integer.valueOf(reader.readLine());
short[][] arrays = new short[k][];
int arrayLength = 0;
int[] minPositionInArrays = new int[k];
for (int i = 0; i < k; i++) {
String str = reader.readLine();
String[] elements = str.split(" ");
arrays[i] = new short[Short.valueOf(elements[0]) + 1];
for (int j = 0; j < elements.length; j++) {
arrays[i][j] = Short.valueOf(elements[j]);
}
arrayLength += Short.valueOf(elements[0]);
minPositionInArrays[i] = 1;
if (arrayLength % 100 == 0) {
System.gc();
}
}
reader.close();
StringBuilder sb = new StringBuilder();
int currentArrayNumber = 0;
int currentPositionInArray = minPositionInArrays[currentArrayNumber];
while (arrayLength > 0) {
short currentMinValue = 101;
for (int i = 0; i < k; i++) {
if (minPositionInArrays[i] <= arrays[i][0] && currentMinValue >= arrays[i][minPositionInArrays[i]]) {
currentMinValue = arrays[i][minPositionInArrays[i]];
currentArrayNumber = i;
currentPositionInArray = minPositionInArrays[i] + 1;
}
}
sb.append(currentMinValue + " ");
minPositionInArrays[currentArrayNumber] = currentPositionInArray;
arrayLength--;
}
System.out.println(sb.toString().trim());
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T11:38:43.600",
"Id": "443552",
"Score": "0",
"body": "Why is there 1x a `1`, but 2x a `96` in the output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T08:13:29.427",
"Id": "445570",
"Score": "1",
"body": "@RobAu Because the first number on each line isn't part of the numbers to be merged, it is telling how many numbers are on that line (or in that array)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T10:32:21.940",
"Id": "445585",
"Score": "0",
"body": "Ah I misread. Thanks!"
}
] |
[
{
"body": "<p>Are you getting the correct output with the recommended complexity? It's been a long time since I've written my own sort but start by confirming that before any of my recommendations below.</p>\n\n<p>I suspect <code>str.split(\" \")</code> is causing problems for you because you're creating lots of strings which you're about to parse and then throw away. How about parsing the integers directly from <code>str</code> in a single pass instead?</p>\n\n<p>Try changing <code>sb.append(currentMinValue + \" \")</code> to <code>sb.append(currentMinValue).append(\" \")</code>. It might be a small optimization but it's easy to do.</p>\n\n<p>How about splitting your <code>main</code> into two methods? The first for everything that uses <code>reader</code>, the second for everything that uses <code>sb</code>. Besides improving the structure of the program this provides a natural point for garbage collection.</p>\n\n<p>What command-line args are you giving to the JVM? Since you know your memory limit try allocating it all at the start to save time allocating more memory later. You might also play with different garbage collection strategies. As you're discovering, forcing garbage collection isn't a good idea. If you're correctly setting the maximum in the JVM it should automatically garbage collect as needed to prevent running out of memory.</p>\n\n<p>Hope at least one of these suggestions helps. I'm curious what gives the biggest improvement.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T02:45:56.027",
"Id": "227700",
"ParentId": "227696",
"Score": "2"
}
},
{
"body": "<p>I was curious about why you kept the initial size inside each of the arrays until I finaly noticed the<br>\n<code>arrays[i][0]</code> in the check if that array still has elements to proces during the algorithm. If we replace that with <code>arrays[i].length-1</code> we no longer need to store those.</p>\n\n<p>Another major issue, like Nathan pointed out is how many String objects you're creating while parsing the input. The easiest solution to this is to use a Scanner instead of a BufferedReader. That way, you can directly read the <code>nextShort()</code>.</p>\n\n<pre><code> Scanner reader = new Scanner(new InputStreamReader(System.in));\n\n short k = reader.nextShort();\n short[][] arrays = new short[k][];\n\n int arrayLength = 0;\n int[] minPositionInArrays = new int[k]; // note here: now correctly initialised to 0's\n for (int i = 0; i < k; i++) {\n short size = reader.nextShort();\n arrays[i] = new short[size];\n for (int j = 0; j < size; j++) {\n arrays[i][j] = reader.nextShort();\n }\n arrayLength += size;\n }\n reader.close();\n</code></pre>\n\n<hr>\n\n<p>The recommended complexity is O(k ⋅ log(k) ⋅ length_array). Yours seems to be O(k ⋅ (k ⋅ length_array)).</p>\n\n<p>Since we need to proces k ⋅ length_array items anyway, we can't change that. So how can you get the other k in that complexity formula down to a log(k)?</p>\n\n<p>The solution is to sort all the lists initially and then use the fact that they're sorted when processing each element. How to actually implement this I'll leave up to you :)</p>\n\n<hr>\n\n<p>Final remark: If the memory limit is 10MB and the input is at most 1024*(10*1024) = 10.485.760 numbers (~=10MB) this seems almost impossible to me. That would mean storying all numbers into a single array in the first place and sorting them in-place. But you don't know how big this array needs to be before you read the last line of the input.</p>\n\n<p>I'm assuming the actual limit is a bit more lenient, or it wasn't set with java in mind :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T09:25:48.787",
"Id": "227711",
"ParentId": "227696",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T01:50:37.253",
"Id": "227696",
"Score": "1",
"Tags": [
"java",
"array",
"mergesort"
],
"Title": "Merge k sorted lists in Java"
}
|
227696
|
<p>How may I optimize the following function to write a xls file from a list of dictionaries using the openpyxl library in Python?</p>
<p>The current logic behind feels very very wrong</p>
<p>The dict list:</p>
<pre><code>things = [
{
"Fruit": "Orange",
"Flavour": "Good",
"Expiration": "21May20"
},
{
"Fruit": "Apple",
"Flavour": "Good",
"Expiration": "19May20"
},
{
"Fruit": "Banana",
"Flavour": "Regular",
"Expiration": "16May20"
}
]
</code></pre>
<p>The functions that I have:</p>
<pre><code>from openpyxl import Workbook, load_workbook
def create_xls(filepath):
wb = Workbook()
wb.save(filepath)
def write_xls(filepath, dictionary):
wb = load_workbook(filepath)
sheet = wb.active
headers = [x for x in dictionary[0]]
for index, value in enumerate(headers):
sheet.cell(row=1, column=index+1).value = value
for i, x in enumerate(dictionary):
for idx,value in enumerate(x.values()):
sheet.cell(row=i+2, column=idx+1).value = value
wb.save(filepath)
</code></pre>
<p>Thank you!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T04:26:10.963",
"Id": "443404",
"Score": "1",
"body": "do you want to have Fruit, Flavor, Expiration as titles and respective values below? or is there something else intended?"
}
] |
[
{
"body": "<p>From <a href=\"https://openpyxl.readthedocs.io/en/stable/usage.html#write-a-workbook\" rel=\"noreferrer\">the documentation</a>, you can see that a worksheet object has an <code>.append</code> method that let you write a row from an iterable at the bottom of said sheet. Documentation from the builtin <code>help</code> is reproduced here:</p>\n\n<pre><code>Help on method append in module openpyxl.worksheet.worksheet:\n\nappend(iterable) method of openpyxl.worksheet.worksheet.Worksheet instance\n Appends a group of values at the bottom of the current sheet.\n\n * If it's a list: all values are added in order, starting from the first column\n * If it's a dict: values are assigned to the columns indicated by the keys (numbers or letters)\n\n :param iterable: list, range or generator, or dict containing values to append\n :type iterable: list|tuple|range|generator or dict\n\n Usage:\n\n * append(['This is A1', 'This is B1', 'This is C1'])\n * **or** append({'A' : 'This is A1', 'C' : 'This is C1'})\n * **or** append({1 : 'This is A1', 3 : 'This is C1'})\n\n :raise: TypeError when iterable is neither a list/tuple nor a dict\n</code></pre>\n\n<p>This means that your can <code>sheet.append(headers)</code> instead of your ugly loop. Similarly, using <code>.values()</code> on your dictionnaries, you can simplify your <code>write_xls</code> function to:</p>\n\n<pre><code>def write_xls(filepath, dictionary):\n wb = load_workbook(filepath)\n sheet = wb.active\n\n headers = list(dictionary[0])\n sheet.append(headers)\n\n for x in dictionary:\n sheet.append(list(x.values()))\n\n wb.save(filepath)\n</code></pre>\n\n<hr>\n\n<p>Now, a few more things to consider.</p>\n\n<p>First off, since you are only interested in creating the file and writing in it, you may be interested in the <a href=\"https://openpyxl.readthedocs.io/en/stable/optimized.html#write-only-mode\" rel=\"noreferrer\">write-only mode</a> provided by <code>openpyxl</code>. This mean you will simplify your code to a single function:</p>\n\n<pre><code>def write_xls(filepath, dictionary):\n wb = Workbook(write_only=True)\n sheet = wb.create_sheet()\n\n headers = list(dictionary[0])\n sheet.append(headers)\n\n for x in dictionary:\n sheet.append(list(x.values()))\n\n wb.save(filepath)\n</code></pre>\n\n<p>Second, you relly very much on your data being presented well ordered and without flaws. This might bite you at some point. I would:</p>\n\n<ol>\n<li>find all possible headers in your dictionnaries and order them;</li>\n<li>use them to recreate each row using the same ordering each time.</li>\n</ol>\n\n<p>This will allow you to have a coherent output, even with inputs such as:</p>\n\n<pre><code>things = [\n {\n \"Fruit\": \"Orange\",\n \"Flavour\": \"Good\",\n \"Expiration\": \"21May20\",\n },\n {\n \"Flavour\": \"Good\",\n \"Fruit\": \"Apple\",\n \"Expiration\": \"19May20\",\n },\n {\n \"Flavour\": \"Regular\",\n \"Expiration\": \"16May20\",\n \"Fruit\": \"Banana\",\n }\n]\n</code></pre>\n\n<p>or even:</p>\n\n<pre><code>things = [\n {\n \"Fruit\": \"Orange\",\n \"Flavour\": \"Good\",\n \"Expiration\": \"21May20\"\n },\n {\n \"Fruit\": \"Apple\",\n \"Flavour\": \"Good\",\n \"Junk\": \"Spam\",\n \"Expiration\": \"19May20\"\n },\n {\n \"Fruit\": \"Banana\",\n \"Flavour\": \"Regular\",\n \"Expiration\": \"16May20\"\n }\n]\n</code></pre>\n\n<hr>\n\n<p>Proposed improvements:</p>\n\n<pre><code>import itertools\n\nfrom openpyxl import Workbook\n\n\ndef write_xls(filename, data):\n wb = Workbook(write_only=True)\n ws = wb.create_sheet()\n\n headers = list(set(itertools.chain.from_iterable(data)))\n ws.append(headers)\n\n for elements in data:\n ws.append([elements.get(h) for h in headers])\n\n wb.save(filename)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T09:58:18.027",
"Id": "227713",
"ParentId": "227698",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "227713",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T02:40:38.377",
"Id": "227698",
"Score": "5",
"Tags": [
"python",
"excel"
],
"Title": "Python List of Dictionaries to XLS"
}
|
227698
|
<p>So I was fiddling around with the Euler challenges. One of the things they mentioned in their discussions of the solutions is the Sieve of Eratosthenes and that you can only use it when you know an upper bound of the primes you want to generate.</p>
<p>I wondered whether the algorithm can be adapted to work without that upper bound. This works be replacing the <code>bool[]</code> for a <code>Dictionary<int, int></code>. Where the original algorithm would fill all multiples immediately after finding a prime, I will fill them one at a time, keeping a dictionary to keep track of which prime has filled that value in the sieve. This way the sieve can be filled incrementally as enumeration continues.</p>
<p>In my version of C#, this method runs out of steam before we reach <code>int.MaxValue</code>, due to the increasing size of the dictionary. If I am correct, this algorithm runs in <span class="math-container">\$O(n)\$</span> space, and <span class="math-container">\$O(n)\$</span> time.</p>
<pre><code>/// <summary>
/// Produce an "infinite" generator for primes.
/// </summary>
/// <remarks>Runs out of memory at prime 1_003_875_373.</remarks>
public static IEnumerable<int> Primes() {
var sieve = new Dictionary<int, int>();
var primeCandidate = 2;
while (true) {
// If sieve contains primeCandidate, it's not a prime. We retrieve its factor from the dictionary.
if (sieve.TryGetValue(primeCandidate, out var smallestFactor)) {
// Not needed anymore
sieve.Remove(primeCandidate);
// Look for the next multiple that isn't already in the sieve.
// Unchecked because if it overflows, we don't really care, since primeCandidate would have overflowed earlier.
unchecked {
var nextMultiple = primeCandidate + smallestFactor;
while (sieve.ContainsKey(nextMultiple)) {
nextMultiple += smallestFactor;
}
sieve[nextMultiple] = smallestFactor;
}
}
else {
// In this case, we have found a prime. Add its square to the sieve:
yield return primeCandidate;
// Unchecked because if it overflows, we don't really care, since primeCandidate would have overflowed earlier.
unchecked { sieve[primeCandidate * primeCandidate] = primeCandidate; }
}
// This cannot overflow!
checked { primeCandidate++; }
}
}
[TestMethod]
public void TestFirst20Primes() {
var actual = Primes().Take(20).ToList();
var expected = new[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71 };
CollectionAssert.AreEqual(expected, actual);
}
</code></pre>
<p>My main concern is efficiency, both in memory and time.</p>
|
[] |
[
{
"body": "<blockquote>\n<pre><code> // Unchecked because if it overflows, we don't really care, since primeCandidate would have overflowed earlier.\n unchecked { sieve[primeCandidate * primeCandidate] = primeCandidate; }\n</code></pre>\n</blockquote>\n\n<p>is wrong. For example, every <code>int</code> in the range 65537 to 80264 inclusive overflows to a value which is greater than itself.</p>\n\n<p>The easy fix is to add an overflow check. That would also fix the memory problem, because <code>sieve</code> would have no more entries than there are primes below 65536.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T10:29:29.090",
"Id": "443424",
"Score": "0",
"body": "Where did you get these _magic_ numbers from? It would make sense with `UInt16` that is converted to `Int32` when done this `unchecked(UInt16.MaxValue + 1)` which creates an `Int32` but I don't get it how it would work with `Int32` that can hold numbers that are lot larger than this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T10:34:58.403",
"Id": "443425",
"Score": "0",
"body": "@t3chb0t, solve $$x < x^2 - 2^{32} < 2^{31}$$"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T10:51:13.707",
"Id": "443427",
"Score": "0",
"body": "Good point. Actually it appears to be worse than that, since the square can also overflow more than once: $$x < x^2 - k2^{32} < 2^{31}$$ for $$k = \\{1, 2, 3, \\dots\\}$$"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T10:51:41.553",
"Id": "443428",
"Score": "0",
"body": "Hence \"*for example*\"."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T10:11:31.867",
"Id": "227715",
"ParentId": "227706",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "227715",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T07:26:51.057",
"Id": "227706",
"Score": "4",
"Tags": [
"c#",
"performance",
"sieve-of-eratosthenes",
"memory-optimization"
],
"Title": "Incremental Sieve of Eratosthenes Generator"
}
|
227706
|
<h2>Problem Description</h2>
<p>I am working on an e-commerce website, when a user wants to sell a product, he would open the product page and he can upload up to 12 photos:</p>
<p><a href="https://i.stack.imgur.com/OuoQc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/OuoQc.png" alt="enter image description here"></a></p>
<h2>Image Upload Process</h2>
<p>This is the process that I follow for saving images. Once user drops an image on the uploader, it would get saved with a temporary prefix and a timespan. So for example when user drops 3 images, I would have: </p>
<pre><code>tmp-0-20190911123456787.jpg
tmp-1-20190911123456777.jpg
tmp-2-20190911123457777.jpg
</code></pre>
<p>Now once the user completes the process, he clicks on <strong>DONE</strong> button, I create an array of 12 strings, representing the latest image names in the 12 uploaders. </p>
<p>Then I open the corresponding folder (where product's temporary images are dropped). I get all images dropped in the folder, if the images is present in the array, I rename it to a permanent image name, if the uploaded image is not present in the array, I would delete the temp image from the upload folder. This is how photos folder looks like once user click on <strong>DONE</strong>:</p>
<pre><code>img-0-20190911123456787-product-title-is-appended-in-image-name.jpg
img-1-20190911123456777-product-title-is-appended-in-image-name.jpg
img-2-20190911123457777-product-title-is-appended-in-image-name.jpg
</code></pre>
<h2>Infrastructure Consideration</h2>
<p>I use different file systems to save the image, in case of Dev environment the images are stored in local file system. In case of Prod environment, images are stored in AWS S3 Bucket.</p>
<h2>DDD/Architecture Considerations</h2>
<p>I want to follow <strong>DDD</strong> principles and also I want to keep the code <strong>DRY</strong>. Since I have two different infrastructure layers (S3 & local disk) I want to remove as much logic as possible from the infrastructure layer (so I don't have to repeat the logic in each infrastructure layer).</p>
<p>Since I want min logic in Infrastructure layer, I need to put the logic somewhere else. (<strong>But where should this logic go?</strong>)</p>
<p>I assume in DDD, domain is a good place for putting the logic, but at the same time, in DDD an entity should not have dependency on infrastructure layer, and here, <code>FileInfo</code> (i.e. System.IO) is the infrastructure layer for Disk I/O/... <strong>I am finding it very difficult to think of a domain object which does not include <code>FileInfo</code> or <code>FileStream</code>.</strong></p>
<p>So finally this is how my DDD layers look like:</p>
<p><a href="https://i.stack.imgur.com/UVFLh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/UVFLh.png" alt="enter image description here"></a></p>
<h2>The Code:</h2>
<h2>Infrastructure Layer Contract</h2>
<p><strong>IImageRepository.cs</strong></p>
<p>This interface defines the contracts the S3 and Disk IO should implement:</p>
<pre><code>public interface IImageRepository
{
string CreateAdFolder(string folderName);
List<string> GetPermanentImageNames(string photosUrlPath);
string UploadTempImage(FileUpload tempImageUpload);
void SavePermanentImages(List<string> curPhotos, string photosUrlPath, ImageInfo imageInfo);
}
</code></pre>
<h2>Domain Objects (this is only for Upload Bounded Context)</h2>
<p><strong>FileUpload.cs</strong></p>
<pre><code>// when user upload an images, we save the file with a temporary prefix, once user Save the form we rename the temp image name to a permanent image name
// user may upload a couple of images, each image is uploaded through an Uploader. In case of advertisement we have 12 uploaders on the form, but in case of
// profile picture, we only have 1 uploader on the form. Regardless of number of uploaders on the form, user may upload several phones on the same uploader
// befor hitting the save button. When user hits save, we need to delete all the temporary images except the final version when is currently in the uploader
// we need to rename this final images from temp name to a permanent image name
public class FileUpload
{
public FileUpload(HttpPostedFileBase fileToUpload, string urlPath, string upoaderNumber)
{
FileToUpload = fileToUpload;
UrlPath = urlPath;
UploaderNumber = upoaderNumber;
}
public HttpPostedFileBase FileToUpload { get; }
public string FileName
{
get
{
return FileToUpload.FileName;
}
}
public string UrlPath { get; }
public string UploaderNumber { get; }
public void ValidateUploaderNumber()
{
// we have 12 image uploaders on the screen, and they are associated with 12 files in ad folder, we need to check uploaderNumber is within this range
if (int.TryParse(UploaderNumber, out int uploaderNumber))
{
if (uploaderNumber >= 0 && uploaderNumber <= GlobalConstants.NoOfImagesPerAd)
{
return;
}
}
throw new Exception($"Invalid Upload Request: Image Uploader Number: {UploaderNumber}");
}
}
</code></pre>
<p><strong>ImageInfo.cs</strong></p>
<pre><code>// Details that we need for saving an image, these details would saved as the text properties of the image
public class ImageInfo
{
public ImageInfo(string title, string category)
{
Title = title;
Category = category;
}
public string Title;
public string Category;
public string GetJPEGTitle()
{
return $"{Category}: {Title} - Buy and Sell";
}
public string GetJPEGComment()
{
return $"Buy and Sell for Free from Shopless {GlobalConfig.CountryLongName}";
}
public string GetJPEGCopyrite()
{
return $"Shopless {DateTime.Now.Year.ToString()}";
}
}
</code></pre>
<p><strong>UserUploadPath.cs</strong></p>
<pre><code>public class UserPhotosPath
{
public UserPhotosPath(long userId)
{
UserId = userId;
}
public long UserId { get; }
/// <summary>
/// each user has his own images folder, append folder name under user's images folder
/// </summary>
/// <param name="folderName"></param>
/// <returns>// returns something like: /file-uploads/images/24/$(foldername)</returns>
public string AppendtoUserPhotosUrlPath(string folderName)
{
return $"{GetUserPhotosUrl()}{folderName}";
}
public void ValidateUserPermissionToPath(string photosUrlPath)
{
if (string.IsNullOrEmpty(photosUrlPath))
{
throw new Exception($"Invalid empthry Path, UserId: {UserId}");
}
// since photosUrlPath is coming from the browser, a hacker could construct a path with a different userId and upload images to that path
// here, we need to validate the requested path matches the current user's photo upload folder
string curUserPath = GetUserPhotosUrl().TrimStart('/');
string trimmedPhotosUrlPath = photosUrlPath.TrimStart(new char[] { '/' });
if (trimmedPhotosUrlPath.StartsWith(curUserPath, StringComparison.InvariantCultureIgnoreCase))
{
return;
}
throw new Exception($"Access denied for UserId: {UserId}, Path: {photosUrlPath}");
}
// returns something like: /file-uploads/images/24/
private string GetUserPhotosUrl()
{
return $"{GlobalConfig.ImageUploadRelativeRoot}{GlobalConstants.UrlSeparator}{UserId.ToString()}{GlobalConstants.UrlSeparator}";
}
}
</code></pre>
<h2>Common Helper</h2>
<p>I could not think of any place to keep this logic (this is for generating temporary and permanent image name) so I have created a static helper class in Common project:</p>
<p><strong>ImageNameHelper.cs</strong></p>
<pre><code>public static class ImageNameHelper
{
public static string GenerateUniqueAdFolderName()
{
return GetIncrementalUniqueString();
}
/// <summary>
/// Permanent images name should be generated using this pattern: img(UploaderNumber)-(dash-separated-title)-(timestamp).(originalFileExtension)
/// </summary>
/// <param name="fileName">original/temporary file name</param>
/// <param name="imageUploaderNumber">image uploader number</param>
/// <param name="title">Title of the advertisement</param>
/// <returns>something like this: img1-beautiful-scarf-for-sale-20180423134055768-hashcode.jpg</returns>
public static string GenerateUniquePermanentImageName(string fileName, string imageUploaderNumber, string title)
{
title = title.ToDashSeparatedString();
if (string.IsNullOrEmpty(title))
{
title = "picture";
}
return $"{GetPermanentPrefix(imageUploaderNumber)}{title}-{GetIncrementalUniqueString()}{Path.GetExtension(fileName)}";
}
/// <summary>
/// Temporary images name should be generated using this pattern: tmp(uploaderNumber)-(TimeStamp-UniqueCode).(originalFileExtension)
/// </summary>
/// <param name="fileName">OrgiginalImageName.jpg</param>
/// <param name="imageUploaderNumber">uploader number, should be between 0 to 11</param>
/// <returns>something like this: tmp-1-TimeStamp-Guid.jpg</returns>
public static string GenerateUniqueTemporaryImageName(string fileName, string imageUploaderNumber)
{
return GetTemporarytPrefix(imageUploaderNumber) + GetIncrementalUniqueString() + Path.GetExtension(fileName);
}
public static string GetPermanentImagePrefixPattern()
{
return GlobalConstants.PermanentPrefix + "*";
}
public static string GetTemporaryImagePrefixPatternForUploader(string imageUploaderNumber)
{
// all temporary images with uploader 1 should start with tmp-1 (pattern would be "tmp1-*")
return GetTemporarytPrefix(imageUploaderNumber) + "*";
}
public static bool DoesImageHaveCorrectPermanentPrefix(string imageName, string imageUploaderNumber)
{
if (imageName.StartsWith(GetPermanentPrefix(imageUploaderNumber), StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
return false;
}
private static string GetPermanentPrefix(string imageUploaderNumber)
{
return GlobalConstants.PermanentPrefix + imageUploaderNumber + "-";
}
private static string GetTemporarytPrefix(string imageUploaderNumber)
{
return GlobalConstants.TemporaryPrefix + imageUploaderNumber + "-";
}
// I am using TimeStap to ensure names generated names are incremental and a Guid to ensure they are unique
private static string GetIncrementalUniqueString()
{
return DateTime.Now.ToCompactDateTimeString() + "-" + Math.Abs(Guid.NewGuid().GetHashCode()).ToString();
}
}
</code></pre>
<h2>Infrastructure Layer (Disk)</h2>
<p>This is the implementation of the contracts for saving images in the file system:</p>
<pre><code>public class DiskImageRepository : IImageRepository
{
private UserPhotosPath _userPath;
private DiskPhysicalPathMapper _physicalPathMapper;
public DiskImageRepository(UserPhotosPath userPath, DiskPhysicalPathMapper physicalPathBuilder)
{
_userPath = userPath;
_physicalPathMapper = physicalPathBuilder;
}
public string CreateAdFolder(string folderName)
{
string photosUrlPath = _userPath.AppendtoUserPhotosUrlPath(folderName);
// no need to check if User directory already exists or not, since it would be automatically created if missing
// Create directory will throw exception if it cannot create the directory
string physicalPath = _physicalPathMapper.ConvertUrlToPhysicalPath(photosUrlPath);
Directory.CreateDirectory(physicalPath);
return photosUrlPath;
}
public List<string> GetPermanentImageNames(string photosUrlPath)
{
int i = 0;
List<string> photos = new List<string>(new string[GlobalConstants.NoOfImagesPerAd]); // initialize list to contain 12 elements
string physicalPath = GetValidatedPhysicalPath(photosUrlPath);
FileInfo[] images = GetFiles(physicalPath, ImageNameHelper.GetPermanentImagePrefixPattern());
foreach (FileInfo image in images)
{
if (i >= GlobalConstants.NoOfImagesPerAd)
{
LogConfig.Logger.Error($"{photosUrlPath} contains more than {GlobalConstants.NoOfImagesPerAd} files, the cause need to be investigated.");
break;
}
photos[i++] = image.Name;
}
return photos;
}
public string UploadTempImage(FileUpload tempImageUpload)
{
// exception is thrown if any of the following validation fails
_userPath.ValidateUserPermissionToPath(tempImageUpload.UrlPath);
tempImageUpload.ValidateUploaderNumber();
var physicalPath = GetValidatedPhysicalPath(tempImageUpload.UrlPath);
DeleteSuperceededTemporaryImagesByUploaderNumber(physicalPath, tempImageUpload.UploaderNumber);
var tmpFileName = ImageNameHelper.GenerateUniqueTemporaryImageName(tempImageUpload.FileName, tempImageUpload.UploaderNumber);
var fullPhysicalPath = Path.Combine(physicalPath, tmpFileName);
tempImageUpload.FileToUpload.SaveAs(fullPhysicalPath);
return tmpFileName;
}
public void SavePermanentImages(List<string> curPhotos, string photosUrlPath, ImageInfo imageInfo)
{
_userPath.ValidateUserPermissionToPath(photosUrlPath);
var physicalPath = GetValidatedPhysicalPath(photosUrlPath);
FileInfo[] images = GetFiles(physicalPath);
for (int i = 0; i < curPhotos.Count; i++)
{
if (!string.IsNullOrEmpty(curPhotos[i]))
{
if (images.Where(img => string.Equals(img.Name, curPhotos[i], StringComparison.InvariantCultureIgnoreCase)).Any() == false)
{
LogConfig.Logger.Error($"photo: {curPhotos[i]}, was not found in ad folder: {photosUrlPath}. This is either a bug or a malicious request.");
curPhotos[i] = string.Empty;
}
}
}
foreach (FileInfo image in images)
{
var index = curPhotos.FindIndex(p => p.Equals(image.Name, StringComparison.InvariantCultureIgnoreCase));
if (index >= 0)
{
if (ImageNameHelper.DoesImageHaveCorrectPermanentPrefix(image.Name, index.ToString()) == false)
{
var permanentImageName = ImageNameHelper.GenerateUniquePermanentImageName(image.Name, index.ToString(), imageInfo.Title);
string fullPhysicalPath = Path.Combine(physicalPath, permanentImageName);
image.MoveTo(fullPhysicalPath);
SetJpegMetadata(fullPhysicalPath, imageInfo);
curPhotos[index] = permanentImageName;
}
}
else
{
image.Delete();
}
}
}
private string GetValidatedPhysicalPath(string urlPath)
{
string physicalPath = _physicalPathMapper.ConvertUrlToPhysicalPath(urlPath);
if (!Directory.Exists(physicalPath))
{
throw new Exception($"Path does not exists: {physicalPath}");
}
return physicalPath;
}
// We have 12 images uploader on the screen which correspond to 12 files (place holders) in ad folder, on the disk drive. If an image is
// uploaded on uploader 1, we need to delete all other temporary images uploaded on uploader 1. We should not delete permanent images at
// this stage, because user may not saves changes, and in that case we need to delete all temporary images
// NOTE: it is considered that path and uploader number are already validated.
private void DeleteSuperceededTemporaryImagesByUploaderNumber(string adFolderFullPhysicalPath, string uploaderNumber)
{
FileInfo[] oldTmpImages = GetFiles(adFolderFullPhysicalPath, ImageNameHelper.GetTemporaryImagePrefixPatternForUploader(uploaderNumber));
foreach (var oldTmpImage in oldTmpImages)
{
oldTmpImage.Delete();
}
}
private FileInfo[] GetFiles(string physicalPath, string searchPattern = "")
{
if (string.IsNullOrEmpty(searchPattern))
{
searchPattern = "*";
}
DirectoryInfo di = new DirectoryInfo(physicalPath);
return di.GetFiles(searchPattern).OrderBy(x => x.Name.PadNumbersForAlphanumericSort()).ToArray();
}
private void SetJpegMetadata(string physicalPathToJpeg, ImageInfo imageInfo)
{
var jpeg = new JpegMetadataAdapter(physicalPathToJpeg);
jpeg.Metadata.Title = imageInfo.GetJPEGTitle();
jpeg.Metadata.Comment = imageInfo.GetJPEGComment();
jpeg.Metadata.Copyright = imageInfo.GetJPEGCopyrite();
jpeg.Save();
}
}
</code></pre>
<p><strong>DiskPhysicalPathMapper.cs</strong></p>
<p>This is just a mapper to translate URL paths to Physical Path (for Disk):</p>
<pre><code>public class DiskPhysicalPathMapper
{
private readonly string _physicalRoot;
private readonly string _urlRoot;
public DiskPhysicalPathMapper(string urlRoot, string physicalRoot)
{
_urlRoot = urlRoot;
_physicalRoot = physicalRoot;
}
public string ConvertUrlToPhysicalPath(string urlPath)
{
if (string.IsNullOrEmpty(urlPath))
{
throw new Exception($"invalid photosUrlPath: {urlPath}");
}
// replace url root with physical root, case insensitive
var path = Regex.Replace(urlPath, _urlRoot, _physicalRoot, RegexOptions.IgnoreCase);
return path.Replace(GlobalConstants.UrlSeparator, @"\");
}
}
</code></pre>
<p>I also have a <code>JPegMethaDataAdapter</code> class that I have not included in the review, it just sets JPEG image properties.</p>
<p>I have also not included the S3 infrastructure layer.</p>
|
[] |
[
{
"body": "<p>at first I thought to write this as a comment, perhaps the comment would be a little to long… </p>\n\n<p>There are many things to consider here, not really inline with your question but perhaps you should consider them. </p>\n\n<ol>\n<li>Transactional scope. You update the database, remove records… you may end-up orphaning the disk images where you have images that are\nnot referenced in your database.</li>\n<li>Disc capacity, when disks get full you need to stripe them, having a\nfull database is easyer to solve as you can just ad a datafile and\nhave a filegroup span multiple disks</li>\n<li>Giving write access to the disk subsystem to your website</li>\n<li>Load balancing becomes hard, you will have to start working with\nmountpoints and add one more point of failure</li>\n<li>Disk and operating system performance with large quantities of files\ndegradates, I have an icon repository, when I load it on my PC I\nloose the ability to preview images.</li>\n</ol>\n\n<p>As to your code, I would consider caching the data where you think it makes sense. At the moment I see no cashing and I guess that this could help reduce some IO, perhaps look at ClientCache and OutputCache.</p>\n\n<p>We ended up storing images in the database and we had a webservice running as a CDN so that browsers make better use of parallel loads and the webservice could better process content and cash the content. Depending on the Trafik and SLA you might get issues, not saying you will, but be aware.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T12:27:06.003",
"Id": "443439",
"Score": "0",
"body": "Thanks for this, I am using AWS S3 bucket and (CloudFront) in Production (disk storage is for Dev environment). CloudFront looks after caching (and Load balancing). S3 bucket does not have storage limitations of local disk storage."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T18:20:33.137",
"Id": "443474",
"Score": "0",
"body": "@HoomanBahreini, excellent that's taking care of a few of the issues, I guess you'd need to consider to make a batch file that allows you to clean-up images that are nolonger used."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T11:54:35.700",
"Id": "227719",
"ParentId": "227709",
"Score": "5"
}
},
{
"body": "<h2>Review</h2>\n\n<p>Modelling the domain is crucial when designing a multi-layered application. Your concerns about polutting the domain with file or web specific code is pivotal to make a clean, extensible, reusable and testable API.</p>\n\n<blockquote>\n <p><em>I am finding it very difficult to think of a domain object which does not include FileInfo or FileStream.</em></p>\n</blockquote>\n\n<hr>\n\n<p>I would suggest the following guidelines for designing your layers.</p>\n\n<h3>Domain Entities</h3>\n\n<ul>\n<li>Use <a href=\"https://en.wikipedia.org/wiki/Plain_old_CLR_object\" rel=\"nofollow noreferrer\">plain and simple classes</a> with public getters and setters.</li>\n<li>Don't include web or file specific references like <code>FileUpload.FileToUpload</code> which is of type <code>System.Web.HttpPostedFileBase</code>. Instead have a property <code>IReadOnlyCollection<byte> Content</code> and <code>string FileName</code>.</li>\n</ul>\n\n<h3>Domain Services</h3>\n\n<ul>\n<li>Put all configuration and validation logic in services, not in the entities. This way, you can inject configuration and validation behavior at runtime using IoC. Entity <code>UserPhotosPath</code> should have its methods extracted to (for example) a <code>IUserPermissionsValidator</code> and <code>IUserPhotoRepository</code> interface. </li>\n<li>Perhaps you could provide a <code>IUserPhotoService</code> as a facade for dealing with the validators and repositories internally. Like Entities, <a href=\"https://en.wikipedia.org/wiki/Domain-driven_design#Building_blocks\" rel=\"nofollow noreferrer\">Services</a> are a thing in DDD :)</li>\n<li>Async methods could provide resource consuming behavior: You might want to include a method <code>async Task<IReadOnlyCollection<byte>> ReadContentAsync();</code></li>\n</ul>\n\n<h3>Infrastructure Services/Repositories</h3>\n\n<ul>\n<li>It is fine for the infrastructure layer to have file and web specific operations. But their public interface should work with the domain classes. Have your services call the infrastructure layer internally. Use the <a href=\"https://en.wikipedia.org/wiki/Dependency_inversion_principle\" rel=\"nofollow noreferrer\">Dependency Inversion Principle</a> to provide the interfaces for the infrastructure layer at the domain layer.</li>\n</ul>\n\n<hr>\n\n<p>When providing the above layers using the aforementioned patterns and principles, you should be able to provide:</p>\n\n<ul>\n<li>DRY code (services with common logic, infrastructure specific implementations)</li>\n<li>an independant domain (no web, no file specific concerns)</li>\n<li>DDD using POCO entities and Services</li>\n<li>Layers communicating through the Dependency Inversion Principle</li>\n<li>Testable and reusable services using interfaces</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T03:35:38.590",
"Id": "444821",
"Score": "0",
"body": "Thanks a lot. Using a domain service had never crossed my mind (great suggestion). If I bring the validation logic out of the entity, would I not move toward an anemic domain model?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T06:39:03.950",
"Id": "444838",
"Score": "0",
"body": "That depends on your definition of domain model. I would argue that both the entities and services make up for the model. By moving domain specific behavior to services and keeping the entities simple, I believe you could benefit best from best practices such as dependency injection to allow for easy configuration and testability of the API."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T14:46:24.310",
"Id": "445434",
"Score": "0",
"body": "`byte[]` properties are discouraged: https://docs.microsoft.com/en-us/visualstudio/code-quality/ca1819-properties-should-not-return-arrays?view=vs-2019"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T14:51:52.927",
"Id": "445634",
"Score": "0",
"body": "@Tseng Good point, since these classes aren't DTO's, we should use IEnumerable or IReadOnlyCollection instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T14:56:53.360",
"Id": "445637",
"Score": "1",
"body": "@Tseng we don't have to follow every suggestion comming from Microsoft, they do not follow their own conventions either, here's an example from ASP.NET-Core https://github.com/aspnet/AspNetCore/blob/87629bbad906e9507026692904b6bcb5021cdd33/src/Middleware/Session/src/NoOpSessionStore.cs#L12] and here a byte array would be much more convenient than other data structures because you can use it directly with streams and the method's name `ReadContentAsync` looks like it is returning a buffer for/from a stream."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T19:02:08.497",
"Id": "228865",
"ParentId": "227709",
"Score": "5"
}
},
{
"body": "<p>Thank you for an interesting question \nHere is the first part of the answer, I will publish more over the weekend at <a href=\"https://github.com/dmitrynogin/shopless\" rel=\"nofollow noreferrer\">https://github.com/dmitrynogin/shopless</a>. </p>\n\n<p>Let’s talk about storage access first. You need to deal with different types of storages, so let’s abstract:</p>\n\n<pre><code>public abstract class Folder : Enumerable<string>\n{\n public static Folder Open(Connection @string) => \n @string.Open<Folder>();\n\n public abstract Stream Write(string file);\n public abstract Stream Read(string file);\n public abstract void Delete(string file);\n}\n</code></pre>\n\n<p>Connection string allows you to resolve concrete storage type and content location at run-time using stringly typed configuration parameter. It adds a lot of flexibility when you are testing, even allows to combine different storages.</p>\n\n<p>Connection looks like this:</p>\n\n<pre><code>public sealed class Connection : ValueObject<Connection>\n{\n public static implicit operator Connection(string @string) => Parse(@string);\n public static Connection Parse(string @string) => new Connection(@string); \n\n Connection(string @string)\n {\n Values = @string.Split(';')\n .Select(nv => nv.Split('='))\n .ToDictionary(\n nv => nv[0].Trim(), \n nv => string.Join(\"=\", nv.Skip(1)).Trim());\n }\n\n IReadOnlyDictionary<string, string> Values { get; }\n\n public T Get<T>(string name, T @default = default(T)) =>\n Values.TryGetValue(name, out var value) \n ? (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(value)\n : @default;\n\n public T Open<T>() => (T)Activator.CreateInstance(\n Type.GetType(Get<string>(\"Type\")), this);\n\n protected override IEnumerable<object> EqualityCheckAttributes => \n new object[] { ToString() };\n\n public override string ToString() => \n string.Join(\";\", from nv in Values\n select $\"{nv.Key}={nv.Value}\");\n}\n</code></pre>\n\n<p>Where concrete disk folder implementation could look like the following:</p>\n\n<pre><code>public sealed class DiskFolder : Folder\n{\n public static Connection String(string path) => \n $\"Type={typeof(DiskFolder).FullName}, {typeof(DiskFolder).Assembly.GetName().Name};\" + \n $\"Path={path}\";\n\n public DiskFolder()\n : this(GetTempPath())\n {\n }\n\n public DiskFolder(Connection @string)\n : this(@string.Get<string>(\"Path\"))\n {\n }\n\n public DiskFolder(string path) \n {\n Path = path ?? throw new ArgumentNullException(nameof(path));\n if (!Exists(Path))\n CreateDirectory(Path);\n }\n\n public string Path { get; }\n\n public override IEnumerator<string> GetEnumerator() => \n EnumerateFiles(Path).Select(GetFileName).GetEnumerator();\n\n public override Stream Write(string file) => \n File.OpenWrite(Combine(Path, file));\n\n public override Stream Read(string file) =>\n File.OpenRead(Combine(Path, file));\n\n public override void Delete(string file) =>\n File.Delete(Combine(Path, file));\n}\n</code></pre>\n\n<p>The home work would be to create <code>S3BucketFolder</code> – just pack all the required parameters into the connection string.</p>\n\n<p>Helpers to be as DRY as possible are:</p>\n\n<pre><code>public abstract class Enumerable<T> : IEnumerable<T>\n{\n IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n public abstract IEnumerator<T> GetEnumerator();\n}\n</code></pre>\n\n<p>And:</p>\n\n<pre><code>public abstract class ValueObject<T> : IEquatable<ValueObject<T>>\n where T : ValueObject<T>\n{\n protected abstract IEnumerable<object> EqualityCheckAttributes { get; }\n\n public override int GetHashCode() =>\n EqualityCheckAttributes\n .Aggregate(0, (hash, a) => unchecked(hash * 31 + (a?.GetHashCode() ?? 0)));\n\n public override bool Equals(object obj) =>\n Equals(obj as ValueObject<T>);\n\n public virtual bool Equals(ValueObject<T> other) =>\n other != null &&\n GetType() == other.GetType() &&\n EqualityCheckAttributes.SequenceEqual(other.EqualityCheckAttributes);\n\n public static bool operator ==(ValueObject<T> left, ValueObject<T> right) =>\n Equals(left, right);\n\n public static bool operator !=(ValueObject<T> left, ValueObject<T> right) =>\n !Equals(left, right);\n}\n</code></pre>\n\n<p>Please note that all projects in the solution have the same default namespace “Shopless” to reduce amount of required <code>using</code> directives to the minimum.</p>\n\n<p>You could test the folder:</p>\n\n<pre><code> [TestMethod]\n public void Stringify()\n {\n Connection connection = DiskFolder.String(\"c:\\\\proj\");\n Assert.AreEqual(\n \"Type=Shopless.IO.DiskFolder, Shopless.Disk;Path=c:\\\\proj\", \n $\"{connection}\");\n }\n</code></pre>\n\n<p>And:</p>\n\n<pre><code> [TestMethod]\n public void Open()\n {\n Folder folder = Folder.Open(\"Type=Shopless.IO.DiskFolder, Shopless.Disk;Path=c:\\\\proj\");\n Assert.IsTrue(folder is DiskFolder df && df.Path == \"c:\\\\proj\");\n }\n</code></pre>\n\n<p>And:</p>\n\n<pre><code> [TestMethod]\n public void Manage_Files()\n {\n var folder = new DiskFolder();\n folder.Delete(\"test.txt\");\n Assert.IsFalse(folder.Contains(\"test.txt\"));\n folder.Write(\"test.txt\").Dispose();\n folder.Read(\"test.txt\").Dispose();\n Assert.IsTrue(folder.Contains(\"test.txt\"));\n folder.Delete(\"test.txt\");\n Assert.IsFalse(folder.Contains(\"test.txt\"));\n }\n</code></pre>\n\n<p>More stuff is coming :)</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Let’s now define a configuration mechanism and use it:</p>\n\n<pre><code>public class Config : ValueObject<Config>\n{ \n public static readonly Config Local = Load(\"local.json\");\n public static readonly Config Stage = Load(\"stage.json\");\n public static readonly Config Published = Load(\"published.json\");\n public static readonly Config Active = Published ?? Stage ?? Local;\n\n public static Config Load(string file) =>\n Exists(file) ? JsonConvert.DeserializeObject<Config>(ReadAllText(file)) : null;\n\n public Config(string uploadFolder, string imageFolder)\n {\n UploadFolder = uploadFolder;\n ImageFolder = imageFolder;\n }\n\n public Connection UploadFolder { get; }\n public Connection ImageFolder { get; }\n\n protected override IEnumerable<object> EqualityCheckAttributes =>\n new object[] { UploadFolder, ImageFolder };\n}\n</code></pre>\n\n<p>Now we will have IStorage to represent folder set across the solution to inject where folder access is required:</p>\n\n<pre><code>public interface IStorage\n{\n Folder Upload { get; }\n Folder Images { get; } \n}\n</code></pre>\n\n<p>My default implementation uses active configuration:</p>\n\n<pre><code>[Service]\npublic class Storage : IStorage\n{\n public Folder Upload => Folder.Open(Config.Active.UploadFolder);\n public Folder Images => Folder.Open(Config.Active.ImageFolder);\n}\n</code></pre>\n\n<p>Have a look at <a href=\"https://github.com/dmitrynogin/shopless/tree/master/Shopless.Autofac\" rel=\"nofollow noreferrer\"><code>Shopless.Autofac</code></a> and <a href=\"https://github.com/dmitrynogin/shopless/tree/master/Demo\" rel=\"nofollow noreferrer\"><code>Demo</code></a> projects to see how <a href=\"https://github.com/dmitrynogin/shopless/blob/master/Shopless.Domain/Base/ServiceAttribute.cs\" rel=\"nofollow noreferrer\"><code>ServiceAttribute</code></a> works.</p>\n\n<p>Now it is time to define our service according to the first paragraph of your question:</p>\n\n<pre><code>public interface IImageUploader\n{\n string Upload(int number, Stream jpeg);\n void Rename(string product, params string[] images);\n}\n</code></pre>\n\n<p>Where the implementation would be:</p>\n\n<pre><code>[Service]\npublic class ImageUploader : IImageUploader\n{\n public ImageUploader(IStorage storage)\n {\n Storage = storage ?? throw new ArgumentNullException(nameof(storage));\n }\n\n IStorage Storage { get; }\n\n public string Upload(int number, Stream jpeg)\n {\n var name = TemporaryImageName.New(number);\n using (var file = Storage.Upload.Write(name))\n jpeg.CopyTo(file);\n\n return name;\n }\n\n public void Rename(string product, params string[] images)\n {\n var pn = ProductName.New(product);\n foreach (var tin in images.Select(TemporaryImageName.Parse))\n if(Storage.Upload.Contains(tin))\n {\n var pin = ProductImageName.New(tin, pn);\n Storage.Upload.MoveTo(Storage.Images, tin, pin);\n }\n }\n}\n</code></pre>\n\n<p>We will need:</p>\n\n<pre><code>public class ProductName : ValueObject<ProductName>\n{\n public static ProductName New(string text) =>\n new ProductName(text.Trim(), Slug.New(text));\n\n public ProductName(string text, Slug slug)\n {\n Text = text ?? throw new ArgumentNullException(nameof(text));\n Slug = slug ?? throw new ArgumentNullException(nameof(slug));\n }\n\n public string Text { get; }\n public Slug Slug { get; }\n\n protected override IEnumerable<object> EqualityCheckAttributes => \n new object[] { Slug };\n}\n</code></pre>\n\n<p>And:</p>\n\n<pre><code>public class Slug : ValueObject<Slug>\n{\n public static Slug New(string text) =>\n new Slug(text\n .Trim()\n .Replace(\" \", \"-\")\n .ToLowerInvariant());\n\n public static Slug Parse(string text) =>\n TryParse(text, out var slug) ? slug : throw new FormatException(\"Malformed slug.\");\n\n public static bool TryParse(string text, out Slug slug) =>\n (slug = IsNullOrWhiteSpace(text) ? null : new Slug(text)) != null;\n\n public Slug(string text)\n {\n Text = text;\n }\n\n public string Text { get; }\n\n public override string ToString() => Text;\n\n protected override IEnumerable<object> EqualityCheckAttributes =>\n new object[] { Text };\n}\n</code></pre>\n\n<p>And:</p>\n\n<pre><code>public class TemporaryImageName : ValueObject<TemporaryImageName>\n{\n public static implicit operator string(TemporaryImageName name) => $\"{name}\";\n\n public static TemporaryImageName New(int number) =>\n new TemporaryImageName(number, Clock.Time());\n\n public static TemporaryImageName Parse(string text) =>\n GetExtension(text) == \".jpg\" &&\n GetFileNameWithoutExtension(text).Split('-') is string[] p &&\n p.Length == 3 && p[0] == \"tmp\" &&\n int.TryParse(p[1], out var n) &&\n DateTime.TryParseExact(p[2], \"yyyyMMddHHmmssfff\", null, DateTimeStyles.None, out var t)\n ? new TemporaryImageName(n, t)\n : throw new FormatException(\"Invalid temporary image name.\");\n\n public TemporaryImageName(int number, DateTime timestamp)\n {\n Number = number;\n Timestamp = timestamp;\n }\n\n public int Number { get; }\n public DateTime Timestamp { get; }\n\n public override string ToString() => $\"tmp-{Number}-{Timestamp:yyyyMMddHHmmssfff}.jpg\";\n\n protected override IEnumerable<object> EqualityCheckAttributes =>\n new object[] { Number, Timestamp };\n}\n</code></pre>\n\n<p>And:</p>\n\n<pre><code>public class ProductImageName : ValueObject<ProductImageName>\n{\n public static implicit operator string(ProductImageName name) => $\"{name}\";\n\n public static ProductImageName New(TemporaryImageName imageName, ProductName productName) => \n new ProductImageName(imageName.Number, imageName.Timestamp, productName.Slug);\n\n public static ProductImageName Parse(string text) =>\n GetExtension(text) == \".jpg\" &&\n GetFileNameWithoutExtension(text).Split('-') is string[] p &&\n p.Length == 4 && p[0] == \"tmp\" &&\n int.TryParse(p[1], out var n) &&\n DateTime.TryParseExact(p[2], \"yyyyMMddHHmmssfff\", null, DateTimeStyles.None, out var t) &&\n Slug.TryParse(p[3], out var slug) \n ? new ProductImageName(n, t, slug)\n : throw new FormatException(\"Invalid product image name.\");\n\n public ProductImageName(int number, DateTime timestamp, Slug product)\n {\n Number = number;\n Timestamp = timestamp;\n Product = product ?? throw new ArgumentNullException(nameof(product));\n }\n\n public int Number { get; }\n public DateTime Timestamp { get; }\n public Slug Product { get; }\n\n public override string ToString() => $\"img-{Number}-{Timestamp:yyyyMMddHHmmssfff}-{Product}.jpg\";\n\n protected override IEnumerable<object> EqualityCheckAttributes => \n new object[] { Number, Timestamp, Product };\n}\n</code></pre>\n\n<p>Please note that we provide persistability of those types by allowing data flow unmodified through public constructor to public readonly properties. We should use a static factory method to produce a new Slug, etc. This way you are safe to modify factory behavior without invalidating the persistent state when/where available.</p>\n\n<p>The integration test would be:</p>\n\n<pre><code>[TestClass]\npublic class ImageUploader_Should\n{\n [TestMethod]\n public void Upload()\n {\n Clock.Time = () => new DateTime(2019, 1, 2, 3, 4, 5, 678);\n\n IStorage storage = new Storage();\n storage.Upload.Clear();\n storage.Images.Clear();\n\n IImageUploader iu = new ImageUploader(storage);\n\n var tin1 = iu.Upload(1, new MemoryStream());\n var tin2 = iu.Upload(2, new MemoryStream());\n\n iu.Rename(\"Best Pasta Ever\", tin1, tin2);\n\n Assert.IsFalse(storage.Upload.Any());\n\n Assert.AreEqual(2, storage.Images.Count());\n Assert.IsTrue(storage.Images.Contains(\"img-1-20190102030405678-best-pasta-ever.jpg\"));\n Assert.IsTrue(storage.Images.Contains(\"img-2-20190102030405678-best-pasta-ever.jpg\"));\n }\n}\n</code></pre>\n\n<p>You can see here a use of ambient system time property which is part of our domain logic: </p>\n\n<pre><code>public class Clock\n{\n public static Func<DateTime> Time { get; set; } = () => DateTime.Now;\n}\n</code></pre>\n\n<p>Please feel free to ping me in skype if you have any questions: <strong>dmitrynogin</strong></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-16T17:59:36.937",
"Id": "445477",
"Score": "0",
"body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/98742/discussion-on-answer-by-dmitry-nogin-ddd-architecture-for-an-e-commerce-website)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T07:22:04.217",
"Id": "228947",
"ParentId": "227709",
"Score": "4"
}
},
{
"body": "<h2>Architecture</h2>\n\n<p>DDD-wise : The most important thing about DDD is that the domain drives the design (so.. DDD). That means that when we look at your domain objects we should be able to understand the whole logic of your application.</p>\n\n<p>Let's summarize what your application is doing : A <em>user</em> posts an <em>product</em> for sale, where the product can have a <em>Youtube link</em>, a <em>website</em> and <em>some photos</em>.</p>\n\n<p>For every noun in there, there should be a corresponding object. Maybe you have them, maybe you don't, I can't tell from the picture you uploaded. The what I can at least tell is that a photo doesn't belong to a user, but to a product (which means that the class <code>UserPhotosPath</code> needs to be re-thought of).</p>\n\n<p>So, your bounded context should look like <code>Product has {Photos, Youtube link, website link}</code> and a user has products.</p>\n\n<hr>\n\n<p>One very important thing I think you misunderstood about DDD is that the domain is the good place to put the domain logic, not <em>all</em> the logic. Domain logic includes : Relationship between entities, validations. That's... pretty much all. So, you need to ask yourself, does my domain depend on some file system? Do you want your domain, which should be comprised of <em>only</em> domain objects, to know that you use a file system to store your images? That's your problem. You have a hard time to create a domain object named <code>FileInfo</code> because it shouldn't be a domain object.</p>\n\n<hr>\n\n<p>Finally, Domain Driven Design is kind of a pain to use in a web context, there's one pitfall you should be very aware of that will kill the scalability and performance of your application. The whole bounded context things should be used <strong>only</strong> when writing to the application. Which means, when you need to show something on your website, have a separate project where all you do is load data in POCOs (plain old C# objects), skipping all business logic, because it doesn't apply to reading.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T05:24:28.120",
"Id": "445117",
"Score": "0",
"body": "Thanks, your explanation is really great (simple words). I have 2 bounded context: `Domain.Main` which holds the product info and `Doman.Upload` which holds file uploads and images. Reading your answer I guess my choice of creating a bounded context for `uploads` was a poor one. They fit better in `Domain.Main` Bounded context which holds Users and Products."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T05:26:20.300",
"Id": "445118",
"Score": "0",
"body": "Regarding your last point, I have my domain `Entities` which are mapped to `ViewModels` for the purpose of display. Does it cover your final point?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T05:59:14.160",
"Id": "445119",
"Score": "0",
"body": "`'UserPhotosPath` entity feels a bit odd to me too, but it's quite functional. Basically I have a directory for each user (the name of directory is the `userId`) and under this directory I create one sub directory for each advertisement. Te whole purpose of this entity is to check current logged in user has permission to file upload request (which contains a path and comes from client/browser). Also when I was to create a new advertisement, this entity create a new path under user's path for the advertisement. This entity is always injected into service that need to work with user path."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T13:14:28.220",
"Id": "446785",
"Score": "0",
"body": "@HoomanBahreini Your bounded context should relate to concepts within your application, according to DDD. So `Main` is probably too large too! Yes your `ViewModels` should cover this problem. I think you should consider using a Database for your data storage instead of a folder system. Also, consider this : If a user has permission over an ad, it should have permission over the images in it."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T13:45:50.877",
"Id": "228972",
"ParentId": "227709",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "228972",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T08:43:09.277",
"Id": "227709",
"Score": "8",
"Tags": [
"c#",
"design-patterns",
"file-system",
"asp.net-mvc",
"ddd"
],
"Title": "DDD Architecture for an e-commerce website (uploading images)"
}
|
227709
|
<p>For my research I'm working on global search methods where a <em>candidate</em> solution can have it's <em>fitness</em> (=score) evaluated in multiple <em>fidelities</em> (=accuracy levels). The goal of the <code>CandidateArchive</code> is to keep a clear overview of which candidate solutions have been evaluated under which fidelities. A candidate is an <code>ndim</code>-dimensional vector of floating point values, with <code>ndim</code> known in advance.</p>
<p>During its usage, new candidates will be added to the archive together with the fitness score for some fidelity-level. High(er) fidelity fitness scores may be added later. The archive can give back all candidates that have a fitness score for a given list of fidelities.</p>
<p>A trivial example of the stored data at some point might look like this:</p>
<pre class="lang-none prettyprint-override"><code>candidate | high-fidelity | low-fidelity
-----------+---------------+---------------
(0.1, 0.2) | NaN | 1.57
(0.2, 0.7) | 2.5 | 1.25
(1.5, 2.1) | NaN | 2.78
(0.2, 1.1) | 3.8 | 4.31
(1.5, 0.5) | NaN | 1.57
</code></pre>
<p>I feel like my interface design for this <code>CandidateArchive</code> is not what I want it to be, but don't quite know how I can improve it. Suggestions for tests (pytest/<a href="https://hypothesis.readthedocs.io/en/latest/index.html" rel="nofollow noreferrer">hypothesis</a>) are also more than welcome.</p>
<pre><code>import numpy as np
from warnings import warn
from collections import namedtuple
CandidateSet = namedtuple('CandidateSet', ['candidates', 'fitnesses'])
class CandidateArchive:
def __init__(self, ndim, fidelities=None):
"""An archive of candidate: fitnesses pairs, for one or multiple fidelities"""
self.ndim = ndim
if not fidelities:
fidelities = ['fitness']
self.fidelities = fidelities
self.data = {}
self.max = {fid: -np.inf for fid in self.fidelities}
self.min = {fid: np.inf for fid in self.fidelities}
def __len__(self):
return len(self.data)
def addcandidates(self, candidates, fitnesses, fidelity=None, *, verbose=False):
"""Add multiple candidates to the archive"""
for cand, fit in zip(candidates, fitnesses):
self.addcandidate(cand, fit, fidelity=fidelity, verbose=verbose)
def addcandidate(self, candidate, fitness, fidelity=None, *, verbose=False):
"""Add a candidate to the archive. Will overwrite fitness value if candidate is already present"""
if len(self.fidelities) == 1 and fidelity is not None and verbose:
warn(f"fidelity specification {fidelity} ignored in single-fidelity case", RuntimeWarning)
elif len(self.fidelities) > 1 and fidelity is None:
raise ValueError('must specify fidelity level in multi-fidelity case')
if fidelity is None:
fidelity = self.fidelities
# Checking types to make sure they are iterable in the right way
if isinstance(fitness, (np.float64, float)):
fitness = [fitness]
if isinstance(fidelity, str):
fidelity = [fidelity]
for fid, fit in zip(fidelity, list(fitness)):
if tuple(candidate) not in self.data:
self._addnewcandidate(candidate, fit, fid, verbose=verbose)
else:
self._updatecandidate(candidate, fit, fid, verbose=verbose)
def _addnewcandidate(self, candidate, fitness, fidelity=None, *, verbose=False):
if len(self.fidelities) == 1:
fit_values = [fitness]
else:
fit_values = np.array([np.nan] * len(self.fidelities))
idx = self.fidelities.index(fidelity)
fit_values[idx] = fitness
self._updateminmax(fidelity, fitness)
self.data[tuple(candidate)] = fit_values
def _updatecandidate(self, candidate, fitness, fidelity=None, *, verbose=False):
fit_values = self.data[tuple(candidate)]
if fidelity is None:
fidelity = 'fitness'
fid_idx = self.fidelities.index(fidelity)
if verbose and not np.isnan(fit_values[fid_idx]):
warn(f"overwriting existing value '{self.data[tuple(candidate), fid_idx]}' with '{fitness}'", RuntimeWarning)
fit_values[fid_idx] = fitness
self._updateminmax(fidelity, fitness)
def getcandidates(self, num_recent_candidates=None, fidelity=None):
"""Retrieve candidates and fitnesses from the archive.
:param num_recent_candidates: (optional) Only return the last `n` candidates added to the archive
:param fidelity: (optional) Only return candidate and fitness information for the specified fidelities
:return: Candidates, Fitnesses (tuple of numpy arrays)
"""
if type(fidelity) in [tuple, list]:
pass
elif fidelity:
fidelity = [fidelity]
else:
fidelity = ['fitness']
indices = [self.fidelities.index(fid) for fid in fidelity]
candidates = []
fitnesses = []
for candidate, fits in self.data.items():
for idx in indices:
if np.isnan(fits[idx]):
break
else:
candidates.append(list(candidate))
fitnesses.append([fits[idx] for idx in indices])
candidates = np.array(candidates)
fitnesses = np.array(fitnesses)
if num_recent_candidates is not None:
candidates = candidates[-num_recent_candidates:]
fitnesses = fitnesses[-num_recent_candidates:]
return CandidateSet(candidates, fitnesses)
def _updateminmax(self, fidelity, value):
if value > self.max[fidelity]:
self.max[fidelity] = value
elif value < self.min[fidelity]:
self.min[fidelity] = value
</code></pre>
|
[] |
[
{
"body": "<h2>Type hints</h2>\n\n<p>PEP484 type hints, such as <code>ndim: int</code>, will help better-define your interface.</p>\n\n<h2>Mutability</h2>\n\n<p>Reading your code, the other members of <code>CandidateArchive</code> only make sense if <code>fidelities</code> are immutable. As such, don't make them a list - make them a tuple. One advantage is that you can safely give a default argument of <code>('fitness',)</code>, whereas you can't safely give a default argument that is a mutable list.</p>\n\n<h2>lower_camel_case</h2>\n\n<p><code>addcandidates</code> should be <code>add_candidates</code>.</p>\n\n<h2>Logic inversion</h2>\n\n<pre><code> if tuple(candidate) not in self.data:\n self._addnewcandidate(candidate, fit, fid, verbose=verbose)\n else:\n self._updatecandidate(candidate, fit, fid, verbose=verbose)\n</code></pre>\n\n<p>Since you have both code paths here, put the positive one first so that you don't need a <code>not</code>:</p>\n\n<pre><code> if tuple(candidate) in self.data:\n fun = self._update_candidate\n else:\n fun = self._add_new_candidate\n fun(candidate, fit, fid, verbose=verbose)\n</code></pre>\n\n<h2>Default arguments</h2>\n\n<pre><code> if fidelity is None:\n fidelity = 'fitness'\n</code></pre>\n\n<p>should be replaced with a default argument of 'fitness'.</p>\n\n<h2>No-op code</h2>\n\n<pre><code> if type(fidelity) in [tuple, list]:\n pass\n</code></pre>\n\n<p>This can be made into an outer condition so that you don't need to <code>pass</code>:</p>\n\n<pre><code>if not isinstance(fidelity, (tuple, list)):\n if fidelity: ...\n else: ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T03:23:21.653",
"Id": "227755",
"ParentId": "227710",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227755",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T09:06:26.727",
"Id": "227710",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"design-patterns",
"unit-testing",
"interface"
],
"Title": "CandidateArchive for model-assisted multi-fidelity global search algorithm"
}
|
227710
|
<p>I write kind of UDP server. It should serves about 50 messages per second.
I would like a review about the general code 'quality' and logic. The server uses the same socket for sending and receiving messages. The messages are short - about 100 bytes (json).</p>
<p>The code:</p>
<pre><code>public class UdpServer extends Thread {
/* Receive timeout in mills */
private static int RCV_TIMEOUT = 100;
/* Buffer size */
final private static int BUFF_SIZE = 512;
/* Number of concurrent handlers */
final private static int THREAD_POOL_SIZE = 10;
/* Socket */
final private DatagramSocket socket;
/* Thread pool executor */
final private ThreadPoolExecutor executor;
/* Termination states */
private boolean terminated = false; //set to true if this server is terminated
private boolean terminating = false; //set to true if this server is in the process of terminating
/*
* Debug flag. If it is ON then server sends
* debug messages to clients
*/
private final static boolean debugModeOn = false;
/*
* Transmitter to use by handler to send response to request
* originator. It encapsulates socket, so handler may only send data.
*/
private DatagramResponder responder;
public UdpServer (String ip, int port)
throws ValidationException, SocketException {
if (port <= 0)
throw new ValidationException("Illegal port: " + port);
InetAddressValidator validator = InetAddressValidator.getInstance();
if (!validator.isValidInet4Address(ip) && !validator.isValidInet6Address(ip))
throw new ValidationException("Illegal Ip address: " + ip);
if (!Utils.isIpLocalAndUp(ip))
throw new ValidationException("Given IP is not a local IP or interface is down");
SocketAddress socketAddress = new InetSocketAddress(ip, port);
socket = new DatagramSocket(socketAddress);
socket.setSoTimeout(RCV_TIMEOUT);
executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(THREAD_POOL_SIZE);
responder = new Responder (socket);
}
public void run() {
while (!terminated) {
byte[] buf = new byte[BUFF_SIZE];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
try {
socket.receive(packet);
} catch (SocketTimeoutException to) {
if (!terminated) continue;
else break;
} catch (Exception e) {
e.printStackTrace();
return;
}
if (!terminating) {
Runnable handler = HandlerFactory.getHandler(packet, responder);
executor.execute(handler);
}
}
socket.close();
}
/**
* @return true if server debug mode is ON
*/
public static boolean isDebugModeOn() {
return debugModeOn;
}
/*
* Stops the server. The method waits (up to 60 seconds)
* until all tasks have completed execution
*/
public void terminate () throws IOException {
if (terminating || terminated)
return;
terminating = true;
try {
executor.awaitTermination(60, TimeUnit.SECONDS);
} catch (InterruptedException e) {};
executor.shutdownNow();
terminated = true;
}
//for resting only, will be removed
private static void setReceiveTO (int timeOut) {
RCV_TIMEOUT = timeOut;
}
private static class Responder implements DatagramResponder {
private DatagramSocket socket;
private Responder (DatagramSocket socket) {
this.socket = socket;
}
@Override
public void send(DatagramPacket packet) throws IOException, SecurityException,
PortUnreachableException, IllegalBlockingModeException, IllegalArgumentException {
socket.send(packet);
}
}
public static void main(String[] args) throws ValidationException, IOException, InterruptedException {
//Test that we can send data while socket is blocked on receive
UdpServer.setReceiveTO(1000 * 60 * 60); //1 hour
UdpServer server = new UdpServer ("127.0.0.1", 1234);
server.start();
TestReceiver rcv = new TestReceiver();
rcv.start();
TestSender tester = new TestSender(server.socket);
tester.start();
}
//Receiver
private static class TestReceiver extends Thread {
private DatagramSocket socket;
private TestReceiver () throws SocketException {
socket = new DatagramSocket(1000);
}
public void run() {
while (true) {
try {
byte [] buf = new byte[100];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
System.out.println("Received: " + new String (packet.getData()));
} catch (IOException e) {
System.out.println (e.getMessage());
}
}
}
}
private static class TestSender extends Thread {
private DatagramSocket socket;
private byte [] buf = "hello".getBytes();
private int port = 1000;
private InetSocketAddress address = new InetSocketAddress("127.0.0.1", port);
private DatagramPacket packet = new DatagramPacket(buf, buf.length, address.getAddress(), port);
private TestSender (DatagramSocket socket) {
this.socket = socket;
}
public void run() {
while (true) {
try {
socket.send(packet);
} catch (IOException e) {
System.out.println (e.getMessage());
}
}
}
}
</code></pre>
<p>}</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T09:47:20.913",
"Id": "443421",
"Score": "0",
"body": "Your code ends with `...`. Is it complete?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T10:04:30.537",
"Id": "443422",
"Score": "0",
"body": "Yes it is complete. Rest of code is irrelavant (test cases and main method), so I cut it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T10:15:53.827",
"Id": "443423",
"Score": "0",
"body": "@bw_dev If you have test cases add them to the question too. Include main method as well. this way we can take a look at how this class is used / tested."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T11:48:49.130",
"Id": "443433",
"Score": "0",
"body": "Code updated - added main and two test classes (will be removed from final version)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T12:14:01.553",
"Id": "443435",
"Score": "0",
"body": "What is the version of Java?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T12:18:51.763",
"Id": "443436",
"Score": "0",
"body": "It is Java 1.8; Target OS: Windows 7/10"
}
] |
[
{
"body": "<h1>General</h1>\n\n<p>Classes should be <code>final</code> unless you intend and have designed them to be extended. Marking local variables as <code>final</code> will clue the reader in that they don't change once assigned, which improves readability.</p>\n\n<p>Use full, descriptive variable names. The extra characters don't cost you anything, and they make the code more clear and easier to read.</p>\n\n<p>The suggested keyword order is <code>private static final</code>, not <code>final private static</code>.</p>\n\n<p>Most of your comments are noise.</p>\n\n<p><code>terminating</code> and <code>terminated</code> are <code>false</code> by default and don't need to be explicitly assigned.</p>\n\n<p>In idiomatic java, </p>\n\n<ul>\n<li>there is no whitespace between the end of method name and the `(`.\n<li>there is no whitespace between a constructor name and the `(`.\n<li>there is no whitespace after a variable type declaration and before the `[]`.\n<li>curly braces are always used, even when they are optional. This makes your code consistent and removes a common class of error when refactoring existing code.\n<li>only constants use UPPERCASE, and all constants should use UPPERCASE.\n</ul>\n\n<h1>UdpServer</h1>\n\n<p>You should be instantiating <code>Runnable</code>, not extending <code>Thread</code>. You have not created a generally-useful thread that adds new functionality, but rather a set of functionality that happens to want to run on a thread.</p>\n\n<p>Adding testing-specific methods is usually a bad idea. In this case, it would be very reasonable for the timeout to be an optional constructor parameter, since clients may very well want a non-default value set. Your test client certainly does.</p>\n\n<p>Try to provide meaningful failure messages. Don't just say something is wrong, give a hint on how to fix it.</p>\n\n<p>You're performing the same check twice in the block that starts <code>if (!validator.isValidInet6Address</code>.</p>\n\n<p>Your debug-mode code doesn't do anything and should be removed. Generally, code shouldn't have this kind of property. You're basically compiling in how much information the client is getting, rather than making it configurable in some way.</p>\n\n<h3>run()</h3>\n\n<p>Sockets should always be closed. This is not the case in your code, where an exception can cause the socket to remain open. Move socket instantiation to <code>run</code> and put it in a try-with-resources block.</p>\n\n<p>It seems to me that you want to stop accepting new data on <code>terminating</code>, not <code>terminated</code>. I don't know your requirements, but at a high level it seems wrong to accept new requests while you're trying to shut down the server. If you do make that logical change, then you can switch from two variables to one, <code>running</code>, which doesn't need to be negated everywhere it's used.</p>\n\n<p>You don't need to check for termination in your <code>catch</code> of <code>SocketTimeoutException</code>. Just <code>continue</code> and the while loop condition will handle the check for you.</p>\n\n<p>Always catch the most specific exception you know how to handle. Catching <code>Exception</code> is a bad idea because it will automatically handle any checked exceptions that get added your <code>try</code> block later, whether that was your intent or not.</p>\n\n<h3>terminate()</h3>\n\n<p>This method doesn't actually throw an IOException. You should turn on compiler warnings aggressively to help notice mistakes like this.</p>\n\n<p>It's probably a better idea to <code>shutdownNow()</code> if somebody sends an interrupt. If you feel strongly against it, inside your catch block you should put <code>Thread.currentThread().interrupt()</code>. This preserves the interrupted status, rather than consuming it.</p>\n\n<h1>Responder</h1>\n\n<p><code>Responder</code>'s constructor should be public. You've declared a class that can only be seen by its parent and who can't be constructed by anybody outside the class. You want a class that can only be seen by its parent but can be constructed by anybody who can see it.</p>\n\n<p>I don't know what a <code>DatagramResponder</code> is, but declaring all those thrown exception types in your <code>send()</code> signature is probably not idea. It's typical to only include checked exceptions in the method signature, and to document in your JavaDoc what unchecked exceptions might be thrown. Typically unchecked exceptions can't be reasonably handled by callers. It also suggests that the send method might be doing too much, if it can throw so many kinds of exception.</p>\n\n<hr/>\n\n<p>I'm not going to review the test code, except to say that if you really need to expose the UdpServer socket for testing, you can make it a private instance variable that gets assigned in <code>run()</code>. You can then expose it with a package-private accessor method. I'd strongly advise against testing this way, though. Test UdpServer by actually running UdpServer.</p>\n\n<hr/>\n\n<p>If you were to make all these changes, your code might look something like:</p>\n\n<pre><code>public final class UdpServer implements Runnable {\n\n private static final int BUFFER_SIZE = 512;\n\n private static final int CONCURRENT_HANDLERS = 10;\n\n private final int receiveTimeoutMillis;\n\n private final SocketAddress socketAddress;\n\n private final ThreadPoolExecutor executor;\n\n private boolean running;\n\n public UdpServer(final String ip, final int port)\n throws ValidationException {\n this(ip, port, 100);\n }\n\n public UdpServer(final String ip, final int port, final int receiveTimeoutMillis)\n throws ValidationException {\n\n if (receiveTimeoutMillis <= 0) {\n throw new ValidationException(\"Timeout must be greater than zero, was: \" + receiveTimeoutMillis);\n }\n this.receiveTimeoutMillis = receiveTimeoutMillis;\n\n if (port <= 0) {\n throw new ValidationException(\"Port must be greater than zero, was: \" + port);\n }\n\n final InetAddressValidator validator = InetAddressValidator.getInstance();\n if (!validator.isValidInet6Address(ip)) {\n throw new ValidationException(\"Illegal Ip address: \" + ip);\n }\n\n if (!Utils.isIpLocalAndUp(ip)) {\n throw new ValidationException(\"Given IP is not a local IP or interface is down\");\n }\n\n this.socketAddress = new InetSocketAddress(ip, port);\n this.executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(CONCURRENT_HANDLERS);\n }\n\n\n @Override\n public void run() {\n this.running = true;\n\n try (final DatagramSocket socket = new DatagramSocket(this.socketAddress)) {\n socket.setSoTimeout(this.receiveTimeoutMillis);\n final Responder responder = new Responder(socket);\n\n while (this.running) {\n final byte[] buffer = new byte[BUFFER_SIZE];\n final DatagramPacket packet = new DatagramPacket(buffer, buffer.length);\n\n try {\n socket.receive(packet);\n } catch (final SocketTimeoutException e) {\n continue;\n } catch (final IOException e) {\n System.err.println(\"Error reading from socket\");\n e.printStackTrace();\n return;\n }\n\n if (this.running) {\n final Runnable handler = HandlerFactory.getHandler(packet, responder);\n this.executor.execute(handler);\n }\n }\n } catch (final SocketException e) {\n System.err.println(\"Error while opening socket\");\n e.printStackTrace();\n }\n }\n\n /**\n * Stops the server. The method waits (up to 60 seconds)\n * until all tasks have completed execution unless interrupted.\n */\n public void terminate() {\n if (!this.running) {\n return;\n }\n\n this.running = false;\n\n try {\n this.executor.awaitTermination(60, TimeUnit.SECONDS);\n this.executor.shutdownNow();\n } catch (final InterruptedException e) {\n this.executor.shutdownNow();\n // or Thread.currentThread().interrupt();\n }\n }\n\n\n /*\n * Transmitter to use by handler to send response to request\n * originator. It encapsulates socket, so handler may only send data.\n */\n private static final class Responder implements DatagramResponder {\n\n private final DatagramSocket socket;\n\n public Responder(final DatagramSocket socket) {\n this.socket = socket;\n }\n\n @Override\n public void send(final DatagramPacket packet)\n throws IOException, PortUnreachableException, IllegalBlockingModeException {\n this.socket.send(packet);\n }\n\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T17:01:06.997",
"Id": "443465",
"Score": "0",
"body": "Thanks for the comment. The only question here: in your implementation server may exit before handlers finished their work. The server thread is \"parent\" of handler threads. May this cause handlers be destroyed without finishing tasks?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T19:51:10.180",
"Id": "443487",
"Score": "0",
"body": "@bw_dev Ah. If you want the handlers to finish, then yes, two variables is a better approach. It depends on what semantics you want for `terminate()`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T15:05:54.207",
"Id": "227728",
"ParentId": "227712",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "227728",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T09:27:56.633",
"Id": "227712",
"Score": "2",
"Tags": [
"java",
"udp"
],
"Title": "Simple UDP server (java)"
}
|
227712
|
<p>Extract the strings from nested arrays in Perl.</p>
<p>It prints: <code>a, b, c, d, E</code></p>
<pre><code>use strict;
use warnings;
use feature qw(say signatures current_sub);
no warnings qw(experimental::signatures);
my $nested = [1, 'a', [2, 3, 'b'], [4, [5, 6, 7, ['c']], [7, [8, 9, [10, 'd']]], 11, 'E']];
print join ', ', @{ extract_strings($nested) };
sub extract_strings($input) {
my @output = ();
my $loop = sub ($val) {
if (ref $val eq 'ARRAY') {
__SUB__->($_) for @{ $val };
} else {
push(@output, $val) if $val =~ /^[a-zA-Z]/;
}
};
$loop->($input);
return \@output;
}
</code></pre>
<p>Any idea for improvement without not core dependencies?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T12:22:59.790",
"Id": "443438",
"Score": "2",
"body": "Looks fine to me :) The name of the sub, `flatten` might be improved to `extract_strings`? If wanted, speed could be improved by using `Inline::C` or XS."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T20:14:33.343",
"Id": "443489",
"Score": "0",
"body": "It is exactly extract_strings in my edit :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T20:24:44.083",
"Id": "443491",
"Score": "1",
"body": "Actually, there is something that might be a bug: `push(@output, $val) if /^[a-zA-Z]/;` vs `push(@output, $val) if $val =~ /^[a-zA-Z]/;` I don't understand why this actually work. What is `$_` in the `else`? I'll edit the function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T07:11:15.277",
"Id": "443521",
"Score": "3",
"body": "It is not allowed to modify the code when answers have been posted. It can invalidate them. I have rolled back your last edit."
}
] |
[
{
"body": "<p>Your concept of \"string\" seems incomplete. I would look to firm up that definition and precisely match the need. Is <code>\"\"</code> a string? Do you want \"valid identifiers\" (<code>/^[^\\d\\W]\\w+$/</code>) or \"plausible ASCII words\" (<code>/^[A-Za-z]+$/</code>) or just \"not numbers\" (<code>!/ ^ ( [+-]? \\d* \\.? \\d+ (?:[Ee][+-]?\\d+)? ) $/x</code>)? </p>\n\n<p>I like <code>use warnings FATAL => 'all';</code> so that I don't miss a warning in the midst of other output. </p>\n\n<p>A fat arrow between arguments of different purpose can enhance readability.</p>\n\n<p>Coding in functional style (with <code>grep</code> and <code>map</code> instead of <code>@output</code>) is a natural fit to this kind of problem. </p>\n\n<p>Plain old recursion is suited to the task and would obviate the need for experimental features. </p>\n\n<p>Having <code>extract_strings</code> take a ref (as it does now) and return a list simplifies the logic even further.</p>\n\n<pre><code>print join ', ' => extract_strings($nested);\n\nsub extract_strings {\n grep /^[a-zA-Z]/ => map { ref eq 'ARRAY' ? extract_strings($_) : $_ } @{ $_[0] } \n}\n</code></pre>\n\n<p>If returning a ref is necessary, wrap and unwrap accordingly:</p>\n\n<pre><code>sub extract_strings {\n [ grep /^[a-zA-Z]/ => map { ref eq 'ARRAY' ? @{ extract_strings($_) } : $_ } @{ $_[0] } ]\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T22:28:21.073",
"Id": "227746",
"ParentId": "227714",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "227746",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T10:00:04.617",
"Id": "227714",
"Score": "6",
"Tags": [
"programming-challenge",
"regex",
"perl"
],
"Title": "Extract strings from nested array in Perl"
}
|
227714
|
<p>I am a C# game developer currently learning C++. I am trying to implement some simplified STL containers. Here is my implementation of vector, which does not have the allocator (because <a href="https://www.youtube.com/watch?v=LIb3L4vKZ7U" rel="noreferrer"><code>std::allocator</code> is to Allocation what <code>std::vector</code> is to Vexation</a>).</p>
<p>My objective is to understand the mechanics how the vector works behind the scenes as well as practice modern C++ techniques.</p>
<p>I have also published code under GitHub. <a href="https://github.com/TheSica/vector/blob/master/vector/Vector.h" rel="noreferrer">Here is the link</a>.</p>
<p>Thank you in advance for taking the time to read my code.</p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include <algorithm>
#include <type_traits>
template<typename T>
class Vector
{
public:
typedef T* iterator;
typedef const T* const_iterator;
typedef T& reference;
typedef const T& const_reference;
typedef T* pointer;
typedef const T* const_pointer;
public:
Vector();
explicit Vector(const size_t size);
Vector(const Vector<T>& other);
Vector(Vector<T>&& other) noexcept (std::is_nothrow_move_constructible_v<T>);
~Vector();
Vector<T>& operator=(const Vector<T>& other);
Vector<T>& operator=(Vector<T>&& other) noexcept(std::is_nothrow_move_assignable_v<T>);
public:
template<class... Args>
reference emplace_back(Args&& ... args);
void push_back(const T& element);
void push_back(T&& element);
iterator insert(iterator pos, const T& value);
iterator insert(iterator pos, T&& value);
iterator erase(iterator pos);
const_iterator erase(const_iterator pos);
iterator erase(iterator pos, iterator last);
reference operator[](const size_t n) noexcept;
const_reference operator[](const size_t n) const noexcept;
reference at(const size_t n);
const_reference at(const size_t n) const;
public:
bool validate() const noexcept;
bool empty() const noexcept;
size_t size() const noexcept;
size_t capacity() const noexcept;
void reserve(const size_t newCapacity);
public:
iterator begin() noexcept;
const_iterator begin() const noexcept;
const_iterator cbegin() const noexcept;
iterator end() noexcept;
const_iterator end() const noexcept;
const_iterator cend() const noexcept;
reference front();
const_reference front() const;
reference back();
const_reference back() const;
pointer data() noexcept;
const_pointer data() const noexcept;
private:
void cleanup();
void reallocate(const size_t desiredCapacity);
void resize();
void swap(Vector<T>& other) noexcept;
void memcopy_trivially(T* src, T* dest, const size_t size);
template<class... Args>
void emplace_back_internal(Args&& ... element);
template<class... U>
void emplace_internal(iterator pos, U&& ... value);
private:
size_t _size;
size_t _capacity;
T* _container;
};
template<typename T>
Vector<T>::Vector()
:
_size(0),
_capacity(0),
_container(nullptr)
{
}
template<typename T>
Vector<T>::Vector(const size_t size)
:
_size(size),
_capacity(size),
_container(static_cast<T*>(_aligned_malloc(sizeof(T)* size, alignof(T))))
{
try
{
for (size_t i = 0; i < size; i += 1)
{
new (_container + i) T();
}
}
catch (...)
{
cleanup();
throw;
}
}
template<typename T>
Vector<T>::Vector(const Vector<T>& other)
:
_size(0),
_capacity(other._size),
_container(static_cast<T*>(_aligned_malloc(sizeof(T)* other._size, alignof(T))))
{
if constexpr (std::is_trivially_copyable_v<T>)
{
memcopy_trivially(_container, other._container, other._size);
}
else
{
try
{
for (_size = 0; _size < other._size; _size += 1)
{
emplace_back_internal(std::forward<T>(other._container[_size]));
}
}
catch (...)
{
cleanup();
throw;
}
}
}
template<typename T>
Vector<T>::Vector(Vector<T>&& other) noexcept (std::is_nothrow_move_constructible_v<T>)
:
_size(other._size),
_capacity(other._capacity),
_container(other._container)
{
other._size = 0;
other._container = nullptr;
}
template<typename T>
Vector<T>::~Vector()
{
cleanup();
}
template<typename T>
Vector<T>& Vector<T>::operator=(const Vector<T>& other)
{
if (&other != this)
{
Vector<T> tmp(other);
tmp.swap(*this);
}
return *this;
}
template<typename T>
Vector<T>& Vector<T>::operator=(Vector<T>&& other) noexcept(std::is_nothrow_move_assignable_v<T>)
{
if (&other != this)
{
other.swap(*this);
}
return *this;
}
template<typename T>
void Vector<T>::push_back(const T& element)
{
if (_size == _capacity)
{
resize();
}
emplace_back_internal(element);
_size += 1;
}
template<typename T>
void Vector<T>::push_back(T&& element)
{
if (_size == _capacity)
{
resize();
}
emplace_back_internal(std::move(element));
_size += 1;
}
template<typename T>
typename Vector<T>::iterator
Vector<T>::insert(iterator pos, const T& value)
{
emplace_internal(pos, value);
_size += 1;
return pos;
}
template<typename T>
typename Vector<T>::iterator
Vector<T>::insert(iterator pos, T&& value)
{
emplace_internal(pos, std::move(value));
_size += 1;
return pos;
}
template<typename T>
typename Vector<T>::iterator
Vector<T>::erase(iterator position)
{
if (position < begin() || position >= end())
{
throw std::out_of_range("Vector::erase -- out of range");
}
std::move(position + 1, end(), position);
back().~T();
_size -= 1;
return position;
}
template<typename T>
typename Vector<T>::const_iterator
Vector<T>::erase(const_iterator position)
{
if (position < begin() || position >= end())
{
throw std::out_of_range("Vector::erase -- out of range");
}
auto destPositon = const_cast<iterator>(position);
return erase(destPositon);
}
template<typename T>
typename Vector<T>::iterator
Vector<T>::erase(iterator first, iterator last)
{
if (first > last || first < begin() || first > end() || last < begin() || last > end())
{
throw std::out_of_range("Vector::erase(first, last) -- out of range");
}
if (first == last)
{
return begin();
}
size_t elementsToRemoveCnt = std::distance(first, last);
auto position = std::move(last, end(), first);
std::destroy(position, end());
_size -= elementsToRemoveCnt;
return first;
}
template<typename T>
template<class... Args>
inline typename Vector<T>::reference
Vector<T>::emplace_back(Args&& ... args)
{
if (_size == _capacity)
{
resize();
}
emplace_back_internal(std::move(args)...);
_size += 1;
return back();
}
template<typename T>
void Vector<T>::cleanup()
{
if constexpr (!std::is_trivially_destructible_v<T>)
{
std::destroy(begin(), end());
}
_aligned_free(_container);
}
template<typename T>
std::enable_if_t<std::is_nothrow_move_constructible_v<T>> uninitialized_move_or_copy(T* first, T* last, T* dest)
{
std::uninitialized_move(first, last, dest);
}
template<typename T>
std::enable_if_t<std::is_copy_constructible_v<T> && !std::is_nothrow_move_constructible_v<T>> uninitialized_move_or_copy(T* first, T* last, T* dest)
{
try
{
std::uninitialized_copy(first, last, dest);
}
catch (...)
{
_aligned_free(dest);
throw;
}
}
template<typename T>
inline void Vector<T>::reallocate(const size_t desiredCapacity)
{
_capacity = desiredCapacity;
if (void* try_alloc_mem = _aligned_malloc(sizeof(T) * _capacity, alignof(T)))
{
try
{
auto alloced_mem = static_cast<T*>(try_alloc_mem);
if constexpr (std::is_trivially_copyable_v<T>)
{
memcopy_trivially(alloced_mem, _container, _size);
}
else
{
uninitialized_move_or_copy<T>(begin(), end(), alloced_mem);
}
cleanup();
_container = alloced_mem;
}
catch (...)
{
_aligned_free(try_alloc_mem);
throw;
}
}
else
{
throw std::bad_alloc();
}
}
template<typename T>
void Vector<T>::resize()
{
reallocate(std::max(static_cast<size_t>(2), _capacity * 2));
}
template<typename T>
inline void Vector<T>::swap(Vector<T>& other) noexcept
{
std::swap(_size, other._size);
std::swap(_capacity, other._capacity);
std::swap(_container, other._container);
}
template<typename T>
void Vector<T>::memcopy_trivially(T* dest, T* src, const size_t size)
{
std::memcpy(dest, src, size * sizeof(T));
_size = size;
}
template<typename T>
template<class... U>
void Vector<T>::emplace_internal(iterator pos, U&& ... value)
{
if (pos < begin() || pos > end())
{
throw std::out_of_range("Vector::insert -- out of range");
}
if (pos == end())
{
if (_size == _capacity)
{
resize();
}
emplace_back_internal(value...);
return;
}
const size_t positionIndex = std::distance(begin(), pos);
if (_size == _capacity)
{
resize();
}
emplace_back_internal(back());
if constexpr (std::is_nothrow_move_assignable_v<T>)
{
std::move_backward(begin() + positionIndex, end() - 1, end());
}
else
{
Vector<T> tmp(*this);
try
{
std::copy_backward(begin() + positionIndex, end() - 1, end()); // does mempcy for trivial objects
}
catch (...)
{
cleanup();
swap(tmp);
throw;
}
}
new(begin() + positionIndex) T(std::forward<U>(value)...);
}
template<typename T>
template<class... Args>
inline void Vector<T>::emplace_back_internal(Args&& ... element)
{
new(_container + _size) T(std::forward<Args>(element)...);
}
template<typename T>
inline bool operator==(const Vector<T>& a, const Vector<T>& b)
{
return ((a.size() == b.size()) && std::equal(a.begin(), a.end(), b.begin()));
}
template<typename T>
typename Vector<T>::reference
Vector<T>::operator[](const size_t index) noexcept
{
return *(begin() + index);
}
template<typename T>
typename Vector<T>::const_reference
Vector<T>::operator[](const size_t index) const noexcept
{
return *(begin() + index);
}
template<typename T>
typename Vector<T>::reference
Vector<T>::at(const size_t index)
{
if (index >= size())
{
throw std::out_of_range("Vector::at -- out of range");
}
return _container[index];
}
template<typename T>
typename Vector<T>::const_reference
Vector<T>::at(const size_t index) const
{
if (index >= size())
{
throw std::out_of_range("Vector::at -- out of range");
}
return _container[index];
}
template<typename T>
inline bool Vector<T>::validate() const noexcept
{
return (_capacity >= _size);
}
template<typename T>
inline bool Vector<T>::empty() const noexcept
{
return _size == 0;
}
template<typename T>
inline size_t Vector<T>::size() const noexcept
{
return _size;
}
template<typename T>
inline size_t Vector<T>::capacity() const noexcept
{
return _capacity;
}
template<typename T>
inline void Vector<T>::reserve(const size_t newCapacity)
{
if (newCapacity <= _capacity)
{
return;
}
if (!empty())
{
reallocate(newCapacity);
}
else if (empty() && _capacity > 0)
{
_aligned_free(_container);
_container = static_cast<T*>(_aligned_malloc(sizeof(T) * newCapacity, alignof(T)));
}
else if (empty() && _capacity == 0)
{
_container = static_cast<T*>(_aligned_malloc(sizeof(T) * newCapacity, alignof(T)));
}
else
{
// ?
throw;
}
_capacity = newCapacity;
}
template<typename T>
inline typename Vector<T>::iterator
Vector<T>::begin() noexcept
{
return _container;
}
template<typename T>
inline typename Vector<T>::const_iterator
Vector<T>::begin() const noexcept
{
return _container;
}
template<typename T>
typename Vector<T>::const_iterator
Vector<T>::cbegin() const noexcept
{
return _container;
}
template<typename T>
inline typename Vector<T>::iterator
Vector<T>::end() noexcept
{
return _container + _size;
}
template<typename T>
inline typename Vector<T>::const_iterator
Vector<T>::end() const noexcept
{
return _container + _size;
}
template<typename T>
typename Vector<T>::const_iterator
Vector<T>::cend() const noexcept
{
return _container + _size;
}
template<typename T>
inline typename Vector<T>::reference
Vector<T>::front()
{
return const_cast<reference>(std::as_const(*this).front());
}
template<typename T>
inline typename Vector<T>::const_reference
Vector<T>::front() const
{
if (empty())
{
throw std::range_error("vector::front -- empty vector");
}
return *begin();
}
template<typename T>
inline typename Vector<T>::reference
Vector<T>::back()
{
return const_cast<reference>(std::as_const(*this).back());
}
template<typename T>
inline typename Vector<T>::const_reference
Vector<T>::back() const
{
if (empty())
{
throw std::range_error("vector::back -- empty vector");
}
return *std::prev(end());
}
template<typename T>
inline typename Vector<T>::const_pointer
Vector<T>::data() const noexcept
{
return _container;
}
template<typename T>
inline typename Vector<T>::pointer
Vector<T>::data() noexcept
{
return _container;
}
</code></pre>
|
[] |
[
{
"body": "<h2>Issue with Default construction</h2>\n<pre><code>try\n{\n for (size_t i = 0; i < size; i += 1)\n {\n new (_container + i) T();\n }\n}\ncatch (...)\n{\n cleanup(); // This will call the destructor on all members of\n // _container. But if you throw an exception here\n // then not all members will have been constructed.\n //\n // A simple fix.\n // Initializer list sets "_size" to zero \n // Initializer list sets "_capacity" to size.\n // Then in the loop above simple go\n // for (;_size < _capacity; ++size)\n throw;\n}\n</code></pre>\n<hr />\n<h2>Weird Look with Copy Construction</h2>\n<p>The copy constructor uses:</p>\n<pre><code>emplace_back_internal(std::forward<T>(other._container[_size]));\n</code></pre>\n<p>This looks like a move operation (<code>std::forward()</code>). The thing that is saving you is that other is <code>const</code> so it does not bind to the rvalue reference. But this makes it look really weird.</p>\n<p>I would simply expect:</p>\n<pre><code>emplace_back_internal(other._container[_size]);\n</code></pre>\n<hr />\n<h2>Issue with Move construction</h2>\n<pre><code>other._size = 0;\nother._container = nullptr;\n</code></pre>\n<p>What about the other capacity?<br />\nIs the capacity also now zero?</p>\n<p>I normally write this as a swap operation.</p>\n<pre><code>Vector<T>::Vector(Vector<T>&& other) noexcept (std::is_nothrow_move_constructible_v<T>)\n :\n _size(0),\n _capacity(0),\n _container(nullptr)\n{\n other.swap(*this);\n}\n</code></pre>\n<hr />\n<h2>Copy Assignment is old style</h2>\n<pre><code>Vector<T>& Vector<T>::operator=(const Vector<T>& other)\n{\n if (&other != this)\n {\n Vector<T> tmp(other);\n tmp.swap(*this);\n }\n return *this;\n}\n</code></pre>\n<p>You are pessimizing the normal operation by checking for assignment to self. Your code works with assignment to self. Yes it will be much more expensive for assignment to self <strong>BUT</strong> it is safe and practically never happens in real code. So you are saving time on an operation that basically never happens at the extra cost for an operation that happens all the time (you risk branch predication failure here) plus the cost of actually doing the branch test.</p>\n<pre><code>Vector<T>& Vector<T>::operator=(const Vector<T>& other)\n{\n Vector<T> tmp(other);\n tmp.swap(*this);\n return *this;\n}\n</code></pre>\n<p>Same with your move operation.</p>\n<hr />\n<h1>Style Oddities.</h1>\n<h2>Increment</h2>\n<p>You keep using +=1</p>\n<pre><code> _size += 1\n</code></pre>\n<p>Where I would expect:</p>\n<pre><code> ++_size;\n</code></pre>\n<hr />\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T19:28:34.210",
"Id": "443485",
"Score": "0",
"body": "Thank you for the review!\n**Issue with Default construction**\nI actually do that exact thing in my copy constructor but I missed doing it in my explicit constructor. \n**Issue with Move construction**:\nDo I have to care that much about the _other_ in the move constructor? Standard states that I have to leave _other_ in a valid, yet unspecified state as nobody is allowed to touch it. I just make sure the destructor is not called and I think I should be done. I avoid `swap` because it creates unnecessary TMP objects.\nP.S: I am yet to find my incrementation style. I know it's weird :("
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T19:38:10.783",
"Id": "443486",
"Score": "0",
"body": "P.P.S: I just now realized you're _the_ Loki Astari. Just wanted to say that your `vector` blog post was a great source of information while implementing my own version. Thanks again!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T22:32:09.627",
"Id": "443498",
"Score": "0",
"body": "Valid yet unspecified. This means that functions that have no preconditions will work. Things like `push_back()` has no pre-conditions (as the vector should re-size if it is too small). So if I call `push_back()` after the vector has been moved away I still expect it to work correctly as it is a valid state (though I could not make any assumptions about what was inside the vector it could be full or empty that's unspecified). But in your case a call to `push_back()` will result in a crash (as you use the nullptr as part of an emplace back)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T22:33:56.183",
"Id": "443499",
"Score": "0",
"body": "If you set the capacity to zero (as well as the size) then your vector will correctly allocate the needed space and continue to work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T08:01:34.353",
"Id": "443532",
"Score": "0",
"body": "I see. That makes sense. Thanks!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T18:22:54.093",
"Id": "227736",
"ParentId": "227716",
"Score": "6"
}
},
{
"body": "<p>As a learner, I think you have done a great job. Here's some suggestions:</p>\n\n<h1>General</h1>\n\n<ul>\n<li><p>Don't use multiple <code>public:</code> labels. It seems your intent is to split the declarations into groups, but that can be achieved better with <code>// iterator</code>, <code>// element access</code>, etc.</p></li>\n<li><p>Some member types are missing: <code>size_type</code>, <code>difference_type</code>, <code>value_type</code>.</p></li>\n<li><p>Reverse iterator support is missing.</p></li>\n<li><p>Try to avoid nonstandard functions like <code>_aligned_malloc</code>. Use portable features — <code>::operator new</code>, for example. It would be beneficial for you to wrap the allocation and deallocation into functions, so you can have an easier time transitioning when you add allocator support in the future.</p></li>\n</ul>\n\n<h1>Constructors, assignment operators, and the destructor</h1>\n\n<ul>\n<li><p>Instead of writing the default constructor, it may be better to use in-class member initializers to ensure that the data members aren't left uninitialized accidentally. And it can (and should) be made <code>noexcept</code>:</p>\n\n<pre><code>Vector() noexcept = default;\n</code></pre>\n\n<p>(Note: <code>= default</code> <em>default-initializes</em> the data members by default, which means data members of type, say, <code>int</code>, will be left uninitialized. There's no problem if you use in-class member initializes as I said above.)</p></li>\n<li><p><code>size_t</code> should be <code>std::size_t</code> or (properly defined) <code>size_type</code>. It's not common practice in C++ to make parameters <code>const</code> — at least not in the declaration. So instead of</p>\n\n<pre><code>explicit Vector(const size_t size);\n</code></pre>\n\n<p>go with</p>\n\n<pre><code>explicit Vector(size_type count);\n</code></pre>\n\n<p>(you may noticed that I used <code>count</code> instead of <code>size</code> to avoid name shadowing.)</p></li>\n<li><p>There's the <code>(count, value)</code> constructor and the <code>(iterator, iterator)</code> constructor. Where are they? :) And the <code>std::initializer_list</code> constructor.</p></li>\n<li><p>The move constructor and assignment operator should be unconditionally <code>noexcept</code> because they don't actually move elements.</p></li>\n<li><p>This is usually phrased as <code>reinterpret_cast</code>:</p>\n\n<pre><code>_container(static_cast<T*>(_aligned_malloc(sizeof(T)* size, alignof(T))))\n</code></pre>\n\n<p>and by the way, I like to put nontrivial code (like memory allocation) in the function body to avoid order dependency problems, but that is purely a matter of taste.</p></li>\n<li><p>Don't reimplement the library:</p>\n\n<pre><code>try\n{\n for (size_t i = 0; i < size; i += 1)\n {\n new (_container + i) T();\n }\n}\ncatch (...)\n{\n cleanup();\n throw;\n}\n</code></pre>\n\n<p>can be written as</p>\n\n<pre><code>std::uninitialized_value_construct_n(_container, size);\n</code></pre>\n\n<p>which is simple to understand and much less error prone. The <code>try</code> block can be removed because the standard library takes care of exception safety.</p></li>\n<li><p>Similarly,</p>\n\n<pre><code>if constexpr (std::is_trivially_copyable_v<T>)\n{\n memcopy_trivially(_container, other._container, other._size);\n}\nelse\n{\n try\n {\n for (_size = 0; _size < other._size; _size += 1)\n {\n emplace_back_internal(std::forward<T>(other._container[_size]));\n }\n }\n catch (...)\n {\n cleanup();\n throw;\n }\n}\n</code></pre>\n\n<p>can be rewritten as</p>\n\n<pre><code>std::uninitialized_copy_n(other.begin(), other.end(), _container);\n</code></pre>\n\n<p>the trivial copy optimization should be handled by any decent implementation, so you don't need to worry about it yourself—:)</p></li>\n<li><p>Use the <a href=\"https://stackoverflow.com/q/3279543\">copy and swap idiom</a>. This saves you a lot of boilerplate. The move constructor can be simplified:</p>\n\n<pre><code>template <typename T>\nVector<T>::Vector(Vector&& other) noexcept\n :Vector{}\n{\n swap(other);\n}\n</code></pre>\n\n<p>The copy and move assignment operators can be unified:</p>\n\n<pre><code>template <typename T>\nauto Vector<T>::operator=(Vector other) noexcept -> Vector&\n{\n swap(other);\n return *this;\n}\n</code></pre>\n\n<p>(the effect of the <code>noexcept</code> here is that move assignment is <code>noexcept</code> while copy assignment is not. Think of it.)</p></li>\n<li><p><code>std::initializer_list</code> assignment operator :)</p></li>\n</ul>\n\n<hr>\n\n<ul>\n<li><p>This function</p>\n\n<pre><code>template<typename T>\nvoid Vector<T>::cleanup()\n{\n if constexpr (!std::is_trivially_destructible_v<T>)\n {\n std::destroy(begin(), end());\n }\n\n _aligned_free(_container);\n}\n</code></pre></li>\n</ul>\n\n<p>is a standard facility — it should be named <code>clear</code>, made <code>public</code>, and made <code>noexcept</code>. (Did you just \"accidentally\" implement a feature?)</p>\n\n<p>Any decent implementation should implement the trivial optimization for <code>std::destroy</code>. Don't do it yourself. If your implementation doesn't, you should complain to them ;) In general, if you are calling a library function, you can be 95% sure that all (relatively) trivial optimizations are implemented.</p>\n\n<p>And you can delegate to <code>erase</code> if you want.</p>\n\n<h1>The <code>assign</code> functions</h1>\n\n<p>Oops, they are missing.</p>\n\n<h1>The member access functions</h1>\n\n<p><code>operator[]</code> should not be made <code>noexcept</code>. <code>noexcept</code> doesn't just mean \"no exceptions\" — it actually means \"this function won't fail\".</p>\n\n<p>Also, you probably need <code>std::launder</code> at some point.</p>\n\n<h1>Capacity</h1>\n\n<p><code>validate</code> is not a standard function and thus should preferably be <code>private</code>.</p>\n\n<p>The logic of the <code>reserve</code> function can be simplified. I am pretty sure you can avoids the <code>if else if else if else</code> chain by refactoring the code somehow. And</p>\n\n<pre><code>else\n{\n // ?\n throw;\n}\n</code></pre>\n\n<p>That's dead code, isn't it? The comment that consists of a single question mark confuses me even more.</p>\n\n<p>Oh, and <code>shrink_to_fit</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T12:49:53.773",
"Id": "443557",
"Score": "0",
"body": "Thank you so much for your review. I use `validate` just for testing purposes.\nthe ` else { // ? throw;}` mess was there just to make sure I didn't get to that stage. I should remove it.\n\nThanks for pointing out that some of the code can be replaced with STD methods. I am trying to use as much STD as possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T13:40:04.723",
"Id": "443567",
"Score": "0",
"body": "@MariusT You are welcome, good job. You can just remove the final `else` clause and replace the last `else if` with `else`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T14:05:34.273",
"Id": "443570",
"Score": "0",
"body": "For the reserve I replaced everything with an if/else and in the else I `_aligned_free` and `_algined_malloc()` . much easier to read and it's the same functionality"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T19:06:20.407",
"Id": "443654",
"Score": "0",
"body": "Making the default constructor `= default;` is probably not a good idea. As the default initialization will not initialize the members (as they are POD types with no initializer)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T09:51:25.623",
"Id": "444718",
"Score": "1",
"body": "@MartinYork I said \"use in-class member initializers\" before giving the `= default` code. Anyway, I'll clarify"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T11:04:37.803",
"Id": "227776",
"ParentId": "227716",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T10:31:12.627",
"Id": "227716",
"Score": "16",
"Tags": [
"c++",
"reinventing-the-wheel",
"template",
"vectors",
"stl"
],
"Title": "YAVI (Yet another vector implementation)"
}
|
227716
|
<p>I have made a <code>ChoiceField</code> into a select and submit button and wondered if this is the correct approach. </p>
<p>forms.py</p>
<pre><code>class PortfolioForm(forms.Form):
def __init__(self, *args, **kwargs):
super(PortfolioForm, self).__init__(*args, **kwargs)
portfolios = [('pf 1', 'pf 1'), ('pf 2', 'pf 2'), ('pf 3', 'pf 3')]
self.fields['portfolios'] = forms.ChoiceField(
widget=forms.Select(),
choices=portfolios,
required=False,
)
</code></pre>
<p>views.py</p>
<pre><code>class PortfolioView(View):
form_class = PortfolioForm
template_name = 'portfolio.html'
def get(self, request):
form = self.form_class()
return render(request, self.template_name, {'form': form})
def post(self, request):
form = self.form_class(self.request.POST)
if form.is_valid():
selected_portfolio = form.cleaned_data.get('portfolios')
print(selected_portfolio)
form = self.form_class(initial={'portfolios': selected_portfolio})
else:
form = self.form_class(initial={'portfolio_name': ''})
return render(self.request, self.template_name, {'form': form})
</code></pre>
<p>and most of the trickery in the template. I use elements of <code>form.portfolios</code> to make the buttons, but it seems I have to include <code>form.portfolios</code> in the template to make it all work. In order not to show I put this in a hidden tag.</p>
<pre><code>{% block content %}
<form id="id_portfolio" method="post">
{% csrf_token %}
<a style="visibility: hidden">{{ form.portfolios }}</a>
{% for portfolio in form.portfolios %}
<p>
{% if portfolio.data.selected %}
<button type="button">{{ portfolio.choice_label }}</button>
{% else %}
<button type="submit" value="{{ portfolio.data.value }}"
name="{{ portfolio.data.name }}">{{ portfolio.choice_label }}</button>
{% endif %}
</p>
{% endfor %}
{% endblock content %}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T15:20:31.530",
"Id": "443593",
"Score": "0",
"body": "I haven't tried replicating this on my own machine, but what goes terribly wrong if you just use Django's built-in form rendering using [``{{ form }}``](https://docs.djangoproject.com/en/2.2/topics/forms/#the-template)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T03:41:08.880",
"Id": "444690",
"Score": "0",
"body": "Just rendering the built-in form `{{ form.portfolios }}` gives me a dropdown list. I want the buttons to be visible at all time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T08:35:07.357",
"Id": "444710",
"Score": "0",
"body": "Do you want there to be a button for each portfolio choice on the page? It may be better to override the `Select` widget and replace the `select.html` template with a template that renders buttons instead of a dropdown select"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T09:21:11.420",
"Id": "444717",
"Score": "0",
"body": "@mikeyl, yes correct I do not want the dropdown but still want to use the choicefied. Can you point me to how to replace the select.html with one that renders buttons."
}
] |
[
{
"body": "<p>If you want the options to appear on the page, I would recommend using the <code>RadioSelect</code> widget instead. You will still need to click a separate button to submit however.</p>\n\n<pre><code>class PortfolioForm(forms.Form):\n\n def __init__(self, *args, **kwargs):\n super(PortfolioForm, self).__init__(*args, **kwargs)\n\n portfolios = [('pf 1', 'pf 1'), ('pf 2', 'pf 2'), ('pf 3', 'pf 3')]\n\n self.fields['portfolios'] = forms.ChoiceField(\n widget=forms.RadioSelect(),\n choices=portfolios,\n required=False,\n )\n</code></pre>\n\n<p>If you would like your own custom widget instead, you can inherit one of the existing widgets and apply your own template.</p>\n\n<pre><code># widgets.py\nclass ButtonSelect(ChoiceWidget):\n template_name = 'widgets/button_select.html'\n option_template_name = 'widgets/button_select_option.html'\n\n\n# templates/widgets/button_select.html\n{% include \"django/forms/widgets/multiple_input.html\" %}\n\n# templates/widgets/button_select_option.html\n\"\"\"\"\nWill need custom widget option code here.\nTake a look at https://github.com/django/django/blob/master/django/forms/templates/django/forms/widgets/input_option.html\n\"\"\"\n</code></pre>\n\n<p>Then you can use it in your <code>PortfolioForm</code></p>\n\n<pre><code>from widgets import ButtonSelect\n\nclass PortfolioForm(forms.Form):\n\n def __init__(self, *args, **kwargs):\n super(PortfolioForm, self).__init__(*args, **kwargs)\n\n portfolios = [('pf 1', 'pf 1'), ('pf 2', 'pf 2'), ('pf 3', 'pf 3')]\n\n self.fields['portfolios'] = forms.ChoiceField(\n widget=ButtonSelect(),\n choices=portfolios,\n required=False,\n )\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T13:39:07.930",
"Id": "228843",
"ParentId": "227720",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T13:20:11.887",
"Id": "227720",
"Score": "2",
"Tags": [
"python",
"django",
"django-template-language"
],
"Title": "Django turn ChoiceField into a submit button"
}
|
227720
|
<p>I am working on a website with an animation that runs at the beginning before the content of the homepage becomes visible.
I've looked at some examples of preloaders and now use that code with some setTimeout to implement the desired effect.
The effect works the way it should but I think the code it's a bit messy. is there be a better way to write that?
It would be great if someone had a suggestion.</p>
<p>Here is the code and and a working HTML in which everything is bind together:</p>
<p><b>The javascript</b></p>
<pre><code>setTimeout(function () {
function run() {
var wrp = document.getElementById("i-w");
var swp = document.getElementById("pink");
wrp.className += "loaded";
swp.classList.add('fd');}
if (document.readyState != 'loading') run();
else if (document.addEventListener) document.addEventListener(
'DOMContentLoaded', run);
else document.attachEvent('onreadystatechange', function () {
if (document.readyState == 'complete') run();
});
}, 2650);
setTimeout(function () {
var swp = document.getElementById("pink");
swp.classList.remove('fd');
}, 3000);
</code></pre>
<p><b>The HTML</b></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-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<title>itr test</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
margin: 0;
padding: 0;
background:yellow;
}
#i-w {
z-index: 9999;
visibility: visible;
-webkit-transform: translateY(0%);
transform: translateY(0%);
-webkit-transition: -webkit-transform .4s ease-in-out;
transition: transform .4s ease-in-out;
will-change: transform;
}
#i-w.loaded {
visibility: hidden;
-webkit-transform: translateY(-100%);
transform: translateY(-100%);
-webkit-transition: -webkit-transform 1.3s cubic-bezier(.96, 0, .07, 1), visibility 0s 1.9s;
transition: transform 1.3s cubic-bezier(.96, 0, .07, 1), visibility 0s 1.9s;
}
#i-w .itr {
z-index: 100000;
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
background: #0f0a05;
display: flex;
justify-content: center;
align-items: center;
text-align: center;
}
#i-w {
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
}
.container {
background: pink;
display: flex;
flex-direction: column;
min-height: 100vh;
justify-content: center;
align-items: center;
transform: translateY(0);
transition: transform .7s cubic-bezier(.96, 0, .07, 1);
will-change: transform;
}
.container.fd {
transform: translateY(100%);
transition: transform .1s cubic-bezier(.96, 0, .07, 1);
}
.hdg {
font-family: Helvetica, sans-serif;
text-transform: uppercase;
text-align: center;
color: #000;
font-size: 18vw;
}
.itr-hdg {
font-family: Helvetica, sans-serif;
text-transform: uppercase;
text-align: center;
color: green;
font-size: 8vw;
opacity: 1;
visibility: hidden;
will-change: transform;
transform: translate3d(0, 150%, 0) skewY(18deg) scale(1);
animation: fd-i 1.3s .6s cubic-bezier(.86,0,.07,1) forwards, trlt-i 1.5s 1s cubic-bezier(.23, 1, .32, 1) forwards, trlt-o .5s 2.9s cubic-bezier(.23, 1, .32, 1) forwards, fd-o .4s 3s ease forwards;
}
@keyframes trlt-i {
to {
-webkit-transform: translateZ(0);
transform: translateZ(0);
}
}
@keyframes trlt-o {
from {
-webkit-transform: translateZ(0);
transform: translateZ(0);
}
to {
-webkit-transform: translate3d(0, -150%, 0) skewY(0deg) scale(1);
transform: translate3d(0, -150%, 0) skewY(0deg) scale(1);
}
}
@keyframes fd-i {
0% {
opacity: 0;
visibility: hidden;
}
to {
opacity: 1;
visibility: visible;
}
}
@keyframes fd-o {
0% {
opacity: 1;
visibility: visible;
}
to {
opacity: 0;
visibility: hidden;
}
}
</style>
<script>
setTimeout(function () {
function run() {
var wrp = document.getElementById("i-w");
var swp = document.getElementById("pink");
wrp.className += "loaded";
swp.classList.add('fd');
}
if (document.readyState != 'loading') run();
else if (document.addEventListener) document.addEventListener(
'DOMContentLoaded', run);
else document.attachEvent('onreadystatechange', function () {
if (document.readyState == 'complete') run();
});
}, 2650);
setTimeout(function () {
var swp = document.getElementById("pink");
swp.classList.remove('fd');
}, 3000);
</script>
</head>
<body>
<div id="i-w">
<div class="itr">
<div class="itr-hdg">
<h1>&#11014; intro &#11014;</h1>
</div>
</div>
</div>
<div class="container" id="pink">
<h1 class="hdg">hello</h1>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>Define your variables at the top of your script outside of the setTimeout. That way, you only need to define every variable once. Also, you can make them <code>const</code>, since they won't change.</p>\n\n<p>The same goes for the run() function. Declare it outside of the setTimeout. You just want to call it inside the setTimeout. I hope this is helpful for you.</p>\n\n<pre><code>const wrp = document.getElementById(\"i-w\");\nconst swp = document.getElementById(\"pink\");\n\n\nfunction run() {\n wrp.className += \"loaded\";\n swp.classList.add('fd');\n}\n\n\nsetTimeout(function () {\n\n if (document.readyState != 'loading') run();\n else if (document.addEventListener) document.addEventListener('DOMContentLoaded', run);\n else document.attachEvent('onreadystatechange', function () {\n if (document.readyState == 'complete') run();\n });\n}, 2650);\n\nsetTimeout(function () {\n swp.classList.remove('fd'); \n}, 3000);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T20:19:56.000",
"Id": "443490",
"Score": "0",
"body": "Thanks for the advice and the clarification."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T14:14:58.753",
"Id": "445284",
"Score": "0",
"body": "It doesn't work i get a \"Uncaught TypeError: Can not read property 'className' from null\" it seems the variables not being passed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T15:01:00.143",
"Id": "445291",
"Score": "1",
"body": "Try moving the script to the bottom of your document, just before the closing body tag. The error occurs because the script gets executed before the HTML elements get rendered."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T16:58:14.767",
"Id": "445307",
"Score": "0",
"body": "Ahh i see, my mistake. Now it works. Thanks!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T14:44:08.853",
"Id": "227724",
"ParentId": "227722",
"Score": "3"
}
},
{
"body": "<p>I would make the following recommendations to clean it up for future maintainability and readability:</p>\n\n<ul>\n<li>Clean up and remove the anonymous functions.\n\n<ul>\n<li>They aren't really needed here and just create extra clutter, decreasing readability.</li>\n</ul></li>\n<li>Remove the additional <code>setTimeout</code> call and just call to show when you're done loading.</li>\n<li>Use more meaningful names.\n\n<ul>\n<li>It was hard to understand what your code was doing, what each element was, and it took me some time to clean it up due to that.</li>\n<li>Using more meaningful names helps readability, and thus improves maintainability.</li>\n</ul></li>\n<li>Ensure you're only listing selectors in CSS once.\n\n<ul>\n<li>You had two instances of <code>#i-w</code> that could be combined into one ruleset instead.</li>\n</ul></li>\n<li>Remove the usage of events unless needed.\n\n<ul>\n<li>I wouldn't rely on the DOM events unless you're only focused on the page content and visuals.</li>\n<li>A reusable loader would begin loading and then show that it's loading until it's done loading, not when the DOM is done.</li>\n<li>A good additive to this is to include the event check once you're done loading just in case you finish before the DOM does.</li>\n</ul></li>\n<li>Do not redefine variables.\n\n<ul>\n<li>You'll notice that I removed one variable (<code>wrp</code>) because it was only used once.</li>\n<li>Also, if you're going to need a variable later, you can pass it to the next function, or you can create it globally at the top of the function that created it for later access.</li>\n<li>I wouldn't create it globally unless you need to, and in this case, I don't think you do since your only variables are <code>wrp</code> and <code>swp</code> which are both used by the pre-loader only.</li>\n</ul></li>\n</ul>\n\n<p>Other than that, it's visually appealing, and a great implementation! Keep up the good work!</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>// Begin loading our stuff from DB, files, etc.\nfunction beginLoading() {\n // Perform some kinds of loading tasks.\n for (var i = 0; i < 65535; i++)\n i++;\n\n // Check the DOM before updating.\n checkDOMForLoadingCompleted();\n}\n\n// Since we're done loading, we want to make sure the DOM is too.\nfunction checkDOMForLoadingCompleted() {\n if (document.readyState != 'loading')\n loadingCompleted();\n else if (document.addEventListener)\n document.addEventListener('DOMContentLoaded', loadingCompleted);\n else\n document.attachEvent('onreadystatechange', onReadyStateChange);\n}\nfunction onReadyStateChange() {\n if (document.readyState == 'complete')\n loadingCompleted();\n}\n\n// Loading has completed on our side and the DOM's so we can complete the pre-loader's life cycle.\nfunction loadingCompleted() {\n document.getElementById(\"pre-loader\").classList.add(\"loaded\");\n var loadedContent = document.getElementById(\"loaded-content\");\n loadedContent.classList.add(\"fd\");\n showLoadedContent(loadedContent);\n}\nfunction showLoadedContent(loadedContent) {\n loadedContent.classList.remove(\"fd\");\n}\n\n\n// This is to simulate starting a loading process.\n// Instead of using setTimeout, just call the begin loading function to start your loading process.\n//beginLoading();\ncallBeginLoadingOnTimeout();\nfunction callBeginLoadingOnTimeout() {\n setTimeout(beginLoading, 2650);\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\n margin: 0;\n padding: 0;\n background: yellow;\n}\n.pre-loader {\n z-index: 9999;\n visibility: visible;\n -webkit-transform: translateY(0%);\n transform: translateY(0%);\n -webkit-transition: -webkit-transform 0.4s ease-in-out;\n transition: transform 0.4s ease-in-out;\n will-change: transform;\n position: fixed;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n}\n.pre-loader.loaded {\n visibility: hidden;\n -webkit-transform: translateY(-100%);\n transform: translateY(-100%);\n -webkit-transition: -webkit-transform 1.3s cubic-bezier(0.96, 0, 0.07, 1), visibility 0s 1.9s;\n transition: transform 1.3s cubic-bezier(0.96, 0, 0.07, 1), visibility 0s 1.9s;\n}\n.pre-loader .intro-wrapper {\n z-index: 100000;\n position: fixed;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n background: #0f0a05;\n display: flex;\n justify-content: center;\n align-items: center;\n text-align: center;\n}\n.container {\n background: pink;\n display: flex;\n flex-direction: column;\n min-height: 100vh;\n justify-content: center;\n align-items: center;\n transform: translateY(0);\n transition: transform 0.7s cubic-bezier(0.96, 0, 0.07, 1);\n will-change: transform;\n}\n.container.fd {\n transform: translateY(100%);\n transition: transform 0.1s cubic-bezier(0.96, 0, 0.07, 1);\n}\n.heading {\n font-family: Helvetica, sans-serif;\n text-transform: uppercase;\n text-align: center;\n color: #000;\n font-size: 18vw;\n}\n.intro-heading {\n font-family: Helvetica, sans-serif;\n text-transform: uppercase;\n text-align: center;\n color: green;\n font-size: 8vw;\n opacity: 1;\n visibility: hidden;\n will-change: transform;\n transform: translate3d(0, 150%, 0) skewY(18deg) scale(1);\n animation: to-visible 1.3s 0.6s cubic-bezier(0.86, 0, 0.07, 1) forwards,\n to-zero-translation-z 1.5s 1s cubic-bezier(0.23, 1, 0.32, 1) forwards,\n to-transform-tss 0.5s 2.9s cubic-bezier(0.23, 1, 0.32, 1) forwards,\n to-hidden 0.4s 3s ease forwards;\n}\n@keyframes to-zero-translation-z {\n to {\n -webkit-transform: translateZ(0);\n transform: translateZ(0);\n }\n}\n@keyframes to-transform-tss {\n from {\n -webkit-transform: translateZ(0);\n transform: translateZ(0);\n }\n to {\n -webkit-transform: translate3d(0, -150%, 0) skewY(0deg) scale(1);\n transform: translate3d(0, -150%, 0) skewY(0deg) scale(1);\n }\n}\n@keyframes to-visible {\n from {\n opacity: 0;\n visibility: hidden;\n }\n to {\n opacity: 1;\n visibility: visible;\n }\n}\n@keyframes to-hidden {\n from {\n opacity: 1;\n visibility: visible;\n }\n to {\n opacity: 0;\n visibility: hidden;\n }\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"pre-loader\" class=\"pre-loader\">\n <div class=\"intro-wrapper\">\n <div class=\"intro-heading\">\n <h1>&#11014; intro &#11014;</h1>\n </div>\n </div>\n</div>\n<div class=\"container\" id=\"loaded-content\">\n <h1 class=\"heading\">hello</h1>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T20:43:48.767",
"Id": "443492",
"Score": "1",
"body": "Thank you for taking the time to describe your changes and recommendations in such detail. I'll take a closer look at that in the next few days, and if I have any questions, I'd like to come back to that. \nThanks again for your support!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T14:05:09.680",
"Id": "445282",
"Score": "0",
"body": "Thank's again. I tried your suggestion but in order to maintain the effect of dragging the loaded content into the field of view, while the preloader screen is moving up, I had to use a second timeout. I also had to declare the variable loadedContent inside that timeout once again and changed the \"container*\" to \"#loaded-content*\" in the css part. \nShould i post the code somewhere?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T15:00:47.387",
"Id": "227727",
"ParentId": "227722",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T13:41:18.160",
"Id": "227722",
"Score": "8",
"Tags": [
"javascript",
"html",
"css",
"dom",
"animation"
],
"Title": "Webpage with a preload animation using JavaScript setTimeout"
}
|
227722
|
<p>I'm making a 2D game which wraps (when you move off the right edge, you appear on the left, etc). The game area is square, all objects are circles (with AABB smaller than the game area, and in most cases, much smaller).</p>
<p>I'm dividing the game area into a grid to perform collision checks. I need to determine which cell(s) an object's AABB lives in.</p>
<p>Right now I have this awkward code to deal with cases when the object passes the left/right boundary... I feel like there must be a better way to write it.</p>
<p><code>gridX</code> is x-dimension of the grid
<br><code>x1</code> is the x-coord of the cell the object's left boundary lives in (before taking into account wrap)
<br><code>x2</code> " " right boundary</p>
<pre><code>if (x1 < 0) {
for (let j = x1 + gridX; j < gridX; j++) someFunction(j)
for (let j = 0; j < x2; j++) someFunction(j)
} else if (x2 >= gridX) {
for (let j = x1; j < gridX; j++) someFunction(j)
for (let j = 0; j < x2 - gridX; j++) someFunction(j)
} else {
for (let j = x1; j <= x2; j++) someFunction(j)
}
</code></pre>
<p><code>someFunction</code> would then contain the <code>y</code> coord version of the above and add to the grid.</p>
<p>Bear in mind I don't want to lose performance (as it will be run multiple times per second).</p>
<p>I want to write out <code>someFunction</code> instead of actually declaring a function so I hope there is a better way to do this - especially if I wanted to make my game 3 dimensional in future. That would be 25 pastes.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T17:11:39.547",
"Id": "443467",
"Score": "0",
"body": "It becomes this when written out https://hasteb.in/apubudet.js"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T00:53:57.487",
"Id": "443507",
"Score": "0",
"body": "You say that all objects are circles. If this is true than why are you using AABB? Point/Circle collision is much faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T13:02:26.010",
"Id": "443559",
"Score": "0",
"body": "@GabrielRohweder I use AABB to determine which grid cells they intersect. I think its faster (since most objects will be smaller than 1 cell)"
}
] |
[
{
"body": "<h2>Some style points first.</h2>\n\n<ul>\n<li><p>Always wrap statement and loop blocks in <code>{}</code> eg you wrote <code>for (let j = 0; j < x2; j++) someFunction(j)</code> to avoid maintenance headaches use the curlies <code>for (let j = 0; j < x2; j++) { someFunction(j) }</code></p></li>\n<li><p>Don't declare the same variable over and over. There is no advantage to locally scoping variables to code blocks unless you are writing very long functions, and you should avoid writing functions more than a page long. </p></li>\n<li><p>In this case <code>j</code> is not the best choice of variable name for the loop counter. <code>x</code> would be far better.</p></li>\n</ul>\n\n<p>Rewriting your function with the above points</p>\n\n<pre><code>var x;\nif (x1 < 0) {\n for (x = x1 + gridX; x < gridX; x++) { someFunction(x) }\n for (x = 0; x < x2; x++) { someFunction(x) }\n} else if (x2 >= gridX) {\n for (x = x1; x < gridX; x++) { someFunction(x) }\n for (x = 0; x < x2 - gridX; x++) { someFunction(x) }\n} else {\n for (x = x1; x <= x2; x++) { someFunction(x) }\n}\n</code></pre>\n\n<h2>The remainder operator <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder\" rel=\"nofollow noreferrer\"><code>%</code></a></h2>\n\n<blockquote>\n <p><em>\"I feel like there must be a better way to write it.\"</em></p>\n</blockquote>\n\n<p>You can simplify the solution by using the remainder operator <code>%</code>. First ensure that <code>x1</code>, and <code>x2</code> are positive by adding the grid width (or height)\nThen use remainder as you loop over the items to get the wrapped coordinate.</p>\n\n<h3>Example replaces your function</h3>\n\n<pre><code>// Assumes x1 is never less than -gridX and that x2 is always > x1\nconst end = x2 + gridX;\nvar x = x1 + gridX; \nwhile (x <= end) { someFunction((x++) % gridX) }\n</code></pre>\n\n<h3>More detailed example of wrapped play-field</h3>\n\n<p>The example below demonstrates using remainder and has two functions that take a x,y gird coordinated and map it to an array. <code>setGrid(x, y, val)</code> as long as the grid coordinates are greater than <code>gridSteps</code> (same as your <code>gridX</code>) <code>* -gridMin</code></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const AABB = { x: 0, y: 0, w: 90, h: 90 } // values in pixels\nconst gridSteps = 10; // same as your gridX\nconst gridMin = 100; // min number of grids below origin 0,0. Used to translate \n // coordinates to positive values\nconst grid = new Uint8Array(gridSteps ** 2); // grid array\n\nfunction setGrid(x, y, val) { \n x += gridSteps * gridMin; // translate to positive space\n y += gridSteps * gridMin; // translate to positive space\n const idx = (x % gridSteps) + (y % gridSteps) * gridSteps;\n grid[idx] = val;\n}\n\n// version 2\nconst gridMinC = gridSteps * gridMin;\nfunction setGrid(x, y, val) { \n const idx = ((x + gridMinC) % gridSteps) + ((y + gridMinC) % gridSteps) * gridSteps;\n grid[idx] = val;\n}\n\n \n\n\n\n\nrequestAnimationFrame(update);\nconst scaleMouse = 0.05; // scales mouse to add movement\nconst inset = 3, inset2 = inset * 2;\nvar w = 1, h = 1;\nconst gridImg = createImage(w, h);\nconst ctx = canvas.getContext(\"2d\");\nconst mouse = {x : 0, y : 0};\ndocument.addEventListener(\"mousemove\", mouseEvents);\nfunction fillGrid(AABB, gridSteps, col = \"#9998\") { // Draw wrapped collision boxes\n var x, y, xs = w / gridSteps, ys = h / gridSteps;\n const yStart = AABB.y / ys | 0, yEnd = (AABB.y + AABB.h) / ys | 0;\n const xStart = AABB.x / xs | 0, xEnd = (AABB.x + AABB.w) / xs | 0;\n ctx.fillStyle = col;\n ctx.beginPath();\n for (y = yStart; y <= yEnd; y += 1) {\n const yy = y % gridSteps;\n for (x = xStart; x <= xEnd; x += 1) {\n const xx = x % gridSteps;\n ctx.rect(xx * xs + inset, yy * ys + inset, xs - inset2, ys - inset2); \n }\n }\n ctx.fill();\n}\nfunction drawBox(AABB, col = \"#000\") { // draws AABB box wrapped\n ctx.strokeStyle = col;\n ctx.lineWidth = 2;\n const x = AABB.x % w;\n const y = AABB.y % h;\n ctx.strokeRect(x, y, AABB.w, AABB.h);\n var corner = 0;\n if (x + AABB.w > w) {\n ctx.strokeRect(x- w, y, AABB.w, AABB.h);\n corner ++;\n } \n if (y + AABB.h > h) {\n ctx.strokeRect(x, y - h, AABB.w, AABB.h);\n corner ++;\n }\n if (corner === 2) { ctx.strokeRect(x - w, y - h, AABB.w, AABB.h) }\n}\nfunction update() {\n if (w !== (innerWidth / 2 | 0) || h !== innerHeight) {\n w = gridImg.width = canvas.width = innerWidth / 2 | 0;\n h = gridImg.height = canvas.height = innerHeight;\n drawGridLines(gridImg.ctx, gridSteps);\n }\n ctx.globalCompositeOperation = \"copy\"; // copy transparent pixels to destination \n ctx.drawImage(gridImg, 0, 0);\n ctx.globalCompositeOperation = \"source-over\"; // default comp mode \n \n //Use mouse dist from center to scale speed of AABB\n AABB.x = (AABB.x + (mouse.x - w / 2) * scaleMouse + w) % w;\n AABB.y = (AABB.y + (mouse.y - h / 2) * scaleMouse + h) % h;\n fillGrid(AABB, gridSteps);\n drawBox(AABB);\n requestAnimationFrame(update);\n}\nfunction mouseEvents(e){\n const bounds = canvas.getBoundingClientRect();\n mouse.x = e.pageX - bounds.left - scrollX;\n mouse.y = e.pageY - bounds.top - scrollY;\n}\nfunction createImage(width, height) {\n const img = document.createElement(\"canvas\");\n img.width = width, img.height = height;\n img.ctx = img.getContext(\"2d\");\n return img;\n}\nfunction drawGridLines(ctx, gridSteps, col = \"red\") {\n var i, xs = w / gridSteps, ys = h / gridSteps;\n ctx.lineWidth = 2;\n ctx.strokeStyle = col;\n ctx.beginPath();\n for (i = 0; i <= gridSteps; i ++) {\n ctx.moveTo(0, i * ys);\n ctx.lineTo(w, i * ys);\n ctx.moveTo(i * xs, 0);\n ctx.lineTo(i * xs, h);\n }\n ctx.stroke();\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>canvas { position : absolute; top : 0px; left : 0px; cursor: crosshair;}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><canvas id=\"canvas\"></canvas></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h2>Last point</h2>\n\n<blockquote>\n <p><em>\"especially if I wanted to make my game 3 dimensional in future.\"</em></p>\n</blockquote>\n\n<p>You would never use a 3D grid for collisions as their size can grow very quickly, a 1024 cube would require a minimum or 1Gig of RAM. What you want are <a href=\"https://en.wikipedia.org/wiki/Quadtreehttps://en.wikipedia.org/wiki/Quadtree\" rel=\"nofollow noreferrer\">Quad Trees</a> or even <a href=\"https://en.wikipedia.org/wiki/Octree\" rel=\"nofollow noreferrer\">Octrees</a> and the many variations, as they provide fast data structures for all sorts of spacial related problems 2D, 3D, and more :D</p>\n\n<p>Collision grids are great for lowres 2D and limited 3D uses but you will need to consider alternatives when resolutions grow.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T13:05:53.060",
"Id": "443560",
"Score": "0",
"body": "I avoided using the % operator as I was under the impression it performs division (slow)? And then for the last point - the same problem surely exists with quad/octrees if you have a game that wraps?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T23:36:21.323",
"Id": "443678",
"Score": "1",
"body": "@Shuri2060 JavaScript has internal `Number` formats. Default double (64bit float) fastest is signed int32. You can force a number to be a int32 in a variety of ways. Apply a bitwise operator. `x |= 0` (OR zero). CPU instruction sets do not generally have an (int) modulo instruction however dividing `op DIV` a remainder is stored in a register (x86/64). For the fastest modulo use a grid that is power of two, 2, 4, 8, 16, 32, etc .. and bitwise mask (AND &) the coordinate. eg `grid = 256; mask = grid - 1;` `x &= mask` very fast and result same as `x %= grid` if 0 <= x < 2**31"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T07:34:03.187",
"Id": "227765",
"ParentId": "227731",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "227765",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T15:41:35.857",
"Id": "227731",
"Score": "3",
"Tags": [
"javascript",
"performance",
"collision"
],
"Title": "Making a grid for collision detection in a game that wraps"
}
|
227731
|
<p>This isn't the actual use-case I have but for simplicity, let's say I have an ActiveRecord Animal model in a Rails app. The Animals have a <code>name</code> (string) and <code>rating</code> (int). There could be animals with the same name but different ratings. In my Animal model I have a hardcoded constant like this:</p>
<pre class="lang-rb prettyprint-override"><code>SPECIAL_ANIMAL_TYPES = [
{ name: 'Cat', rating: 3 },
{ name: 'Dog', rating: 5 },
{ name: 'Fish', rating: 1 }
]
</code></pre>
<p>I want to grab a single ActiveRecord:Relation with all Animals that match these attributes <em>exactly</em>. I can't pass an array to the <code>where</code> clause like <code>where(name: ['Cat', 'Dog', etc], rating: [3, 5, 1])</code> because I only want cats that are rating 3, and dogs that are rating 5 and so on. Like I said, there could be multiple records with the same name but different ratings.</p>
<p>In the Animal model I have a class method (basically a scope) to grab the records that match the types specified in SPECIAL_ANIMAL_TYPES. The following code does what I want, but clearly is pretty ugly and if I added more types to SPECIAL_ANIMAL_TYPES I'd have to modify this method:</p>
<pre class="lang-rb prettyprint-override"><code>def self.special_animals_only
where(SPECIAL_ANIMAL_TYPES[0]).or(where(SPECIAL_ANIMAL_TYPES[1])).or(where(SPECIAL_ANIMAL_TYPES[2]))
end
</code></pre>
<p>I also tried something like:</p>
<pre class="lang-rb prettyprint-override"><code>def self.special_animals_only
SPECIAL_ANIMAL_TYPES.collect { |types| where(types) }.sum
end
</code></pre>
<p>But that returns an array and I want an ActiveRecord Relation. So is there a more elegant way to write this class method so I can continue modifying/adding types to the constant and have this method work dynamically?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T15:38:10.413",
"Id": "443602",
"Score": "0",
"body": "The code snippets I posted do work absolutely correctly (see code snippet #2), but it could be improved, it's not the most elegant solution, which is what I thought this Stack Exchange was for. Would appreciate some actual feedback on how to improve this question!"
}
] |
[
{
"body": "<p>Turns out the last code snippet in my question was close to what I ended up needing:</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>def self.special_animals_only\n SPECIAL_ANIMAL_TYPES.collect { |types| where(types) }.reduce(:or)\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T20:16:37.070",
"Id": "227739",
"ParentId": "227735",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "227739",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T18:17:18.993",
"Id": "227735",
"Score": "2",
"Tags": [
"ruby",
"ruby-on-rails",
"active-record"
],
"Title": "Dynamically combine ActiveRecord Relation results"
}
|
227735
|
<p>The object of the code is to prompt the user with a quiz and collect the g's, y's, 0's, and 1's and if there is more than one then the user passes (else, they fail). I am a beginner and would like to know if there is a more efficient direction for this code to go in.</p>
<pre><code>from time import sleep
print(pic1)
def check(name):
if name.lower() == "brandon":
print("Welcome home master")
else:
print("Let's find some data")
sleep(0.5)
print("What is your favorite color?")
color = input("fav_color>>> ")
if color == "":
print("No skipping!")
print(check(input("Enter Name Here>>> ")))
print("What is your dream car?")
car = input("fav_car>>> ")
if car == "":
print("No skipping!")
print(check(input("Enter Name Here>>> ")))
print("What team are you on?")
team = input("team_name>>> ")
if team == "":
print("No skipping!")
print(check(input("Enter Name Here>>> ")))
print("Who is your best friend?")
crush = input("best_friend>>> ")
if crush == "":
print("No skipping!")
print(check(input("Enter Name Here>>> ")))
print("What color is your shirt?")
shirt = input("shirt_color>>> ")
if shirt == "":
print("No skipping!")
print(check(input("Enter Name Here>>> ")))
print("You got clout?")
clout = input("clout_level>>> ")
if clout == "":
print("No skipping!")
print(check(input("Enter Name Here>>> ")))
print("Do you think you passed the test?")
passed = input("passed?>>> ")
if passed == "":
print("No skipping!")
print(check(input("Enter Name Here>>> ")))
print("Calculating...")
sleep(2.5)
def add():
color_counted = color.count("g")
car_counted = car.count("g")
team_counted = team.count("g")
crush_counted = crush.count("g")
shirt_counted = shirt.count("g")
clout_counted = clout.count("y")
clout_counted2 = clout.count("1")
clout_counted3 = clout.count("0")
passed_counted = passed.count("y")
total = color_counted + car_counted + team_counted + clout_counted3 + passed_counted
total = crush_counted + shirt_counted + clout_counted + clout_counted2
return total
if add() > 1:
print("passed")
else:
print("failed")
print("Congrats on your result!")
sleep(100)
check(input("Enter Name Here>>> "))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T22:11:49.620",
"Id": "443495",
"Score": "0",
"body": "also do not mind the print(pic1) at the beginning of the code, it was something I was messing around with and forgot to delete."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T23:35:36.000",
"Id": "443503",
"Score": "2",
"body": "Welcome to Code Review! I made the title a bit more descriptive of the code. From [How to Ask](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". If there is a more appropriate description then feel free to update it via [edit]."
}
] |
[
{
"body": "<p>Welcome to CodeReview! This isn't great code, but that doesn't mean that this is a bad question. I think that you've come to the right place.</p>\n\n<h2>Recursion</h2>\n\n<pre><code> if color == \"\":\n print(\"No skipping!\")\n print(check(input(\"Enter Name Here>>> \")))\n</code></pre>\n\n<p>This uses recursion when it shouldn't. In other words, <code>check</code> is calling itself needlessly, and if the user tries to \"skip\" enough times, you'll get a stack overflow. Instead of doing this, just loop until you have valid input.</p>\n\n<h2>Fake delays</h2>\n\n<pre><code> print(\"Calculating...\")\n sleep(2.5)\n</code></pre>\n\n<p>Few things bother me more than when a user interface lies to me. This output suggests that it takes 2.5 seconds for a calculation to be done, but that simply isn't so. Don't lie to your users - just show the results.</p>\n\n<p><code>sleep(100)</code> is actively harmful - the user needs to Ctrl+C to kill the program; otherwise it sits there preventing the user from getting their shell terminal back. This should just be deleted.</p>\n\n<h2>Don't repeat yourself</h2>\n\n<p>There are many places in the program that are expressed in a repetitive manner, especially user input (the \"no skipping\" mechanism), the call to <code>count</code>, and the additions to get <code>total</code>. I suggest the following:</p>\n\n<pre><code>def input_without_skip(prompt: str) -> str:\n while True:\n result = input(f'{prompt}>>>')\n if result:\n return result\n print('No skipping!')\n\n\ndef is_master() -> bool:\n return input_without_skip('Enter Name Here') == 'Hercules'\n\n\ndef get_counts():\n for question, prompt, chars in (\n ( 'What is your favorite color?', 'fav_color', 'g'),\n ( 'What is your dream car?', 'fav_car', 'g'),\n ( 'What team are you on?', 'team_name', 'g'),\n ( 'Who is your best friend?', 'best_friend', 'g'),\n ( 'What color is your shirt?', 'shirt_color', 'g'),\n ( 'You got clout?', 'clout_level', 'y10'),\n ('Do you think you passed the test?', 'passed?', 'y')\n ):\n print(question)\n answer = input_without_skip(prompt)\n yield sum(answer.count(c) for c in chars)\n\n\ndef main():\n if is_master():\n print('Welcome home, master.')\n return\n\n print(\"Let's find some data!\")\n total = sum(get_counts())\n\n if total > 1:\n print(\"passed\")\n else:\n print(\"failed\")\n print(\"Congrats on your result!\")\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T17:10:30.903",
"Id": "443625",
"Score": "0",
"body": "Thanks great content the only reason I put sleep 100 is because I am converting this program into an .exe and it stops running as soon as showing the result without giving the user time to read it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T17:12:00.217",
"Id": "443626",
"Score": "0",
"body": "The solution is not to sleep, it's too change the way that you execute the program. Either execute it from a command window, or change the properties of your shortcut."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T17:21:57.337",
"Id": "443631",
"Score": "0",
"body": "Alright, and also since I am just getting into Python what is with the -> str while defining a function? Sorry to bother, but I just have some questions of the code you suggested."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T17:22:52.930",
"Id": "443632",
"Score": "0",
"body": "Those are PEP484 type hints. That one says that the function returns a string."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T17:24:39.730",
"Id": "443634",
"Score": "0",
"body": "Alright so it is not necessary but helpful?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T17:25:33.123",
"Id": "443635",
"Score": "0",
"body": "Right! Think of it like a comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T17:26:12.477",
"Id": "443636",
"Score": "0",
"body": "Ok thanks, I have to go now but I have more questions I will ask later, that ok?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T18:12:57.777",
"Id": "443645",
"Score": "0",
"body": "Alright so in general your response is a lot more advanced than my knowledge of Python and I hope to learn more about this as I progress, thanks a lot for your help!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T19:41:15.413",
"Id": "443657",
"Score": "0",
"body": "@pythonier500 You're welcome. Yes, you can ask questions later, but please do it in this chat: https://chat.stackexchange.com/rooms/98513/personal-quiz-with-input-validation rather than in the comments."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T21:19:28.363",
"Id": "443664",
"Score": "0",
"body": "I would, the only problem is I do not have enough reputation to use a chat room"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T03:02:52.280",
"Id": "227753",
"ParentId": "227744",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227753",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T22:10:44.190",
"Id": "227744",
"Score": "1",
"Tags": [
"python",
"beginner",
"python-3.x",
"quiz"
],
"Title": "Personal quiz with input validation"
}
|
227744
|
<p>A Kotlin class that I wrote fairly early on while learning Kotlin which is used by another program to build and generate HTML visualisations of timetables. I'd be grateful for any feedback, especially if there's any way (that's not too verbose) of tidying up the multilayer data structure.</p>
<pre><code>import data.Session
import data.Slot
import java.io.PrintWriter
// Boolean is true if this is the first slot for this session, as this is where the HTML tag should be placed.
typealias Cell = Pair<MutableList<Session>?, Boolean>
typealias Grid = Array<Array<Cell>>
typealias Day = MutableList<Grid>
typealias Semester = Array<Day>
class HTMLTimetable {
val sessions: Array<Semester> = Array(2) {
// 2 semesters
Array(5) {
// 5 days
MutableList(1) {
// Variable number of layers
Array(12) {
// 12 weeks
Array(12) {
// 12 slots
Pair(null as MutableList<Session>?, false)
}
}
}
}
}
fun newGrid(): Grid = Array(12) { Array(12) { Pair(null as MutableList<Session>?, false)}}
fun addSession(newSession : Session, weekFilter : (Int) -> Boolean) {
var tryingLayer = 0
var thisLayerOK = false
var mergePossible = false
var mergeDebug: Session? = null
var mergeDebugSlot : Cell? = null
var mergeDebugLayer = 0
var mergeDebugWeek = 0
var mergeDebugOrd = 0
// Check a slot exists.
if (newSession.slot == null) {
println("Trying to HTML timetable a session with no slot, $newSession")
return
}
// Find a layer with free space in the appropriate position
val semDayLayerArray = sessions[newSession.semester-1][newSession.slot!!.day]
while (!thisLayerOK) {
thisLayerOK = true
// See if there's any week in which this layer is blocked
// This makes sure that all weeks of a module will be on the same layer
// In each week the module runs..
checkFreeLayerLoop@ for (week in (0..11).filter {newSession.runsInWeek(it) && weekFilter(it)} ) {
val tryingWeekArray = semDayLayerArray[tryingLayer][week]
// For each slot the module occupies in those weeks..
val startSlot = newSession.slot!!.ordinalInDay
val endSlot = newSession.lastSlot.ordinalInDay
for (daySlot in startSlot..endSlot) {
val tryingSlot = tryingWeekArray[daySlot]
// Is slot occupied?
if (tryingSlot.first != null) {
// If the session we're adding is already there, don't add it again at all
if (tryingSlot.first!!.contains(newSession)) return
// There's a session there, maybe it's mergable though?
val existingSession = tryingSlot.first!![0]
if ((existingSession.module == newSession.module) || (existingSession.isMergedWith(newSession))) {
if (existingSession.type == newSession.type) {
if (existingSession.slot == newSession.slot) {
if (existingSession.length == newSession.length) {
// println("Merge possible between $existingSession and $newSession triggered by $tryingSlot")
mergePossible = true
mergeDebugSlot = tryingSlot
mergeDebug = existingSession
mergeDebugLayer = tryingLayer
mergeDebugWeek = week
mergeDebugOrd = daySlot
continue@checkFreeLayerLoop
}
}
}
}
// Slot is occupied and merge not possible. Break checking loop and go to next layer
mergePossible = false
thisLayerOK = false
break@checkFreeLayerLoop
}
}
}
// If loop was broken without finding a layer, try next layer
if (!thisLayerOK) {
tryingLayer++
// If that was the last layer, add another layer, then add event to that
// (Since the new layer will be empty, it will certainly be unblocked)
if (tryingLayer > semDayLayerArray.lastIndex) {
semDayLayerArray.add(newGrid())
thisLayerOK = true
mergePossible = false
}
}
}
// thisLayerOK should now be true.
// mergePossible: layer has existing sessions in these slots which are mergable.
//
var isFirst : Boolean
for (week in (0..11).filter {newSession.runsInWeek(it) && weekFilter(it)}) {
isFirst = true
for (dayOrdinal in (newSession.slot!!.ordinalInDay)..(newSession.slot!!.ordinalInDay + newSession.length - 1)) {
if (mergePossible) {
if (semDayLayerArray[tryingLayer][week][dayOrdinal].first == null) {
// This can occur in the following circumstances:
// A module is added in an earlier pass with a week filter that includes only some earlier sessions.
// Then added again in a later pass (eg, staff as well as room clash) with a more permissive week filter.
// It is identified as a merge based on the earlier sessions, but then the later sessions have no
// merge target, because even though the session runs in the later weeks, they were not previously
// added due to the week filter.
semDayLayerArray[tryingLayer][week][dayOrdinal] = Pair(mutableListOf(newSession), isFirst)
isFirst = false
continue
}
semDayLayerArray[tryingLayer][week][dayOrdinal].first!!.add(newSession)
} else {
semDayLayerArray[tryingLayer][week][dayOrdinal] = Pair(mutableListOf(newSession), isFirst)
isFirst = false
}
}
}
}
fun output(target: PrintWriter, header: String, colorizer: (MutableList<Session>) -> String) {
target.println("<html><head><title>$header</title></head><body style=\"font-family: sans-serif\"><h1>$header</h1>")
for (semester in 0..1) {
for (day in 0..4) {
val semDayLayerArray = sessions[semester][day]
// If no sessions on this day/semester, stop
if (semDayLayerArray[0].all {
it.all {
it.first == null
}
})
continue
target.println("<h3>${Slot.dayNames[day]}, Semester ${semester+1} </h3>")
val maxLayer = semDayLayerArray.size
val colSpan = when {
maxLayer == 1 -> 1
else -> maxLayer + 1
}
target.println("<table><tr><th></th>")
for (headerWeek in 0..11) {
target.println("<th colspan=$colSpan>Week ${headerWeek+1} </th>")
}
target.println("</tr>")
for (slot in 0..11) {
target.println("<tr>")
target.println("<th>${slot+9} - ${slot+10}</th>")
for (week in 0..11) {
for (layer in semDayLayerArray) {
val thisSlot = layer[week][slot]
if ((thisSlot.second) && (thisSlot.first != null)) {
val thisSessions = thisSlot.first!!
val bgcol = colorizer(thisSessions)
target.println("<td style=\"border: 2px solid black; background-color: $bgcol\" rowspan=${thisSessions[0].length}>")
val names = thisSessions.map { "${it.module.name} ${it.module.fullName} (${it.module.level})" }.distinct().toString()
target.println("$names<br>${thisSlot.first!![0].type}<br>")
if (thisSlot.first!!.size > 1) {
target.println("${thisSlot.first!!.size} sets<br>")
for (session in thisSlot.first!!) {
target.print("${session.room!!.name}: ")
session.staffLoadingByWeek[week].forEach { (staffer, int) ->
target.print("${staffer.name} ")
}
target.println("<br>")
}
} else {
target.println("${thisSlot.first!![0].room!!.name}<br>")
if (!thisSlot.first!![0].mandatory) {
target.println("${thisSlot.first!![0].altThread + 1} / ${thisSlot.first!![0].altThreadMax}<br>")
}
thisSlot.first!![0].staffLoadingByWeek[week].forEach { (staffer, int) ->
target.println("${staffer.name} <br>")
}
}
target.println("</td>")
} else if (thisSlot.first == null) {
target.println("<td style=\"border: 1px solid gray;\"></td>")
}
}
if (maxLayer > 1) {
target.println("<td style=\"border: 1px solid black; background-color: black;\"></td>")
}
}
target.println("</tr>")
}
target.println("</table><br><br>")
}
}
target.println("</body></html>")
target.flush()
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T07:58:32.630",
"Id": "444848",
"Score": "1",
"body": "is _newSession.slot!!.ordinalInDay + newSession.length - 1_ the same as _newSession.lastSlot.ordinalInDay_?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T16:49:26.923",
"Id": "444920",
"Score": "0",
"body": "Good point, it should be."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T15:06:24.997",
"Id": "448270",
"Score": "0",
"body": "another question. I like the excelrcise, so even if you are ready, please provide them... \nI like to have te Session and the slot-classes. \n(or at least without implementation, but the var/val such that i know which is nullable etc.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T17:31:17.863",
"Id": "448295",
"Score": "0",
"body": "One little question, do you need mergeDebug, mergeDebugSlot, mergeDebugLayer, mergeDebugWeek, mergeDebugOrd at the top layer where you have define them? Thats the part which makes it challenging. Simplifying the rest is easy..."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T22:26:33.773",
"Id": "227745",
"Score": "0",
"Tags": [
"kotlin",
"data-visualization"
],
"Title": "Kotlin HTML timetable visualisation generator"
}
|
227745
|
<h1>Context</h1>
<p>I'm trying to build a system in which a tool (the Client) will generate a header to be used as part of an HTTP request from the user's browser.</p>
<ul>
<li>The user should be able to choose their own implementation of the Client.</li>
<li>The user should <strong>not</strong> have to install a plugin or extension to their browser.</li>
</ul>
<h1>Summary</h1>
<p>A 3rd party will serve a small wrapper (the Shim) which will keep track of where to load the Client from. It will store this in the browser's IndexedDB under its own origin.</p>
<p>The Shim and the Client will be loaded in iframes of their own origin, so that they (and the Host website) can only access each-other's functionality through the defined methods (based on MessageChannels and postMessage() calls).</p>
<h1>Parties, Prerogatives, and Restrictions</h1>
<ul>
<li>The Host website is at <a href="https://codereview.stackexchange.com/questions/227748/nested-cors-iframes-for-secure-user-configurable-javascript-tools">www.host.com</a>.</li>
<li>They shouldn't be able to know what implementation of the Client is in use,</li>
<li>nor should they be able to affect the Client in any way <em>except</em> by requesting header values.</li>
<li>(As it stands the Host is able to suggest a default Client; when I actually build the set-Client-address tool for the Shim, I'll get rid of this.)</li>
<li>The Shim is served from <a href="https://codereview.stackexchange.com/questions/227748/nested-cors-iframes-for-secure-user-configurable-javascript-tools">www.shim.com</a>.</li>
<li>They're assumed to be trustworthy <em>in the sense that people know what code they're serving</em>. (Even this isn't ideal; <a href="https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity#Examples" rel="nofollow noreferrer">subresource integrity checks</a> would be great if they worked on iframes.)</li>
<li>Their code obviously knows who the Client is, and can see the requests and responses as they're passed back and forth, but all of this stays on the user's machine as far as the Shim is concerned.</li>
<li>They can only affect the client by requesting the header values.</li>
<li>The Client is served from <a href="https://codereview.stackexchange.com/questions/227748/nested-cors-iframes-for-secure-user-configurable-javascript-tools">www.client.com</a>.</li>
<li>At present this is being passed in as a default, but in practice it should have been saved into the IndexedDB on the user's machine belonging to the <a href="http://www.shim.com" rel="nofollow noreferrer">www.shim.com</a> origin. (It will get put there by some other tool I haven't written yet.)</li>
<li>It's fine for the client to know who the Host is; I may even add that as an explicit property of each request.</li>
<li>There's an image or some other resource that the Host wants to load on their page, but requesting that image requires a custom <code>Receipts-Receipt</code> HTTPS header, the value for which needs to come from the Client. Let's suppose this image is at <a href="https://codereview.stackexchange.com/questions/227748/nested-cors-iframes-for-secure-user-configurable-javascript-tools">https://www.target.com/target.png</a>, but it could just as easily be in the same origin as the Host website itself.</li>
</ul>
<h1>Code</h1>
<h3><a href="http://www.host.com/host.html" rel="nofollow noreferrer">www.host.com/host.html</a></h3>
<pre class="lang-html prettyprint-override"><code><!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>Host</title>
<script
src="https://www.shim.com/shim.js"
data-default="https://www.client.com/client.html">
</script>
<script>
_page_loaded = ()=>{
window.FOTR.fetch(
new Request('https://www.target.com/target.png')
).then((response)=>{
return response.blob();
}).then((b)=>{
const i = window.document.createElement('img');
i.src = URL.createObjectURL(b);
document.getElementById("testTarget").appendChild(i);
});
};
</script>
</head>
<body onload="_page_loaded()">
<h1>Host</h1>
<p>Lorem ipsum dolor sit amet.</p>
<p id="testTarget"></p>
<p>Text continues.</p>
</body>
</html>
</code></pre>
<h3><a href="http://www.shim.com/shim.js" rel="nofollow noreferrer">www.shim.com/shim.js</a></h3>
<pre class="lang-js prettyprint-override"><code>((toolName)=>{
if(typeof window[toolName] === 'undefined'){
const loaderUtilities = { //This is exactly the same between shim.html and shim.js.
domReady: new Promise((resolve, reject)=>{
if(document.readyState === "loading"){
document.addEventListener('DOMContentLoaded', resolve);
}
else{
resolve();
} // add error handler?
}),
origin: (uri)=>{
const parser = window.document.createElement('a');
parser.href = uri;
return `${parser.protocol}//${parser.host}`;
},
loadTool: (uri)=>{
return new Promise((resolve, reject)=>{
const tag = window.document.createElement('iframe');
tag.src = uri;
tag.width = 0;
tag.height = 0;
tag.style = "visibility: hidden";
window.addEventListener("message",
(e)=>{
if(e.origin == loaderUtilities.origin(uri)){ //is it possible to refine the origin check?
resolve(e.data);
}
},
false);
loaderUtilities.domReady.then(()=>{
document.body.appendChild(tag);
});
}); // add error handler?
},
requestOverPort: (port, resource)=>{
return new Promise((resolve, reject)=>{
const disposableChannel = new MessageChannel();
disposableChannel.port1.onmessage = (e)=>{
resolve(e.data);
disposableChannel.port1.close();
};
port.postMessage(
{
resource: resource,
port: disposableChannel.port2
},
[disposableChannel.port2]);
});
},
};
const defaultClient = document.currentScript.getAttribute("data-default") || '';
const gotClientPort = loaderUtilities.loadTool(`https://www.shim.com/shim.html#${defaultClient}`);
window[toolName] = {
fetch: (request)=>{
return gotClientPort
.then((clientPort)=>{
return loaderUtilities.requestOverPort(
clientPort,
{
url: request.url,
method: request.method
});
})
.then((receipt)=>{
return window.fetch(
request,
{
headers: new Headers({ 'Receipts-Receipt': receipt }),
});
});
}
}
}
})(document.currentScript.getAttribute("data-name") || "FOTR")
</code></pre>
<h3><a href="http://www.shim.com/shim.html" rel="nofollow noreferrer">www.shim.com/shim.html</a></h3>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<title>The FOTR Shim</title>
<meta charset="UTF-8">
<script type="text/javascript">
const loaderUtilities = { //This is exactly the same between shim.html and shim.js.
domReady: new Promise((resolve, reject)=>{
if(document.readyState === "loading"){
document.addEventListener('DOMContentLoaded', resolve);
}
else{
resolve();
} // add error handler?
}),
origin: (uri)=>{
const parser = window.document.createElement('a');
parser.href = uri;
return `${parser.protocol}//${parser.host}`;
},
loadTool: (uri)=>{
return new Promise((resolve, reject)=>{
const tag = window.document.createElement('iframe');
tag.src = uri;
tag.width = 0;
tag.height = 0;
tag.style = "visibility: hidden";
window.addEventListener("message",
(e)=>{
if(e.origin == loaderUtilities.origin(uri)){ //is it possible to refine the origin check?
resolve(e.data);
}
},
false);
loaderUtilities.domReady.then(()=>{
document.body.appendChild(tag);
});
}); // add error handler?
},
requestOverPort: (port, resource)=>{
return new Promise((resolve, reject)=>{
const disposableChannel = new MessageChannel();
disposableChannel.port1.onmessage = (e)=>{
resolve(e.data);
disposableChannel.port1.close();
};
port.postMessage(
{
resource: resource,
port: disposableChannel.port2
},
[disposableChannel.port2]);
});
},
};
const indexedDBPromise = (request)=>{
return new Promise(
(resolve, reject)=>{
request.onsuccess = (e)=>{
resolve(e.target.result);
};
request.onerror = (e)=>{
reject(e.target.error);
};
});
};
const defaultClient = window.location.href.split('#')[1] || '';
const objectStoreName = "chosen_clients";
const openDB = window.indexedDB.open("FOTR", 1);
openDB.onupgradeneeded = (e)=>{
e.target.result.createObjectStore(objectStoreName);
};
indexedDBPromise(openDB)
.then(
(db)=>{
const tx = db.transaction(objectStoreName, "readonly");
tx.oncomplete = ()=>{
db.close();
};
return indexedDBPromise(tx.objectStore(objectStoreName).getAll());
})//handle open-db error?
.then(
(db_result)=>{
const clientURI = db_result.uri || defaultClient;
return loaderUtilities.loadTool(clientURI);
})//handle db-read error?
.then(
(innerPort)=>{
const outerChannel = new MessageChannel();
outerChannel.port1.onmessage = (e)=>{
const newPort = e.data.port;
const request = e.data.resource;
console.log(`Forwarding request for [${request.method}]${request.url}.`);
loaderUtilities.requestOverPort(innerPort, request)
.then((response)=>{
console.log(`Forwarding requested value "${response}" for [${request.method}]${request.url}`);
newPort.postMessage(response);
newPort.close();
});
};
window.parent.postMessage(outerChannel.port2, '*', [outerChannel.port2]);
});//handle tool-load error?
</script>
</head>
<body></body>
</html>
</code></pre>
<h3><a href="http://www.client.com/client.html" rel="nofollow noreferrer">www.client.com/client.html</a></h3>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<title>The stupidest client.</title>
<meta charset="UTF-8">
<script type="text/javascript">
const pipe = new MessageChannel();
const work = (request)=>{
return "555";
};
pipe.port1.onmessage = (e)=>{
const newPort = e.data.port;
const request = e.data.resource;
const response = work(request);
console.log(`Receipt requested for [${request.method}]${request.url}; returning "${response}"`);
newPort.postMessage(response);
newPort.close();
};
window.parent.postMessage(pipe.port2, '*', [pipe.port2]); //should I be more restrictive of the recipient?
</script>
</head>
<body</body>
</html>
</code></pre>
<h1>Comments</h1>
<ul>
<li>The above <em>works</em>, in the sense that the image loads and the request for that image has the correct custom header.</li>
<li>The Client presented is just a test rig that always returns '555'.</li>
</ul>
<h1>Question</h1>
<p><strong>Mostly I'm concerned with the security and usability of the Shim.</strong></p>
<ul>
<li>Is the usage of iframes, Promises, indexedDB, and inter-frame messaging trustworthy? Am I doing them correctly?</li>
<li>Does this Shim system provide the protections described in <em>"Parties, Prerogatives, and Restrictions"</em>, insofar as any modern web-browser is secure?</li>
<li>How should I approach error-handling?</li>
<li>What else should I do to test this system?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-12T13:09:26.370",
"Id": "475156",
"Score": "0",
"body": "Is this for advertising in websites?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-12T14:51:58.960",
"Id": "475165",
"Score": "0",
"body": "I haven't been working on this for months. The context at the time was a micro-transactions system, but this particular piece of the system could be adapted for use for lots of different things."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T23:02:22.797",
"Id": "227748",
"Score": "10",
"Tags": [
"javascript",
"security",
"promise",
"cors",
"indexeddb"
],
"Title": "Nested cross-origin iframes for secure user-configurable javascript tools"
}
|
227748
|
<p>I'm writing a function to generate a permutation of given <code>[]int</code>:</p>
<pre><code>// Input: [1,2,3]
// Output:
// [
// [1,2,3],
// [1,3,2],
// [2,1,3],
// [2,3,1],
// [3,1,2],
// [3,2,1]
// ]
func permute(nums []int) [][]int {
var tmp []int
var res [][]int
invalid_pos := make([]bool, len(nums))
res = backtrack(nums, tmp, invalid_pos, res)
return res
}
// backtrack generates all the permutations of the given `nums` and put them into `res`.
// `invalid_pos` keeps track of which number is valid to pick from `nums` to form a permutation
// `tmp`
func backtrack(nums []int, tmp []int, invalid_pos []bool, res [][]int) [][]int {
if len(tmp) == len(nums) {
tmp2 := make([]int, len(tmp))
copy(tmp2, tmp)
res = append(res, tmp2)
} else {
for i, num := range nums {
if invalid_pos[i] {
continue
}
invalid_pos[i] = true
tmp = append(tmp, num)
res = backtrack(nums, tmp, invalid_pos, res)
invalid_pos[i] = false
tmp = tmp[:len(tmp)-1]
}
}
return res
}
</code></pre>
<p>My question is do I need to make a copy <code>copy(tmp2, tmp)</code>? I read about <a href="https://stackoverflow.com/questions/52980172/cannot-understand-5-6-1-caveat-capturing-iteration-variables">capturing iteration variables</a> and I was wondering if this will have any side effect? I think I can simplify the code by removing <code>copy</code>...</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T12:24:33.637",
"Id": "445263",
"Score": "0",
"body": "from a codereview perspective, recursive function call should be avoided in go as TCO is not provided by the compiler (https://medium.com/@felipedutratine/iterative-vs-recursive-vs-tail-recursive-in-golang-c196ca5fd489). As a consequence you better implement it using non recursive version of the algorithm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T12:30:03.727",
"Id": "445264",
"Score": "0",
"body": "also it is possible to write this using a more generic []interface{} input and [][]interface{} output. avoiding many copy-paste if you want to permute something that is not an int."
}
] |
[
{
"body": "<p>To make it nicer for your reviewers you could post as a complete and\nrunnable example:</p>\n\n<pre><code>package main\n\nimport \"fmt\"\n\n...\n\nfunc main() {\n input := []int{1, 2, 3}\n output := permute(input)\n fmt.Printf(\"Input: %v\\nOutput:\\n\", input)\n for _, x := range output {\n fmt.Printf(\" %v\\n\", x)\n }\n}\n</code></pre>\n\n<hr>\n\n<p>With that out of the way, I'd simplify <code>permute</code> a bit:</p>\n\n<pre><code>func permute(nums []int) [][]int {\n return backtrack(nums, []int{}, make([]bool, len(nums)), [][]int{})\n}\n</code></pre>\n\n<p>In <code>backtrack</code> I'd consider <code>return</code>ing early for the first case, that\nlets you remove one level of indentation for the rest:</p>\n\n<pre><code>func backtrack(nums []int, tmp []int, invalid_pos []bool, res [][]int) [][]int {\n if len(tmp) == len(nums) {\n tmp2 := make([]int, len(tmp))\n copy(tmp2, tmp)\n return append(res, tmp2)\n }\n ...\n}\n</code></pre>\n\n<hr>\n\n<p>Regarding your question: Well, what happens if you remove the <code>copy</code>\ncall?</p>\n\n<pre><code>0 go % go run perm.go\nInput: [1 2 3]\nOutput:\n [0 0 0]\n [0 0 0]\n [0 0 0]\n [0 0 0]\n [0 0 0]\n [0 0 0]\n</code></pre>\n\n<p>Clearly it does something and you cannot remove it just like that. It\nalso has nothing to do with capturing iteration variables, the only ones\nyou have here are <code>i</code> and <code>num</code> - both aren't even part of the <code>copy</code>\ncall, plus, you're not capturing anything, there's no <code>func() {...}</code>\ndeclaration anywhere that even <em>could</em> capture variables.</p>\n\n<p>Variable capturing and the (most common?) problem with it comes only if you have a construction like this:</p>\n\n<pre><code>for i := ... {\n x := func() {\n foo(i)\n }\n}\n</code></pre>\n\n<p>The <code>i</code> in the anonymous function is the one from the loop - and since it's always the same variable, all the created functions reference ... the same variable! That <em>can</em> be confusing since people might expect that on each iteration of the loop we're capturing that one value that <code>i</code> currently has. Go <em>could've</em> done that, but I'm guessing mostly for performance reasons that's not being done and you've to explicitly make it happen yourself:</p>\n\n<pre><code>for i := ... {\n j := i\n x := func() {\n foo(j)\n }\n}\n</code></pre>\n\n<p>Now <code>foo</code> gets called with all the different values of <code>i</code>.</p>\n\n<hr>\n\n<p>Okay so that's that, now I'd just recommend simplifying this algorithm\nto get rid of <code>invalid_pos</code>, <code>tmp</code> and the <code>res</code> parameter and do it all\nfunctionally and recursively. I'm saying that because the code right\nnow is pretty complex for the problem and yet it doesn't do everything\nupfront that it could, like preallocating the <code>res</code> array to the final\nlength, so it seems this is more of a learning exercise.</p>\n\n<p>Start with the base cases, empty list and one element, then consider the\none element longer list:</p>\n\n<pre><code>func permute2(nums []int) [][]int {\n if len(nums) <= 1 {\n return [][]int{nums}\n }\n result := [][]int{}\n for i, x := range nums {\n ...\n }\n return result\n}\n</code></pre>\n\n<p>Don't optimise to early for reusing things, that can also follow once\nthe algorithm is in its most simple form; clarity comes first.</p>\n\n<p>Hint: You can do it without <code>copy</code> or manually instantiating any\nmore slices via <code>[]int{}</code>, just check out\n<a href=\"https://golang.org/pkg/builtin/#append\" rel=\"nofollow noreferrer\"><code>append</code></a> and how to do\n<a href=\"https://tour.golang.org/moretypes/7\" rel=\"nofollow noreferrer\">subslices</a>. Take particular care to not simply <code>append</code> slices together without considering how the underlying data is going to be shared (that's why <code>append([]int{}, <slice here>)</code> might be necessary to prevent the slice from being modified).</p>\n\n<hr>\n\n<p>As a spoiler:</p>\n\n<blockquote class=\"spoiler\">\n <p> <pre>func permute2(nums []int) [][]int {\n if len(nums) <= 1 {\n return [][]int{nums}\n }\n result := [][]int{}\n for i, x := range nums {\n without := append(append([]int{}, nums[:i]...), nums[i+1:]...)\n for _, y := range permute2(without) {\n result = append(result, append([]int{x}, y...))\n }\n }\n return result\n }</pre></p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T04:10:39.223",
"Id": "444825",
"Score": "0",
"body": "Thanks for your detailed answer. I run your `main` locally; remove `tmp2 := make([]int, len(tmp))` and `copy(tmp2, tmp)`; and I still get the correct result. I'm running on a Mac. I'm not sure what happened. Also, I was wondering where I need to use \"subslice\" in the `...`? Can you please illustrate a little bit more? Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T09:39:37.223",
"Id": "444866",
"Score": "0",
"body": "I'm not sure what happened, I'm very sure though that the `copy` copies over the values, so I don't see how removing it can keep the behaviour the same ...\n\nOkay, I'll amend the example."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T23:09:59.033",
"Id": "227818",
"ParentId": "227752",
"Score": "2"
}
},
{
"body": "<p>Personally, I would remove the <strong>invalid_pos</strong> slice.\nAlternatively, you can call your recursive function using a copy of the original slice with the used element removed. The following function can remove that element and return a copy:</p>\n\n<pre><code>func cutSlice(nums []int, i int) []int {\n res := append(append([]int{}, nums[:i]...), nums[i+1:]...)\n return res\n}\n</code></pre>\n\n<p>Additionally, your function does not need to return anything. You can change the header of the slice <strong>res</strong> (which keeps some metadata and a pointer to the slice). To change that header you need to pass a pointer to your function.</p>\n\n<pre><code>func permute(nums []int) [][]int {\n var res [][]int\n permuteHelper(nums, []int{}, &res)\n return res\n}\n</code></pre>\n\n<p>This way the code is simplified, and you can have a more concise and readable code.</p>\n\n<pre><code>func permuteHelper(nums []int, list []int, res *[][]int) {\n if len(nums) == 0 {\n *res = append(*res, list)\n return\n }\n for j, el := range nums {\n tmp := append(append([]int{}, list...), el)\n permuteHelper(cutSlice(nums, j), tmp, res)\n }\n}\n</code></pre>\n\n<p>Regarding the <strong>copy</strong> function in that case, it is not needed. A copy of the list under construction is passed in the recursive call in the first place.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T16:59:09.893",
"Id": "242579",
"ParentId": "227752",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T02:59:57.180",
"Id": "227752",
"Score": "4",
"Tags": [
"go",
"combinatorics",
"backtracking"
],
"Title": "Go function to generate permutations of a given integer array"
}
|
227752
|
<p>So I have this:</p>
<p><a href="https://i.stack.imgur.com/R7GP6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/R7GP6.png" alt="Bidirectional breadth first search using Algotype.js"></a></p>
<p>And the typesetting code is here:</p>
<pre><code><html>
<head>
<style>
#step_id1 {
color: black;
}
#comment_id1 {
color: black;
}
#step_id2 {
color: brown;
}
#comment_id2 {
color: black;
}
#step_id3 {
color: black;
}
#comment_id3 {
color: blue;
}
#step_id4 {
color: brown;
}
#comment_id4 {
color: blue;
}
#yield_id {
color: blueviolet;
}
.upper_header_bar {
border-top: 3px solid #ff2222 !important;
width: 550px;
}
.lower_header_bar {
border-bottom: 2px solid black !important;
width: 550px;
}
.footer_bar {
background-color: #ff2222;
width: 550px;
height: 3px;
}
</style>
<script src="Algotype.js"></script>
</head>
<body>
<alg-algorithm header="Bidirectional-Breadth-First-Search$(s, t)$"
algorithm-upper-header-class="upper_header_bar"
algorithm-lower-header-class="lower_header_bar"
algorithm-footer-class="footer_bar">
<alg-if condition="$s = t$">
<alg-return>$\langle s \rangle$</alg-return>
</alg-if>
<alg-step>$Q_A \leftarrow \langle s \rangle$</alg-step>
<alg-step>$Q_B \leftarrow \langle t \rangle$</alg-step>
<alg-step>$\pi_A \leftarrow \{ (s \mapsto \Nil) \}$</alg-step>
<alg-step>$\pi_B \leftarrow \{ (t \mapsto \Nil) \}$</alg-step>
<alg-step>$\delta_A \leftarrow \{ (s \mapsto 0) \}$</alg-step>
<alg-step>$\delta_B \leftarrow \{ (t \mapsto 0) \}$</alg-step>
<alg-step>$C \leftarrow \infty$</alg-step>
<alg-step>$\mu \leftarrow \Nil$</alg-step>
<alg-while condition="$|Q_A| > 0 \; \And \; |Q_B| > 0$">
<alg-step>$\Delta_A \leftarrow \delta_A($Front$(Q_A))$</alg-step>
<alg-step>$\Delta_B \leftarrow \delta_B($Front$(Q_B))$</alg-step>
<alg-if condition="$\mu \neq \Nil \; \And \; C \lt \Delta_A + \Delta_B$">
<alg-return>Traceback-Path$(\mu, \pi_A, \pi_B)$</alg-return>
</alg-if>
<alg-if condition="$|\delta_A| < |\delta_B|$">
<alg-step>$u \leftarrow $Remove-First$(Q_A)$</alg-step>
<alg-foreach condition="$v \in $Children$(u)$">
<alg-if condition="$v\;\Not\;\Mapped\;\In\;\delta_A$">
<alg-step>$\delta_A(v) \leftarrow \delta_A(u) + 1$</alg-step>
<alg-step>$\pi_A(v) \leftarrow u$</alg-step>
<alg-step>Add-Last$(Q_A, v)$</alg-step>
<alg-if condition="$v\; \Mapped \; \In \; \delta_B \; \And \; C \gt \delta_A(v) + \delta_B(v)$">
<alg-step>$C \leftarrow \delta_A(v) + \delta_B(v)$</alg-step>
<alg-step>$\mu \leftarrow v$</alg-step>
</alg-if>
</alg-if>
</alg-foreach>
</alg-if>
<alg-else>
<alg-step>$u \leftarrow $Remove-First$(Q_B)$</alg-step>
<alg-foreach condition="$v \in $Parents$(u)$">
<alg-if condition="$v\;\Not\;\Mapped\;\In\;\delta_B$">
<alg-step>$\delta_B(v) \leftarrow \delta_B(u) + 1$</alg-step>
<alg-step>$\pi_B(v) \leftarrow u$</alg-step>
<alg-step>Add-Last$(Q_B, v)$</alg-step>
<alg-if condition="$v\; \Mapped \; \In \; \delta_A \; \And \; C \gt \delta_A(v) + \delta_B(v)$">
<alg-step>$C \leftarrow \delta_A(v) + \delta_B(v)$</alg-step>
<alg-step>$\mu \leftarrow v$</alg-step>
</alg-if>
</alg-if>
</alg-foreach>
</alg-else>
</alg-while>
<alg-error>No path between $s$ and $t$.</alg-error>
</alg-algorithm>
<alg-algorithm header="Traceback-Path$(\mu, \pi_A, \pi_B)$"
algorithm-upper-header-class="upper_header_bar"
algorithm-lower-header-class="lower_header_bar"
algorithm-footer-class="footer_bar">
<alg-step>$p \leftarrow \langle \rangle$</alg-step>
<alg-step>$u \leftarrow \mu$</alg-step>
<alg-while condition="$u \neq \Nil$">
<alg-step>Add-First$(p, u)$</alg-step>
<alg-step>$u \leftarrow \pi_A(u)$</alg-step>
</alg-while>
<alg-step>$u \leftarrow \pi_B(u)$</alg-step>
<alg-while condition="$u \neq \Nil$">
<alg-step>Add-Last$(p, u)$</alg-step>
<alg-step>$u \leftarrow \pi_B(u)$</alg-step>
</alg-while>
<alg-return>$p$</alg-return>
</alg-alg-algorithm>
</body>
</html>
</code></pre>
<p>(The <code>Algotype.js</code> lives <a href="https://github.com/coderodde/Algotype.js" rel="nofollow noreferrer">here</a>.)</p>
<p>Please tell me whatever comes to mind.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-10T20:52:04.943",
"Id": "453180",
"Score": "0",
"body": "Why is this tagged [tag:latex] when the norm, here, is to tag latex as [tag:tex]? Also isn't this using just plain TeX at best and MathJax at worst, so I'm not sure it should have either tag."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T07:25:24.110",
"Id": "227763",
"Score": "1",
"Tags": [
"algorithm",
"html",
"breadth-first-search",
"typesetting"
],
"Title": "Typesetting bidirectional breadth first search with Algotype.js"
}
|
227763
|
<p>I have project where I'm using <code>BindableBase</code> for my <code>INotifyPropertyChanged</code> implementation. Some of my objects however are generating a very rapid and bursty stream of INPC notifications, which is causing my UI to update unnecessarily often - to the point of making it laggy. To compensate, I'm attempting to throttle the speed at which these notifications are sent (e.g. once per 500ms for certain objects). Also, as part of this exercise, I've written unit tests for the throttling behavior, and I'd appreciate feedback on those as well.</p>
<p>The expected usage of the <code>TaskScheduler</code> dependency is that a free-threaded object (e.g. a model class), the <code>BindableBaseWithThrottling</code> could use <code>TaskScheduler.Default</code> (i.e. the <code>ThreadPoolTaskScheduler</code>) to allow continuations on a background thread, whereas a thread-affine object might use <code>TaskScheduler.FromCurrentSynchronizationContext()</code> or a custom scheduler to preserve thread affinity for the notifications. Also, it greatly simplifies controlling timing while running tests. :)</p>
<p>BindableBaseWithThrottling.cs:</p>
<pre><code>using System;
using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace ThrottlingReview
{
public abstract class BindableBaseWithThrottling : BindableBase
{
private readonly TimeSpan _throttleLimit;
private readonly TaskScheduler _taskScheduler;
private readonly ConcurrentDictionary<string, Task> _cooldownTasks;
private readonly ConcurrentDictionary<string, string> _pendingNotifications;
public BindableBaseWithThrottling(TimeSpan throttleLimit, TaskScheduler taskScheduler)
{
_throttleLimit = throttleLimit;
_taskScheduler = taskScheduler;
_cooldownTasks = new ConcurrentDictionary<string, Task>();
_pendingNotifications = new ConcurrentDictionary<string, string>();
}
protected override void NotifyPropertyChanged([CallerMemberName] string propName = "")
{
if (_pendingNotifications.ContainsKey(propName))
{
// do nothing, it's already pending
}
else if (_cooldownTasks.TryGetValue(propName, out _))
{
// in cooldown, but not pending yet
_pendingNotifications.TryAdd(propName, propName);
}
else
{
// fire right away if we're not already in a cool down
base.NotifyPropertyChanged(propName);
Cooldown(propName);
}
}
private void Cooldown(string propName)
{
var newCooldown = new Task(async () => await Task.Delay(_throttleLimit));
if (_cooldownTasks.TryAdd(propName, newCooldown))
{
newCooldown.Start(_taskScheduler);
newCooldown.ContinueWith((t) => CheckForPendingNotifications(propName), _taskScheduler);
}
}
private void CheckForPendingNotifications(string propName)
{
_cooldownTasks.TryRemove(propName, out _);
// if there was a new pending request during the cooldown, service it now
if (_pendingNotifications.TryRemove(propName, out _))
{
base.NotifyPropertyChanged(propName);
Cooldown(propName);
}
}
}
}
</code></pre>
<p>BindableBaseWithThrottlingTests.cs:</p>
<pre><code>using System;
using System.Threading.Tasks;
using Xunit;
namespace ThrottlingReview
{
public class BindableBaseWithThrottlingTests
{
[Fact]
public void NotifyPropertyChanged_CalledOnce_FiresImmediately()
{
int count = 0;
var scheduler = new DeterministicTaskScheduler();
var sut = new TestBindableObject(TimeSpan.FromMilliseconds(1), scheduler);
sut.PropertyChanged += (s, e) =>
{
count++;
};
sut.Value = 1; // trigger INPC notification
Assert.Equal(1, count);
}
[Fact]
public void NotifyPropertyChanged_CalledOnce_FiresOnce()
{
int count = 0;
var scheduler = new DeterministicTaskScheduler();
var sut = new TestBindableObject(TimeSpan.FromMilliseconds(1), scheduler);
sut.PropertyChanged += (s, e) =>
{
count++;
};
sut.Value = 1; // trigger INPC notification
scheduler.RunTasksUntilIdle();
Assert.Equal(1, count);
}
[Fact]
public void NotifyPropertyChanged_CalledTwiceImmediately_OnlyOneEventFiredImmediately()
{
int count = 0;
var scheduler = new DeterministicTaskScheduler();
var sut = new TestBindableObject(TimeSpan.FromMilliseconds(1), scheduler);
sut.PropertyChanged += (s, e) =>
{
count++;
};
sut.Value = 1; // trigger INPC notification
sut.Value = 2; // trigger after cooldown, but taskScheduler has not run any tasks, still in cooldown
Assert.Equal(1, count);
}
[Fact]
public void NotifyPropertyChanged_CalledTwiceImmediately_FiresSecondWithDelay()
{
int count = 0;
var scheduler = new DeterministicTaskScheduler();
var sut = new TestBindableObject(TimeSpan.FromMilliseconds(1), scheduler);
sut.PropertyChanged += (s, e) =>
{
count++;
};
sut.Value = 1; // trigger INPC notification
sut.Value = 2; // trigger INPC notification after cooldown
scheduler.RunTasksUntilIdle();
Assert.Equal(2, count);
}
[Fact]
public void NotifyPropertyChanged_CalledThriceImmediately_FiresSecondWithDelay()
{
int count = 0;
var scheduler = new DeterministicTaskScheduler();
var sut = new TestBindableObject(TimeSpan.FromMilliseconds(1), scheduler);
sut.PropertyChanged += (s, e) =>
{
count++;
};
sut.Value = 1; // trigger INPC notification
sut.Value = 2; // trigger INPC notification after cooldown
sut.Value = 3; // falls within 2nd notification
scheduler.RunTasksUntilIdle();
Assert.Equal(2, count);
}
[Fact]
public void NotifyPropertyChanged_CalledTwiceWithDelay_FiresSecondImmediately()
{
int count = 0;
var scheduler = new DeterministicTaskScheduler();
var sut = new TestBindableObject(TimeSpan.FromMilliseconds(1), scheduler);
sut.PropertyChanged += (s, e) =>
{
count++;
};
sut.Value = 1; // trigger INPC notification
scheduler.RunTasksUntilIdle();
sut.Value = 2; // trigger INPC notification after cooldown
Assert.Equal(2, count);
}
[Fact]
public void NotifyPropertyChanged_CalledWithDifferentPropertyNames_FiresImmediatelyForEach()
{
int count = 0;
var scheduler = new DeterministicTaskScheduler();
var sut = new TestBindableObject(TimeSpan.FromMilliseconds(1), scheduler);
sut.PropertyChanged += (s, e) =>
{
count++;
};
sut.Value = 1; // trigger INPC notification
sut.SecondValue = "test"; // trigger INPC notification for 2nd property name before cooldowns are run
Assert.Equal(2, count);
}
private class TestBindableObject : BindableBaseWithThrottling
{
private int _value;
private string _secondValue;
public TestBindableObject(TimeSpan throttleLimit, TaskScheduler taskScheduler)
: base(throttleLimit, taskScheduler)
{
}
public int Value
{
get { return _value; }
set { SetProperty(ref _value, value); }
}
public string SecondValue
{
get { return _secondValue; }
set { SetProperty(ref _secondValue, value); }
}
}
}
}
</code></pre>
<p>I'm using the <code>DeterministicTaskScheduler</code> described <a href="https://msdn.microsoft.com/en-us/magazine/dn818494.aspx" rel="nofollow noreferrer">here</a> to control execution flow of the cooldowns during tests. A full copy of all the files referenced (i.e. including <code>BindableBase</code> and <code>DeterministicTaskScheduler</code>) can be found in <a href="https://gist.github.com/jimmylewis/423b51a6029575a37b7b39797c62d389" rel="nofollow noreferrer">this gist</a>.</p>
<p>Edit: responding to the CR feedback</p>
<ol>
<li>Race conditions: valid point. The two potential race conditions I could see are somehow getting multiple notifications to fire, or having one notification be put into pending but skipping the cooldown trigger - it wouldn't fire unless another trigger came through. For my use case, this isn't likely to be an issue, but it could be in other use cases.</li>
<li>Thread pool consumption: Shouldn't be a problem. Creating task objects doesn't schedule them right away, and only one should ever get scheduled at a time (whichever one gets added to the <code>_cooldownTasks</code> collection).</li>
<li>WPF Binding Delay property: this property affects the delay when a target updates the source in a two-way bind. I'm trying to throttle the rate at which the source updates the target, so it unfortunately doesn't help my case.</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T16:36:27.213",
"Id": "443606",
"Score": "1",
"body": "Your UI is WPF? http://www.jonathanantoine.com/2011/09/21/wpf-4-5-part-4-the-new-bindings-delay-property/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T16:50:16.823",
"Id": "443616",
"Score": "1",
"body": "@dfhwze Wow thanks I didn't even think to look for a solution via the binding. Well, this was a good learning exercise either way. ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T04:26:22.170",
"Id": "444693",
"Score": "0",
"body": "On further investigation, the Delay property doesn't help, since I'm in a one-way bind and need to limit the rate from the source. It was a good suggestion though."
}
] |
[
{
"body": "<h3>Race Conditions</h3>\n\n<p>You are using 2 concurrent dictionaries, which are each thread-safe, but used together there may be race conditions now and then. Think about possible impact and worst case scenarios.</p>\n\n<blockquote>\n<pre><code>_cooldownTasks = new ConcurrentDictionary<string, Task>();\n_pendingNotifications = new ConcurrentDictionary<string, string>();\n</code></pre>\n</blockquote>\n\n<h3>Thread Pool Resource Consumption</h3>\n\n<p>Since you expect massive amounts of updates, having a <code>Task</code> for each update might just put too much pressure on the thread pool:</p>\n\n<blockquote>\n<pre><code>var newCooldown = new Task(async () => await Task.Delay(_throttleLimit));\n</code></pre>\n</blockquote>\n\n<h3>WPF Binding Delay</h3>\n\n<p>If you don't mind using a built-in solution (as we have established your UI is in WPF), you could go for a <a href=\"https://www.c-sharpcorner.com/UploadFile/mahesh/binding-delay-in-wpf-4-5/\" rel=\"nofollow noreferrer\"><code>Delay</code> on the <code>Binding</code></a>. Something like this:</p>\n\n<pre><code>Value=\"{Binding ElementName=ValueText, Delay=500, Path=Text, Mode=TwoWay}\"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T16:58:55.767",
"Id": "227797",
"ParentId": "227767",
"Score": "4"
}
},
{
"body": "<p>I would personally prefer a simpler approach, using <code>System.Reactive</code> (Rx.NET):</p>\n\n<pre><code>public abstract class ViewModel : INotifyPropertyChanged\n{\n public ViewModel(int throttlingPeriod = 250)\n : this(TimeSpan.FromMilliseconds(throttlingPeriod))\n {\n }\n\n public ViewModel(TimeSpan throttlingPeriod)\n {\n Subject = new Subject<string>();\n Subject\n .GroupBy(pn => pn)\n .SelectMany(g => g.Sample(throttlingPeriod))\n .Select(pn => new PropertyChangedEventArgs(pn))\n .ObserveOn(SynchronizationContext.Current)\n .Subscribe(e => PropertyChanged(this, e));\n }\n\n public event PropertyChangedEventHandler PropertyChanged = delegate { };\n Subject<string> Subject { get; } \n protected void RaisePropertyChanged([CallerMemberName] string propertyName = null) => \n Subject.OnNext(propertyName);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-22T06:45:45.190",
"Id": "229444",
"ParentId": "227767",
"Score": "1"
}
},
{
"body": "<p>An offline code review came up with a critical piece of feedback:</p>\n\n<p>The constructor for Task takes an <code>Action<T></code>. The async delegate therefore generates an <code>async void</code> method, which has 2 implications:</p>\n\n<ol>\n<li>If an unhandled exception is thrown from the <code>async void</code> method, it will crash the process (unlikely, since it's just calling <code>Task.Delay()</code>, but it's an unintended risk - especially if the code is changed/refactored later).</li>\n<li>The <code>async void</code> will return when it reaches the first await. An explanation on why is <a href=\"https://devblogs.microsoft.com/pfxteam/potential-pitfalls-to-avoid-when-passing-around-async-lambdas/\" rel=\"nofollow noreferrer\">here</a>. The continuation will then run almost immediately. The unit test coverage happened to miss this behavior because the continuation was scheduled on the <code>DeterministicTaskScheduler</code>, so it wasn't made apparent that the code wasn't actually waiting for the <code>Task.Delay()</code> to return. (The tests could be changed to not use <code>RunTasksUntilIdle()</code> since it hides how many tasks are scheduled then executed, and instead better inspect/execute the order that code was run.)</li>\n</ol>\n\n<p>TL;DR: don't pass an async delegate to an <code>Action<...></code> parameter. Instead find an overload that takes in <code>Func<..., Task></code>, or implement the delegate as synchronous code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T05:08:31.823",
"Id": "230247",
"ParentId": "227767",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227797",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T08:06:28.113",
"Id": "227767",
"Score": "3",
"Tags": [
"c#",
"unit-testing",
"asynchronous"
],
"Title": "BindableBase with a throttle"
}
|
227767
|
<p>Below I created a function to format all the floats in a pandas DataFrame to a specific precision (6 d.p) and convert to string for output to a GUI (hence why I didn't just change the pandas display options). Is this the most efficient way to convert all floats in a pandas DataFrame to strings of a specified format?</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df = pd.DataFrame({'x':[5.4525242,6.5254245,7.254542],'y':[5.4525242,6.5254245,7.254542]})
def _format_floats(df):
df.loc[:,df.dtypes==float]=df.loc[:,df.dtypes==float].apply(lambda row: ["{:.6f}".format(num) for num in row])
_format_floats(df)
#Example output numbers changes to string with 6 decimals
df.iloc[0,0]
#'5.452524'
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T08:41:58.583",
"Id": "443541",
"Score": "1",
"body": "Welcome to Code Review! Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. Is there anything bothering you? Do you want feedback about style, best practices, or do you need improved performance? See also [ask]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T15:06:20.157",
"Id": "443587",
"Score": "0",
"body": "Are you sure this code works, _as you've posted it here_? That ``df.loc[...] == ...`` looks like it should just be ``df.loc[...] = ...``."
}
] |
[
{
"body": "<ul>\n<li><p>Since you're already calling <code>.apply</code>, I'd stick with that approach to iteration rather than mix that with a list comprehension.</p></li>\n<li><p>It's generally better to avoid making data modifications in-place within a function unless explicitly asked to (via an argument, like <code>inplace=False</code> that you'll see in many Pandas methods) or if it's made clear by the functions name and/or docstring.</p></li>\n<li><p>The logic is reasonably complex, so it might be clearer as a named function. </p></li>\n<li><p>The leading <code>_</code> in the function name is usually reserved for \"private\" functions, whereas this seems to be a general utility function. It's fine if you don't want external code to touch it, that's just not clear from this code snippet.</p></li>\n</ul>\n\n<p>Here's one way you might re-write the function to follow these tips:</p>\n\n<pre><code>def format_floats(df):\n \"\"\"Replaces all float columns with string columns formatted to 6 decimal places\"\"\"\n def format_column(col):\n if col.dtype != float:\n return col\n return col.apply(\"{:.6f}\".format)\n\n return df.apply(format_column)\n</code></pre>\n\n<p>And a usage example:</p>\n\n<pre><code>In [1]: format_floats(pd.DataFrame([{'a': 1, 'b': 2.3}, {'a': 2, 'b': 3.0}]))\nOut[1]:\n a b\n0 1 2.300000\n1 2 3.000000\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T15:15:12.880",
"Id": "227791",
"ParentId": "227768",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "227791",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T08:10:37.283",
"Id": "227768",
"Score": "2",
"Tags": [
"python",
"pandas"
],
"Title": "Changes all floats in a pandas DataFrame to string"
}
|
227768
|
<p>Plugin is a small editor that allows to create a filter such as a price slider, checkboxes of "brands", a drop-down of "seasons".</p>
<p>An example of how plugin work can be seen on page: <a href="http://demo-product-filters.anexter.net/" rel="nofollow noreferrer">http://demo-product-filters.anexter.net/</a></p>
<p>Such plugins are used in many stores, and they need to be easily scalable.</p>
<p><em>Element classes is main classes of plugin but they has too many responsibilities</em>, such as</p>
<ul>
<li><strong><em>generate_controls</strong> method</em> - creating controls for editor in admin
panel (pic. <a href="https://i.stack.imgur.com/JDH3z.png" rel="nofollow noreferrer">https://i.stack.imgur.com/JDH3z.png</a>)</li>
<li><strong><em>render_template</strong> method</em> - show element for front end with which user
will interact</li>
<li><strong><em>apply_filter_to_query</strong> method</em> - applying selected options to product
request. For example, if customer chose category "cat1" in element,
then it is necessary to change query to database so that there are
only products of this category</li>
</ul>
<p>As well as methods that return a list of options that will be displayed in front end, such as a list of categories, brands or other</p>
<p>Base element class that has two abstractions (creating controls for editor in admin panel and rendering element in front end)</p>
<pre class="lang-php prettyprint-override"><code>
abstract class Abstract_Element extends Component {
protected $project;
protected $wp_post;
public function get_project() {
return $this->project;
}
public function set_project( Project $project ) {
$this->project = $project;
}
public function get_wp_post() {
return $this->wp_post;
}
public function set_wp_post( \WP_Post $post ) {
$this->wp_post = $post;
}
public function get_id() {
return $this->wp_post->ID;
}
public function get_title() {
return $this->wp_post->post_title;
}
public function get_options() {
return get_post_meta( $this->get_id(), 'wcpf_options', [] );
}
public function set_options( array $options ) {
update_post_meta( $this->get_id(), 'wcpf_options', $options );
}
public function get_option( $index, $default_value = null ) {
$options = $this->get_options();
return array_key_exists( $index, $options ) ? $options[ $index ] : $default_value;
}
public function set_option( $index, $value ) {
$this->set_options( array_merge( $this->get_options(), [ $index => $value ] ) );
}
public function has_option( $index ) {
$options = $this->get_options();
return array_key_exists( $index, $options );
}
public function remove_option( $index ) {
$options = $this->get_options();
if ( array_key_exists( $index, $options ) ) {
unset( $options[ $index ] );
$this->set_options( $options );
}
}
public function get_default_options() {
return [];
}
public abstract function get_element_slug();
public abstract function get_element_title();
public abstract function generate_controls();
public abstract function render_template();
}
</code></pre>
<p>Interface for elements that allows to add ability filtering for element</p>
<pre class="lang-php prettyprint-override"><code>interface Filtering_Element_Interface {
function get_filter_value( $default_value = null );
function set_filter_value( $filter_value );
function get_url_key();
function apply_filter_to_query( \WP_Query $product_query, $filter_value );
}
abstract class Abstract_Filtering_Element extends Abstract_Element implements Filtering_Element_Interface {
protected $filter_value = null;
public function get_filter_value( $default_value = null ) {
return is_null( $this->filter_value ) ? $default_value : $this->filter_value;
}
public function set_filter_value( $filter_value ) {
$this->filter_value = $filter_value;
}
}
</code></pre>
<p>Class dropdown element</p>
<pre class="lang-php prettyprint-override"><code>class Drop_Down_Element extends Abstract_Filtering_Element {
public function get_element_slug() {
return 'drop-down';
}
public function get_element_title() {
return __( 'Drop Down' );
}
public function generate_controls() {
$editor_panel = new Tabs_Layout( [
'title' => $this->get_element_title(),
'tabs' => [
'general' => [
'label' => __( 'General', 'wcpf' ),
'controls' => [
new Control\Text_Control( [
'key' => 'postTitle',
'control_source' => 'post',
'label' => __( 'Title', 'wcpf' ),
'placeholder' => __( 'Title', 'wcpf' ),
'required' => true
] ),
new Control\Text_Control( [
'key' => 'optionKey',
'label' => __( 'URL key', 'wcpf' ),
'placeholder' => __( 'option-key', 'wcpf' ),
'control_description' => __( 'The “URL key” is the URL-friendly version of the title. It is usually all lowercase and contains only letters, numbers, and hyphens', 'wcpf' ),
'required' => true
] ),
new Control\Select_Control( [
'key' => 'itemsSource',
'label' => __( 'Source of options', 'wcpf' ),
'control_description' => __( 'Select source of options, that will be using to filter products', 'wcpf' ),
'options' => [
'attribute' => __( 'Attribute', 'wcpf' ),
'category' => __( 'Category', 'wcpf' ),
'tag' => __( 'Tag', 'wcpf' ),
'taxonomy' => __( 'Taxonomy', 'wcpf' )
],
'default_value' => 'attribute'
] ),
new Control\Select_Control( [
'key' => 'itemsSourceAttribute',
'label' => __( 'Attribute', 'wcpf' ),
'options' => wcpf_get_attribute_taxonomies(),
'control_description' => __( 'Choose one of the attributes created in “Products > Attributes”', 'wcpf' ),
'display_rules' => [
[
'optionKey' => 'itemsSource',
'operation' => '==',
'value' => [
'attribute'
]
]
],
'required' => true
] ),
new Control\Select_Control( [
'key' => 'itemsSourceCategory',
'label' => __( 'Category', 'wcpf' ),
'options' => wcpf_get_categories(),
'control_description' => __( 'Choose one of the categories created in “Products > Categories”', 'wcpf' ),
'default_value' => 'all',
'display_rules' => [
[
'optionKey' => 'itemsSource',
'operation' => '==',
'value' => [
'category'
]
]
],
'required' => true
] ),
new Control\Select_Control( [
'key' => 'itemsSourceTaxonomy',
'label' => __( 'Taxonomy', 'wcpf' ),
'options' => wcpf_get_taxonomies(),
'control_description' => __( 'The “Taxonomy” is a grouping mechanism for posts. For example, "product tags" and "product attributes" are also taxonomies', 'wcpf' ),
'display_rules' => [
[
'optionKey' => 'itemsSource',
'operation' => '==',
'value' => [
'taxonomy'
]
]
],
'required' => true
] ),
],
],
'visual' => [
'label' => __( 'Visual', 'wcpf' ),
'controls' => [
new Control\Text_Control( [
'key' => 'cssClass',
'label' => __( 'CSS Class', 'wcpf' ),
'placeholder' => __( 'class-name', 'wcpf' )
] )
]
]
]
]);
return $editor_panel;
}
public function get_url_key() {
return $this->get_option( 'url-key' );
}
public function apply_filter_to_query( \WP_Query $product_query, $filter_value ) {
$items_source = $this->get_option( 'itemsSource' );
$taxonomy = false;
if ( $items_source == 'attribute' ) {
$taxonomy = wc_attribute_taxonomy_name( $this->get_option( 'itemsSourceAttribute' ) );
} else if ( $items_source == 'tag' ) {
$taxonomy = 'product_tag';
} else if ( $items_source == 'category' ) {
$taxonomy = 'product_cat';
} else if ( $items_source == 'taxonomy' ) {
$taxonomy = $this->get_option( 'itemsSourceTaxonomy' );
}
$tax_query_item = [
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $filter_value,
'operator' => 'OR'
];
$product_query->set(
'tax_query',
array_merge(
$product_query->get( 'tax_query', [] ),
[ $this->get_url_key() => $tax_query_item ]
)
);
}
public function render_template() {
$this->get_teplate_loader()->render_template( 'elements/drop-down.php', [
'element' => $this,
'items' => $this->get_items()
] );
}
protected function get_items() {
$items = [];
$items_source = $this->get_option( 'itemsSource' );
$taxonomy = false;
if ( $items_source == 'attribute' ) {
$taxonomy = wc_attribute_taxonomy_name( $this->get_option( 'itemsSourceAttribute' ) );
} else if ( $items_source == 'tag' ) {
$taxonomy = 'product_tag';
} else if ( $items_source == 'category' ) {
$taxonomy = 'product_cat';
} else if ( $items_source == 'taxonomy' ) {
$taxonomy = $this->get_option( 'itemsSourceTaxonomy' );
}
if ( ! taxonomy_exists( $taxonomy ) ) {
return [];
}
$terms = get_terms( [
'taxonomy' => $taxonomy,
'hierarchical' => true,
'menu_order' => 'asc',
'order' => 'asc'
] );
foreach ( $terms as $term ) {
$key = urldecode( $term->slug );
$items[] = [
'key' => $key,
'title' => $term->name,
];
}
return $items;
}
}
</code></pre>
<p><strong>Update</strong></p>
<p>I have an idea to realize something similar to a facade.</p>
<p>What do you think?</p>
<p>Example:</p>
<pre class="lang-php prettyprint-override"><code>class Drop_Down_Element {
protected $elementFiltering;
protected $elementDisplay;
protected $elementControls;
public function get_element_slug() {
return 'drop-down';
}
public function get_element_title() {
return __( 'Drop Down' );
}
public function __construct() {
$this->elementControls = new Drop_Down_Controls();
$this->elementFiltering = new Drop_Down_Filtering();
$this->elementDisplay = new Drop_Down_Display();
}
public function generate_controls() {
$this->elementControls->generate_controls();
}
public function apply_filter_to_query( \WP_Query $product_query, $filter_value ) {
$this->elementFiltering->apply_filter_to_query( $product_query, $filter_value );
}
public function render_template() {
$this->elementDisplay->render();
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T09:32:46.467",
"Id": "227771",
"Score": "3",
"Tags": [
"php",
"object-oriented",
"wordpress"
],
"Title": "Product Filters wordpress plugin: implement single responsibility principle for elements classes"
}
|
227771
|
<p>I am just testing how I solved simple stuff.</p>
<p><strong>Goal:</strong> The aim is to expand the width of an <code>input</code> and collapse it.</p>
<p>When <code>mouseover</code> expand,.</p>
<p>When <code>mouseout</code> collapse.</p>
<p>When you have text inside the <code>input</code> keep it expanded.</p>
<hr>
<p>To me it seems too much, repeating some stuff in JS.
Also thought about adding a debouncer or throttle but was not successful.</p>
<p>There's probably another way to solve it with pure CSS.</p>
<p>HTML:</p>
<pre><code><body>
<p>
2 inputs, 1 is collapsed
the other is expanded
</p>
<br>
collapsed
<br>
<input type="text" class="collapsed">
<br>
<br>
expanded
<br>
<input type="text" class="expanded">
</body>
</code></pre>
<p>CSS:</p>
<pre><code>input {
width: 20px;
transition: width 1s;
}
.expanded{
width: 256px;
}
</code></pre>
<p>JS: </p>
<pre><code>let collapsedInput = document.querySelector('.collapsed');
const handleMouseOut = () => {
collapsedInput.classList.remove('expanded');
}
const handleMouseOVer = () => {
collapsedInput.classList.add('expanded');
}
collapsedInput.addEventListener('mouseover', handleMouseOVer);
collapsedInput.addEventListener('mouseout', handleMouseOut);
collapsedInput.addEventListener('input', () => {
if(collapsedInput.value !== ""){
collapsedInput.classList.add('expanded');
collapsedInput.removeEventListener('mouseout', handleMouseOut);
} else {
collapsedInput.classList.remove('expanded');
collapsedInput.addEventListener('mouseout', handleMouseOut);
}
})
</code></pre>
|
[] |
[
{
"body": "<h2>Review</h2>\n\n<p>The biggest critique about the Javascript I have is that <code>collapsedInput</code> could be declared with <code>const</code> because it doesn't get re-assigned.</p>\n\n<p>It is possible that the code in the event listener for the <code>input</code> event could be simplified using <code>classList.toggle()</code>.</p>\n\n<p>If there is only one element with class name <code>collapsed</code> then perhaps it would be better to use an <code>id</code> attribute and use <code>document.getElementById()</code> to select it. Those older methods <a href=\"https://www.sitepoint.com/community/t/getelementbyid-vs-queryselector/280663/2\" rel=\"nofollow noreferrer\">are faster than the <code>querySelector()</code> varieties</a>. </p>\n\n<h2>Dramatic simplification</h2>\n\n<p>The question contained this text:</p>\n\n<blockquote>\n <p>There's probably another way to solve it with pure CSS.</p>\n</blockquote>\n\n<p>That is correct. One way is to use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#required\" rel=\"nofollow noreferrer\"><code>required</code></a> attribute on the first <code><input></code> element along with the <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/:valid\" rel=\"nofollow noreferrer\"><code>:valid</code></a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/:hover\" rel=\"nofollow noreferrer\"><code>:hover</code></a> pseudo-selectors :</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-css lang-css prettyprint-override\"><code>input {\n width: 20px;\n transition: width 1s;\n}\n\ninput:valid,\ninput:hover,\n.expanded {\n width: 256px;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><p>\n 2 inputs, 1 is collapsed \n the other is expanded\n\n</p> \n<br>\ncollapsed \n<br>\n <input type=\"text\" class=\"collapsed\" required>\n <br>\n <br>\n expanded\n <br>\n <input type=\"text\" class=\"expanded\"></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Perhaps someday the CSS pseudo-class <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/:blank\" rel=\"nofollow noreferrer\"><code>:blank</code></a> will be supported by some browsers... If that is the case, then the <code>required</code> attribute wouldn't be needed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T23:55:52.600",
"Id": "443680",
"Score": "0",
"body": "+1 however a very minor point in regard to transitions. 1 second is way too long, 1/5th - 1/3rd second still adds wiz-bang without giving an interface a slow feel"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T00:01:09.110",
"Id": "443681",
"Score": "0",
"body": "At the risk of sounding naive, could you explain more about \"wiz-bang\"? If you have enough for an answer maybe we could get this up to a HNQ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T00:05:55.583",
"Id": "443682",
"Score": "0",
"body": "wiz-bang as in look good, or slick. Better than no transition at all."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T15:58:18.547",
"Id": "227794",
"ParentId": "227772",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "227794",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T10:29:33.977",
"Id": "227772",
"Score": "6",
"Tags": [
"javascript",
"css",
"ecmascript-6",
"event-handling",
"dom"
],
"Title": "Simple input class change with vanilla JS"
}
|
227772
|
<p><strong>Edit</strong>: The comments have been incorporated to <a href="https://github.com/mimosinnet/P6-Color-RangeToColor/blob/master/lib/Color/GradientGenerator.rakumod" rel="nofollow noreferrer">this module</a> in GitHub. The final code has been included at the end of this thread. Thanks very much for the detailed and brilliant suggestions.</p>
<hr />
<p>Inspired in this <a href="http://www.herethere.net/%7Esamson/php/color_gradient/" rel="nofollow noreferrer">color gradient generator</a>, this is a gradient generator in perl6. I wonder if the code could be simplified or improved. It converts the hex colour to base10, calculates the gradient colours, and then converts the colour to base16.</p>
<pre><code>my $initial_color = '#FF0000';
my $final_color = '#00FF00';
my $gradient = 10;
my @initial = ($initial_color ~~ /\#(..)(..)(..)/).list.map: { .Str.parse-base(16) };
my @final = ($final_color ~~ /\#(..)(..)(..)/).list.map: { .Str.parse-base(16) };
my @range = @final Z- @initial;
my @increment = @range.map: { $_ / $gradient };
my @color;
@color.push: @initial;
for (1..$gradient) -> $i {
@color.push: @(@color[$i-1]) Z+ @increment;
}
for (0..$gradient) -> $i {
@color[$i] = '#' ~ ( @(@color[$i]).map: { .base(16,0).fmt('%02s') } ).join;
}
my $fh = open '/tmp/delete.html', :w;
for (0..$gradient) -> $i {
$fh.print: "<span style='background-color:@color[$i]'>&nbsp;</span>";
}
$fh.print: '&nbsp';
$fh.close;
run <elinks -dump -dump-color-mode 3 /tmp/borrem.html>;
</code></pre>
|
[] |
[
{
"body": "<p>I'm going to limit my initial answer to not include modules, but I'll also cover a module that can help out some here too later.</p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>my $initial_color = '#FF0000';\nmy $final_color = '#00FF00';\n</code></pre>\n\n<p>While there's nothing wrong with using underscores, the tendency in Perl 6 has been to move towards hyphens, which would give us <code>$initial-color</code> and <code>$final-color</code>. </p>\n\n<pre><code>my @initial = ($initial_color ~~ /\\#(..)(..)(..)/).list.map: { .Str.parse-base(16) };\n</code></pre>\n\n<p>This is a bit of personal preference, I'd write this as </p>\n\n<pre><code>my @initial = .map: *.Str.parse-base(16) with $initial-color ~~ /\\#(..)(..)(..)/;\n</code></pre>\n\n<p>Since it allows you to get rid of most of the parentheses/braces. Note that in any case, you don't need the <code>.list</code> because your <code>Match</code> is already an <code>Iterable</code>. But this is of course a pure matter of taste (some might prefer parentheses around the <code>.map</code> to emphasize it's separate from the <code>with</code> postfix.</p>\n\n<p>You can also prestore the regex, particularly if you plan on using it more often:</p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>my $hex-format = /\\#(..)(..)(..)/;\nmy @initial = .map: *.Str.parse-base(16) with $initial-color ~~ $hex-format;\n</code></pre>\n\n<p>Your next two lines have two different techniques for applying math operators across lists: </p>\n\n<pre><code>my @range = @final Z- @initial; \nmy @increment = @range.map: { $_ / $gradient };\n</code></pre>\n\n<p>You could use a zip operator for both ( <code>@range Z/ ($gradient xx 3)</code> ), or you could opt for a hyper meta operator:</p>\n\n<pre><code>my @range = @final «-» @initial;\nmy @increment = @range «/» $gradient\n</code></pre>\n\n<p>Now for generating the colors themselves, you had</p>\n\n<pre><code>my @color;\n@color.push: @initial;\nfor (1..$gradient) -> $i {\n @color.push: @(@color[$i-1]) Z+ @increment;\n}\n\nfor (0..$gradient) -> $i {\n @color[$i] = '#' ~ ( @(@color[$i]).map: { .base(16,0).fmt('%02s') } ).join;\n}\n</code></pre>\n\n<p>First the easy things. If I see a variable <code>@color</code>, I assume it is a single entity with multiple constituent entities (one color, three values — R, G, B). But in this case, it's a list of colors, so the variable name is best used in plural. Also, you don't need parentheses around the list for the for loop. Just <code>for 0..$gradient -> $i</code> works. </p>\n\n<p>Your first for loop uses the previous item to determine the next one, so you have a push outside the loop. There's a few ways to solve this. If you have to do an initial step like that, I like to put it in the loop using <code>FIRST</code> (or <code>once</code>, both are functionally equivalent here).</p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>my @color;\nfor 1..$gradient -> $i {\n FIRST @color.push(@initial);\n @color.push: @(@color[$i-1]) Z+ @increment;\n}\n</code></pre>\n\n<p>But we can actually rewrite this to calculate the value without relying upon the previous entry:</p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>my @color;\nfor 0..$gradient -> $step {\n @color.push: @initial «+» @increment «*» $step;\n}\n</code></pre>\n\n<p>This could be even further reduced into a one liner, but I don't think that's necessary nor desirable here. What's great here about the hyper operators is that they read like scalar arithmetic (<code>$initial + $increment * $step</code>) so readability is maintained.</p>\n\n<p>Your second loop can also be simplified quite a bit by just looping on the values. I think it makes most sense to just put them into a new array</p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>my @html-colors;\nfor @colors -> @color {\n @html-colors.push: '#' ~ @color.map( *.base(16,0).fmt: '%02s' ).join;\n}\n</code></pre>\n\n<p>Anytime, though, you have a <code>.map</code> that has another method chain in its code block, you have a candidate for a hyper method call <code>».</code> </p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>my @html-colors;\nfor @colors -> @color {\n @html-colors.push: '#' ~ @color».base(16,0)».fmt('%02s').join;\n}\n</code></pre>\n\n<p>Basically, <code>».foo</code> means <em>take every element and <code>.foo</code> it</em>, and it returns a list of the values, which can be <code>».bar</code> on every element. Note that <code>.join</code> doesn't have the hyperoperator, because we want to act on the resulting list.</p>\n\n<p>But you could also loop in a rw manner (notice the <code><-></code>) with</p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>for @colors <-> @color {\n @colors = '#' ~ @color».base(16,0)».fmt('%02s').join;\n}\n</code></pre>\n\n<p>Because now both loops though are <code>0 .. $gradient</code>, it might make sense to merge them:</p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>my @colors\nfor 0..$gradient -> $step {\n my @intermediate = @initial »+» @increment »*» $step;\n @colors.push: '#' ~ @intermediate».base(16,0)».fmt('%02s').join;\n}\n</code></pre>\n\n<p>Lastly when you print, remember you can just loop on the color items:</p>\n\n<pre><code>for @colors -> $color {\n $fh.print: \"<span style='background-color:$color'>&nbsp;</span>\"; \n}\n</code></pre>\n\n<p>Which also allows a one liner using the topic variable <code>$_</code> (and in this case, absent doing anything else, makes more sense to me):</p>\n\n<pre><code>$fh.print: \"<span style='background-color:$_'>&nbsp;</span>\" for @colors;\n</code></pre>\n\n<p>Since it's effectively the same loop, this is, of course, a candidate for putting back in the main loop, but there's something to be said for separating the calculations from the final output. </p>\n\n<p>Rewritten, my version would be:</p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>my $initial-color = '#FF0000';\nmy $final-color = '#00FF00';\nmy $gradient = 10;\n\nmy $hex-format = /\\#(..)(..)(..)/;\n\nmy @initial = .map: *.Str.parse-base(16) with $initial-color ~~ $hex-format;\nmy @final = .map: *.Str.parse-base(16) with $final-color ~~ $hex-format;\n\nmy @increment = (@final »-» @initial) »/» $gradient;\n\nmy @colors;\n\nfor 0..$gradient -> $step {\n my @intermediate = @initial »+» @increment »*» $step;\n @colors.push: '#' ~ @intermediate».base(16,0)».fmt('%02s').join;\n}\n\nmy $fh = open '/tmp/delete.html', :w;\n$fh.print: \"<span style='background-color:$_'>&nbsp;</span>\" for @colors; \n$fh.print: '&nbsp';\n$fh.close;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T14:35:16.613",
"Id": "227785",
"ParentId": "227774",
"Score": "5"
}
},
{
"body": "<p>Some ideas to improvement.</p>\n\n<p>If I need <code>List of Str</code> I prefer <code>comb</code> to <code>match</code>.</p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>my @initial = $initial_color.comb(/<xdigit> ** 2/)».parse-base(16);\n#or\nmy @final = $final_color.substr(1).comb(2)».parse-base(16);\n</code></pre>\n\n<p>You can use the sequence operator <code>...</code> to make sequence of colors.</p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>my @color = @initial, { @^p Z+ @increment } ... * ~~ @final;\n</code></pre>\n\n<p>Method <code>fmt</code> works with list and can convert to hex numbers.</p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>@color .= map: '#' ~ *.fmt: '%02X', q{} ;\n</code></pre>\n\n<p>One more, I use <code>fmt</code> on <code>List</code> to make HTML color gradient.</p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>my $html-color-gradient = @color.fmt( q{<span style='background-color:%s'>&nbsp;</span>}, q{}) ~ '&nbsp';\n</code></pre>\n\n<p>Last two steps in one by method <code>tree</code>.</p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>my $html-color-gradient = @color.tree(\n *.fmt( q{<span style='background-color:%s'>&nbsp;</span>}, q{}) ~ '&nbsp',\n '#' ~ *.fmt( '%02X', q{} ),\n )\n</code></pre>\n\n<p>You could use <code>spurt</code> instead of <code>open, print, close</code>.</p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>spurt '/tmp/delete.html', $html-color-gradient;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T10:28:04.430",
"Id": "228835",
"ParentId": "227774",
"Score": "3"
}
},
{
"body": "<p>I have learned a lot from these detailed and brilliant responses. This is the module I have built from your suggestions, and <a href=\"https://github.com/mimosinnet/P6-Color-RangeToColor/blob/master/lib/Color/GradientGenerator.rakumod\" rel=\"nofollow noreferrer\">this is the link</a> to the module in GitHub. Thanks very much!</p>\n<pre><code>unit module Color::GradientGenerator;\n\nsub gradient_generator( Str :$initial-color = '#FF0000', Str :$final-color = '#00FF00', Int :$gradient = 10) is export(:gradient_generator) {\n\n # Transform Str HEX to Array (R,G,B)\n my @RGB-ini-color = $initial-color.substr(1).comb(2)».parse-base(16);\n my @RGB-final-color = $final-color.substr(1).comb(2)».parse-base(16);\n my @RGB-range = @RGB-final-color «-» @RGB-ini-color; \n my @RGB-increment = @RGB-range «/» $gradient;\n\n # RGB gradient: inicial-color, range from (initial-color + increment) TO (watever matches final-color)\n my @RGB-gradient = @RGB-ini-color, { @^a «+» @RGB-increment } ... (* ~~ @RGB-final-color);\n\n # Return (R,G,B) to HEX \n return @RGB-gradient.map: '#' ~ *.fmt: '%02X', q{} ;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-30T11:19:05.247",
"Id": "248655",
"ParentId": "227774",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "227785",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T10:46:34.457",
"Id": "227774",
"Score": "6",
"Tags": [
"html",
"raku"
],
"Title": "perl6: html color gradient generator"
}
|
227774
|
<p><strong>I want to insert a small str into a larger one in the most pythonic way.</strong></p>
<p>Maybe I missed a useful str method or function ? The function that insert the small str into the larger one is <code>insert_tag</code>.</p>
<p>I have tried something with reduce but it didn't work and it was too complex.</p>
<p>Code:</p>
<pre><code>from random import choice, randrange
from typing import List
def insert_tag(text: str, offsets: List[int], tags: List[str]) -> str:
text: str = text
for offset, tag in zip(offsets, tags):
# text = f'{text[:offset]}{tag}{text[offset:]}' # solution 1
text = text[:offset] + tag + text[offset:] # solution 2
return text
if __name__ == '__main__':
tag_nbr = 30
# Text example
base_text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do ' \
'eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut ' \
'enim ad minim veniam, quis nostrud exercitation ullamco laboris ' \
'nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor ' \
'in reprehenderit in voluptate velit esse cillum dolore eu fugiat ' \
'nulla pariatur. Excepteur sint occaecat cupidatat non proident, ' \
'sunt in culpa qui officia deserunt mollit anim id est laborum.' \
.replace(',', '').replace('.', '')
# Random list of tag only for testing purpose
tag_li: List[str] = [f'<{choice(base_text.split())}>' for _ in range(tag_nbr)]
# Ordered list of random offset only for testing purpose
offset_li: List[int] = [randrange(len(base_text)) for _ in range(tag_nbr)]
offset_li.sort(reverse=True)
# Debug
print(tag_li, offset_li, sep='\n')
# Review
new_text: str = insert_tag(base_text, offset_li, tag_li)
# End Review
# Debug
print(new_text)
</code></pre>
<p>Output:</p>
<pre><code>"Lorem ips<consectetur>u<Lorem>m dolo<Lorem>r sit amet consecte<Lorem>tur <nostrud>adipiscing eli<aute>t sed d<anim>o eiusmod tempo<voluptate>r <exercitation>incid<anim>i<non>dunt ut l<quis>abor<do>e et dol<reprehenderit>ore magna aliqua Ut enim ad minim veniam quis nostrud exercitatio<est>n ullamco laboris nisi ut aliquip ex<nulla> ea <consectetur>commodo consequat Duis aute irure dolor in repreh<deserunt>enderit in voluptate vel<sint>it esse cillum dolore eu f<qui>ugiat nulla pariatur <magna>Excepteur sin<ex>t occaecat cup<labore>i<ut>datat non proident sun<est>t<in> in cul<fugiat>pa qui officia<enim> deserunt mollit anim i<in><anim>d est laborum"
</code></pre>
<p><strong>PS: The rest of the code is not my primary concern, but if it can be improved, tell me, thanks.</strong></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T15:32:45.260",
"Id": "443600",
"Score": "4",
"body": "Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 5 → 3"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T15:35:04.697",
"Id": "443601",
"Score": "3",
"body": "`Do not add an improved version of the code after receiving an answer. Including revised versions of the code makes the question confusing, especially if someone later reviews the newer code.`\nI didn't see that, thank you"
}
] |
[
{
"body": "<p>Besides your approach there are a few other alternatives to solve this problem: (1) collect segments of the input <code>text</code> (using values in <code>offsets</code>) and the tags into a <code>list</code>, then call <code>''.join(<list>)</code> at the end to generate the output; (2) split <code>text</code> into segments, create a format string using <code>'{}'.join(segments)</code>, then finally apply the format string to <code>tags</code> to generate the output.</p>\n\n<p>Be aware that your approach consumes more memory and has a theoretical time complexity of <span class=\"math-container\">\\$O(n^2)\\$</span> to join <span class=\"math-container\">\\$n\\$</span> strings because memory reallocation is needed for each intermediate concatenated string. It could be more efficient in some cases on small <span class=\"math-container\">\\$n\\$</span>s but will be less efficient when <span class=\"math-container\">\\$n\\$</span> becomes larger. Therefore, this is not recommended by <a href=\"https://www.python.org/dev/peps/pep-0008/#id51\" rel=\"nofollow noreferrer\">PEP 8</a>:</p>\n\n<blockquote>\n <ul>\n <li>Code should be written in a way that does not disadvantage other implementations of Python (PyPy, Jython, IronPython, Cython, Psyco,\n and such).</li>\n </ul>\n \n <p>For example, do not rely on CPython's efficient implementation of\n in-place string concatenation for statements in the form a += b or a =\n a + b. This optimization is fragile even in CPython (it only works for\n some types) and isn't present at all in implementations that don't use\n refcounting. In performance sensitive parts of the library, the\n ''.join() form should be used instead. This will ensure that\n concatenation occurs in linear time across various implementations.</p>\n</blockquote>\n\n<p><strong>EDIT</strong>: <a href=\"https://www.kaggle.com/miracle0/tag-insert-performance-comparison\" rel=\"nofollow noreferrer\">Here</a> is my version of performance measurements of various methods using the input format mentioned under the comment of <a href=\"https://codereview.stackexchange.com/a/227786/207952\">this answer</a>, where <code>offsets</code> and <code>tags</code> are 'merged' into a single list of tuples. It can be seen that CPython's optimization of concatenation operation using <code>+</code> does take effect and the performance of <em>the best</em> concatenation-based method is on par with several <code>str.join</code>-based methods when the text length (the tag count equals to text length in the experiments) is less than 600, but eventually loses out due to its quadratic complexity. However, as PEP8 suggests, similar performance cannot be expected from other Python interpreters.</p>\n\n<p>Performance measurements:</p>\n\n<pre><code> Mean exec time (us) Text Length (equals to tag count) \nMethod 150 300 450 600 750 900 \ntag_insert_no_op 19.02 35.58 52.44 70.42 87.27 104.33 \ntag_insert_concat1 52.14 109.22 171.93 238.59 302.76 369.56 \ntag_insert_concat2 66.05 146.94 247.86 359.57 475.49 590.77 \ntag_insert_concat3 63.04 139.67 238.23 342.51 453.53 599.11 \ntag_insert_join1 65.18 127.26 194.70 256.11 311.22 371.54 \ntag_insert_join1_local 51.53 99.95 147.47 197.71 245.54 290.79 \ntag_insert_join1_extend 50.36 95.91 143.63 192.76 238.07 281.91 \ntag_insert_join1_yield 55.01 103.39 155.92 210.74 256.53 306.94 \ntag_insert_join1_yield2 52.82 101.89 155.55 208.33 255.97 305.05 \ntag_insert_join2 61.59 118.39 175.99 234.68 287.70 341.65 \ntag_insert_join3 60.82 120.61 177.78 238.28 286.85 343.49 \ntag_insert_join3_iter 59.65 117.34 172.51 235.55 282.96 339.15 \ntag_insert_format 64.98 124.01 184.88 245.21 302.68 362.70 \ntag_insert_string_io 54.08 108.49 161.08 214.71 264.93 315.87 \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T14:37:12.657",
"Id": "443575",
"Score": "0",
"body": "The offset still valid since I do `offset_li.sort(reverse=True)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T02:27:38.763",
"Id": "444677",
"Score": "0",
"body": "For some measurements of time efficiency (memory efficiency ignored), refer to https://codereview.stackexchange.com/a/228822/25834"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T10:01:18.193",
"Id": "444720",
"Score": "1",
"body": "@DorianTurba I have added my implementation of several methods with performance measurements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T12:22:08.523",
"Id": "444739",
"Score": "0",
"body": "I accept your answer because solutions you provide does make the memory improvement of the answer of Scnerd, and is more understandable. Since Pythonic is my primary concern, your answer suit better the question."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T14:28:24.853",
"Id": "227784",
"ParentId": "227778",
"Score": "8"
}
},
{
"body": "<p>The core code (I'd prefer the f-string if you can guarantee Python 3.6+, else the addition or <code>\"{}{}{}\".format(...)</code> if you need to support older Python versions) looks fine. However, you overwrite <code>text</code> each loop, but continue to use the originally provided <code>offset</code>'s, which could be very confusing since the offsets will become incorrect after the first tag insertion. The code doesn't crash, but I'd argue it doesn't \"work\", certainly not as I'd intuitively expect:</p>\n\n<pre><code>In [1]: insert_tag('abc', [1, 2], ['x', 'y'])\nOut[1]: 'axyyxbc'\n</code></pre>\n\n<p>I'd expect this to produce <code>'axbyc'</code>. If that output looks correct to you, ignore the rest of this answer.</p>\n\n<p>It would be better to break the original string apart first, then perform the insertions. As is typical in Python, we want to avoid manual looping if possible, and as is typical for string generation, we want to create as few new strings as possible. I'd try something like the following:</p>\n\n<pre><code>In [2]: def insert_tags(text: str, offsets: [int], tags: [str]):\n ...: offsets = [0] + list(offsets)\n ...: chunks = [(text[prev_offset:cur_offset], tag) for prev_offset, cur_offset, tag in zip(offsets[:-1], offset\n ...: s[1:], tags)]\n ...: chunks.append([text[offsets[-1]:]])\n ...: return ''.join(piece for chunk_texts in chunks for piece in chunk_texts)\n\n\nIn [3]: insert_tags('abc', [1, 2], ['x', 'y'])\nOut[3]: 'axbyc'\n</code></pre>\n\n<p>Other stylistic considerations:</p>\n\n<ul>\n<li><p>Your function supports the insertion of multiple tags, so it should probably be called \"insert_tags\" (plural) for clarity.</p></li>\n<li><p>Type annotation are generally good (though recall that they lock you in to newer versions of Python 3.X), but getting them right can be a nuisance. E.g., in this case I'd suggest using <code>Sequence</code> instead of <code>List</code>, since you really just need to be able to loop on the offsets and tags (e.g., they could also be tuples, sets, or even dicts with interesting keys). I also find them to often be more clutter than useful, so consider if adding type annotations really makes this code clearer, or if something simpler, like a succinct docstring, might be more helpful.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T14:38:30.600",
"Id": "443576",
"Score": "0",
"body": "The offset still valid since I do offset_li.sort(reverse=True), I update the output to show it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T14:41:39.877",
"Id": "443578",
"Score": "3",
"body": "That should either be built into the function (something like ``offsets, tags = zip(*sorted(zip(offsets, tags), reverse=True))``) or made crystal clear in the function's documentation. The function shouldn't fail horribly like I show because the user expects the function to behave the same regardless of the order of the offsets."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T14:45:19.043",
"Id": "443581",
"Score": "0",
"body": "To answer the question in your answer : with `insert_tag('abc', [1, 2], ['x', 'y'])` you will get `'axybc'`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T14:48:19.423",
"Id": "443582",
"Score": "0",
"body": "The fact is that in the real program, tag and offset is linked together because they are in the same object, so def of `insert_tag` will look like this : `def insert_tag(tags: List[Tuple(int, str)]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T15:00:54.873",
"Id": "443585",
"Score": "0",
"body": "That updated type annotation is still overly specific. You don't need the tags to be a list, you just need to be able to iterate over them. As I mentioned, making good type annotations can be helpful, but more difficult that it seems like it should be. If you require a List, everyone using your code will have IDE/lint warnings thrown at them unless they cast their objects to lists, which shouldn't be necessary and may, in some cases, be very badly advised."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T15:02:53.373",
"Id": "443586",
"Score": "0",
"body": "Atomicity is invaluable in making clear, understandable code, and having the behavior of your function change depending on the order of the offsets seems very confusing to me. My critique stands, that I think that even your updated expected behavior of the function seems confusing, and I'd suggest making the function clearer and, if you want that kind of behavior, make it happen in the code that calls this function (by passing `[1, 1], ['x', 'y']`)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T15:07:57.847",
"Id": "443588",
"Score": "0",
"body": "Yes, I will sort on offset inside the insert_tag function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T09:12:39.273",
"Id": "444716",
"Score": "0",
"body": "I got a warning from my linter on this: `chunks.append([tmp_str[offsets[-1]:]])`, because chunks is a list of tuple, and you append a list of 1 elem. I change the line by `chunks.append((text[offsets[-1]:], ''))` in order to fix this, what do you think ?"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T14:37:09.263",
"Id": "227786",
"ParentId": "227778",
"Score": "12"
}
},
{
"body": "<p>Ignoring for now the various gotchas that @scnerd describes about offsets, and making some broad assumptions about the monotonicity and order of the input, let's look at the performance of various implementations. Happily, your implementations are close to the most efficient given these options; only the shown \"naive\" method is faster on my machine:</p>\n\n<pre><code>#!/usr/bin/env python3\n\nfrom io import StringIO\nfrom timeit import timeit\n\n\n# Assume that 'offsets' decreases monotonically\n\n\ndef soln1(text: str, offsets: tuple, tags: tuple) -> str:\n for offset, tag in zip(offsets, tags):\n text = f'{text[:offset]}{tag}{text[offset:]}'\n return text\n\n\ndef soln2(text: str, offsets: tuple, tags: tuple) -> str:\n for offset, tag in zip(offsets, tags):\n text = text[:offset] + tag + text[offset:]\n return text\n\n\ndef gen_join(text: str, offsets: tuple, tags: tuple) -> str:\n offsets += (0,)\n return ''.join(\n text[offsets[i+1]:offsets[i]] + tag\n for i, tag in reversed(tuple(enumerate(tags)))\n ) + text[offsets[0]:]\n\n\ndef naive(text: str, offsets: tuple, tags: tuple) -> str:\n output = text[:offsets[-1]]\n for i in range(len(tags)-1,-1,-1):\n output += tags[i] + text[offsets[i]:offsets[i-1]]\n return output + text[offsets[0]:]\n\n\ndef strio(text: str, offsets: tuple, tags: tuple) -> str:\n output = StringIO()\n output.write(text[:offsets[-1]])\n for i in range(len(tags)-1,-1,-1):\n output.write(tags[i])\n output.write(text[offsets[i]:offsets[i-1]])\n output.write(text[offsets[0]:])\n return output.getvalue()\n\n\ndef ranges(text: str, offsets: tuple, tags: tuple) -> str:\n final_len = len(text) + sum(len(t) for t in tags)\n output = [None]*final_len\n offsets += (0,)\n\n begin_text = 0\n for i in range(len(tags)-1,-1,-1):\n o1, o2 = offsets[i+1], offsets[i]\n end_text = begin_text + o2 - o1\n output[begin_text: end_text] = text[o1: o2]\n\n tag = tags[i]\n end_tag = end_text + len(tag)\n output[end_text: end_tag] = tag\n\n begin_text = end_tag\n\n output[begin_text:] = text[offsets[0]:]\n return ''.join(output)\n\n\ndef insertion(text: str, offsets: tuple, tags: tuple) -> str:\n output = []\n offsets = (1+len(tags),) + offsets\n for i in range(len(tags)):\n output.insert(0, text[offsets[i+1]: offsets[i]])\n output.insert(0, tags[i])\n output.insert(0, text[:offsets[-1]])\n return ''.join(output)\n\n\ndef test(fun):\n actual = fun('abcde', (4, 3, 2, 1), ('D', 'C', 'B', 'A'))\n expected = 'aAbBcCdDe'\n assert expected == actual\n\n\ndef main():\n funs = (soln1, soln2, gen_join, naive, strio, ranges, insertion)\n for fun in funs:\n test(fun)\n\n N = 5_000 # number of averaging repetitions\n L = 150 # input length\n text = 'abcde' * (L//5)\n offsets = tuple(range(L-1, 0, -1))\n tags = text[-1:0:-1].upper()\n\n print(f'{\"Name\":10} {\"time/call, us\":15}')\n for fun in funs:\n def call():\n return fun(text, offsets, tags)\n dur = timeit(stmt=call, number=N)\n print(f'{fun.__name__:10} {dur/N*1e6:.1f}')\n\n\nmain()\n</code></pre>\n\n<p>This yields:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Name time/call, us \nsoln1 134.2\nsoln2 133.2\ngen_join 289.7\nnaive 116.8\nstrio 159.6\nranges 513.9\ninsertion 204.7\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T03:25:24.743",
"Id": "444687",
"Score": "0",
"body": "One problem of the tests is that it assumes that `offsets` is in descending order, which adds unnecessary overhead to all the `str.join` implementations here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T03:28:04.813",
"Id": "444688",
"Score": "1",
"body": "@GZ0 The alternatives - probably adding a `sort()` somewhere, to be more robust - are probably going to incur more cost than assuming descending order. Iterating in reverse order is efficient, especially with indexes. Only one of the methods calls `reversed`, and it's difficult to say whether that's the limiting factor in speed of that method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T03:50:10.557",
"Id": "444692",
"Score": "1",
"body": "Meanwhile, the slowness of `insertion` is due to all the insertions happening at the beginning of the list. The implementation would not be so awkward if not because of the decending order."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T10:15:02.987",
"Id": "444724",
"Score": "1",
"body": "I have added my version of performance tests in my post. I tried my best to optimize each method to achieve its best performance. For some methods, several variations are implemented for comparison."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T12:33:36.877",
"Id": "444741",
"Score": "0",
"body": "@GZ0 I'm glad that you did some performance analysis and updated your answer. Note that the `tuple` call is *not* redundant because `reversed` cannot accept an iterator."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T12:37:54.827",
"Id": "444743",
"Score": "0",
"body": "My bad. I had a wrong impression about `reversed`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T15:36:18.107",
"Id": "444765",
"Score": "0",
"body": "While I appreciate profiling answers when they contribute useful information, this doesn't seem to address either the question asked (\"what is the most pythonic way\") nor the general goal of CodeReview, which is to provide holistic suggestions/critique for working code. This simply enumerates a bunch of ways to concatenate strings and demonstrates that, unless you're doing this **a lot**, it doesn't really matter how you do it, except that the OP's original code is plenty clean and efficient."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T02:24:57.487",
"Id": "228822",
"ParentId": "227778",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227784",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T11:35:48.850",
"Id": "227778",
"Score": "9",
"Tags": [
"python",
"strings"
],
"Title": "Insert str into larger str in the most pythonic way"
}
|
227778
|
<p>I've been developing my first real python gui-program for a while now. Having watched some tutorials to tkinter and OOP I've gotten quite far, but now I just can't get my code to do what I want it to. </p>
<p>So here's my code so far:</p>
<pre><code>import random
import string
import time
import datetime
import tkinter as tk
import pandas as pd
# GUI
# Define text variabels:
intro_txt = "Welcome to Typetrainer!\n This program will help you get faster at typing on your PC"
instr_txt = "Instructions:\n-Place your right index finger on the letter J, your left index finger on F" \
"\n-Type the string you see as fast as you can using all ten fingers" \
"\n-Don't look at the keyboard !"
diff_txt = "Please select a difficulty"
go_txt = "Type the above string as fast as you can and hit enter !"
# Create custom fontvariables
NORMAL_FONT=("Verdana", 12)
LARGE_FONT=("Verdana", 18)
# Define difficulties
diff_levels = {"Easy": 5, "Medium": 10, "Hard": 15, "Expert": 20}
class TypeTrainerGUI(tk.Tk):
def __init__(self, *args, **kwargs): # initialize the TypeTrainerGUI class;
# *args: generally used for all the arguments, **kwargs: passing through dictionaries
tk.Tk.__init__(self, *args, **kwargs) # initialize Tkinter within the TypeTrainerGUI class
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {} # this holds all the different "windows" that the GUI can show and the user can interact with
for F in (StartPage, DifficultySelection, TypePage): # "activates" the frames so that
# they can be cycled through
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew") # .grid defines where the frame sits; sticky defines
# alignment and strech
self.title("Type Trainer")
self.show_frame(StartPage)
def show_frame(self, cont): # define the .show_page method; moves a frame to the top so
# the user can interact with it
frame = self.frames[cont]
frame.tkraise()
def init_game(self, diff_in): # set the parameters for the game to run with
global cnt
global score
print(diff_in) # check if the correct value is passed
# Define a object that creates a lowercase letter string of length a
self.question_txt = ''.join(random.choice(string.ascii_lowercase) for x in range(diff_in))
print(self.question_txt) # check if correct text is generated
cnt = 0 # Counter for the no of rounds
score = 0 # Track the score
class StartPage(tk.Frame): # Create start page
def __init__(self, parent, controller): # initialize the frame
tk.Frame.__init__(self, parent) # initialize tkinter
label = tk.Label(self, text=intro_txt, font=LARGE_FONT) # create label
label_2 = tk.Label(self, text=instr_txt, font=NORMAL_FONT) # create label
label.pack(pady=10, padx=10)
label_2.pack(pady=10, padx=10)
next = tk.Button(self, text="Next", command=lambda: controller.show_frame(DifficultySelection))
next.pack()
class DifficultySelection(tk.Frame): # Create difficulty selection page
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text=diff_txt, font=NORMAL_FONT, justify=tk.LEFT)
label.pack(pady=10, padx=10)
self.choice = tk.IntVar()
for (diff, val) in diff_levels.items():
tk.Radiobutton(self, text=diff, padx=20, variable=self.choice, value=val,
command=lambda: controller.init_game(self.choice.get())).pack(anchor=tk.W)
start = tk.Button(self, text="Start game", command=lambda: controller.show_frame(TypePage))
start.pack()
class TypePage(tk.Frame): # Create the interaction page
def __init__(self, parent, init_game):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text=go_txt, font=NORMAL_FONT)
label.pack(pady=10, padx=10)
question = tk.Label(self, text=question_txt, font=NORMAL_FONT)
question.pack(pady=10, padx=10)
usr_input = tk.Entry(self)
usr_input.pack(pady=10, padx=10)
usr_input.focus_set()
gui = TypeTrainerGUI()
gui.mainloop()
</code></pre>
<p>Ok, so what I want to do is get the value that's selected by clicking a radiobutton and pass it to <code>init_game</code> to create <code>question_txt</code> (and other stuff but I'm leaving that out for now). To do this I use this part of code </p>
<pre><code>self.choice = tk.IntVar()
for (diff, val) in diff_levels.items():
tk.Radiobutton(self, text=diff, padx=20, variable=self.choice, value=val,
command=lambda: controller.init_game(self.choice.get())).pack(anchor=tk.W)
</code></pre>
<p>This all works just fine. <code>init_game</code> does what I want it to do (checked with <code>print(diff_in)</code> and <code>print(question_txt)</code>). Now I want to use <code>question_txt</code> in the <code>TypePage</code> class as text for the question label. </p>
<pre><code>question = tk.Label(self, text=question_txt, font=NORMAL_FONT)
question.pack(pady=10, padx=10)
</code></pre>
<p>Doing this throws a name error: "name 'question_txt' is not defined". I just don't get how I can use <code>question_txt</code> in a different class. I tried to make it a global variable, but that also didn't solve the problem.</p>
<p>I would really appreciate any help with this. Thanks !</p>
<p>N.B.: Since this is my first try at OOP AND tkinter please be leneant. Though all comments on how to write better/more understanbale code are greatly appreciated ! </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T12:35:40.510",
"Id": "443555",
"Score": "3",
"body": "Welcome to Code Review! Unfortunately \"*[...] but now I just can't get my code to do what I want it to.*\" makes your question [off-topic](https://codereview.meta.stackexchange.com/a/3650), since we [only review code that is fully working to the best of your knowledge](/help/on-topic) here on this site. [so] is usually the place to go to if you're looking for help to get a program working the way you want. Once it works, we will be more than happy to provide feedback about possible improvements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T12:37:01.290",
"Id": "443556",
"Score": "3",
"body": "Alright, I'll move it there then. Thanks !"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T12:16:50.140",
"Id": "227779",
"Score": "1",
"Tags": [
"python",
"object-oriented",
"tkinter"
],
"Title": "TypeTrainer OOP Tkinter program"
}
|
227779
|
<p>Recently, I needed a class that could execute code in a FIFO fashion in order to update parts of a WinForms or WPF UI which did not block the UI Thread and left the UI responsive to any interaction the user did on it.</p>
<p>To achieve that objective, I developed the following code, which meets its requirements and performs decently enough to not be a burden.</p>
<pre><code>using System;
using System.Collections.Concurrent;
using System.ComponentModel;
using System.Threading;
namespace Rayffer.PersonalPortfolio.QueueManagers
{
public class BackgroundWorkerActionQueueManager : IDisposable
{
public bool IsBusy { get; private set; }
private BlockingCollection<Action> actionQueue;
private readonly BackgroundWorker backgroundWorker;
private CancellationTokenSource cancellationTokenSource;
public BackgroundWorkerActionQueueManager()
{
backgroundWorker = new BackgroundWorker();
actionQueue = new BlockingCollection<Action>();
cancellationTokenSource = new CancellationTokenSource();
backgroundWorker.WorkerSupportsCancellation = true;
backgroundWorker.DoWork += BackgroundWorker_ManageQueue;
backgroundWorker.RunWorkerAsync();
}
public void EnqueueAction(Action actionToEnqueue)
{
actionQueue.Add(actionToEnqueue);
}
private void BackgroundWorker_ManageQueue(object sender, DoWorkEventArgs e)
{
while (!backgroundWorker.CancellationPending)
{
Action actionToPerform = null;
try
{
IsBusy = false;
actionToPerform = actionQueue.Take(cancellationTokenSource.Token);
IsBusy = true;
}
catch (OperationCanceledException ex)
{
// This exception control intends to capture only when the cancellationToken has been requested to cancel
break;
}
if (actionToPerform != null)
{
actionToPerform.Invoke();
actionToPerform = null;
}
}
}
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
backgroundWorker.CancelAsync();
cancellationTokenSource.Cancel();
backgroundWorker.DoWork -= BackgroundWorker_ManageQueue;
cancellationTokenSource.Dispose();
backgroundWorker.Dispose();
}
disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
}
}
}
</code></pre>
<p>This code can be used to perform any action enqueued, from doing a simple sum, to manipulating members of a class ensuring that the operations are carried out in the order they are enqueued.</p>
<p>I was wondering which optimisations I can apply to this code or if there are any bad practices or missusages of the classes.</p>
<p>An example of use would be the following</p>
<pre><code>public class BackGroundWorkerActionQueueManagerTest
{
private BackgroundWorkerActionQueueManager sorterActionQueueManager = new BackgroundWorkerActionQueueManager ();
private BackgroundWorkerActionQueueManager sorterVisualizerActionQueueManager = new BackgroundWorkerActionQueueManager ();
private bool sorterHasEnded = false;
public Sorter sorter { get; }
public void StartSorterQueueTest(int[] arrayToSort)
{
sorterActionQueueManager.EnqueueAction(() =>
{
sorter.SortAscending(arrayToSort);
sorterHasEnded = true;
});
}
public void StartSorterQueueVisualisation()
{
sorterVisualizerActionQueueManager.EnqueueAction(() =>
{
while(!sorterHasEnded)
{
Thread.Sleep(100);
}
// Perform operations to visualise the sorting here
});
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T13:26:41.520",
"Id": "443565",
"Score": "1",
"body": "Could you provide an example or explanation of how you would expect to use this? In particular, I'm clear why you have `IsBusy`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T13:35:59.947",
"Id": "443566",
"Score": "2",
"body": "I added an example of how I expect the class to be used, hope it is enough as it is just a proof of concept."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T09:11:41.677",
"Id": "444859",
"Score": "1",
"body": "I have rolled back your last edit because it's not allowed to change the code when answers have been posted. This could invalide them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T09:13:48.373",
"Id": "444860",
"Score": "0",
"body": "@t3chb0t how can I edit correctly the question to reflect the answers in order to provide an updated code, should I answer my own question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T09:15:04.903",
"Id": "444861",
"Score": "0",
"body": "Yes, a self-answer would be the right way to post the updated code. Keep in mind, however, that it also has to be like a review this means you should not just post the new code but also summarize the changes you've made."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T09:16:00.097",
"Id": "444862",
"Score": "0",
"body": "Ok, I'll do, thanks a lot for the insight"
}
] |
[
{
"body": "<p><code>EnqueueAction</code> may want to throw an <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.objectdisposedexception?view=netframework-4.8\" rel=\"noreferrer\"><code>ObjectDisposedException</code></a> if the queue is disposed, depending on the precise API you want.</p>\n\n<hr />\n\n<p>I don't see the value of <code>IsBusy</code>, and it won't be cleared if the task is cancelled.</p>\n\n<hr />\n\n<p>I little padding inside the <code>while</code> loop would make that code much easier to understand. I'd be temped to pull the logic for retrieving the next action out into its own method so that it can read more clearly:</p>\n\n<pre><code>if (TryGetNextAction(out Action nextAction))\n{\n // invoke etc.\n}\nelse\n{\n break;\n}\n</code></pre>\n\n<p>This will make it easier to extend and modify the conditions under which the worker should terminate. You could make it a local function if you want to prevent misuse.</p>\n\n<p>For example, <code>cancellationTokenSource.Token</code> could throw an <code>ObjectDisposedException</code>, which should probably be a case where you fail cleanly, but handling this logic would clutter the existing method.</p>\n\n<hr />\n\n<p>You never change any of your private members, so you might consider making them <code>readonly</code>. Alternatively you might consider setting them to <code>null</code> upon disposal. Implementation of <code>IDispose</code> looks standard, and I <em>think</em> disposing the <code>BackgroundWorker</code> there is OK, but I'm less than certain.</p>\n\n<hr />\n\n<p>Some inline documentation would help to confirm the precise API this class is providing, and should clarify things like \"if the object is disposed, then pending tasks are dropped\", and \"order of operations is FIFO as observed from a single thread\", etc. <code>BackGroundWorkerActionQueueManagerTest</code> doesn't really elucidate its behaviour.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T16:39:04.053",
"Id": "443609",
"Score": "0",
"body": "In which conditions the token can throw an object disposed exception? I hold a reference to it throughout the whole lifetime of the class, as it is intended only to cancel the .Take()"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T16:41:16.113",
"Id": "443612",
"Score": "0",
"body": "It's a public class, other consumers could use it in a way the lifetime is handled differently than you intended, so you should guard against it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T16:44:13.293",
"Id": "443614",
"Score": "0",
"body": "@OscarGuillamon disposing the `CancellationTokenSource` will invalided it, and the call to `Token` may duly fail. (i.e. `var cts = new CancellationTokenSource(); cts.Dispose(); var t = cts.Token;` will throw)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T17:00:06.223",
"Id": "443620",
"Score": "0",
"body": "@dfhwze but the token is private, which is only disposed at the object's disposal itself, I fail to see what's wrong, can you further expand please?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T17:03:51.867",
"Id": "443622",
"Score": "0",
"body": "there can be a race condition in which _Dispose_ already disposed the token while _BackgroundWorker_ManageQueue_ still uses it one last time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T06:33:18.660",
"Id": "444836",
"Score": "0",
"body": "So, even if I cancel the token and capture the OperationCanceledException and break out of the while loop, the backgroundworker can try to use it one last time?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T08:23:29.727",
"Id": "444854",
"Score": "0",
"body": "@OscarGuillamon If you break out of the while loop then it won't try; however, all the cancel stuff in `Dispose` could be run between testing the loop condition and looking up the token (at which point it will throw). I'm not terribly familiar with the background worker API, but I can see no reason why this couldn't happen."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T08:24:37.760",
"Id": "444855",
"Score": "0",
"body": "Oh, that's a really good one, thanks for the heads-up, didn't think of that one!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T09:07:02.627",
"Id": "444858",
"Score": "0",
"body": "Also, regarding the IsBusy flag, it is used to convey whether an action is being called or it is waiting for a new action, so instead of the `sorterHasEnded` flag you can use `sorterActionQueueManager.IsBusy` flag to wait for the current action to complete either succesfully or not. Where specifically you do not see the value of IsBusy?"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T14:38:41.530",
"Id": "227787",
"ParentId": "227781",
"Score": "7"
}
},
{
"body": "<p>I think, I would provide the <code>CancellationToken</code> to each action, in order to let them respond to a possible cancellation request. Especially if the action is long running it would be a good idea.</p>\n\n<pre><code>BlockingCollection<Action<CancellationToken>> actionQueue\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> while(!sorterHasEnded)\n {\n Thread.Sleep(100);\n }\n</code></pre>\n</blockquote>\n\n<p>This tells me, that you are in the need for a mechanism that tells you when each queued action has finished. May be an event. You could then bind each action to a user defined Id of some kind and signal that, when the action is completed:</p>\n\n<pre><code>private BlockingCollection<ActionItem> actionQueue;\n\n\npublic void EnqueueAction(string id, Action<CancellationToken> actionToEnqueue)\n{\n if (string.IsNullOrWhiteSpace(id)) new ArgumentException(\"Can not be empty or null\", nameof(id));\n if (actionToEnqueue == null) new ArgumentNullException(nameof(actionToEnqueue));\n\n actionQueue.Add(new ActionItem(id, actionToEnqueue));\n}\n</code></pre>\n\n<p>And the background worker could be as something like:</p>\n\n<pre><code>private void BackgroundWorker_ManageQueue(object sender, DoWorkEventArgs e)\n{\n while (!backgroundWorker.CancellationPending)\n {\n ActionItem actionItem;\n try\n {\n IsBusy = false;\n actionItem = actionQueue.Take(cancellationTokenSource.Token);\n IsBusy = true;\n }\n catch (OperationCanceledException)\n {\n // This exception control intends to capture only when the cancellationToken has been requested to cancel\n break;\n }\n\n actionItem.Action(cancellationTokenSource.Token);\n OnActionEnded(actionItem.Id);\n }\n}\n\npublic event EventHandler<ActionEndedEventArgs> ActionEnded;\n\nprivate void OnActionEnded(string id)\n{\n ActionEnded?.Invoke(this, new ActionEndedEventArgs(id));\n}\n</code></pre>\n\n<p>Where <code>ActionItem</code> is defined as:</p>\n\n<pre><code>class ActionItem\n{\n public ActionItem(string id, Action<CancellationToken> action)\n {\n Id = id;\n Action = action;\n }\n\n public string Id { get; }\n public Action<CancellationToken> Action { get; }\n}\n</code></pre>\n\n<p>Maybe the <code>ActionEnded</code> event should be fired in a separate thread in order to not block the execution queue while a client responds to it?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T16:36:51.913",
"Id": "443607",
"Score": "0",
"body": "How would you go about firing 'actionended' on a separate thread"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T16:38:52.570",
"Id": "443608",
"Score": "0",
"body": "@OscarGuillamon: Wouldn't it be possible in a `ThreadPool` thread?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T16:39:52.370",
"Id": "443610",
"Score": "1",
"body": "Yeah, that's what I was thinking about, Ive not worked a lot with threadpool threads, so I'll give it a shot and read about it"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T16:33:26.437",
"Id": "227795",
"ParentId": "227781",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "227795",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T12:52:06.707",
"Id": "227781",
"Score": "7",
"Tags": [
"c#",
"multithreading",
"asynchronous"
],
"Title": "Action queue manager to perform action in a FIFO fashion"
}
|
227781
|
<p>I use NodeJS along with the MongoDB NodeJS Driver to store tweets into my local MongoDB server. In the following setup, mongos <code>insertOne</code> method gets invoked quite often by a socket event.</p>
<pre><code>const MongoClient = require('mongodb').MongoClient;
const TwitterClient = require('node-tweet-stream');
const twitter = new TwitterClient({
consumer_key: '',
consumer_secret: '',
token: '',
token_secret: ''
});
MongoClient.connect('mongodb://localhost:27017/', { useNewUrlParser: true }).then(client => {
/**
* Version 1
*/
twitter.on('tweet', tweet => {
client.db('twitter').collection('tweets').insertOne(tweet).then(rs => {
console.log('tweet received', tweet);
});
});
/**
* Version 2
*/
const tweetsCol = client.db('twitter').collection('tweets');
twitter.on('tweet', tweet => {
tweetsCol.insertOne(tweet).then(rs => {
console.log('tweet received', tweet);
});
});
});
</code></pre>
<p>In version 1 <code>client.db('twitter').collection('tweets').insertOne(tweet)</code> is executed on every <code>tweet</code> event. Whereas in Version 2 the reference of the collection is stored in a variable.</p>
<p>Does the mongodb driver handle such repetitive calls like in version 1 and should I care changing the code structure to version 2 in terms of performance?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T16:12:10.523",
"Id": "443604",
"Score": "1",
"body": "These code excerpts are so sketchy that I can't even tell whether the code is repetitive or not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T13:01:30.210",
"Id": "444748",
"Score": "0",
"body": "The question is: Is calling `client.db('news').collection('items')` over and over again efficient compared with storing `client.db('news')` and `collection('items')` into variables and use them in the actual method which gets invoked say every second."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T13:56:09.857",
"Id": "444751",
"Score": "1",
"body": "Don't play charades. Show us your code. See [ask]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T15:52:24.933",
"Id": "444768",
"Score": "0",
"body": "@200_success I edited the post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-18T14:33:16.730",
"Id": "472282",
"Score": "0",
"body": "Can you show us your schema as well."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T13:37:42.460",
"Id": "227782",
"Score": "1",
"Tags": [
"javascript",
"node.js",
"comparative-review",
"mongodb"
],
"Title": "Store tweets to a local MongoDB server"
}
|
227782
|
<p>I am new to this <code>CompletableFuture</code> function in Java. I have the following code below that works fine but looks quite messy IMHO.</p>
<pre><code>CompletableFuture<String> cf = CompletableFuture.completedFuture(isRQMRunning_3);
if(cf.isDone()) {
System.out.println("Value- " + cf.get());
cf = CompletableFuture.completedFuture(startRQM_4);
if(cf.isDone()) {
System.out.println("Value- " + cf.get());
cf = CompletableFuture.completedFuture(pendingChangesStatus);
if(cf.isDone()) {
System.out.println("Value- " + cf.get());
cf = CompletableFuture.completedFuture(acceptPendingChanges_8);
if(cf.isDone()) {
System.out.println("Value- " + cf.get());
cf = CompletableFuture.completedFuture(loadWorkspace_5);
if(cf.isDone()) {
System.out.println("Value- " + cf.get());
cf = CompletableFuture.completedFuture(acceptPendingChanges_8);
if(cf.isDone()) {
System.out.println("Value- " + cf.get());
cf = CompletableFuture.completedFuture(fixConflicts_9);
if(cf.isDone()) {
System.out.println("Value- " + cf.get());
}
}
}
}
}
}
}
</code></pre>
<p>Is it possible to make that look a lot nicer/easier to read?</p>
|
[] |
[
{
"body": "<p>You have a lot of repetition in your code.\nThe only thing different with the 2 lines of code repeated over and over is the argument.</p>\n\n<p>You could put all of these arguments into a list and iterate over them, running those 2 lines of code for each:</p>\n\n<pre><code>List<String> states = Arrays.asList(isRQMRunning_3, startRQM_4, \n pendingChangesStatus, acceptPendingChanges_8, \n loadWorkspace_5, acceptPendingChanges_8, fixConflicts_9);\n\nfor (String state : states)\n{\n // Loop until array is complete\n CompletableFuture<String> cf = CompletableFuture.completedFuture(state);\n\n if (!cf.isDone())\n {\n break;\n }\n\n System.out.println(\"Value- \" + cf.get());\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T15:10:47.207",
"Id": "443589",
"Score": "0",
"body": "Great suggestion @dustytrash! However, i am in need of also including the **batDir** with each."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T15:13:52.967",
"Id": "443590",
"Score": "0",
"body": "would it just need to be this **CompletableFuture.completedFuture(steps(state, batDir));**?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T15:27:22.897",
"Id": "443597",
"Score": "0",
"body": "Also, should **if (!cf.isDone()) {** be **if (cf.isDone()) {**? If its done then break out, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T15:28:52.063",
"Id": "443598",
"Score": "0",
"body": "@StealthRT no, if it's done you want to continue. You stop once isDone returns false. What I wrote should do the exact same thing your code does."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T15:02:34.477",
"Id": "227789",
"ParentId": "227788",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "227789",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T14:53:23.780",
"Id": "227788",
"Score": "3",
"Tags": [
"java",
"asynchronous"
],
"Title": "Chain of CompletableFutures in Java"
}
|
227788
|
<p>I am using a function in a SpringBoot @RestController, with Lombok</p>
<p>This function is an intermediate result that permit me to do an aggregation between two classes.</p>
<p>This 2 classes are:</p>
<pre><code>@Data
public class AchMatiereCmdCptAggDto implements Serializable {
private static final long serialVersionUID = 4022154955808447185L;
private String codService;
private String codSociete;
private String numCompte;
private String codCommande;
private Double mntCommandeHTLCY;
private Double mntLivreHTLCY;
private Double mntFactureHTLCY;
}
@Getter
@Setter
public class AchMatiereCompteCommandeAggFullDto extends AchMatiereCmdCptAggDto implements Serializable {
private static final long serialVersionUID = 6357406952790844723L;
private Date dateCommande;
private String codFournisseur;
private String libFournisseur;
private Boolean booFournisseurIntragroupe;
private Long idCommandeEtat;
}
public static String stringConcat(String ... elements) {
return new StringBuilder().append(elements).toString();
}
</code></pre>
<p>I use them that way, and I want to improve <em>forEach</em> part, and any other improvable piece of code:</p>
<pre><code> public List<AchMatiereCompteCommandeAggFullDto> mergeAchat(List<AchMatiereCompteCommandeAggFullDto> achats,
List<AchMatiereCmdCptAggDto> achats2) {
Set<AchMatiereCmdCptAggDto> setAchats = new HashSet<>(achats2);
Map<String, AchMatiereCmdCptAggDto> map = setAchats.stream()
.collect(Collectors.toMap(
p -> stringConcat(p.getNumCompte(), p.getCodCommande()),
p -> p, (ach1, ach2) -> ach2
));
achats.stream().forEach(achat -> {
String k = stringConcat(achat.getCodSociete(), achat.getCodService(), achat.getNumCompte(), achat.getCodCommande());
if (map.containsKey(k)) {
achat.setMntFactureHTLCY(map.get(k).getMntFactureHTLCY());
}
});
return achats;
}
</code></pre>
<p>I was thinking about using a <code>StringBuilder</code> for the concatenation of attributes.</p>
<p>I would also like to avoid <em>forEach</em>, and use a <code>Map</code> or something like this.</p>
<p>Thanks for your help.</p>
|
[] |
[
{
"body": "<p>From java 8 it is available in the <code>String</code> class the method <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.CharSequence...-\" rel=\"nofollow noreferrer\">join</a> that achieves the same result of your method <code>stringConcat</code> so instead of:</p>\n\n<pre><code>String k = stringConcat(achat.getCodSociete(), achat.getCodService(), achat.getNumCompte(), achat.getCodCommande());\n</code></pre>\n\n<p>You can use <code>String.join</code> with <code>\"\"</code> delimiter:</p>\n\n<pre><code>String k = String.join(\"\", achat.getCodSociete(), achat.getCodService(), achat.getNumCompte(), achat.getCodCommande());\n</code></pre>\n\n<p>It is also possibile to avoid <em>forEach</em> and use <code>Map</code> instead but because you are modifying the <code>achats</code> list elements, you have to map every element of the list to a new instance of your class and after you obtain your new list. To achieve this you can define a new copy constructor for the class:</p>\n\n<pre><code>achats.stream()\n .map(original -> {\n String k = //omitted for brevity : see above the code for k\n AchMatiereCompteCommandeAggFullDto copy = new AchMatiereCompteCommandeAggFullDto(original);\n if (map.containsKey(k)) {\n copy.setMntFactureHTLCY(map.get(k).getMntFactureHTLCY());\n }\n return copy;\n }).collect(Collectors.toList()); //<- return the new list \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T06:55:31.730",
"Id": "444703",
"Score": "0",
"body": "Thanks for your answer, is String.join better than StringBuiler ? in terms of performance for example ?\nOn the other hand, in terms of performance, do you think that its better without forEach ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T08:44:29.913",
"Id": "444711",
"Score": "0",
"body": "@DrissNejjar, in this case if you would to use `StringBuilder` , you should iterate over fields of you class , appending them in your stringbuilder and after convert it to `String`, instead with `String.join` you have already a method to do it. In terms of performance your custom method maybe is better, but I don't think you can notice it in a complicate code. For the second question, the use of `map` implies the creation of a new list of modified old elements (all new instances) and I prefer your old solution `forEach`. Probably the use of `stream` is an overkill, better loop over list."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T08:53:54.817",
"Id": "444713",
"Score": "0",
"body": "Okey for `StringBuilder` and `String.join`.\nif you think that stream is an overkill, what do you suggest instead ? when you say loop over list, do you think about a for loop ?\nThanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T09:04:47.170",
"Id": "444714",
"Score": "0",
"body": "@DrissNejjar Yes, just a `for` loop of list and inside call the setter method if condition is true, so no use of `Stream` in this case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T10:06:55.840",
"Id": "444723",
"Score": "0",
"body": "I tried the code, but I don't get the same result. Could you provide the way you have created `AchMatiereCompteCommandeAggFullDto` constructor please ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T14:20:07.623",
"Id": "444756",
"Score": "1",
"body": "If you want to use `Map` solution you have to define a copy constructor or equivalent method to create new instances of your class and after obtain the new list; otherwise if you don't want to touch code of your class use your `forEach` solution you already have."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T20:45:18.183",
"Id": "227808",
"ParentId": "227792",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "227808",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T15:41:29.993",
"Id": "227792",
"Score": "3",
"Tags": [
"java",
"iterator",
"lombok"
],
"Title": "Aggregation on list forEach and maps improvals"
}
|
227792
|
<p>As a project to better my skills in Python, I wrote a password manager. It's a website that has user login/logout functionality, the ability to add websites and passwords, and displays the websites/passwords when the user logs in. Since this is my first project integrating Python with <code>Flask</code>, I would like feedback concerning security for the most part. I don't work with websites often, so the measures I've taken to secure this website might not be good enough.</p>
<p><strong>File Structure</strong></p>
<pre><code>Password_Manager
| __pycache__
| creds
| creds.txt
| usernames.txt
| data
| ...generated folders and saved websites/passwords...
| templates
| data.html
| index.html
| login.html
| signup.html
| config.py
| encryption.py
| server.py
| utils.py
</code></pre>
<p><strong>server.py</strong></p>
<pre><code>"""
Written by: Ben Antonellis
Github: https://github.com/Linnydude3347
Sever Module for starting and stopping the server, and for dealing with
user signin, signout, adding websites to password list, and other server
functions
"""
import os
from functools import wraps
from flask import Flask, render_template, request, redirect, url_for, session, flash
from config import APP_KEY
from encryption import encrypt, decrypt
from utils import generate_uid, divide_data
APP = Flask(__name__)
APP.secret_key = APP_KEY
LOGGED_IN_USER = None
def login_required(func):
"""
A decorator that requires the user to be logged in
in order to access home and logout functionality
"""
@wraps(func)
def wrap(*args, **kwargs):
if 'logged_in' in session:
return func(*args, **kwargs)
flash("You need to login first.")
return redirect(url_for("login"))
return wrap
@APP.route("/")
def main():
"""
Function that returns the homepage for the
password manager
"""
return render_template("index.html")
@APP.route("/login", methods=["GET", "POST"])
def login():
"""
Function for logging in the user
"""
global LOGGED_IN_USER
error = None
if request.method == "POST":
username = request.form['username']
password = request.form['password']
if not user_login(username, password):
error = "Invalid username/password. Please try again."
else:
session['logged_in'] = True
LOGGED_IN_USER = username
flash("You were just logged in!")
return redirect(url_for("main"))
return render_template("login.html", error=error)
@APP.route("/logout")
@login_required
def logout():
"""
Logs out the user
"""
global LOGGED_IN_USER
session.pop("logged_in", None)
LOGGED_IN_USER = None
flash("You were just logged out!")
return redirect(url_for("main"))
@APP.route("/signup", methods=["GET", "POST"])
def signup():
"""
Adds a user to the credentials file
"""
error = None
if request.method == "POST":
with open("creds/creds.txt", "ab") as creds_file:
username = request.form["username"]
password = request.form["password"]
if username == password:
flash("Username cannot equal password!")
return redirect(url_for("signup"))
if not username or not password:
flash("You must provide both a usernamd and password!")
return redirect(url_for("signup"))
if not duplicate_user(username):
creds_file.write(encrypt(username))
creds_file.write(b"\n")
creds_file.write(encrypt(password))
creds_file.write(b"\n")
with open("creds/usernames.txt", "a") as usernames_file:
usernames_file.write(f"{username} {generate_uid()}\n")
else:
flash("There is already a user with that username. Try again.")
return redirect(url_for("signup"))
flash("You were signed up!")
return redirect(url_for("login"))
return render_template("signup.html", error=error)
@APP.route("/data", methods=["GET", "POST"])
@login_required
def data():
"""
This returns a website that contains all the saved websites and passwords
for those websites. It gets the UUID from the currently logged in user,
gets the websites and passwords associated with that user, and passes them
to the website to be displayed
"""
if request.method == "POST":
website = request.form['website']
password = request.form['password']
uuid = get_user_uuid()
path = f"data/{uuid}/"
filename = "data.txt"
if not os.path.isdir(f"data/{uuid}"):
os.mkdir(path)
new_file = open(path + filename, "w")
new_file.close()
with open(path + filename, "wb") as data_file:
data_file.write(encrypt(website))
data_file.write(b"\n")
data_file.write(encrypt(password))
data_file.write(b"\n")
return redirect(url_for("data"))
uuid = get_user_uuid()
sites, pswds = get_data(uuid)
return render_template(
"data.html",
websites=sites,
passwords=pswds
)
def user_login(username: str, password: str) -> bool:
"""
Returns a boolean if a username and password pair match
and in the credentials file
"""
with open("creds/creds.txt", "rb") as creds_file:
try:
data_ = creds_file.read().split(b"\n")
credentials = list(divide_data(data_))
for pair in credentials:
if username == decrypt(pair[0]) and password == decrypt(pair[1]):
return True
return False
except Exception as _:
return False
def duplicate_user(username: str) -> bool:
"""
Returns a boolean based on if the passed username already
exists in the credentials file
"""
with open("creds/usernames.txt", "r") as usernames_file:
data_ = usernames_file.read().split("\n")
usernames = [user.split(" ")[0] for user in data_]
return username in usernames
def get_user_uuid() -> int:
"""
Gets the UUID for the currently logged in user
"""
with open("creds/usernames.txt", "r") as usernames_file:
data_ = usernames_file.read().split("\n")
if data_:
usernames = [user.split(" ")[0] for user in data_ if user != '']
uuids = [uuid.split(" ")[1] for uuid in data_ if uuid != '']
for username, uuid in zip(usernames, uuids):
if username == LOGGED_IN_USER:
return uuid
return None
def get_data(uuid) -> list:
"""
Gathers all the websites and passwords for those
websites and returns them
"""
path = f"data/{uuid}/"
filename = "data.txt"
if not os.path.isdir(f"data/{uuid}"):
os.mkdir(path)
new_file = open(path + filename, "w")
new_file.close()
with open(path + filename, "rb") as data_file:
data_ = data_file.read().split(b"\n")
print(data_)
websites = [decrypt(data_[0]) for site in data_ if site != b'']
passwords = [decrypt(data_[1]) for password in data_ if password != b'']
return websites, passwords
if __name__ == '__main__':
APP.run(debug=True, host="0.0.0.0", port=80)
</code></pre>
<p><strong>encryption.py</strong></p>
<pre><code>"""
Written by: Ben Antonellis
Github: https://github.com/Linnydude3347
Module for handing encryption and decryption of data
"""
from cryptography.fernet import Fernet
KEY = b'aQKbfHRvFtvN3QJwPWywwmcQ-0h_JwoOo3k-MjVUecw='
FERNET = Fernet(KEY)
CIPHER_SUITE = FERNET
def encrypt(data_: str) -> bytes:
"""
Returns an encrypted version of the passed data
"""
return CIPHER_SUITE.encrypt(bytes(data_, encoding="utf-8"))
def decrypt(data_: bytes) -> str:
"""
Returns a decrypted version of the passed data
"""
return CIPHER_SUITE.decrypt(data_).decode("utf-8")
</code></pre>
<p><strong>utils.py</strong></p>
<pre><code>"""
Written by: Ben Antonellis
Github: https://github.com/Linnydude3347
Utility functions
"""
import random
def generate_uid() -> int:
"""
Returns a random number between 10,000,000 and 99,999,999
"""
return random.randint(10000000, 99999999)
def divide_data(data_: list) -> None:
"""
Returns a 2D list of lists that contain a
username and password, encrypted
"""
for i in range(0, len(data_), 2):
yield data_[i:i + 2]
</code></pre>
<p><strong>config.py</strong></p>
<pre><code>"""
Written by: Ben Antonellis
Github: https://github.com/Linnydude3347
Configuration file for containing the Flask secret_key
"""
APP_KEY = "w456789oKNbvCDE456789oKNBVfr56YHGvGT6tf"
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T17:47:01.233",
"Id": "443640",
"Score": "1",
"body": "Now that you've posted your private keys all over the internet, you should change them right away. And make sure they stay private next time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T18:04:28.760",
"Id": "443644",
"Score": "0",
"body": "@MathiasEttinger I appreciate the concern, but the Flask Secret Key is basically a face slam on my computer, and the encryption key is a randomly generated flask key that I copy pasted. I realize in production these keys are never to be revealed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T22:26:29.003",
"Id": "443668",
"Score": "4",
"body": "Perhaps consider using SSL/TLS since you're dealing with, uh, sensitive data, the port 80 there is a bit worrying without knowing more about the setup."
}
] |
[
{
"body": "<p>Disclaimer: I haven't done authentication in Flask before.</p>\n\n<p>Tl;dr: Don't do authentication yourself, it's VERY hard to do right (and using a global ain't right); also, separate the user's authentication from their key store: the former you should ONLY be able to verify, not decode, and the latter should be inaccessible to your server without some secret information from the user.</p>\n\n<p>Your code example is fairly long and I'm not terribly experienced with Flask, so I won't provide a robust judgement of the whole thing, though I will give you the compliment that your code was fairly easy to read and follow, with excellent docstrings, good modularization, and following general good practices... except that you use global variables, which is the death knell for this entire server. The user's identity should be pulled from the session, not stored in a global variable. As it is, only one user can be logged in a time, and if I log in first, then you log in second, then I can potentially see all of your passwords.</p>\n\n<p>Here are some code-related suggestions, before I dive into how a password manager, as an entire application, should probably function:</p>\n\n<ol>\n<li><p>Use standard packages for standard tasks, particularly authentication.</p></li>\n<li><p>Avoid globals. The only exception, <em>maybe</em>, is you can have a config.py with non-secret constants. Otherwise, these are more likely to get you into trouble when your server starts running in multiple threads or processes, and state management becomes an issue.</p></li>\n<li><p>Don't be afraid to store things in a database. DB's are essential to just about every web app, and are very secure and very very fast. Getting familiar with using them is a basic necessity as you move forward with building bigger web apps.</p></li>\n<li><p>Load secure keys from files or environment variables, don't hard-code them. If you use files, they should be explicitly excluded from source control, so that someone with access to your source code won't also have access to your data.</p></li>\n<li><p>The fact that your \"encrypt\" and \"decrypt\" functions don't take keys as arguments should be indicative that you're doing something wrong. If the external code doesn't need to know anything secret about a data blob in order to access it, then why is it encrypted at all? If all you care about is encryption at-rest on-disk, there are better ways to do that (encrypted file systems, secure databases, password-protected zip files, etc.) where you don't need to manage, and thus perhaps introduce vulnerabilities into, the encryption/decryption process yourself.</p></li>\n</ol>\n\n<p>As a philosophical suggestion, a robust password manager should probably 1) authenticate the user using standard best practices, then 2) provide an opaque blob to the client, who can then decrypt the data locally using some secret key of their own (maybe the same password they used to log in to the server). Ideally, at no point should the server be capable of accessing the user's secrets, and thus be capable of leaking them to internal or external threats.</p>\n\n<p>For #1, you <em>need</em> to look into using a standard Flask authentication package, which will probably leverage a database of some sort. This database should be protected using usual means (password-protected, and only be accessible from the web server), and it should only store password hashes, no cleartext passwords. If you find a good authentication package, it'll do this for you. I know Django comes with robust authentication built-in (including session management, password hashing, etc.), so I'm sure something comparable exists for Flask. Do not build stuff like this from scratch, it's a big hassle/waste of time, makes your code messy, and will result in your application being riddled with security vulnerabilities.</p>\n\n<p>For #2, this becomes tricky to do in a static website (hence why the most secure password managers usually involve a client-side browser plugin or other OS-installed component). It is possible using a little javascript embedded in the HTML page you return to the user, with some degree of security. You could pass the encrypted password store (binary data can be sent/stored in JSON using base64 encoding), then have the user re-enter their password client-side and have the javascript locally decrypt the blob and present its contents somehow. To update the data, just do so in-browser (don't send anything in cleartext to the server) and have the javascript re-package the blob, encrypt it, and send that encrypted blob back to the server. So long as the encryption library you use (and there are plenty of options) is implemented correctly, the password blob will be as safe as the algorithm and keysize you use (e.g., AES 256). This way, there's absolutely no way the server could reveal one user's secrets to another, since the server is never given the ability to decrypt any user's secrets, only authenticate them and given them their encrypted data blob.</p>\n\n<p>Even if you're just building this as a toy to learn Python/Flask and don't actually care about making a decent password manager, you should still encrypt the user's data blob using some piece of information unique to that user that's stored somewhere secure (e.g. in the database). E.g., when they POST their password, use it to authenticate them first, then if that succeeds, use it to decrypt some random gibberish that you've stored in the User table of your database which is their unique key to their password store, and store that key in their session data (either in a cookie or in a session table in the database). When their session ends, the server becomes incapable of accessing the user's password store again and everything returns to being secure.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T17:04:11.133",
"Id": "227798",
"ParentId": "227793",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "227798",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T15:48:17.867",
"Id": "227793",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"security",
"flask"
],
"Title": "Python/Flask Password Manager"
}
|
227793
|
<p>The following program calls a function, which prompts the user for input. The function then returns one of three enum constants; <code>INPUT_SUCCESSFUL</code>, <code>INPUT_TOOLONG</code>, or <code>INPUT_FAILED</code>. If successful, it prints the text entered by the user. Otherwise, it prints an error message, and takes the appropriate action.</p>
<p>The function contains three parameters. The first one is a constant character array, which gets passed the text that will be used to prompt the user. The second is a character array, in which the text entered by the user will be placed. And the third is the size of the character array.</p>
<p>I have the following questions...</p>
<p>1) Would it have been better to let the called function handle the printing of error messages, exiting the program, etc, instead of the main function?</p>
<p>2) Would it have been better to pass a pointer to the function so that it could allocate the appropriate memory, instead of passing it a fixed array?</p>
<p>3) Any potential issues with the program or improvements that can be made to the code?</p>
<p>The program was compiled as follows...</p>
<pre><code>gcc -std=c99 -Wall -Wextra -Wpedantic main.c user_input.c
</code></pre>
<p>...and received only warnings about unused parameters <code>argc</code> and <code>argv</code>. Here are the files...</p>
<p><strong>main.c</strong></p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "user_input.h"
#define MAX_STR_LEN 50
int main(int argc, char *argv[])
{
char user_input[MAX_STR_LEN + 2]; /* +2 for newline character (\n) and terminating null character (\0) */
input_status status;
while (1)
{
status = get_user_input("Enter your name: ", user_input, sizeof(user_input));
if (status == INPUT_FAILED)
{
fprintf(stderr, "Unable to read user input\n");
exit(EXIT_FAILURE);
}
if (status == INPUT_TOOLONG)
{
fprintf(stderr, "Entry exceeds %d characters\n", MAX_STR_LEN);
continue;
}
if (strlen(user_input) == 0)
{
fprintf(stderr, "Entry is missing\n");
continue;
}
if (user_input[0] == 0x18) /* user entered Ctrl+X (^x) to cancel */
{
fprintf(stderr, "User cancelled\n");
return 0;
}
break;
}
printf("User entered: %s\n", user_input);
return 0;
}
</code></pre>
<p><strong>user_input.h</strong></p>
<pre><code>#ifndef USER_INPUT_H
#define USER_INPUT_H
typedef enum
{
INPUT_SUCCESSFUL,
INPUT_TOOLONG,
INPUT_FAILED
} input_status;
void flush_input();
input_status get_user_input(const char *prompt, char *user_input, size_t size);
#endif
</code></pre>
<p><strong>user_input.c</strong></p>
<pre><code>#include <stdio.h>
#include <string.h>
#include "user_input.h"
void flush_input()
{
int c;
while ((c = getchar()) != '\n' && c != EOF)
/* skip it */ ;
}
input_status get_user_input(const char *prompt, char *user_input, size_t size)
{
printf("%s", prompt);
if (fgets(user_input, size, stdin) == NULL)
return INPUT_FAILED;
char *pNewline;
if ((pNewline = strchr(user_input, '\n')) == NULL)
{
flush_input();
return INPUT_TOOLONG;
}
*pNewline = '\0';
return INPUT_SUCCESSFUL;
}
</code></pre>
|
[] |
[
{
"body": "<p>It seems fairly sane; I only picked up a couple of things:</p>\n\n<h2>Don't ignore <code>errno</code></h2>\n\n<p>You do check for failure, which is good; but you ignore <code>errno</code>. You should use it, and/or <code>perror</code>, to get more detailed failure information.</p>\n\n<h2>Assign-in-condition</h2>\n\n<p>There's not a compelling reason to do this:</p>\n\n<pre><code>char *pNewline;\nif ((pNewline = strchr(user_input, '\\n')) == NULL)\n</code></pre>\n\n<p>Just assign <code>pNewLine</code> where it's declared, not where it's used in the condition.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T23:21:42.897",
"Id": "443671",
"Score": "0",
"body": "Thank you so much for your feedback, I really appreciate it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T23:23:05.640",
"Id": "443672",
"Score": "0",
"body": "`errno` - Do I check within the main function where I test for `status == INPUT_FAILED`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T23:23:38.647",
"Id": "443673",
"Score": "0",
"body": "`Assign-in-condition` - Is this considered poor programming practice?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T23:24:41.807",
"Id": "443674",
"Score": "0",
"body": "By the way, I like your comment - `It seems fairly sane`. :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T23:31:23.157",
"Id": "443676",
"Score": "0",
"body": "Regarding `errno` - there are various strategies for this. One strategy is, rather than returning an enum, return `errno` itself, with 0 indicating no error. Or, you could check in the calling function what `errno` is if you've received a `FAILED`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T23:32:13.727",
"Id": "443677",
"Score": "0",
"body": "Regarding assignment-in-condition - yes, it's usually considered poor programming practice. It's confusing and prone to human error. In narrow contexts it can make the code more legible but usually it should be avoided."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T23:39:01.937",
"Id": "443679",
"Score": "1",
"body": "That's great, thank you very much for your help, I really appreciate it. Cheers!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T02:20:25.697",
"Id": "444675",
"Score": "1",
"body": "Regarding the assignment in conditions: it's common to have it in `while` loops, in order to avoid writing the same code twice. A typical example is `while ((ch = fgetc(stdin)) != EOF) { … }`. In `if` statements though, the condition is always evaluated once, so there's no need to squash it together into the same line of code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T10:05:21.503",
"Id": "444722",
"Score": "0",
"body": "@RolandIllig Oh, I see. That's great, thank you very much. Cheers!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T08:32:32.283",
"Id": "447211",
"Score": "0",
"body": "\"but you ignore `errno`\" --> C does **not** require `errno` to be set with `fgets()`. Portable code would not rely on `errno` being set to indicate an I/O issue."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T22:20:36.260",
"Id": "227813",
"ParentId": "227806",
"Score": "4"
}
},
{
"body": "<ul>\n<li><blockquote>\n <p>1) Would it have been better to let the called function handle the printing of error messages, exiting the program, etc, instead of the main function?</p>\n</blockquote>\n\n<p>It is always better to separate error handling from the rest of the code. But you could have placed the error handling in a separate function.</p>\n\n<p>Related to this, you could have created a more meaningful loop condition in the caller than <code>while(1)</code>. Also, the presence of <code>continue</code> in a C program is always \"code smell\"; it is a dead certain indication that a loop can be rewritten in better ways. There is a very sound programming rule saying that C code should never jump non-conditionally upwards - this applies to <code>continue</code> and <code>goto</code> both. </p>\n\n<p>For example you could create a separate function for error handling the type <code>input_status</code>, which could either be part of user_input.h/user_input.c, or defined in the caller, whatever makes most sense program design-wise.</p>\n\n<pre><code>bool input_status_ok (input_status status)\n{\n if(status == INPUT_FAILED)\n {\n fprintf(stderr, \"Unable to read user input\\n\");\n exit(EXIT_FAILURE);\n return false; // never executed but might block potential compiler warnings\n }\n if (status == INPUT_TOOLONG)\n {\n fprintf(stderr, \"Entry exceeds %d characters\\n\", MAX_STR_LEN);\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>(In case of a whole lot of different error codes, we could perhaps replace the <code>if</code> chain with a <code>switch</code>.)</p>\n\n<p>With that out of the way of your loop, you can have one loop checking the errors returned by the function, and another, outer loop for checking the data contents:</p>\n\n<pre><code>bool user_cancel = false;\n\nwhile (!user_cancel)\n{\n do \n {\n status = get_user_input(\"Enter your name: \", user_input, sizeof(user_input));\n } while( !input_status_ok(status) );\n\n if (user_input[0] == CANCEL) /* user entered Ctrl+X (^x) to cancel */\n {\n fprintf(stderr, \"User cancelled\\n\");\n user_cancel = true;\n }\n}\n</code></pre>\n\n<p>We've now separated error handling of the function result from error handling of the data contents. There are no icky non-conditional branches and the code is overall easier to read.</p></li>\n<li><blockquote>\n <p>2) Would it have been better to pass a pointer to the function so that it could allocate the appropriate memory, instead of passing it a fixed array?</p>\n</blockquote>\n\n<p>No, it is always better to leave allocation to the caller when you have that option. That way, you separate memory allocation from algorithm which is better program design - meaning your function will only do its designated task, and it won't care if the memory used is allocated statically, on the stack or on the heap.</p></li>\n</ul>\n\n<hr>\n\n<blockquote>\n <p>3) Any potential issues with the program or improvements that can be made to the code?</p>\n</blockquote>\n\n<ul>\n<li><p>Avoid \"magic numbers\" - add something like <code>#define CANCEL 0x18u</code> instead of using the magic number 0x18 in the middle of the code.</p></li>\n<li><p>Never write functions with an empty parenthesis for the parameter list in C, such as <code>void flush_input()</code>. This is obsolete style and has poor type safety, since it means \"function that accepts any parameters\". C is different from C++ here, in C++ the empty parenthesis is encouraged and equivalent to <code>(void)</code>.</p></li>\n<li><p>Avoid assignment inside conditions. This is problematic for many reasons: </p>\n\n<ul>\n<li>Assignments introduce an extra side-effect that might have dependencies in relation to the right-hand side of the assignment.</li>\n<li>The classic == vs = bug. All modern compiler can check for this, but if you never write = inside conditions you don't need to worry. (Better yet, you won't have to deal with people who's been living under a rock since the 1980s and therefore still suggest that you should use the unreadable <a href=\"https://en.wikipedia.org/wiki/Yoda_conditions\" rel=\"nofollow noreferrer\">Yoda conditions</a> )</li>\n<li>Mashing as many operations as possible into a single line makes the code harder to read. </li>\n</ul>\n\n<p>Instead, simply write:</p>\n\n<pre><code>char *pNewline = strchr(user_input, '\\n');\nif (pNewline == NULL)\n</code></pre></li>\n<li><p>You should place all library <code>#includes</code> in the h file. This documents all library dependencies to the user of your code, who should only need to read the public h file.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T16:51:20.550",
"Id": "444772",
"Score": "0",
"body": "Lundin, this is absolutely fantastic, great insight. I can't wait to implement everyone of your suggestions and follow your advice. Thank you so much for all your help. I really appreciate it. And I like your comment \"...living under a rock since the 1980s...\". :-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T14:32:30.420",
"Id": "228846",
"ParentId": "227806",
"Score": "4"
}
},
{
"body": "<p><strong>Incorrect test</strong></p>\n\n<p>Not finding a <code>'\\n'</code> is a \"too long a line\" when <code>strlen(user_input) + 1 == size</code></p>\n\n<pre><code>// not quite the right test\nif ((pNewline = strchr(user_input, '\\n')) == NULL) {\n flush_input();\n return INPUT_TOOLONG;\n}\n</code></pre>\n\n<p>Not finding a <code>'\\n'</code> can occur when that was all that was left in <code>stdin</code> and end-of-file occurred without the last character as a <code>'\\n'</code>.</p>\n\n<pre><code>size_t size_used = strlen(user_input) + 1;\nif (size_used == size) {\n flush_input();\n return INPUT_TOOLONG;\n}\n</code></pre>\n\n<p>Advanced issue not handled: Not finding a <code>'\\n'</code> can occur when a <em>null character</em> was read as <code>strchr(user_input, '\\n')</code> stops at the read <em>null character</em> and not the appended one.</p>\n\n<p><strong>Spinning CPU cycles</strong></p>\n\n<p>No need to run down the length of the string to find it length. Simply test first element.</p>\n\n<pre><code>// if (strlen(user_input) == 0)\nif (user_input[0] == 0)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T02:06:55.440",
"Id": "449718",
"Score": "0",
"body": "my apologies for not getting back to you sooner, for some reason I didn't get a notification of your reply, and so I didn't see your post until today."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T02:07:21.263",
"Id": "449719",
"Score": "0",
"body": "I'm probably missing something, but I'm having trouble understanding why checking for '\\n' would fail. Can you please provide an example?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T03:29:54.257",
"Id": "449723",
"Score": "0",
"body": "@Domenic \"why checking for '\\n' would fail\" --> 1) line longer than `sizeof(user_input)` or 2) input consisted of a `'\\0'` before the `'\\n'`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-15T13:22:22.777",
"Id": "449773",
"Score": "0",
"body": "That's great, thank you for your help, I really appreciate it, cheers!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T08:30:07.253",
"Id": "229786",
"ParentId": "227806",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T20:04:06.630",
"Id": "227806",
"Score": "6",
"Tags": [
"c",
"io"
],
"Title": "Function to prompt user for input"
}
|
227806
|
<p>I'd had a hard time getting this to work. I’d like to parse a file containing data and copy this data into a struct.</p>
<p>The data file (<code>test.dat</code>) looks like this:</p>
<pre><code>1,"Tom","Smith"
2,"Peter","Perth Junior"
3,"Cathy","Johnson"
</code></pre>
<p>I use the following function.</p>
<pre><code>func parseDataFile() {
struct person {
var id: Int
var first: String
var last: String
}
var friends: [person] = []
let filePath = Bundle.main.path(forResource: "test", ofType: "dat")
guard filePath != nil else { return }
let fileURL = URL(fileURLWithPath: filePath!)
do {
let file = try String(contentsOf: fileURL, encoding: .utf8)
let arrayOfLines = file.split { $0.isNewline }
for line in arrayOfLines {
let arrayOfItems = line.components(separatedBy: ",")
let tempPerson = person(id: Int(arrayOfItems[0])!,
first: arrayOfItems[1].replacingOccurrences(of: "\"", with: ""),
last: arrayOfItems[2].replacingOccurrences(of: "\"", with: "")
)
friends.append(tempPerson)
}
} catch {
print(error)
}
}
</code></pre>
<p>I read the data into a string, split it up into an array (every line is a record). The records are copied into the struct <code>person</code>. This works fine, but I'm sure this is far from optimum.</p>
<p>I was testing a lot with <code>PropertyListDecoder().decode()</code>, but this seems to accept only dictionary formatted data (not sure though ?!).</p>
<p>Next, is it necessary to use an array record, as intermediate step, prior putting the line into a struct?</p>
<p>Last, is there no method to copy all comma separated strings to an array, without filling every property of the struct individually (like I did)?</p>
<p>Besides that, I believe that there is also a much more efficient way to get rid of the string delimiting quotes than using <code>replacingOccurrences(of:with:)</code>?</p>
<p>Any comments would be appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T08:56:53.917",
"Id": "444857",
"Score": "0",
"body": "Is this struct used outside of this function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T13:10:33.337",
"Id": "444893",
"Score": "0",
"body": "Yes it is. But this would just be to put the struct outside the function."
}
] |
[
{
"body": "<p>This</p>\n\n<pre><code>let filePath = Bundle.main.path(forResource: \"test\", ofType: \"dat\")\nguard filePath != nil else { return }\nlet fileURL = URL(fileURLWithPath: filePath!)\n</code></pre>\n\n<p>is an anti-pattern in Swift, see also <a href=\"https://stackoverflow.com/q/29717210/1187415\">When should I compare an optional value to nil?</a> on Stack Overflow. Instead of testing a value against <code>nil</code> and then force-unwrapping it, you should use optional binding:</p>\n\n<pre><code>guard let filePath = Bundle.main.path(forResource: \"test\", ofType: \"dat\") else { return }\nlet fileURL = URL(fileURLWithPath: filePath)\n</code></pre>\n\n<p>This can be further simplified by retrieving an URL in the first place, instead of getting a file path and converting that to an URL:</p>\n\n<pre><code>guard let fileURL = Bundle.main.url(forResource: \"test\", withExtension: \"dat\")\n else { return }\n</code></pre>\n\n<p>But actually this is a situation where I would prefer force-unwrapping: A missing resource file in the application bundle is a <em>programming error</em> and there is no way of recovering from that situation in a sensible way. It should be detected early during development:</p>\n\n<pre><code>let fileURL = Bundle.main.url(forResource: \"test\", withExtension: \"dat\")!\n</code></pre>\n\n<p>The same reasoning applies to reading and decoding the file:</p>\n\n<pre><code>let file = try! String(contentsOf: fileURL, encoding: .utf8)\n</code></pre>\n\n<p>Using <code>split()</code> here</p>\n\n<pre><code>let arrayOfLines = file.split { $0.isNewline }\n</code></pre>\n\n<p>is good: It creates an array, but the array elements are <em>substrings,</em> i.e. they contain references into the character storage of the original <code>file</code> string. The same method can be applied to split each line to avoid data duplication:</p>\n\n<pre><code>for line in arrayOfLines {\n let arrayOfItems = line.split(separator: \",\")\n // ...\n}\n</code></pre>\n\n<p>This</p>\n\n<pre><code>let tempPerson = Person(id: Int(arrayOfItems[0])!,\n first: arrayOfItems[1].replacingOccurrences(of: \"\\\"\", with: \"\"),\n last: arrayOfItems[2].replacingOccurrences(of: \"\\\"\", with: \"\")\n</code></pre>\n\n<p>would crash if a line has less than 3 comma-separated items, or if the first item is not an integer. However, as mentioned above, this is acceptable if the data is read from your own resource file (and not from some external resource): We can rely on the data to be well-formed.</p>\n\n<p>It is a bit difficult to read though, and I would split the single statement into parts:</p>\n\n<pre><code>let id = Int(arrayOfItems[0])!\nlet firstName = arrayOfItems[1].replacingOccurrences(of: \"\\\"\", with: \"\")\nlet lastName = arrayOfItems[2].replacingOccurrences(of: \"\\\"\", with: \"\")\nlet tempPerson = Person(id: id, first: firstName, last: lastName)\n</code></pre>\n\n<p>With respect to removing the delimiters: What you do is fine if the data file has <em>exactly</em> the format from your example, and there are no embedded quotation marks or commas in the fields. An alternative is</p>\n\n<pre><code>let firstName = String(arrayOfItems[1].dropFirst().dropLast())\nlet lastName = String(arrayOfItems[2].dropFirst().dropLast())\n</code></pre>\n\n<p>which might be slightly more efficient because it does not need bridging to <code>NSString</code>. (But I did not measure it.)</p>\n\n<p>Finally note that your code does not parse all valid CSV files. Problems are for example</p>\n\n<ul>\n<li>embedded commas: <code>4,\"Sammy\",\"Davis, Jr.\"</code></li>\n<li>embedded quotation marks: <code>5,\"John\",\"Foo\"\"Bar\"</code></li>\n<li>or embedded newlines.</li>\n</ul>\n\n<p>Before you try to implement all those features yourself I would suggest to have a look at some existing Swift CSV parsing libraries.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T15:05:15.600",
"Id": "450762",
"Score": "0",
"body": "Many thanks! I included most of it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T15:33:57.393",
"Id": "229191",
"ParentId": "227807",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "229191",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T20:31:23.687",
"Id": "227807",
"Score": "4",
"Tags": [
"parsing",
"file",
"swift",
"serialization"
],
"Title": "Parse data into an array of structs"
}
|
227807
|
<p>good afternoon.
I'm learning c++ and I made this app to "manage" lockers.
I would like you to review it please, you can find the source code at my github: <a href="https://github.com/VitalZero/lockermanager" rel="nofollow noreferrer">https://github.com/VitalZero/lockermanager</a></p>
<p>The app is made up by 3 main clases:</p>
<ul>
<li>CDocument: Takes care of file input/output </li>
<li>CLockers: The lockers itself, stores it's info</li>
<li>CLockManager: Takes care of the lockers and the document</li>
</ul>
<p>Also, there's a "helper" class I made to show the functionality, SimpleMenu, that is not part of the main "program"</p>
<p>To use it as is, just create an instance, feed the file name and thats it:</p>
<pre><code>#include "CLockManager.h"
#include "SimpleMenu.h"
int main()
{
CLockManager manager("database.txt");
SimpleMenu menu(manager);
menu.ShowMenu();
return 0;
}
</code></pre>
<h2>File CDocument.h:</h2>
<pre><code>#ifndef CDOCUMENT_H_
#define CDOCUMENT_H_
/*
* CDocument.h
* It is used by CLockManager.
* Just used to load and save data from a file using a vector of CLockers
* CLockers overloads stream operators >> and <<
* Just feed a vector of CLockers and it's all good!
*/
#include <fstream>
#include <string>
#include <vector>
#include "CLockers.h"
class CDocument{
public:
CDocument() = delete;
CDocument(const std::string& path_in)
:
path(path_in)
{
}
~CDocument()
{
if(inFile.is_open())
inFile.close();
}
bool SaveData(std::vector<CLockers>& lockers);
bool LoadData(std::vector<CLockers>& lockers);
private:
std::fstream inFile;
std::string path;
};
#endif /* CDOCUMENT_H_ */
</code></pre>
<h2>File CDocument.cpp</h2>
<pre><code>#include "CDocument.h"
bool CDocument::SaveData(std::vector<CLockers>& lockers)
{
inFile.open(path.c_str(), std::ios_base::out | std::ios_base::trunc);
if(inFile.is_open())
{
for(unsigned int i = 0; i < lockers.size(); ++i)
{
inFile << lockers.at(i);
}
inFile.close();
return true;
}
return false;
}
bool CDocument::LoadData(std::vector<CLockers>& lockers)
{
inFile.open(path.c_str(), std::ios_base::in);
if(inFile.is_open())
{
CLockers tmp;
lockers.clear();
while( (inFile.good()) && (inFile >> tmp) ) // here is the problem from CLockers, even though is being checked in here
{ // it gives another extra loop after the fail bit is set
lockers.push_back(tmp);
}
inFile.close();
return true;
}
else
{
// Probably move this out to menu.cpp
// interaction only should occur outside the class
std::cout << "\tThe file "
<< path << " doesn't exist or can't be opened.\n";
std::cout << "Do you want to create it? y/n: ";
std::string stringAnswer;
std::getline(std::cin, stringAnswer);
if( (stringAnswer == "y") || (stringAnswer == "Y") )
{
inFile.open(path, std::ios_base::out | std::ios_base::trunc);
inFile.close();
return true;
}
}
return false;
}
</code></pre>
<p>Thank you in advance! and any suggestion/correction is highly appreciated!. Greetings.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T21:15:44.750",
"Id": "443663",
"Score": "2",
"body": "While it's reasonable to add other code in a link to provide more context to tell us more about the usage of the code under review, you really need to put the code to be reviewed into the question. The question needs to contain enough that it remains a complete and meaningful question even when any external links die."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T21:32:06.157",
"Id": "443665",
"Score": "0",
"body": "Thank you!, I added some more relevant code. I don't know of I can include the rest as is a lot of code (for me :) )."
}
] |
[
{
"body": "<h2>Close on destruction</h2>\n\n<p>You shouldn't need to explicitly close your file member on destruction. Since it's a safe variable and not an unsafe pointer, <code>fstream</code>'s own destructor will be called and the file will be closed.</p>\n\n<h2>Const members</h2>\n\n<p>You should make <code>path</code> <code>const</code>, since it doesn't change over the course of the object's lifetime.</p>\n\n<h2>File object scope</h2>\n\n<p><code>inFile</code> is not opened in the constructor, and it's always used in open/close pairs in your methods. That means that it shouldn't be a member at all; just use local variables. One benefit is that you won't need to explicitly close those files; when the variable goes out of scope the file will be closed.</p>\n\n<h2>Error handling</h2>\n\n<p>If you want to drink more of the OOP kool-aid, you shouldn't be using boolean return values, which is a pattern inherited from C code. Instead, your methods would be <code>void</code>-typed, and you'd throw an exception if something goes wrong.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T17:28:29.303",
"Id": "444775",
"Score": "0",
"body": "Hi!, thank you for your comments, I'll take into accout what you say, specially for fstream's objects. Now, as for the error handling. Most likely I'm using boolean values so I can return to some menu instead of exiting the program. Havent practiced exceptions that much, I'm not really sure if I can use that as handling boolean values in the functions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T00:09:06.553",
"Id": "227819",
"ParentId": "227809",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227819",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T21:01:14.500",
"Id": "227809",
"Score": "2",
"Tags": [
"c++",
"object-oriented",
"file"
],
"Title": "Locker Manager app c++"
}
|
227809
|
<p>I have completed this mockup eCommerce app using Javascript. This version can add products into a shopping cart and automatically calculate the order summary in the shopping cart. It can also delete one item and all items in the shopping cart.</p>
<p>Checkout and login functions are not included.</p>
<p>Appreciate all comments and code review especially on Javascript and coding style and best practices. Thanks a lot in advance.</p>
<hr>
<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>// Initialization of data and page variables - start.
// For actual system, get data from database via API call either in JSON format.
var productList = [
{ id: 101, product: "Logitech Mouse", unitprice: 45.0 },
{ id: 102, product: "Logitech Keyboard", unitprice: 50.0 },
{ id: 103, product: "HP Mouse", unitprice: 35.0 }
];
var cart = [];
cart.length = 0;
$shoppingCartContainer = document.getElementById("shoppingCartContainer");
$clearAll = document.getElementById("clearAll");
$shoppingCart = document.getElementById("shoppingCart");
$totalCartItems = document.getElementById("totalCartItems");
$summary = document.getElementById("summary");
// Initialization of data and page variables - end.
// Functions - start -------------------------------------
const createCartHTMLElements = object => {
// Check type
if (typeof object !== "object") return false;
// Start our HTML
var html = "<table><tbody>";
// Loop through members of the object
debugger;
object.forEach(function(item) {
html += `<tr class=productData><td class="productName">${item.product}</td>\
<td class="productPrice">${item.unitprice.toFixed(2)}</td>\
<td class="quantityProduct">\
<button class="plus-btn" data-id="${item.id}">+</button>\
<label class="quantity">${item.quantity}</label>\
<button class="minus-btn" data-id="${item.id}">-</button>\
</td>\
<td class="total">${item.total.toFixed(2)}</td>\
<td class="deleteProduct"><i class="fa fa-remove del" data-id="${
item.id
}"></i></td>\
</tr>`;
});
// Finish the table:
html += "</tbody></table>";
// Return the table
return html;
};
const updateQuantity = (operation, productId, tr) => {
// Update the quantity in UI
let $quantity = tr.find(".quantity");
let n = $quantity.html();
let i;
switch (operation) {
case "plus":
i = parseInt(n) + 1;
break;
case "minus":
i = parseInt(n) - 1;
if (i < 0) i = 0; // prevent negative quantity
if (i == 0) {
// Duplicate code with delete function
cart = cart.filter(function(el) {
return el.id != productId;
});
if (cart.length === 0) {
$shoppingCart.innerHTML = "";
debugger;
$clearAll.style.display = "none";
$summary.style.display = "none";
}
updateCartCount();
updateOrderSummary();
tr.closest("tr").remove();
}
break;
}
$quantity.html(i);
// Update the total price in UI
let $price = tr.find(".productPrice");
let price = parseFloat($price.html());
let $total = tr.find(".total");
let total = i * price;
$total.html(total.toFixed(2));
// Update the quantity and total in list object
// Find index of specific object using findIndex method.
let objIndex = cart.findIndex(obj => obj.id == productId);
if (objIndex >= 0) {
// Update object's name property.
cart[objIndex].quantity = i;
cart[objIndex].total = total;
updateOrderSummary();
}
};
const populateProducts = arrOfObjects => {
// Start our HTML
var html = "";
// Loop through members of the object
arrOfObjects.forEach(function(item) {
html += `<div class="column"><div class="card">\
<h2>${item.product}</h2>
<p class="price">RM ${item.unitprice.toFixed(2)}</p>
<p><button class=AddToCart data-id="${
item.id
}">Add to Cart</button></p>\
</div></div>`;
});
return html;
};
const updateOrderSummary = () => {
document.getElementById("totalItem").innerHTML = cart.length + " item";
const subTotal = cart
.reduce(function(acc, obj) {
return acc + obj.total;
}, 0)
.toFixed(2);
const shippingFee = 10;
document.getElementById("subTotal").innerHTML = subTotal;
document.getElementById("shippingFee").innerHTML = shippingFee.toFixed(2);
document.getElementById("total").innerHTML = (
parseInt(subTotal) + shippingFee
).toFixed(2);
};
const updateCartCount = () => {
$totalCartItems.innerHTML = cart.length;
};
// Functions - End -------------------------------------
// Event listener - start -------------------------------------
const CreateAddToCartEventListener = () => {
var addToCart = document.getElementsByClassName("AddToCart");
updateCartCount();
Array.prototype.forEach.call(addToCart, function(element) {
element.addEventListener("click", function() {
debugger;
// Filter the selected "AddToCart" product from the ProductList list object.
// And push the selected single product into shopping cart list object.
productList.filter(prod => {
if (prod.id == element.dataset.id) {
debugger;
// Update the quantity in list object
// Find index of specific object using findIndex method.
let objIndex = cart.findIndex(
obj => obj.id == parseInt(element.dataset.id)
);
if (objIndex >= 0) {
// Old item found
cart[objIndex].quantity = cart[objIndex].quantity + 1;
cart[objIndex].total = cart[objIndex].quantity * prod.unitprice;
} else {
// For new item
prod.quantity = 1;
prod.total = prod.unitprice;
cart.push(prod);
}
$shoppingCart.innerHTML = createCartHTMLElements(cart);
CreateDeleteEventListener();
$totalCartItems.style.display = "block";
$clearAll.style.display = "block";
$summary.style.display = "block";
updateCartCount();
updateOrderSummary();
return;
}
});
});
});
};
const CreateDeleteEventListener = () => {
var del = document.getElementsByClassName("del");
Array.prototype.forEach.call(del, function(element) {
element.addEventListener("click", function() {
// Duplicate code with minus quantity function
// When quantity is zero, it will delete that item
cart = cart.filter(function(el) {
return el.id != element.dataset.id;
});
if (cart.length === 0) {
$shoppingCart.innerHTML = "";
debugger;
$clearAll.style.display = "none";
$summary.style.display = "none";
}
updateCartCount();
updateOrderSummary();
element.closest("tr").remove();
});
});
};
$(document.body).on("click", ".plus-btn", function() {
let productId = $(this).attr("data-id");
let $tr = $(this).closest("tr");
updateQuantity("plus", productId, $tr);
});
$(document.body).on("click", ".minus-btn", function() {
let productId = $(this).attr("data-id");
let $tr = $(this).closest("tr");
updateQuantity("minus", productId, $tr);
});
$clearAll.addEventListener("click", function() {
$shoppingCart.innerHTML = "";
cart.length = 0;
$clearAll.style.display = "none";
$summary.style.display = "none";
updateOrderSummary();
updateCartCount();
});
document.getElementById("cartIcon").addEventListener("click", function() {
if ($shoppingCartContainer.style.display === "none") {
$shoppingCartContainer.style.display = "block";
} else {
$shoppingCartContainer.style.display = "none";
}
});
window.addEventListener("load", function() {
$shoppingCartContainer.style.display = "none";
window.setTimeout(function() {}, 1000); // prevent flickering
document.getElementById("productRow").innerHTML = populateProducts(
productList
);
CreateAddToCartEventListener();
});
// Event listener - end -------------------------------------</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.card {
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
margin: auto;
text-align: center;
font-family: arial;
width: 18em;
}
.price {
color: grey;
font-size: 1.5em;
}
.card button {
border: none;
outline: 0;
padding: 12px;
color: white;
background-color: #000;
text-align: center;
cursor: pointer;
width: 100%;
font-size: 1em;
}
.card button:hover {
opacity: 0.7;
}
.productContainer {
margin: 15px;
}
.summaryDetails {
width: 100px;
text-align: right;
}
#productRow {
display: flex;
flex-wrap: wrap;
}
.column {
flex: 1;
margin-top: 12px;
}
@media (max-width: 1333px) {
.column {
flex-basis: 33.33%;
}
}
@media (max-width: 1073px) {
.column {
flex-basis: 33.33%;
}
}
@media (max-width: 815px) {
.column {
flex-basis: 50%;
}
}
@media (max-width: 555px) {
.column {
flex-basis: 100%;
}
}
#header {
width: 100%;
display: flex;
justify-content: space-between;
height: 50px;
}
#left,
#right {
width: 30%;
padding: 10px;
padding-right: 30px;
}
#right {
text-align: right;
position: relative;
}
#main {
max-width: 1000px;
border: 1px solid black;
margin: 0 auto;
position: relative;
}
#shoppingCartContainer {
width: 400px;
background-color: lightyellow;
border: 1px solid silver;
margin-left: auto;
position: absolute;
top: 50px;
right: 0;
padding: 10px;
}
.fa-shopping-cart {
font-size: 36px;
color: blue;
cursor: pointer;
}
.fa-remove {
font-size: 24px;
color: red;
cursor: pointer;
}
#totalCartItems {
margin: 0px 0px -2px -7px;
color: red;
padding: 2px;
border-radius: 25px;
width: 10px;
margin-left: auto;
font-size: 1em;
position: absolute;
}
.plus-btn img {
margin-top: 2px;
}
tr.productData,
td.productName,
td.productPrice,
td.quantityProduct,
td.price,
td.deleteProduct {
padding: 10px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
/>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div id="main">
<div id="header">
<div id="left">Login as Joe Doe, <a href="">Logout</a></div>
<div id="right">
<i id="cartIcon" class="fa fa-shopping-cart"> </i>
<span id="totalCartItems"></span>
</div>
</div>
<hr />
<div class="productContainer">
<div id="productRow"></div>
</div>
<div id="shoppingCartContainer">
<div id="shoppingCart"></div>
<button id="clearAll">Clear Cart</button>
<div id="summary">
<hr />
<h3>Order Summary</h3>
<table>
<tr>
<td>Subtotal (<span id="totalItem"></span>)</td>
<td class="summaryDetails"><span id="subTotal"></span></td>
</tr>
<tr>
<td>Shipping Fee</td>
<td class="summaryDetails"><span id="shippingFee"></span></td>
</tr>
<tr>
<td>Total</td>
<td class="summaryDetails"><span id="total"></span></td>
</tr>
</table>
<button>Proceed to checkout</button>
</div>
</div>
</div>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="app.js"></script></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p><strong><em>I am by no means a <code>javascript/html/css</code> developer, just somethings I noticed, and some things I would recommend as a customer. I invite someone who is more experienced with javascript to review this code, as I rarely touch on it in this review.</em></strong></p>\n\n<h1>Tags</h1>\n\n<p>Unless you're using <code>XHTML</code>, which it doesn't look like it, <code><link></code> does not need to be closed (<code>/></code>), as it's a \"self closing\" tag. The same goes with the <code><hr></code> tag and the <code><meta></code> tag.</p>\n\n<h1>Scaling</h1>\n\n<p>I would recommend putting this piece of html in the header as well:</p>\n\n<pre><code><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n</code></pre>\n\n<p>This is used to set styles and other website attributes to render the site on different devices. This tag decides how to scale the website. If I open the website on my computer, it will scale accordingly. If I open the website on my phone, a much smaller screen (at the time of writing, you never know), it will scale according to that smaller screen size.</p>\n\n<h1>Customer Perspective</h1>\n\n<p>Here are some things I noticed, if I was a customer on this website:</p>\n\n<ul>\n<li><strong>Shopping Cart</strong>: Let's say I wanted to buy two <code>Logitech Mouse</code>, one to use and another one as a backup if the first one craps out. I press the button twice, and check the cart, only to see one item in my cart! The cart should display how many <em>total</em> items are in the cart, regardless if they are the same item or not. With the way it's set up now, someone can keep pressing the <code>Add to Cart</code> button, not knowing at checkout they are buying <strong>8</strong> mice! Of course they'll notice the price, hopefully...</li>\n<li><strong>Description</strong>: I would have a short description about the item, maybe even being redirected to this description after pressing <code>Add to Cart</code>. If you go down this route, consider changing the name of the button to <code>View Product</code> or something along those lines. I realize that this is a mockup, but it's something to consider.</li>\n<li><strong>Joe Doe?</strong>: I see that you have a user already signed in, and a <code>logout</code> button available. If you intend on having users log in and buying these items, you have a whole other beast to conquer. <a href=\"https://www.formget.com/jquery-login-form/\" rel=\"nofollow noreferrer\">Here</a> is a simple login form using jQuery you might want to take a look at.</li>\n<li><strong>Pizzazz</strong>: When creating a website, for any reason, it should be inviting. As it stands, your website is just black and white. Add a cool background image, some different colors, something! Just having a little color can go a long way. Even just a little color and having images for your products can make your website seem professional. Take a look at <a href=\"https://www.amazon.com/\" rel=\"nofollow noreferrer\">Amazon</a>. Without the images and adds, their website is very simple. You don't need crazy colors and other out-of-this-world imagery to attract users. A splash of color here and there can do wonders.</li>\n</ul>\n\n<h1>Javascript</h1>\n\n<p>My <strong>one</strong> thing on <code>javascript</code>, that I notice in some <code>java</code>/<code>c#</code> programs too.</p>\n\n<pre><code>// Check type\nif (typeof object !== \"object\") return false;\n</code></pre>\n\n<p>I'm sorry, but I <em>can't stand</em> not having brackets around one line if statements. It makes it look so separated from everything else, and just doesn't look appealing to me. In my opinion, this code should look like</p>\n\n<pre><code>//Check type\nif (typeof object !== \"object\") {\n return false;\n}\n</code></pre>\n\n<p>Yeah, it takes up two more lines, but it's <em>two bytes</em> more, and it makes it consistent with all the bracketed code around it. Those are my two cents on your <code>javascript</code>.</p>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web\" rel=\"nofollow noreferrer\">Mozilla Developer Network</a>, a comprehensible, usable, and accurate resource for everyone developing on the Open Web (thanks to <a href=\"https://codereview.stackexchange.com/users/120114/s%E1%B4%80%E1%B4%8D-on%E1%B4%87%E1%B4%8C%E1%B4%80\">Sᴀᴍ Onᴇᴌᴀ</a> for pointing this resource out.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T15:45:48.013",
"Id": "445032",
"Score": "2",
"body": "I know it has likely improved a bit in recent years but a while back I had cited w3schools and been pointed to [w3fools.com](https://www.w3fools.com/). While [MDN](http://developer.mozilla.org/) is continually a work in progress as well, it is deemed a better resource."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T16:53:35.900",
"Id": "445044",
"Score": "2",
"body": "@SᴀᴍOnᴇᴌᴀ Thanks for the update, will update answer accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T17:19:25.990",
"Id": "445049",
"Score": "2",
"body": "cool - nice update, however the link to MDN points to the archive from 2011... perhaps a better URL would be https://developer.mozilla.org/ or https://developer.mozilla.org/en-US/docs/Web"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T20:45:36.380",
"Id": "445073",
"Score": "2",
"body": "@SᴀᴍOnᴇᴌᴀ Updated again :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T01:42:09.367",
"Id": "228936",
"ParentId": "227820",
"Score": "4"
}
},
{
"body": "<h2>General feedback</h2>\n\n<p>Overall this code isn’t bad but could be simplified quite a bit. The biggest thing I noticed is that jQuery is used for a few things but could be used a lot more - e.g. selecting DOM elements and manipulating them, adding event handlers, etc. There are some who believe jQuery isn't needed (see sites like <a href=\"http://youmightnotneedjquery.com/\" rel=\"nofollow noreferrer\">youmightnotneedjquery.com</a>. Some of the advice below comes after I read <a href=\"https://ilikekillnerds.com/2015/02/stop-writing-slow-javascript/\" rel=\"nofollow noreferrer\">this article <em>Stop Writing Slow Javascript</em></a> - I know it is from a few years ago but the concepts are still relevant. It also touches on the usage of jQuery in todays web.</p>\n\n<p>If you really want to clean things up, run your code through a linter like eslint, jshint, etc. One of the first warnings will likely be to include <code>\"use strict\"</code> at the top of the JavaScript.</p>\n\n<h2>Targeted feedback</h2>\n\n<h3>JS</h3>\n\n<ul>\n<li><strong>functions doing more than necessary?</strong> I see the function <code>CreateAddToCartEventListener()</code> calls <code>updateCartCount()</code>. Is that really necessary when adding an event listener?</li>\n<li><strong>scoping and DOM ready</strong> wrap JS in a DOM ready callback (I.e. <a href=\"https://api.jquery.com/ready\" rel=\"nofollow noreferrer\"><code>$(function() {})</code></a> - formerly <code>.ready()</code>) or else an <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/IIFE\" rel=\"nofollow noreferrer\">IIFE</a> to limit scope of variables</li>\n<li><p><strong>utilize jQuery more</strong> As mentioned above, it can be used a lot more - e.g. instead of:</p>\n\n<blockquote>\n<pre><code> $clearAll = document.getElementById(\"clearAll\");\n</code></pre>\n</blockquote>\n\n<p>Just select it with the jQuery function:</p>\n\n<pre><code>$clearAll = $(“#clearAll”);\n</code></pre>\n\n<p>Note that such a variable would then contain a jQuery collection and not a single DOM reference anymore, so with that one can call jQuery methods on the collection like <a href=\"https://api.jquery.com/hide/\" rel=\"nofollow noreferrer\"><code>.hide()</code></a> and <a href=\"https://api.jquery.com/show\" rel=\"nofollow noreferrer\"><code>.show()</code></a></p>\n\n<blockquote>\n<pre><code>$clearAll.style.display = \"none\";\n</code></pre>\n</blockquote>\n\n<p>Can be changed to:</p>\n\n<pre><code>$clearAll.hide();\n</code></pre>\n\n<p>Also I see things like this:</p>\n\n<blockquote>\n<pre><code>const CreateAddToCartEventListener = () => {\n var addToCart = document.getElementsByClassName(\"AddToCart\");\n updateCartCount();\n Array.prototype.forEach.call(addToCart, function(element) {\n element.addEventListener(\"click\", function() {\n</code></pre>\n</blockquote>\n\n<p>Why not simplify the event handler registration to the jQuery syntax, like the code already does for other elements (e.g. with class name <code>plus-btn</code>, <code>minus-btn</code>). Instead of looping through all elements with the class name <code>.AddToCard</code> like the code does above, just use this:</p>\n\n<pre><code>$(document.body).on(\"click\", \".AddToCart\", function() {\n</code></pre>\n\n<p>or event simpler with the <a href=\"https://api.jquery.com\" rel=\"nofollow noreferrer\"><code>.click()</code></a> shortcut method:</p>\n\n<pre><code>$(document).click('.AddToCart', function() {\n</code></pre></li>\n<li><p><strong>global variables</strong> - any variable not declared with <code>var</code> (inside a function), <code>let</code> or <code>const</code> e.g. <code>$shoppingCartContainer</code> will be stored as a global variable - on <code>window</code>. In a small application that likely wouldn’t be an issue but it is a good habit to avoid those - especially when you get into a larger application and the same name is used to hold different data. </p></li>\n<li><strong>variables starting with dollar symbol</strong> when using jQuery, that can be a sign that a variable represents a jQuery collection, so if <code>$shoppingCartContainer</code> is not a jQuery collection, somebody trying to extend your code might think it is a jQuery collection and use jQuery methods on it, which would lead to an error. See <a href=\"https://stackoverflow.com/a/553734/1575353\">more in this post</a>.</li>\n<li><strong>default to using <code>const</code></strong> for variables that don’t need to be reassigned - e.g. <code>$quantity</code> and then switch to <code>let</code> if it is determined that reassignment is necessary. </li>\n<li><p><strong>setting length of new array to zero</strong> - when would the length of a new array be something other than zero?</p>\n\n<blockquote>\n<pre><code>var cart = [];\ncart.length = 0;\n</code></pre>\n</blockquote></li>\n<li><p><strong>use spread operator</strong> - since <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged 'ecmascript-6'\" rel=\"tag\">ecmascript-6</a> features like arrow operators are used then instead of calling: </p>\n\n<blockquote>\n<pre><code>Array.prototype.forEach.call(addToCart, function(element) {\n</code></pre>\n</blockquote>\n\n<p>The collection can be put into an array with the spread operator:</p>\n\n<pre><code>[...addToCart].forEach( function(element) {\n</code></pre></li>\n<li><p>I see this line</p>\n\n<blockquote>\n<pre><code>window.setTimeout(function() {}, 1000); // prevent flickering\n</code></pre>\n</blockquote>\n\n<p>but I am not convinced that calling an empty function after 1 second will prevent flickering. How did you reach that conclusion?</p>\n\n<p><strong>EDIT</strong>: It might be better to wait for the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event\" rel=\"nofollow noreferrer\"><code>DOMContentLoaded</code></a> instead of the <code>load</code> event before starting to interact with the DOM. And as I mentioned above, the <a href=\"https://api.jquery.com/ready/\" rel=\"nofollow noreferrer\">jQuery DOM ready function</a> is available for this. </p>\n\n<p>If the flickering you are seeing is the shopping cart container, then add <code>style=\"display: none\"</code> to that HTML element instead of waiting for the DOM to be loaded to hide it. Then it can still be displayed dynamically via JS. If that was in the CSS then it would make displaying it more challenging. </p></li>\n</ul>\n\n<h3>HTML</h3>\n\n<ul>\n<li><strong>The <code><script></code> tags</strong> are outside the <code><html></code> tags. They are typically placed in the <code><head></code> or at the end of the <code><body></code> tag. For more information on this, <a href=\"https://stackoverflow.com/a/24070373/1575353\">refer to this post</a>.</li>\n</ul>\n\n<h3>CSS</h3>\n\n<ul>\n<li><p><strong>multiple max-width media queries with same style</strong> I see the following rulesets:</p>\n\n<blockquote>\n<pre><code>@media (max-width: 1333px) {\n .column {\n flex-basis: 33.33%;\n }\n}\n\n@media (max-width: 1073px) {\n .column {\n flex-basis: 33.33%;\n }\n}\n</code></pre>\n</blockquote>\n\n<p>The second ruleset is overriding the first, but it doesn't appear to do anything different.</p></li>\n<li><p><strong>excess margin style</strong>: <code>#totalCartItems</code> has <code>margin</code> with top, right, bottom and left, but then there is a separate style for <code>margin-left: auto</code>. Why not move that <code>auto</code> into the first <code>margin</code> style if it is needed?</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T02:27:48.713",
"Id": "445216",
"Score": "2",
"body": "Thanks for the great code review. I managed to refactor my code accordingly. \" I am not convinced that calling an empty function after 1 second will prevent flickering\". I haven't found a better solution yet. Thus, I use the 1 second hack as a temporary solution :). About the register event handler, I can't understand what you mean."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T18:53:46.387",
"Id": "445841",
"Score": "3",
"body": "You're welcome. I have edited my answer. Does that provide more detail?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T15:36:21.523",
"Id": "228978",
"ParentId": "227820",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "228978",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T00:10:55.173",
"Id": "227820",
"Score": "7",
"Tags": [
"javascript",
"jquery",
"ecmascript-6",
"event-handling",
"e-commerce"
],
"Title": "eCommerce Mockup App in JS"
}
|
227820
|
<p>I've written this simplified code to compute Pi for educational/demonstration purposes.</p>
<p>These methods are based upon the generalized means: see <a href="https://maths-people.anu.edu.au/~brent/pd/JBCC-Brent.pdf" rel="noreferrer">a presentation on Pi and the AGM.</a></p>
<p>Archimedes' method gives linear convergence, which means you get two extra bits of precision per iteration.</p>
<p>Gauss's method gives quadratic convergence, which means your precision doubles every iteration.</p>
<p>One can wrap these methods in timers or print current results to see how they converge.</p>
<p>Archimedes' method could have been used to disprove a millennia of false claims about Pi. Alas, history.</p>
<pre><code>import decimal
def pi_arc():
"""Archimedes c. ~230 B.C.E."""
a, b = D(3).sqrt() / D(6), D(1) / D(3)
pi = 0
while True:
an = (a + b) / 2
b = (an * b).sqrt()
a = an
piold = pi
pi = 2 / (a + b)
if pi == piold:
break
return D(str(pi)[:-3])
def pi_agm():
"""Gauss AGM Method c. ~1800 A.D. """
a, b, t = 1, D(0.5).sqrt(), 1 / D(2)
p, pi, k = 2, 0, 0
while True:
an = (a + b) / 2
b = (a * b).sqrt()
t -= p * (a - an)**2
a, p = an, 2**(k + 2)
piold = pi
pi = ((a + b)**2) / (2 * t)
k += 1
if pi == piold:
break
return D(str(pi)[:-3])
if __name__ == "__main__":
prec = int(input('Precision for Pi: '))
"""Plus 3 for error"""
decimal.getcontext().prec = prec + 3
D = decimal.Decimal
print(pi_arc())
print(pi_agm())
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T00:46:21.290",
"Id": "443684",
"Score": "0",
"body": "Is there a specific part of the code you'd like us to review? It's unclear if you'd like this to be reviewed or if you just want to post this for educational purposes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T01:13:19.663",
"Id": "443685",
"Score": "8",
"body": "All? Open to all suggestions to optimize or make more presentable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T16:55:06.300",
"Id": "444773",
"Score": "0",
"body": "Asking out of curiosity: what are *a millenia of false claims about Pi*?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T18:15:24.817",
"Id": "444782",
"Score": "0",
"body": "From the article: 'David Bailey has observed that there are at least eight\nrecent papers in the “refereed” literature claiming that\nπ = (14 −√2)/4 = 3.1464 · · · , and another three claiming that\nπ = 17 − 8√3 = 3.1435 · · · .'"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T22:38:17.853",
"Id": "444801",
"Score": "0",
"body": "@TheHoyt: That's really weird, since both are worse approximations than 22/7. Surely 22/7 should suffice for everyone's \"wrong π\" needs!"
}
] |
[
{
"body": "<h2>Convergence testing</h2>\n\n<pre><code> if pi == piold:\n break\n</code></pre>\n\n<p>This is not usually done, because float equality has a lot of gotchas. In this case it's possible due to the numbers being Decimal, but if you need to move away from Decimal you're going to encounter issues.</p>\n\n<p>Usually, convergence is measured as the absolute error decreasing below a chosen epsilon, a very small positive number. One advantage is that if you start checking for convergence to epsilon, your code will be compatible with arbitrary-precision math, where the two numbers will never equal each other exactly but you still need sane termination criteria.</p>\n\n<h2>Formatting/rounding</h2>\n\n<pre><code>D(str(pi)[:-3])\n</code></pre>\n\n<p>This looks troublesome. You're converting a float to a string, and then selecting a certain number of fixed digits. Don't do this. Instead, just use the built-in <code>round</code>, which works with <code>Decimal</code>s just fine.</p>\n\n<h2>Order of Operations</h2>\n\n<pre><code>pi = ((a + b)**2) / (2 * t)\n</code></pre>\n\n<p>Exponentiation takes precedence over division, so you can drop the first pair of outer parens.</p>\n\n<h2>Import assignment</h2>\n\n<pre><code>D = decimal.Decimal\n</code></pre>\n\n<p>Usually you shouldn't do this, and instead you should use normal import syntax:</p>\n\n<pre><code>from decimal import Decimal as D\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T03:33:51.983",
"Id": "444689",
"Score": "3",
"body": "Excellent points, I will be implementing everything you have stated. The decimal equality is a luxury I'm taking here in Python to demonstrate a certain aspect of the AGM, but I agree with you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T19:36:06.143",
"Id": "444793",
"Score": "1",
"body": "I would recommend https://docs.python.org/3/library/math.html#math.isclose specifically for convergence testing. It works for (mixtures of) all the types I've used in python, and relative tolerance is also a nice option. (especially if you're worried about things changing to floats at some point, isclose \"just works\" with any combination of floats and decimals as the values or as the tolerances)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T02:38:31.000",
"Id": "228823",
"ParentId": "227821",
"Score": "14"
}
},
{
"body": "<p>A few more points:</p>\n\n<ul>\n<li><p>The precision of the decimal context is set at the top-level of the code, while the result of computation is rounded within the two methods. That is not good because in this case the methods actually have no knowledge about how the precision is adjusted based on user input. These two operations should be handled on the same level: either both on the top-level or both on the method level (the precision value needs to be passed down as a function argument). I personally prefer the latter option.</p></li>\n<li><p>Despite the precision of the decimals are increased from user input, for convergence testing that might not be necessary. For example, if a precision value of three is requested, checking <code>abs(pi_old - pi) < Decimal(\"0.001\")</code> seems enough to me (since the <span class=\"math-container\">\\$\\pi>1\\$</span>, only two digits after decimal points are needed).</p></li>\n<li><p>Convergence testing can be done more cleanly using <a href=\"https://docs.python.org/3/library/math.html#math.isclose\" rel=\"nofollow noreferrer\"><code>math.isclose</code></a> (thanks to @StevenJackson's comment)</p></li>\n<li><p>Keeping the full class name <code>Decimal</code> rather than shortening it to a single-letter name <code>D</code> improves code readability. Nowadays most IDEs can autocomplete long names therefore using short names does really save much time.</p></li>\n<li><p>Multiple classes / methods can be imported in the one statement.</p>\n\n<pre><code>from decimal import Decimal, getcontext\n</code></pre></li>\n<li><p>Since the code is for demonstration purpose, it might be better to keep it as close to the presented pseudocode / description as possible. For example, a more direct implementation of the core loop of the Gauss-Legendre algorithm on page 31 of the linked PDF could be like the following.</p>\n\n<pre><code>from itertools import count\nfrom math import isclose\n\na = Decimal(1)\nb = Decimal(0.5).sqrt()\ns = 1 / Decimal(4)\npi = 0\nmin_delta = Decimal(\"0.001\") # minimum difference between steps to continue loop\n\nfor n in count(): # Use itertools.count to generate an infinite sequence starting from 0\n a_next = (a + b) / 2\n pi_old = pi\n pi = a_next ** 2 / s\n if isclose(pi, pi_old, rel_tol=0, abs_tol=min_delta):\n break\n\n b = (a * b).sqrt()\n s -= 2**n * (a - a_next)**2\n a = a_next\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T19:38:55.600",
"Id": "444794",
"Score": "0",
"body": "I would always recommend https://docs.python.org/3/library/math.html#math.isclose for convergence testing. It handles comparisons even across types cleanly and there's not ever a compelling reason not to use it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T19:52:41.220",
"Id": "444795",
"Score": "0",
"body": "@StevenJackson Thanks. I've updated my answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T13:17:08.060",
"Id": "228842",
"ParentId": "227821",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "228823",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T00:34:42.623",
"Id": "227821",
"Score": "13",
"Tags": [
"python",
"performance",
"algorithm",
"python-3.x",
"numerical-methods"
],
"Title": "Mean π: Archimedes vs. Gauss - π computation through generalized means"
}
|
227821
|
<p>This is my first smart contract, and it isn't finished yet, but the remaining bits are complicated enough that I'd like to make sure I'm on the right track first. My concerns are:</p>
<ul>
<li>At line 117, is the missing division an actual division or a modular multiplicative inverse? (BigNumber provides neither; the <code>bn_div</code> method is just for <em>verifying</em> a division.) I'm not clear on what the universe of discourse is for the elliptic curve.</li>
<li>Should any other operations be modular that aren't?</li>
<li>I've already moved the square-root function and a coprimality test off-chain (hence the 7th through 10th parameters to <code>submitPrime</code>). Any other parts that can easily be moved off-chain and verified?</li>
<li>The part of <code>ellipticCurveCheck</code> that I've written so far doesn't use B at all. Should it?</li>
<li>All the BigNumber method names are qualified with the library name, which makes the code kind of unwieldy. Does Solidity have an equivalent of Java's <code>import static</code> that I can use instead? Googling doesn't turn anything up.</li>
</ul>
<p>NB: BigNumber is my personal fork, updated to work with Solidity 0.5.x and with the tests run against 0.5.8.</p>
<pre><code>pragma experimental ABIEncoderV2;
pragma solidity >=0.5.11 <0.6;
import "https://raw.githubusercontent.com/Pr0methean/solidity-BigNumber/2bddf04709f0e1ed649b37b5533264cef8c5cbfe/contracts/BigNumber.sol";
contract PrimeNumberBounty {
BigNumber.instance ZERO = BigNumber._new(hex"00",false,false);
BigNumber.instance ONE = BigNumber._new(hex"01",false,false);
BigNumber.instance TWO = BigNumber._new(hex"02",false,false);
BigNumber.instance THREE = BigNumber._new(hex"03",false,false);
BigNumber.instance FOUR = BigNumber._new(hex"04",false,false);
BigNumber.instance TWENTY_SEVEN = BigNumber._new(hex"1B",false,false);
BigNumber.instance BOUNTY_THRESHOLD = BigNumber._new(hex"010000000000000000000000000000000000000000000000000000000000000000",false,false);
mapping(bytes => BigNumber.instance) knownPrimes;
uint256 constant public bountyAmount = 1e12 wei;
address payable owner;
constructor(bytes32) public {
owner = msg.sender;
knownPrimes[TWO.val] = TWO;
}
function selfDestruct() public {
require(msg.sender == owner, 'Only the owner can call this');
selfdestruct(owner);
}
function square(BigNumber.instance memory input) private view returns (BigNumber.instance memory) {
return BigNumber.bn_mul(input, input);
}
function cube(BigNumber.instance memory input) private view returns (BigNumber.instance memory) {
return BigNumber.bn_mul(square(input), input);
}
function mapContains(
mapping(bytes => BigNumber.instance) storage haystack,
BigNumber.instance memory needle)
private view returns (bool) {
return BigNumber.cmp(needle, haystack[needle.val], true) == 0;
}
function verifySquareRoot(BigNumber.instance memory input, BigNumber.instance memory sqrt) view private {
require(BigNumber.cmp(square(sqrt), input, false) <= 0, 'Square root too high');
BigNumber.instance memory sqrtPlusOne = BigNumber.prepare_add(sqrt, ONE);
BigNumber.instance memory nextSquare = BigNumber.bn_mul(sqrtPlusOne, sqrtPlusOne);
require(BigNumber.cmp(input, nextSquare, false) < 0, 'Square root too low');
}
/**
* Assert that prime and 4A^3 + 27B^2 are coprime, using certificate method from
* https://math.stackexchange.com/questions/2163034/proving-a-coprime-certificate-of-x-y.
* Do not inline (causes a "Stack too deep" error).
*/
function verifyCoprimality(
BigNumber.instance memory prime,
BigNumber.instance memory A,
BigNumber.instance memory B,
BigNumber.instance memory coprimeCertX,
BigNumber.instance memory coprimeCertY) private view {
require (BigNumber.cmp(ONE,
BigNumber.prepare_add(
BigNumber.bn_mul(coprimeCertX, prime),
BigNumber.bn_mul(coprimeCertY, BigNumber.prepare_add(
BigNumber.bn_mul(FOUR, cube(A)),
BigNumber.bn_mul(TWENTY_SEVEN, square(B))))),
true) == 0, 'Coprimality certificate verification failed');
}
/**
* assert q > 2*prime^(1/4) + prime^(1/2) + 1
* TODO: Does rounding the roots *before* adding affect this bounds check?
*/
function boundsCheckQ(
BigNumber.instance memory q,
BigNumber.instance memory sqrtPrime,
BigNumber.instance memory fourthRootPrime) private view {
require (BigNumber.cmp(q,
BigNumber.prepare_add(ONE, BigNumber.prepare_add(sqrtPrime, BigNumber.bn_mul(fourthRootPrime, TWO))), false)
> 0, 'Requires q > 2 * ⁴√(prime) + √(prime) + 1');
}
/**
* assert My² = Mx³ + AMx + B
*/
function verifyPointOnCurve(
BigNumber.instance memory Mx,
BigNumber.instance memory My,
BigNumber.instance memory A,
BigNumber.instance memory B) private view {
BigNumber.instance memory expectedMySquared = BigNumber.prepare_add(B,
BigNumber.bn_mul(Mx, BigNumber.prepare_add(A, square(Mx))));
require (BigNumber.cmp(square(My), expectedMySquared, false) == 0, 'Requires My² = Mx³ + AMx + B');
}
/**
* Only works for curves with no term in y, xy or x²
*
* Based on https://crypto.stanford.edu/pbc/notes/elliptic/explicit.html (a1 = a2 = a3 = 0)
*/
function ellipticCurvePointAdd(
BigNumber.instance memory x1,
BigNumber.instance memory y1,
BigNumber.instance memory x2,
BigNumber.instance memory y2,
BigNumber.instance memory A) private view returns (BigNumber.instance memory x3, BigNumber.instance memory y3) {
BigNumber.instance memory run = BigNumber.prepare_sub(x2, x1);
BigNumber.instance memory rise;
BigNumber.instance memory slope;
if (BigNumber.cmp(ZERO, run, false) == 0) {
require (BigNumber.cmp(y2, y1, false) == 0, 'Attempt to add two points with same x and different y in elliptic curve');
run = BigNumber.bn_mul(y1, TWO);
rise = BigNumber.prepare_add(A, BigNumber.bn_mul(square(x1), THREE));
} else {
rise = BigNumber.prepare_sub(y2, y1);
}
require(BigNumber.cmp(BigNumber.bn_mod(rise, run), ZERO, false) == 0, 'Elliptic curve cannot be computed in integer arithmetic');
// TODO: Need on-chain division to set slope = rise / run!
x3 = BigNumber.prepare_sub(BigNumber.prepare_sub(square(slope), x1), x2);
y3 = BigNumber.prepare_sub(BigNumber.bn_mul(slope, BigNumber.prepare_sub(x1, x3)), y1);
}
function ellipticCurveCheck(
BigNumber.instance memory Mx,
BigNumber.instance memory My,
BigNumber.instance memory A,
BigNumber.instance memory B,
BigNumber.instance memory q) private view returns (bool) {
// Then M = (Mx, My) is a non-identity point on the elliptic curve y^2 = x^3 + Ax + B.
// Let kM be M added to itself k times using
// standard elliptic-curve addition. Then, if qM is the identity element I, then n is prime.
BigNumber.instance memory qMx;
BigNumber.instance memory qMy;
BigNumber.instance memory Nx = Mx;
BigNumber.instance memory Ny = My;
BigNumber.instance memory remainingQ = q;
while (BigNumber.cmp(remainingQ, ZERO, false) != 0) {
if (BigNumber.is_odd(remainingQ) != 0) {
(qMx, qMy) = ellipticCurvePointAdd(qMx, qMy, Nx, Ny, A);
}
remainingQ = BigNumber.right_shift(remainingQ, 1);
(Nx, Ny) = ellipticCurvePointAdd(Nx, Ny, Nx, Ny, A);
}
// TODO: Determine if qMx, qMy is an identity element
return false;
}
/**
* Use this method to submit an Atkin–Goldwasser–Kilian–Morain certificate to be verified and added to the list.
* A bounty of bountyAmount is paid to the sender if the prime is new to the list and sufficiently large. This type of
* certificate uses an elliptic curve of the form y² = x³ + Ax + B.
*
* Some additional off-chain-calculated parameters are required,
* to limit the gas cost of verification. coprimeCertX and coprimeCertY are such that
* coprimeCertX * prime + coprimeCertY * (4*A*A*A + 27*B*B) == 1.
*
* @param prime the prime number to add to the list
* @param Mx the x-coordinate of the certifying point
* @param My the y-coordinate of the certifying point
* @param A the elliptic curve's coefficient in x
* @param B the elliptic curve's constant term
* @param q a previously-submitted prime, or 2 for bootstrapping
* @param sqrtPrime the square root of prime, rounded down
* @param fourthRootPrime the fourth root of prime, rounded down
* @param coprimeCertX term in the prime for the coprimality certificate
* @param coprimeCertY term in 4A³ + 27B² for the coprimality certificate
*/
function submitPrime(
BigNumber.instance memory prime,
BigNumber.instance memory Mx,
BigNumber.instance memory My,
BigNumber.instance memory A,
BigNumber.instance memory B,
BigNumber.instance memory q,
BigNumber.instance memory sqrtPrime,
BigNumber.instance memory fourthRootPrime,
BigNumber.instance memory coprimeCertX,
BigNumber.instance memory coprimeCertY) public {
require (!prime.neg && !Mx.neg && !My.neg && !A.neg && !B.neg && !q.neg && !sqrtPrime.neg && !fourthRootPrime.neg,
'Inputs prime,Mx,My,A,B,q must be non-negative');
require (BigNumber.cmp(Mx, prime, false) < 0, 'Mx must be less than the prime');
require (BigNumber.cmp(My, prime, false) < 0, 'My must be less than the prime');
require (BigNumber.cmp(A, prime, false) < 0, 'A must be less than the prime');
require (BigNumber.cmp(B, prime, false) < 0, 'B must be less than the prime');
require (BigNumber.is_odd(prime) != 0, 'Not odd, and 2 is already claimed; therefore not prime');
require (mapContains(knownPrimes, q), 'Submit a primality certificate for q first');
require (!mapContains(knownPrimes, prime), 'Already claimed');
verifySquareRoot(prime, sqrtPrime);
verifySquareRoot(sqrtPrime, fourthRootPrime);
verifyCoprimality(prime, A, B, coprimeCertX, coprimeCertY);
boundsCheckQ(q, sqrtPrime, fourthRootPrime);
verifyPointOnCurve(Mx, My, A, B);
require (ellipticCurveCheck(Mx, My, A, B, q), 'Elliptic-curve test failed');
knownPrimes[prime.val] = prime;
if (BigNumber.cmp(prime, BOUNTY_THRESHOLD, false) > 0) {
msg.sender.transfer(bountyAmount);
}
}
function donate() payable {}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T01:42:16.133",
"Id": "228820",
"Score": "1",
"Tags": [
"primes",
"mathematics",
"blockchain",
"solidity"
],
"Title": "Solidity: verifying primality certificates, bounty for large primes"
}
|
228820
|
<p>Is there a way to improve this code? I'd like to use the enum type <code>PaymentMethod</code>directly in the angular template without renaming it to <code>_PaymentMethod</code>.</p>
<hr>
<pre><code>export enum PaymentMethod {
CreditCard,
EFT
}
@Component()
export class PaymentComponent {
// ReSharper disable once InconsistentNaming
_PaymentMethod = PaymentMethod;
paymentMethod: PaymentMethod;
}
<ng-template *ngIf="paymentMethod == _PaymentMethod.CreditCard">
Enter your card details
</ng-template>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T05:46:12.343",
"Id": "228824",
"Score": "5",
"Tags": [
"template",
"typescript",
"enum",
"angular-2+"
],
"Title": "Reference enum values in Angular template without aliasing the enum type"
}
|
228824
|
<p>I've currently started solving some competitive programming Graph questions. But Started using adjacency list as <code>HashMap<Integer,ArrayList<Integer>> list</code> . But in some problems, this doesn't work. so I decided to implement class Graph other than this HashMap.
I would like a review of efficiency and general code quality. Please let me know if this follow standard adjacency list implementation and best and worst-case scenarios.</p>
<h2>Node class</h2>
<pre><code>class Node
{
public int id;
public boolean visited;
public List<Node> adjecent;
Node(int id)
{
this.id =id;
adjecent = new ArrayList<>();
}
}
</code></pre>
<h2>Graph</h2>
<pre><code>class Graph
{
private List<Node> nodes;
Graph()
{
nodes = new ArrayList<>();
}
boolean check(int id)
{
boolean flag = false;
for(Node temp:nodes)
{
if(temp.id == id)
flag =true;
}
return flag;
}
Node getNode(int id)
{
for(Node temp:nodes)
{
if(temp.id == id)
return temp;
}
return null;
}
void addEdge(int src,int dest)
{
Node s = check(src) ? getNode(src):new Node(src);
Node d = check(dest) ? getNode(dest):new Node(dest);
s.adjecent.add(d);
d.adjecent.add(s);
if(!check(src)) nodes.add(s);
if(!check(dest)) nodes.add(d);
}
void print()
{
for(Node temp : nodes)
{
System.out.print(temp.id+" -> ");
temp.adjecent.forEach(e->System.out.print(e.id+" "));
System.out.println();
}
}
void dfs(Node root)
{
if(root == null) return;
System.out.print(root.id+" ");
root.visited = true;
for(Node t : root.adjecent)
{
if(!t.visited)
dfs(t);
}
}
void refresh()
{
for(Node temp : nodes)
{
temp.visited =false;
}
}
void bfs(Node root)
{
Queue<Node> q =new LinkedList<>();
root.visited =true;
q.add(root);
while(!q.isEmpty())
{
Node temp = q.poll();
System.out.print(temp.id+" ");
for(Node n:temp.adjecent)
{
if(!n.visited)
{
n.visited=true;
q.add(n);
}
}
}
}
public static void main(String[] args) {
Graph g = new Graph();
/*
* 0
* / | \
* 1 2 3
* / \ \ \
* 4 5 6 7
*/
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(0, 3);
g.addEdge(1, 4);
g.addEdge(1, 5);
g.addEdge(2, 6);
g.addEdge(3, 7);
g.print();
System.out.println(g.nodes.size());
g.dfs(g.getNode(0));
System.out.println();
g.refresh();
g.bfs(g.getNode(0));
}
}
</code></pre>
<p>Any suggestions to make this code leverage to better efficiency is appreciated.</p>
|
[] |
[
{
"body": "<p>Don't store method flow flags as state in classes. This is a breach in object-oriented design.</p>\n\n<blockquote>\n<pre><code>class Node\n{\n public boolean visited;\n // .. other\n}\n</code></pre>\n</blockquote>\n\n<p>Search methods like <code>dfs</code> should use a map of some sort to store which nodes are visited.</p>\n\n<p>By storing this flag incorrectly as state, you'll get in trouble when multiple threads search the graph concurrently.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T08:20:48.913",
"Id": "444709",
"Score": "0",
"body": "I just put a visited flag to every node so I check whether it is visited or not"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T18:03:00.753",
"Id": "444778",
"Score": "0",
"body": "exactly my point :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T08:11:33.607",
"Id": "228831",
"ParentId": "228826",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "228831",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T06:46:49.417",
"Id": "228826",
"Score": "1",
"Tags": [
"java",
"graph"
],
"Title": "Graph implementation for solving graph problems (java)"
}
|
228826
|
<p>I need a little bit of refactor my initialize method because I think it will make initializer more flexible and readable.</p>
<pre><code>class LogAdminData
DEFAULT_EXCLUDED_PARAMS = %w[
encrypted_password
reset_password_token
reset_password_sent_at
].freeze
def initialize(admin_obj:, action_type:, old_data:, new_data:, excluded_params: %w[])
excluded_params += DEFAULT_EXCLUDED_PARAMS
@old_data = old_data.reject { |k, _v| excluded_params.include? k }
@new_data = new_data.reject { |k, _v| excluded_params.include? k }
@action_type = action_type
@admin_email = admin_obj.email
@admin_role = admin_obj.role
end
def call
AdminPanelLog.create(
admin_email: admin_email,
admin_role: admin_role,
action_type: action_type,
new_data: new_data,
old_data: old_data,
)
end
</code></pre>
<p>Maybe something like </p>
<pre><code> def cleanup_data(data)
excluded_params += DEFAULT_EXCLUDED_PARAMS
data.reject { |k, _v| excluded_params.include? k }
end
</code></pre>
<p>But how to call it in initializer using <code>old_data</code> and <code>new_data</code>?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T03:24:52.817",
"Id": "444819",
"Score": "2",
"body": "What does this code do, and how is it used? Is this the entire class? As it is, it looks like some essential parts of the code are missing, and your question makes little sense."
}
] |
[
{
"body": "<p>If this is a Rails project (or you use ActiveSupport) you can replace</p>\n\n<p><code>@old_data = old_data.reject { |k, _v| excluded_params.include? k }</code>\nwith\n<code>@old_data = old_data.except(excluded_params)</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T23:40:15.150",
"Id": "228882",
"ParentId": "228833",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T09:37:29.123",
"Id": "228833",
"Score": "1",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Rails initializer to be more clean"
}
|
228833
|
<blockquote>
<p>2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.</p>
<p>What is the sum of the digits of the number 2^1000?</p>
</blockquote>
<pre><code> BigInteger big = new BigInteger("2");
big = big.pow(1000);
String num = big.toString();
System.out.println(num);
int result = 0;
for(char i : num.toCharArray()) {
result += Integer.parseInt(String.valueOf(i));
}
System.out.println(result);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T14:22:42.743",
"Id": "444757",
"Score": "1",
"body": "What kind of feedback are you looking for? Is there anything about the code you've posted that you're not satisfied with?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T06:48:23.937",
"Id": "444839",
"Score": "0",
"body": "yes, I feel that there is a better way. instead of converting BigInteger to string and then to charArray and again I return it to int"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T10:38:06.117",
"Id": "444989",
"Score": "1",
"body": "Use Character.getNumericalValue(char) instead of Integer.parseInt(String.valueOf(i))."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T09:56:34.830",
"Id": "445245",
"Score": "0",
"body": "@TorbenPutkonen yeah it's more clear. thanks a lot."
}
] |
[
{
"body": "<p>This looks good. I assume this results in correct answer.</p>\n\n<ul>\n<li>What you can use instead of converting to <code>String</code> and back to <code>int</code> is to use <code>divideAndRemainder</code> method with <code>10</code> since we need to treat this as a base 10 number. </li>\n<li>This method is available in <code>BigInteger</code> for situations like this.</li>\n<li>We can also directly use BigInteger constants such as <code>TWO</code> and <code>TEN</code>.</li>\n</ul>\n\n<hr>\n\n<p><strong>Alternative Implementation</strong> </p>\n\n<pre><code>BigInteger big = BigInteger.TWO.pow(1000);\nString num = big.toString();\nSystem.out.println(num);\n\nint result = 0;\nBigInteger[] components;\n\ncomponents = big.divideAndRemainder(BigInteger.TEN);\nwhile (components[0].signum() != 0) {\n result += components[1].intValue();\n components = components[0].divideAndRemainder(BigInteger.TEN);\n}\nresult += components[1].intValue();\nSystem.out.println(result);\n</code></pre>\n\n<ul>\n<li><sub>I've used <code>signum</code> method here to check if result after integer division is zero.</sub></li>\n<li><sub><strong>Note</strong>: This seems to be creating lot of objects.</sub></li>\n</ul>\n\n<hr>\n\n<p><strong>Benchmark with JMH</strong></p>\n\n<p>After the some discussion in comments with @TorbenPutkonen, I agreed with <code>TorbenPutkonen</code> that alternative implementation might be creating more objects. However there is no way to see which implementation performs faster without doing a benchmark.</p>\n\n<pre><code>public class X {\n\n public static void main(String[] a) throws Exception {\n org.openjdk.jmh.Main.main(a);\n }\n\n @State(Scope.Benchmark)\n public static class BenchmarkState {\n BigInteger multiple = BigInteger.TWO.pow(1000);\n public BenchmarkState() {\n System.out.println(multiple);\n }\n }\n\n @Benchmark\n @Warmup(iterations = 5)\n public int withDivide(BenchmarkState x) {\n BigInteger[] components;\n components = x.multiple.divideAndRemainder(BigInteger.TEN);\n int result = 0;\n while (components[0].signum() != 0) {\n result += components[1].intValue();\n components = components[0].divideAndRemainder(BigInteger.TEN);\n }\n result += components[1].intValue();\n return result;\n }\n\n @Benchmark\n @Warmup(iterations = 5)\n public int withChars(BenchmarkState x) {\n String num = x.multiple.toString();\n int result = 0;\n for(char i : num.toCharArray()) {\n result += Integer.parseInt(String.valueOf(i));\n }\n return result;\n }\n\n @Benchmark\n @Warmup(iterations = 5)\n public int withCharsNumerical(BenchmarkState x) {\n String num = x.multiple.toString();\n int result = 0;\n for(char i : num.toCharArray()) {\n result += Character.getNumericValue(i);\n }\n return result;\n }\n\n @Benchmark\n @Warmup(iterations = 5)\n public int withCharAt(BenchmarkState x) {\n String num = x.multiple.toString();\n int len = num.length();\n int result = 0;\n for(int i = 0; i < len; i++) {\n result += Integer.parseInt(String.valueOf(num.charAt(i)));\n }\n return result;\n }\n\n @Benchmark\n @Warmup(iterations = 5)\n public int withCharsNumericalCharAt(BenchmarkState x) {\n String num = x.multiple.toString();\n int len = num.length();\n int result = 0;\n for(int i = 0; i < len; i++) {\n result += Character.getNumericValue(num.charAt(i));\n }\n return result;\n }\n}\n</code></pre>\n\n<pre>\n# Run complete. Total time: 00:21:29\n\nBenchmark Mode Cnt Score Error Units\nX.withCharAt thrpt 200 117285.320 ± 644.505 ops/s\nX.withChars thrpt 200 116882.706 ± 779.233 ops/s\nX.withCharsNumerical thrpt 200 110849.659 ± 3901.095 ops/s\nX.withCharsNumericalCharAt thrpt 200 121480.705 ± 2040.597 ops/s\nX.withDivide thrpt 200 11306.787 ± 35.711 ops/s\n</pre>\n\n<ul>\n<li>This concludes that original version is roughly <code>10x</code> faster than <code>divideAndRemainder</code></li>\n<li>Original version is also slightly faster than using <code>getNumericValue</code> by itself.</li>\n<li>However we can use <code>charAt</code> and avoid creating a character array too.</li>\n</ul>\n\n<hr>\n\n<p><strong>Why is using <code>divideAndRemainder</code> slow?</strong> </p>\n\n<ul>\n<li><code>toString</code> method of <code>BigInteger</code> uses a faster algorithm to create the string representation.</li>\n<li><code>divideAndRemainder</code> creates lot of BigInteger objects.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T10:59:27.710",
"Id": "444874",
"Score": "0",
"body": "That 's what i looking for... thanks alot"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T12:22:48.820",
"Id": "444885",
"Score": "1",
"body": "@OmarAhmed Updated my answer with code. Also if you want to it would be more fun to write the BigInt yourself ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T09:16:53.543",
"Id": "444977",
"Score": "0",
"body": "Looking quickly at the code in divideAndRemainder I'd say this approach results in about 2000 or more unnecessary object creations. Despite toString().toCharArray() creating an unnecessary array I would bet that it'd be much more efficient to do it char by char."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T10:13:33.490",
"Id": "444983",
"Score": "0",
"body": "@TorbenPutkonen doesn't `Integer.parseInt(String.valueOf(i))` create temporary objects too? This avoids string conversion all together (except for printing). However I'm now curious to run a benchmark and see. "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T10:29:14.613",
"Id": "444985",
"Score": "0",
"body": "@bhathiya-perera Character.getNumericValue(char) does it without creating an Integer object. Benchmarking with 300 digit number is probably not going to show much difference, though. My point is that divideAndRemainder is more costly than it appears on the surface and that should be taken into account if performance is being thrown around."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T10:36:08.557",
"Id": "444988",
"Score": "0",
"body": "BTW, instead of new BigInteger(\"2\") you should use BigInteger.TWO and BigInteger.TEN or BigInteger.valueOf(int). Those reuse constants when they are available. Not that it matters on single use, but it's a good pattern to learn."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T16:10:24.097",
"Id": "445158",
"Score": "2",
"body": "@TorbenPutkonen I've updated the answer with a benchmark. Seems like you are correct. Good catch. :)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T10:33:36.253",
"Id": "228898",
"ParentId": "228838",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "228898",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T11:26:36.713",
"Id": "228838",
"Score": "2",
"Tags": [
"java",
"programming-challenge"
],
"Title": "Project Euler #16 - Sum of all digits of 2^1000"
}
|
228838
|
<p>I have written a <a href="https://npmjs.com/package/kruptein" rel="nofollow noreferrer">cryptography NPM package called kruptein</a>. The code is also hosted on <a href="https://github.com/jas-/kruptein/tree/f08f8baed413ac6477fe646de3ed12cdd27e2c75" rel="nofollow noreferrer">GitHub</a>.</p>
<p>Having used multiple "best practices" with regards to key management, algorithm selection, key size, iv size etc. I could use someone with experience in this area to help validate the implementation.</p>
<p>I could use some help determining if I have flaws in any of the following:</p>
<ol>
<li><p><a href="https://github.com/jas-/kruptein/blob/f08f8baed413ac6477fe646de3ed12cdd27e2c75/lib/kruptein.js#L204" rel="nofollow noreferrer">Key sizes</a>: <code>_matrix(algo)</code> - Are the appropriate key, iv & authentication tag sizes being identified and used correctly based on the algorithm selection? i.e. AES-128-CBC or AES-256-XTS</p>
<pre><code> _matrix(algo) {
let obj = {
at_size: 16,
iv_size: 16,
key_size: 32
};
if (algo.match(/ccm|ocb|gcm/i))
obj.iv_size = 12;
if (algo.match(/aes/) && algo.match(/ecb/))
obj.iv_size = 0;
if (algo.match(/aes/) && algo.match(/128/))
obj.key_size = 16;
if (algo.match(/aes/) && algo.match(/192/))
obj.key_size = 24;
if (algo.match(/aes/) && algo.match(/xts/))
obj.key_size = 32;
if (algo.match(/aes/) && algo.match(/xts/) && algo.match(/256/))
obj.key_size = 64;
return obj;
}
}
</code></pre></li>
<li><p><a href="https://github.com/jas-/kruptein/blob/f08f8baed413ac6477fe646de3ed12cdd27e2c75/lib/kruptein.js#L160" rel="nofollow noreferrer">Key derivation</a>: <code>_derive_key(secret)</code> - When deriving keyed material from a provided secret are enough iterations used? Is there a problem with the salt generation used for the resulting keyed material? What about the resulting key? For both the IV and key I am concerned about possible weakening of the material when converting to a buffer and slicing to the appropriate sizes.</p>
<pre><code> _derive_key(secret) {
let key, hash, salt, result, derived_key;
try {
hash = this.crypto.createHash(this.hashing);
hash.update(secret);
salt = hash.digest();
} catch(err) {
throw err;
}
salt = (Buffer.isBuffer(salt)) ?
salt.slice(0, 16) : salt.substr(0, 16);
key = this.crypto.pbkdf2Sync(secret, salt, 10000, 64, this.hashing);
return Buffer.from(key.toString(this.encodeas)).slice(0, this.key_size);
}
</code></pre></li>
<li><p><a href="https://github.com/jas-/kruptein/blob/f08f8baed413ac6477fe646de3ed12cdd27e2c75/lib/kruptein.js#L196" rel="nofollow noreferrer">IV generation</a>: <code>_iv(iv_size)</code> - When generating a new IV is there a problem with slicing the results. Most of the node.js crypto API functions use buffers and the sizes must match but I can't help but think it is weakening the IV.</p>
<pre><code> _iv(iv_size) {
let iv = this.crypto.randomBytes(iv_size);
return Buffer.from(iv.toString(this.encodeas),
this.encodeas).slice(0, iv_size);
}
</code></pre></li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T11:48:26.997",
"Id": "444732",
"Score": "0",
"body": "I hate to break it to you, but that is not how crypto-review works. Basically, you have to already be a well-known, respected cryptographer to begin with. Then, you publish your work in a reputable, peer-reviewed cryptography journal and/or submit your work to a competition. Step #3: wait 10 years while the crypto community at large reviews your work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T12:22:28.610",
"Id": "444733",
"Score": "1",
"body": "The question posed isn’t about algorithm design, nor is the question without merit. Please read again, as the question is specifically about an engineered solution soliciting review of implementation according to cited best practices."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T10:56:10.790",
"Id": "444872",
"Score": "1",
"body": "Hey there. I've reverted your rollback for two reasons: 1. the link to github that your old post contained pointed to `master`, which is not a defined deeplink, and therefore may point to a revision different from the one you're presenting here. To avoid confusion a community member linked to a specfic revision. And secondly they also edited the title to be more in line with the title format this community expects. As such the edit was IMO a definitive improvement and should remain applied."
}
] |
[
{
"body": "<p>think I should prefix this by saying I'm not a JS or Crypto nerd, but am interested in both! to other people seeing this question, this code/module seems to mostly reimplement the CCM demo at the bottom of the Crypto docs: <a href=\"https://nodejs.org/api/crypto.html#crypto_ccm_mode\" rel=\"nofollow noreferrer\">https://nodejs.org/api/crypto.html#crypto_ccm_mode</a></p>\n\n<p>anyway on with a few issues I noticed:</p>\n\n<ol>\n<li><p>why isn't <code>_iv</code> just returning <code>crypto.randomBytes(iv_size)</code>? encoding to a string and then getting bytes seems counterproductive at best, it just seems to throw away entropy</p></li>\n<li><p>why use PBKDF2 over just hashing the secret? it's not being saved anywhere, and by using the secret as the salt you've just opened it wide up to rainbow table exploitation again. further, by doing your string encoding things you've just thrown away even more entropy</p></li>\n<li><p>your use of regexes in <code>_matrix</code> looks suspect. why not just match against a few common patterns (e.g. <code>/^\\w+-\\w+-\\w+/</code>) and handle the groups explicitly. allowing modes like ECB at all here looks like a mistake</p></li>\n<li><p>catching exceptions just to immediately rethrow doesn't seem very useful</p></li>\n<li><p>can you think of a better name for the member variable <code>flag</code>? maybe something like <code>is_aead_mode</code></p></li>\n</ol>\n\n<p>update:</p>\n\n<p>another big issue just occurred to me; that you're not including any cryptographic details in the structure. this allows the suite used to be upgraded (e.g. NIST update their recommendations) while maintaining backwards compatibility. i.e. you should be saying that you're hashing the secret with SHA512, which algorithm was used for encryption, what you've used as a HMAC (if you've used it, CCM already includes its own MAC so HMAC isn't needed).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T21:31:46.033",
"Id": "444941",
"Score": "0",
"body": "The module tries to handle every cipher type and mode, including ECB. Regarding `_iv(iv_size)`, the node.js crypto API uses buffers extensively and although specifying the size as `x`,the result is a UTF-8 which is 1-4 bytes per element returned from `.getRandomBytes()`, slicing the UTF-8 encoded buffer is necessary to maintain the `iv` size for all algorithms. So am I really throwing away entropy? Thanks for pointing out the variable name and the salt, I will adjust and generate a new random set of bytes for the salt. Use of PBKDF conforms to the recommended key derivation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T08:52:51.340",
"Id": "444976",
"Score": "0",
"body": "what's `getRandomBytes`? `crypto.randomBytes(4)` gives me (node v12) a `Buffer` of length 4, as expected. not sure why you're talking about utf8. the `randomBytes` code had a big [rework for v10](https://github.com/nodejs/node/commit/2d9c3cc89d) where `Buffer`s which introduced the non-callback functionality, but it's always returned a `Buffer`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T11:12:50.233",
"Id": "444995",
"Score": "0",
"body": "You are right, that was a typo and the buffer does return the correct size. Can you explain to me how this project is similar to the code for the CCM module? Use of `.randomBytes()` for a salt; if I do it this way I have to include the salt in the returned object in order to decrypt correct? Can you explain how this opens it up to rainbow table exploitation?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T13:25:21.677",
"Id": "445011",
"Score": "0",
"body": "by \"rainbow table\" I mean that the value returned from `_derive_key` is (assuming the hash algorithm is fixed) uniquely determined by the \"secret\", an attacker can easily precalculate/reuse the output of this function. wikipedia explains [cryptographic salt](https://en.wikipedia.org/wiki/Salt_(cryptography)) reasonably well, and also reiterates that this is used for storing hashed passwords, which you're not doing"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T21:56:03.157",
"Id": "445077",
"Score": "0",
"body": "Thanks! How is that different than the `crypt()` function and it’s use of a randomly generated salt embedded in the resulting hash for sha512 etc? I ask because that is always a fixed length value which can then be reused to crack the original value applied to the key derivation could it not? NIST SP 800-132 recommends a random value of 128 bits so I suppose I need to refactor and pass the salt along like other implementations. Regarding the format of crypt output and the salt being included in the hash: https://www.tunnelsup.com/hash-analyzer/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T09:37:28.960",
"Id": "445132",
"Score": "0",
"body": "it's all about changing the ratio of work between attacker and defender. when the hash is a deterministic function of the password an attacker can just hash common passwords to a file and look them up later. when you use `n` bits of salt it would make this file `2**n` times as large, and this attack quickly becomes useless. because adding salt is basically free for the defender, you've made this attack `2**n` times harder. if the salt is predictable, as in your scheme, this weakens things; work has been added for the defender while not for the attacker (who can precompute things)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T10:20:36.343",
"Id": "445136",
"Score": "0",
"body": "The latest branch `v2.0.0` is implementing these refactorizations & optionally adding support `crypt.scrypt()`. Thanks again, these are oversights I needed to have reviewed!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T13:33:40.760",
"Id": "445147",
"Score": "0",
"body": "you've broken things even more! your `scrypt` code means that everything now needs to be run on a computer that reports having the same number of CPUs. you must persist this state into the encrypted object, then read it back out and use it when decrypting"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T14:17:03.453",
"Id": "445151",
"Score": "0",
"body": "I am not seeing anything regarding this as a requirement to scrypt as a key derivation function. Please provide references"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T15:51:35.647",
"Id": "445157",
"Score": "0",
"body": "just run `scrypt` yourself on the same password & salt and vary the parallelism parameter! you get different values back..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T21:12:57.737",
"Id": "445204",
"Score": "0",
"body": "Your statement “you broke it more” is misleading and quite frankly doesn’t add up as the optional use of scrypt for the key derivation on the same system it is used on would use the same memory and cpu parameters. I suppose if you are moving data between system the need would arise to pass the parameters but what about that is “broken”?"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T12:51:51.750",
"Id": "228903",
"ParentId": "228839",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "228903",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T11:22:57.903",
"Id": "228839",
"Score": "3",
"Tags": [
"javascript",
"node.js",
"cryptography"
],
"Title": "kryptein cryptography package for Node.js"
}
|
228839
|
<p>I have written a small program that reads input from a text file and then writes this output to a text file. The method contains a switch which decides whether to output to the file as text or as a literal string of the bytes. How could I refactor this code to only include a single if statement block instead of two to switch between these two modes? I am also interested if there is a more optimal way of writing this code overall.</p>
<p>I have tried to create just one switch at the beginning of the code which would change the output files from output-text-txt to output-bytes.txt (which are located in the resources folder) as well as changing the writing method (whether it writes the integer or string literals). I encounter difficulty when I need to write the bytes because the method asks for either an integer or a string and I am not sure how I would change these writing methods with just one if statement at the beginning of the code (due to it asking for int c as a parameter)</p>
<pre><code>public class ByteStreamTest {
private static File input;
private static File output;
public static void main(String args[]) throws Exception {
new ByteStreamTest().write(true);
new ByteStreamTest().write(false);
}
public ByteStreamTest() {}
public void write(boolean asText) {
input = new File(getClass().getClassLoader().getResource("input.txt").getPath());
if (asText) {
output = new File(getClass().getClassLoader().getResource("output-text.txt").getPath());
} else {
output = new File(getClass().getClassLoader().getResource("output-bytes.txt").getPath());
}
FileInputStream in = null;
FileWriter fw = null;
try {
in = new FileInputStream(input);
fw = new FileWriter(output);
int c;
while ((c = in.read()) != -1) {
if (asText) {
fw.write(c);
} else {
fw.write(String.valueOf(c) + System.getProperty("line.separator"));
}
}
in.close();
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
</code></pre>
<p>This isn't really a question that has to do with the functionality of the code, I am simply interested in refactoring the code to include as little if statements as possibly optimizing it further.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T14:01:45.163",
"Id": "444752",
"Score": "0",
"body": "In order to give you proper advice for refactoring, we need to understand your real-world use cases. Why would you want to output a string of bytes, and how do you decide which mode to use?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T14:18:25.507",
"Id": "444755",
"Score": "1",
"body": "@200_success There is no real world case. I am doing this only for my own information. I would like to practice reading and writing from files and also how to manipulate byte data. The entire purpose of this program is to provide a function that can read a file, and write those file contents to a new file, with a switch that allows me to choose whether it writes the text or the string representation of the bytes to the output file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T15:46:02.990",
"Id": "444766",
"Score": "1",
"body": "You could apply the *strategy* design pattern. Define an abstract class with the abstract method `write()`. Then write two implementations: MyTextWriter and MyBinaryWriter. Now you only need one if statement to decide which class to instantiate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T06:37:11.043",
"Id": "444837",
"Score": "0",
"body": "@AedvaldTseh Instead of subclassing and overriding, the transformation should be implemented as a separate component (interface), which is injected into the ByteStreamTest class."
}
] |
[
{
"body": "<p>Please note I am not an expert in Java, I do know something about object oriented programming.</p>\n\n<p>Java is an object oriented programming language. To write good object oriented programs it's best to keep 5 programming principles in mind. Together these 5 principles are called <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">SOLID</a> programming. The 5 programming principles are</p>\n\n<ul>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> </li>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle\" rel=\"nofollow noreferrer\">Open-closed principle</a> </li>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Liskov_substitution_principle\" rel=\"nofollow noreferrer\">Liskov substitution principle</a> </li>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Interface_segregation_principle\" rel=\"nofollow noreferrer\">Interface segregation principle</a> </li>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Dependency_inversion_principle\" rel=\"nofollow noreferrer\">Dependency inversion principle</a></li>\n</ul>\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>This program violates the single responsibility principle in 2 ways, first the function <code>main()</code> is included in the class and second the <code>write()</code> function is too complex (does too much) and should be simplified.</p>\n\n<p>The function <code>write()</code> might be better named <code>copy()</code>. It should do only one thing, which is copy the input file to the output file. There could be 2 <code>copy()</code> functions, one for <code>text</code> and one for <code>strings</code>. The decision on which way to write to the output file should be outside the <code>copy</code> functions.</p>\n\n<p>Opening and closing the files should be outside the <code>write</code> function. The program should only open the input file once and possibly reset it to the beginning the second time.</p>\n\n<p>The <code>ByteStreamTest</code> constructor could open the input file.\nThere could be a Boolean member of the <code>ByteStreamTest</code> class that is either public and gets modified by <code>main()</code> or private with accessor functions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T06:31:09.803",
"Id": "444835",
"Score": "1",
"body": "A third S-violation is that the \"copier\" is also responsible for transforming the incoming data into the desired output format. This should be fixed by creating an interface with which an input byte (int) can be converted to a desired output bytes and passing an implementation of that interface to the copier instead of the boolean flag. This would also fulfill the desire to avoid if-statements."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T16:23:43.210",
"Id": "228854",
"ParentId": "228840",
"Score": "3"
}
},
{
"body": "<p>Opening this in an IDE already shows a bunch of problems to fix.</p>\n\n<ul>\n<li><code>input</code> and <code>output</code> can be local variables, in fact this is all\nrather procedural, so it makes sense that the containing class is just\nto contain the main method anyway.</li>\n<li>The empty constructor is pointless.</li>\n<li>The <code>args</code> parameter is written weirdly, it should be <code>String[] args</code>.</li>\n<li><code>throws Exception</code> doesn't do anything.</li>\n<li>The catch-all block for <code>Exception</code> doesn't even catch all exceptions\nas the input and output files are opened outside of it.</li>\n<li>Initialisation to <code>null</code> is the same as not writing it explicitly.</li>\n<li><code>String.valueOf(c)</code> doesn't do much, <code>c</code> itself is just fine for\n<code>c + \"some string\"</code> already.</li>\n<li><code>getResource</code> can return <code>null</code> - here it's probably to ignore that.</li>\n</ul>\n\n<p>And after some more manual inspection:</p>\n\n<ul>\n<li>Don't call <code>close</code>, use a <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\">try-with block</a>.</li>\n<li>Perhaps only get the line separator once, not in a loop (although\nthat's <em>probably</em> optimised away).</li>\n<li>The <code>while</code> loop is very inefficient, but that's probably not a\nconcern here, so I'm not sure what to recommend. Maybe that the\nstring concatenation can be avoided by going for two method calls\ninstead. You'd have to profile it regardless if that makes any\nmeasurable difference at all.</li>\n<li><code>boolean</code> arguments are easy to get wrong (that's why some IDEs show\nthe name of argument at call sites. That can be avoided by using a\n<a href=\"https://en.wikipedia.org/wiki/Builder_pattern\" rel=\"nofollow noreferrer\">builder pattern</a>, aka <code>new ...().asText(true).write()</code> or something\nalong those lines.</li>\n</ul>\n\n<pre><code>public class ByteStreamTest {\n public static void main(String[] args) throws IOException {\n new ByteStreamTest().write(true);\n new ByteStreamTest().write(false);\n }\n\n private File open(String filename) {\n return new File(getClass().getClassLoader().getResource(filename).getPath());\n }\n\n private void write(boolean asText) throws IOException {\n File input = open(\"input.txt\");\n File output = open(asText ? \"output-text.txt\" : \"output-bytes.txt\");\n\n try (FileInputStream in = new FileInputStream(input);\n FileWriter fw = new FileWriter(output)) {\n String separator = System.getProperty(\"line.separator\");\n\n int c;\n while ((c = in.read()) != -1) {\n fw.write(c);\n if (!asText) {\n fw.write(separator);\n }\n }\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Anyway, as an exercise how to avoid <code>if</code>s it can always be rewritten in\nterms of two classes where one class does the <code>true</code> branch, the other\nthe <code>false</code> branch. That also means that suddenly there's a big\nincrease in code to read for nothing much of a benefit.</p>\n\n<p>For a nicer to use API, I'd imagine something like this would make way\nmore sense though:</p>\n\n<pre><code>public class ByteStreamTest {\n public static void main(String[] args) throws IOException {\n copy(open(\"input.txt\"), open(\"output-text.txt\"), true)\n copy(open(\"input.txt\"), open(\"output-bytes.txt\"), false)\n }\n\n private static void copy(File input, File output, boolean asText) throws IOException {...}\n private static File open(String filename) {...}\n}\n</code></pre>\n\n<p>It's all procedural after all. Secondly as was already said, <code>copy</code>\nmakes more sense and <code>open</code> can use\n<code>ByteStreamTest.class.getClassLoader()...</code> without having to actually\ncreate an object of the class.</p>\n\n<p>(Why is it writing to the locations from the class loader? That\nwouldn't work at all if this was running from a JAR, wouldn't it?)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T21:14:30.537",
"Id": "228874",
"ParentId": "228840",
"Score": "1"
}
},
{
"body": "<p>Yes, you can get rid of the <code>if</code>. I'd leverage a <code>Function mapToOutput</code>, with value either <code>x -> x</code> (no change) or <code>x -> String.valueOf(x) + System.getProperty(\"line.separator\")</code> (your other logic).</p>\n\n<p>Keep in mind that it may not actually be desirable to do this, though - it adds complexity, while only saving you a little repetition. I've done it below, and also added some comments on the rest of your code:</p>\n\n<pre><code>public class ByteStreamTest {\n\n private static File input;\n private static File output;\n private static Function mapToOutput;\n\n public static void main(String args[]) throws Exception {\n new ByteStreamTest().write(true);\n new ByteStreamTest().write(false); \n }\n\n public ByteStreamTest() {}\n\n public void write(boolean asText) {\n\n input = new File(getClass().getClassLoader().getResource(\"input.txt\").getPath());\n\n if (asText) {\n output = new File(getClass().getClassLoader().getResource(\"output-text.txt\").getPath());\n mapToOutput = x -> x; // could replace with Function.identity()\n } else {\n output = new File(getClass().getClassLoader().getResource(\"output-bytes.txt\").getPath());\n mapToOutput = x -> String.valueOf(x) + System.getProperty(\"line.separator\");\n }\n</code></pre>\n\n<p>The block above is effectively setting the <em>parameters</em> for the block below:</p>\n\n<pre><code> FileInputStream in = null;\n FileWriter fw = null;\n</code></pre>\n\n<p>These could go in a try-with-resources, e.g. <code>try (FileInputStream in = new FileInputStream(input); FileWriter fw = new FileWriter(output)) { ...</code></p>\n\n<pre><code> try {\n\n in = new FileInputStream(input);\n fw = new FileWriter(output);\n</code></pre>\n\n<p>I'm a big fan of either <code>fr</code> and <code>fw</code> (in this case you're not using a <code>FileReader</code>, so the point is moot), <strong>or</strong> <code>in</code> and <code>out</code>, but not the two mixed together :)</p>\n\n<pre><code> int c;\n</code></pre>\n\n<p>Why <code>c</code>? It's not a great name.</p>\n\n<pre><code> while ((c = in.read()) != -1) {\n fw.write(mapToOutput.apply(c));\n }\n\n in.close();\n fw.close();\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n</code></pre>\n\n<p>It would be good to have a <code>finally</code> block to close your resources, or else create them in a try-with-resources. This try-catch <em>does not</em> guarantee your resources will be closed.</p>\n\n<pre><code> }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T21:16:58.650",
"Id": "228875",
"ParentId": "228840",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T12:38:32.787",
"Id": "228840",
"Score": "3",
"Tags": [
"java",
"io"
],
"Title": "Copy a FileInputStream to a file, either as text or as a string of bytes"
}
|
228840
|
<p>Here is a working Python implementation of primality test. Is there something that I could change in code to achieve a better running time? For more information about algorithm see <a href="https://mathoverflow.net/q/286304/88804">this post.</a> </p>
<pre><code>from sympy import *
from sympy.abc import x
n=int(input("Enter a number : "))
def xmat(r,n):
return Matrix([[2*x, -1], [1, 0]])*rem(1,x**r-1)*(1%n)
def smallestr(n):
if n==1 or n%2==0:
return 0
else:
r=3
while r<1000000:
u=n%r
if u==0 and r<n:
return 0
elif not(u==0) and not(u==1) and not(u==r-1):
return r
else:
r=nextprime(r)
def myisprime(n):
r=smallestr(n)
if r==0:
return n==2
else:
xp=(xmat(r,n)**n)*Matrix([[x],[1]])
return trunc(xp[1],n)==(rem(x*(1%n),x**r-1))**n
if myisprime(n):
print("prime")
else:
print("composite")
</code></pre>
<p>You can run this code <a href="https://sagecell.sagemath.org/?z=eJxdUstugzAQPOOvWKWKZCxS4fRW1cce-wWIA0mNagkvaDGq8_ddG_KqJZB3dneYGdHT6GG--OkCzk8jBVCiv2Gv3el8xaMQL_CJwRJ0gIs_WRICjdZCfNseou-CpArLd1GQDQshfHWBXJRNc1SxgoNuK2h0BXXbloqsl7qKStFBl0rqPZYrz-y7YbBzIJmpXA9ojIaRAPdHY2rGrvy1KOww24yYN37__rjBAn3oOp_UKBaDe0oXZlp4Hzr85hHMzQemgrnSx8Yg01iZ57ZKP1VJ8dM2rdurkgL4kEEbw0TOW0mbMX9x84qsGZlHp9koPdtj38e7wzgZectYKX5u8ca2ajSHel8NtOBZxolhnjZGprjjGvM19EQikmDh_otLFrjCIHcZ3JVik7Gh55H_idkF7vwBsUCk2A==&lang=python&interacts=eJyLjgUAARUAuQ==" rel="nofollow noreferrer">here</a>.</p>
<p><strong>EDIT</strong></p>
<p>To clarify things, this Python code represents my attempt to translate the following <a href="https://sagecell.sagemath.org/?z=eJxVUNtqwzAMfc9XaIUWO7gQpw9leP6EfkFIoGwJGGo5KC64tNu3T25C1j1JR5ejo4NWvx8Ppkj-HAUplGChqcukYK8NaAVVW57Cl9AqdbTXcgEoTTH58-XST5EESnt3g0BrNTwegNva2koB9fFKKCopzRBoJOd7Qcx_UBCC8jdxtbgladwAnNoKdjsg-AD8t_rsvs1djnqJLGYdI8lz34W_uWm-kgUxfz72qnIm46qFP3mYYc09Xkgjb6xWdFg2Sen2R5o0NnWbB_P7aTVhMaVDvs4GvApQnGAUmyferPAz-DFMLnJJml9w3HEY&lang=gp&interacts=eJyLjgUAARUAuQ==" rel="nofollow noreferrer">PARI/GP code</a> which is very fast. </p>
|
[] |
[
{
"body": "<p>Ooooh boy, a prime number finder with the question, \"how do I make this faster.\" It's like asking a bartender what their favorite drink is: it really depends. However, before we get to performance, let's tackle some of the stylistic considerations in this code.</p>\n\n<ol>\n<li><p><a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">Wrap the actual executing code in a <code>if __name__ == '__main__'</code> block</a>.</p></li>\n<li><p><a href=\"https://realpython.com/python-pep8/#naming-conventions\" rel=\"nofollow noreferrer\">Follow standard naming conventions for functions and variables</a> (<a href=\"https://realpython.com/python-pep8/#whitespace-in-expressions-and-statements\" rel=\"nofollow noreferrer\">not to mention spacing</a>).</p></li>\n<li><p>The algorithm you're implementing is fairly complicated. <a href=\"https://realpython.com/python-pep8/#comments\" rel=\"nofollow noreferrer\">Add some brief comments and docstrings to explain what's going on</a>.</p></li>\n<li><p>Either use descriptive names for your variables or add comments/docstrings explaining what they are.</p></li>\n<li><p>Name your constants. Why <code>r < 1000000</code>? This would be clearer if we had something like <code>MAX_PRIME_VALUE = 1000000</code>, <code>r < MAX_PRIME_VALUE</code>.</p></li>\n</ol>\n\n<p>Now in terms of performance. Are there ways to make this faster? Yes, of course. If you had a dictionary of all prime numbers <= 1000000, then you could do a simple lookup and be done. The ultimate trade-off between runtime and storage space is to simply pre-compute all the answers to your question. Also, it depends on what hardware/software you have available (pure no-library python? Only sympy? Numpy? Numba? Cython? CUDA?). So in order to answer this question, you really need to ask what your use case is and what trade-offs you're able to make.</p>\n\n<p>For the sake of argument, let's use your code above as our basic requirements. Let's say we have access to sympy and basic Python, but nothing else. As a baseline, let's consider a trivial prime number finder that use nothing but pure Python. We'll just count up from 3 up to sqrt(n): it's naive, it's dead simple to write, and it's actually reasonably fast just because Python is a decent language (and it even has an O(sqrt(N)) runtime, which is not a bad place to start):</p>\n\n<pre><code>def naive_is_prime(n):\n if n == 2:\n return True\n if n < 2 or n % 2 == 0:\n return False\n\n # Consolidated code thanks to GZ0's comment\n return all(n % i != 0 for i in range(3, int(n ** 0.5 + 1), 2)) \n</code></pre>\n\n<p>And a couple benchmarks:</p>\n\n<pre><code>%timeit myisprime(11)\n1.23 ms ± 26.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n%timeit naive_is_prime(11)\n1.11 µs ± 47.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n</code></pre>\n\n<p>Uh oh, that's not a good place to begin, with the naive code giving us a 1000x speedup. Well, maybe that's just because the numbers are so small; maybe the overhead of using sympy will shine when we start considering larger primes. Unfortunately, it slows down rapidly, and waiting for it to compute if tiny numbers are prime takes an unbearable amount of time:</p>\n\n<pre><code>%time myisprime(61)\nWall time: 28.3 s\n</code></pre>\n\n<p>whereas the naive implementation above continues to be almost instantaneous up until fairly large primes:</p>\n\n<pre><code>%timeit naive_is_prime(2**31 - 1) # 2147483647\n2.7 ms ± 160 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n</code></pre>\n\n<p>I think the moral of the story is that \"<a href=\"https://stackify.com/premature-optimization-evil/\" rel=\"nofollow noreferrer\">premature optimization is the root of all evil</a>\". I fall into this all the time, and even did so while answering this question (I had a more complicated baseline to show off that performed much worse than that trivial code), and it's very tempting to use a fancy package like sympy to accomplish what's not a very fancy problem. <a href=\"https://www.techopedia.com/definition/20262/keep-it-simple-stupid-principle-kiss-principle\" rel=\"nofollow noreferrer\">Start simple</a>, then look into some common approaches to the problem (<a href=\"https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">like the Sieve approach</a>) and figure out if they actually help you or not.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T18:10:22.590",
"Id": "444780",
"Score": "0",
"body": "The overall review is great however there is a minor bug in the implemention: the upper bound should not be `int(math.ceil(math.sqrt(n)))`, it should be `int(n**0.5) + 1` (this does not require `math` import), or alternatively `math.floor(math.sqrt(n)) + 1`. Otherwise it fails on some square numbers such as `9`. Also, the loop can be written in a one-liner using the built-in `all` function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T18:41:49.270",
"Id": "444787",
"Score": "0",
"body": "For performance simply writing `all(n % i for i ...)` is slightly faster despite that it hurts readablity a bit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T07:57:38.393",
"Id": "444847",
"Score": "0",
"body": "Please, see EDIT"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T08:37:04.733",
"Id": "444856",
"Score": "0",
"body": "@PeđaTerzić It's likely that the PARI/GP has a faster implementation than the nextprime you seem to be importing from sympy. It's possible that you could speed up your code if you create a generator for your primes there. But so far, this answer is very valid to your question, which was \"how do I speed up this primality check\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T09:37:01.933",
"Id": "444864",
"Score": "0",
"body": "@Gloweye, `nextprime` doesn't even register in the profile output."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T10:00:13.883",
"Id": "444867",
"Score": "0",
"body": "Then I'm very curious where that function is coming from. I'm nearly certain it's guilty of any slowdown there. Also shows how important it is to NEVER `from module import *`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T10:08:12.603",
"Id": "444869",
"Score": "0",
"body": "@Gloweye, let me rephrase: `nextprime` accounts for less than 1 millisecond of the 42 seconds spent verifying that 61 is prime. It is completely irrelevant. I've already explained where the time is going in my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T10:12:58.273",
"Id": "444870",
"Score": "0",
"body": "Oh, in that way. Yeah, I see that."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T16:39:25.467",
"Id": "228855",
"ParentId": "228847",
"Score": "7"
}
},
{
"body": "<h3>Implementation</h3>\n\n<blockquote>\n<pre><code>def xmat(r,n):\n return Matrix([[2*x, -1], [1, 0]])*rem(1,x**r-1)*(1%n)\n</code></pre>\n</blockquote>\n\n<p>Am I correct in thinking that <code>n</code> will always be a positive integer greater than 2? If so, <code>*rem(1,x**r-1)*(1%n)</code> can be optimised away entirely.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>def myisprime(n):\n r=smallestr(n)\n if r==0:\n return n==2\n else:\n xp=(xmat(r,n)**n)*Matrix([[x],[1]])\n ...\n</code></pre>\n</blockquote>\n\n<p>How to parse <code>smallestr</code>? Is it <code>small_e_str</code>? PEP8 promotes using underscores to separate words in names.</p>\n\n<p>I inserted here a debug line:</p>\n\n<pre><code> print(r, xp)\n</code></pre>\n\n<p>When <code>n = 3</code> we get</p>\n\n<pre><code>5 Matrix([[-4*x**2 + x*(2*x*(4*x**2 - 1) - 2*x) + 1], [x*(4*x**2 - 1) - 2*x]])\n</code></pre>\n\n<p>It seems that sympy is manipulating expression trees rather than polynomials, and not simplifying at all ever. If you can't find a way to make it auto-simplify, it would probably be faster to roll your own polynomial class.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> return trunc(xp[1],n)==(rem(x*(1%n),x**r-1))**n\n</code></pre>\n</blockquote>\n\n<p>Simplifying:</p>\n\n<blockquote>\n<pre><code> return trunc(xp[1],n)==x**n\n</code></pre>\n</blockquote>\n\n<p>Now, <code>trunc</code> implies that you should be working over <span class=\"math-container\">\\$\\mathbb{Z} / n\\mathbb{Z}\\$</span> rather than <span class=\"math-container\">\\$\\mathbb{Z}\\$</span>. <code>xmat(r,n)**n</code> is going to generate coefficients which are exponentially larger than <code>n</code>: working modulo <code>n</code> all the way through would be far far faster.</p>\n\n<p>(I implemented a naïve version out of curiosity, and it tests <code>61</code> in about 2.4 milliseconds, vs 42 seconds for your code).</p>\n\n<hr>\n\n<h3>Deep dive into the algorithm</h3>\n\n<p>By diagonalisation, if I haven't messed up the algebra,</p>\n\n<p><span class=\"math-container\">$$ \\begin{pmatrix}2x & -1 \\\\ 1 & 0\\end{pmatrix}^n \\begin{pmatrix}x \\\\ 1\\end{pmatrix}\n%= \\left(S J S^{-1} \\right)^n \\begin{pmatrix}x \\\\ 1\\end{pmatrix}\n%= S \\left(J \\right)^n S^{-1} \\begin{pmatrix}x \\\\ 1\\end{pmatrix}\n%= \\begin{pmatrix} x-\\sqrt{x^2-1} & x+\\sqrt{x^2-1} \\\\ 1 & 1 \\end{pmatrix} \\begin{pmatrix} x-\\sqrt{x^2-1} & 0 \\\\ 0 & x+\\sqrt{x^2-1} \\end{pmatrix}^n \\begin{pmatrix} -\\frac{1}{2\\sqrt{x^2-1}} & \\frac{x}{2\\sqrt{x^2-1}}+\\frac12 \\\\ \\frac{1}{2\\sqrt{x^2-1}} & \\frac12 - \\frac{x}{2\\sqrt{x^2-1}} \\end{pmatrix} \\begin{pmatrix}x \\\\ 1\\end{pmatrix} \\\\\n%= \\begin{pmatrix} x-\\sqrt{x^2-1} & x+\\sqrt{x^2-1} \\\\ 1 & 1 \\end{pmatrix} \\begin{pmatrix} (x-\\sqrt{x^2-1})^n & 0 \\\\ 0 & (x+\\sqrt{x^2-1})^n \\end{pmatrix} \\begin{pmatrix}\\frac12 \\\\ \\frac12\\end{pmatrix} \\\\\n%= \\begin{pmatrix} x-\\sqrt{x^2-1} & x+\\sqrt{x^2-1} \\\\ 1 & 1 \\end{pmatrix} \\begin{pmatrix}\\frac12 (x-\\sqrt{x^2-1})^n \\\\ \\frac12 (x+\\sqrt{x^2-1})^n \\end{pmatrix} \\\\\n= \\frac12 \\begin{pmatrix}\n(x-\\sqrt{x^2-1})^{n+1} + (x+\\sqrt{x^2-1})^{n+1} \\\\\n(x-\\sqrt{x^2-1})^n + (x+\\sqrt{x^2-1})^n\n \\end{pmatrix}\n$$</span></p>\n\n<p>So what this test boils down to is <span class=\"math-container\">$$(x-\\sqrt{x^2-1})^n + (x+\\sqrt{x^2-1})^n \\equiv 2x^n \\pmod n$$</span></p>\n\n<p>Expanding the LHS, <span class=\"math-container\">$$(x-\\sqrt{x^2-1})^n + (x+\\sqrt{x^2-1})^n = \n\\sum_{i=0}^n \\binom{n}{i} x^{n-i} \\left( (-\\sqrt{x^2-1})^{i} + (\\sqrt{x^2-1})^{i}\\right) \\\\\n= \\sum_{i=0}^n \\binom{n}{i} x^{n-i} (\\sqrt{x^2-1})^{i} \\left( (-1)^i + 1^i\\right) \\\\\n= \\sum_{i=0}^{n/2} \\binom{n}{2i} x^{n-2i} (\\sqrt{x^2-1})^{2i} \\\\\n= \\sum_{i=0}^{n/2} \\binom{n}{2i} x^{n-2i} (x^2-1)^{i} \\\\\n= \\sum_{i=0}^{n/2} \\binom{n}{2i} x^{n-2i} \\sum_{j=0}^i \\binom{i}{j} (x^2)^{i-j} (-1)^j \\\\\n= \\sum_{j=0}^{n/2} (-1)^j x^{n-2j} \\sum_{i=j}^{n/2} \\binom{n}{2i} \\binom{i}{j} \\\\\n$$</span></p>\n\n<p>So the test is that <span class=\"math-container\">$$\\forall 0 < j \\le \\tfrac n2: \\sum_{i=j}^{n/2} \\binom{n}{2i} \\binom{i}{j} \\equiv 0 \\pmod n$$</span></p>\n\n<p>But a direct calculation on that basis is worse than simply verifying that <span class=\"math-container\">$$\\forall 0 < j \\le \\tfrac n2: \\binom{n}{2j} \\equiv 0 \\pmod n$$</span> which is a perfectly valid primality test for odd <span class=\"math-container\">\\$n\\$</span>. And that itself is clearly worse than simply testing <span class=\"math-container\">$$\\forall 1 < j \\le \\sqrt{n}: n \\not \\equiv 0 \\pmod j$$</span></p>\n\n<p>So we're relying on the matrix exponentiation being extremely fast. Roughly speaking, we do <span class=\"math-container\">\\$O(1)\\$</span> polynomial multiplications for polynomials of order <span class=\"math-container\">\\$1, 2, 4, \\ldots, n\\$</span>, so if a multiplication of polynomials of length <span class=\"math-container\">\\$\\ell\\$</span> takes <span class=\"math-container\">\\$\\Theta(\\ell^\\alpha)\\$</span> then the overall exponentiation also takes <span class=\"math-container\">\\$\\Theta(n^\\alpha)\\$</span>. There's no way that <span class=\"math-container\">\\$\\alpha < \\tfrac12\\$</span>, so no matter how well optimised the implementation is it won't be faster than a naïve trial division.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T11:56:57.353",
"Id": "444880",
"Score": "1",
"body": "The number `r` seems to be completely irrelevant in the algorithm. I think it is quite likely that there is something wrong in the original implementation and `r` should take effect in some way (e.g. bound the polynominal lengths)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T12:16:00.320",
"Id": "444883",
"Score": "1",
"body": "Playing around the GP version of the code, it seems that the actual intention of `*rem(1,x**r-1)*(1%n)` is to create a symbolic representation of `% (x**r - 1)` and `% n` for each matrix element, which takes effect during the computation of matrix power."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T12:29:38.717",
"Id": "444886",
"Score": "0",
"body": "For more information see this post: https://mathoverflow.net/q/286304/88804"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T12:42:53.033",
"Id": "444888",
"Score": "0",
"body": "@PeđaTerzić The link should be put in the main post (ideally, from the very beginning) so that others do not need to spend time on inferring the algorithm from the code. And you might want to explain that your intention is to implement that specific algorithm rather than needing a primality test program that works."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T13:32:10.077",
"Id": "444897",
"Score": "0",
"body": "@GZ0, I could edit your observations into my answer, but I'd prefer it if you posted an answer pointing out how the Python code fails to port the Pari/GP code because you should get the rep for your efforts, not me."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T08:45:11.920",
"Id": "228895",
"ParentId": "228847",
"Score": "3"
}
},
{
"body": "<p>The provided implementation in the post is flawed and fails to port the Pari/GP code. In this statement </p>\n\n<pre><code>Matrix([[2*x, -1], [1, 0]])*rem(1,x**r-1)*(1%n)\n</code></pre>\n\n<p>the actual intentions of <code>rem(1, x**r-1)</code> and <code>(1%n)</code> are to create symbolic representations of <br /> <code>% (x**r - 1)</code> and <code>% n</code> for each matrix element, which is going to take effect during the computation of matrix power.</p>\n\n<p>However, under this implementation, <code>rem(1, x**r-1)</code> and <code>(1%n)</code> are both evaluated right away:</p>\n\n<pre><code>r = 3\nn = 11\nprint(rem(1, x**r-1), (1 % n))\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>1 1\n</code></pre>\n\n<p>Therefore, these are not no longer symbolic representations and would be eliminated immediately after being multiplied to the matrix.</p>\n\n<p>All in all I do not think the overall algorithm could be implemented easily using the <code>sympy</code> library. It would be more convenient to implement the matrix power-modulo operation yourself with the help of <code>numpy</code> to work with polynominal computations (see <a href=\"https://docs.scipy.org/doc/numpy/reference/routines.polynomials.html\" rel=\"nofollow noreferrer\">doc</a>). By the way, I am not sure whether that helps but <code>numpy</code> actually have a <a href=\"https://docs.scipy.org/doc/numpy/reference/routines.polynomials.chebyshev.html\" rel=\"nofollow noreferrer\"><code>chebyshev</code></a> module.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T16:12:36.483",
"Id": "444915",
"Score": "0",
"body": "[Hand-rolled](https://gist.github.com/pjt33/c9eb8b8adecc16d8b1d1afd5977abb68) it's still slower than a naïve approach, but notably faster than my previous rewrite of OP's code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T16:42:22.990",
"Id": "444917",
"Score": "0",
"body": "@PeterTaylor Given all those complex computations, there is no way that the performance of *a pure python implementation* could beat the naive approach *on small numbers*. The advantage on time complexity can only outweigh the overhead on significantly large inputs. Using `numpy` would delegate all the polynomial manipulation jobs to C, which should lead to some speedup."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T19:05:42.473",
"Id": "444934",
"Score": "0",
"body": "The disclaimer was preemptive: *someone* would have complained that it was still slower than trial division. But I wasn't actually basing anything on *pure* Python: I tested with PyPy. There *may* be some size of `n` at which NumPy gets an advantage, but its far far slower than the code I linked above for small `n`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T23:06:38.670",
"Id": "444945",
"Score": "0",
"body": "Yeah, the computation is still way too much for small `n`s and `numpy` definitely would not save that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T07:38:41.300",
"Id": "444962",
"Score": "0",
"body": "My point was that a hand-rolled implementation of Chebyshev polynomials modulo (n, x^r-1) using PyPy was orders of magnitude faster than an implementation using numpy polynomials. I.e. using numpy makes things worse, not better. PyPy seems to be a more effective way of bringing the speedup of native code to the problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T07:45:41.380",
"Id": "444963",
"Score": "0",
"body": "@PeterTaylor Do you have a `numpy`-based implementation? Meanwhile, you can [use `numpy` with PyPy](http://doc.pypy.org/en/latest/faq.html#should-i-install-numpy-or-numpypy) as well. They are not on the same level. PyPy is another Python interpreter. And `numpy` is a Python module. It seems to be comparing apples to oranges."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T08:11:52.093",
"Id": "444968",
"Score": "0",
"body": "Ah, you have to install modules separately for PyPy. How confusing. Will re-benchmark when I get home."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T16:16:56.150",
"Id": "445038",
"Score": "0",
"body": "Gist updated with NumPy version for comparison. I can't test NumPy+PyPy myself because `pypy3 -m pip` is broken, and I don't have a round tuit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T16:48:22.377",
"Id": "445041",
"Score": "0",
"body": "@PeterTaylor You could try [this](https://github.com/antocuni/pypy-wheels). By the way, have you timed NumPy-based vs. the pure Python implementation on the default CPython interpreter? If so, how was the result?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T16:53:49.893",
"Id": "445045",
"Score": "0",
"body": "Fair point. NumPy version takes 25 times longer than hand-rolled over n=1 to 1000."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T19:54:31.503",
"Id": "445069",
"Score": "0",
"body": "@PeterTaylor It turns out that most logic of the `Polynomial` class in `numpy` is written in pure Python and only a few core operations on the coefficient array is delegated to C. Therefore, when the number `r` is small, the extra overhead of creating new `Polynomial` objects and all the boilerplate code (for generality) significantly outweighs the core computation time, leading to its inefficiently. For better performance, the only resort seems to be working directly on the coefficient array with `numpy` rather than relying on the `Polynomial` class."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T14:28:06.857",
"Id": "228911",
"ParentId": "228847",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T15:15:12.323",
"Id": "228847",
"Score": "1",
"Tags": [
"python",
"performance",
"primes"
],
"Title": "Primality test in Python"
}
|
228847
|
<p>I have this little project i am about to release.</p>
<p><a href="https://github.com/holli-holzer/perl6-Win-VT" rel="noreferrer">https://github.com/holli-holzer/perl6-Win-VT</a></p>
<p>I would be happy about a code review and suggestions for a better name. </p>
<p>Discussion in IRC yielded Terminal::Win::VT or Terminal::Win32::VT::Enable as better alternatives. Or even Win32::Console::VT. </p>
<p>This is the gist of it. There are additional files, but those provide just sugar.</p>
<pre><code>unit module Win::VT;
use NativeCall;
constant STD_INPUT_HANDLE = -0xA;
constant STD_OUTPUT_HANDLE = -0xB;
constant ENABLE_VIRTUAL_TERMINAL_INPUT = 0x0200;
constant ENABLE_PROCESSED_INPUT = 0x0001;
constant ENABLE_PROCESSED_OUTPUT = 0x0001;
constant ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004;
constant DWORD := uint32;
constant BOOL := int32;
constant HANDLE := Pointer[void];
sub GetConsoleMode(HANDLE, DWORD is rw) is native('Kernel32') returns BOOL { * };
sub SetConsoleMode(HANDLE, DWORD) is native('Kernel32') returns BOOL { * };
sub GetStdHandle(DWORD) is native('Kernel32') returns HANDLE { * };
my HANDLE $input-handle;
my HANDLE $output-handle;
my DWORD $output-mode;
my DWORD $input-mode;
INIT {
if $*VM.osname eq "mswin32"
{
$input-handle = GetStdHandle( STD_INPUT_HANDLE );
$output-handle = GetStdHandle( STD_OUTPUT_HANDLE );
}
}
sub vt-on(Bool :$vt-input=True, Bool :$vt-output=True ) returns Bool is export(:MANDATORY)
{
return False
unless $input-handle.defined && $output-handle.defined;
return False
unless GetConsoleMode($input-handle, $input-mode) && GetConsoleMode($output-handle, $output-mode);
my $new-input-mode = $input-mode +| ENABLE_PROCESSED_INPUT +| ENABLE_VIRTUAL_TERMINAL_INPUT;
my $new-output-mode = $output-mode +| ENABLE_PROCESSED_OUTPUT +| ENABLE_VIRTUAL_TERMINAL_PROCESSING;
return (
( $vt-input ?? SetConsoleMode($input-handle, $new-input-mode) !! 1 ) &&
( $vt-output ?? SetConsoleMode($output-handle, $new-output-mode) !! 1 )
).Bool;
}
sub vt-off() returns Bool is export(:MANDATORY) {
return (
$input-handle.defined && $output-handle.defined &&
SetConsoleMode($output-handle, $output-mode) &&
SetConsoleMode($input-handle, $input-mode)
).Bool;
}
sub cls() is export(:cls) {
vt-on;
print chr(27) ~ '[2J' ~ chr(27) ~ '[;H';
vt-off;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T23:00:04.537",
"Id": "444802",
"Score": "1",
"body": "`*::ANSI` maybe? The VT series may have introduced these codes but they were formalized by an ANSI spec and most people would call them \"ANSI escape sequences\" today. Also `chr(27)` seems like it should be a constant."
}
] |
[
{
"body": "<p>Since no one else has replied, here's somewhat of a <a href=\"https://www.dreamincode.net/forums/topic/374098-any-thoughts-on-rubber-duck-code-reviews/\" rel=\"nofollow noreferrer\">\"rubber duck code review\"</a> given that I don't know much about Windows, vt, and NativeCall. Plus I've got a suggestion about the API and module name.</p>\n\n<hr>\n\n<p>It looks like the not-explicitly-initialized <code>$input-mode</code> and <code>$output-mode</code> variables are actually constants implicitly initialized to zero. I think the code would be less confusing if they were declared as constants or even if you used literal <code>0</code>s instead of them. Perhaps other code or configuration you have, or have in mind, will vary these values? Anyhow, at the very least, I think a comment making it clear the values the user passes to <code>vt-on</code> don't alter these, and <code>vt-off</code> is resetting them no matter what <code>vt-on</code> did, would be helpful.</p>\n\n<hr>\n\n<p>From an API perspective, aiui, if one calls <code>vt-on</code> it turns the vt stuff on for both input and output. You have to pass <code>:vt-input(False)</code> if you only want <code>vt-output</code> and vice-versa. And <code>vt-off</code> always turns both off.</p>\n\n<p>To me, having to write <code>vt-input(False)</code> is a bit ugly because:</p>\n\n<ul>\n<li><p>It repeats the <code>vt</code>;</p></li>\n<li><p>Mentions <code>input</code> when what one is trying to do is control <code>output</code>;</p></li>\n<li><p>Requires explicit use of <code>False</code>.</p></li>\n</ul>\n\n<p>It seems to me it could be more ergonomic to have just one routine, <code>vt</code>. To switch both input and output on use <code>vt :on</code>. To switch both off use <code>vt :off</code>. To switch just one on and leave the other as it is, use <code>vt :on<input></code> or <code>vt :on<output></code>. To switch just one <em>off</em> and leave the other as it is, use <code>vt :off<input></code> or <code>vt :off<output></code>.</p>\n\n<p>I've never used vt stuff and could imagine one doesn't need the extra flexibility of the API I suggest but my suggestion is really more about keeping the API sweet than it is about the additional flexibility.</p>\n\n<hr>\n\n<p>As for the module name...</p>\n\n<p>I currently think we should shift all of our emphasis related to module <em>discovery</em> to an assumption of widespread use of global search via keywords, tags, etc. For now that means eg <a href=\"https://modules.perl6.org/t/TERMINAL\" rel=\"nofollow noreferrer\">'terminal' tag search</a> or <a href=\"https://modules.perl6.org/search/?q=TERMINAL\" rel=\"nofollow noreferrer\">'terminal' keyword search</a> but one day there'll surely be search of a module's Pod and other aspects as well. In summary, imo, don't worry about a name's <em>discoverability</em>.</p>\n\n<p>To the degree that a module's name matters, I think it's beyond discoverability. I think the two key things are considering clustering with names already chosen or likely to be chosen by other module authors, and making a name nice in a <code>use</code> statement. For these latter aspects I'd say:</p>\n\n<ul>\n<li><p>Consider following <em>accepted hierarchical namespace norms</em> already established for <a href=\"https://modules.perl6.org/\" rel=\"nofollow noreferrer\">modules.perl6.org</a>. But don't sweat it.</p></li>\n<li><p>If there are no obvious relevant norms to follow then keep a module name fairly short and sweet. Do you really need bumpy case or hyphens? Do you really need more than one <code>::</code> divider? Then again, don't pick something egregiously short-sighted. You could name it just <code>VT</code> but a module such as yours doesn't warrant such a name.</p></li>\n</ul>\n\n<hr>\n\n<p>Other than that the code all makes sense to me and looks fine to me from a pure P6 perspective.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T13:26:38.410",
"Id": "229061",
"ParentId": "228850",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T15:48:01.120",
"Id": "228850",
"Score": "6",
"Tags": [
"modules",
"raku"
],
"Title": "Raku / Perl6: A module to enable escape codes in the win32 console, naming suggestions"
}
|
228850
|
<p>The code takes a list of names and extracts the three letter pattern from the names. Then return the list of names as a value in the dictionary with key as a pattern. The list name has a fixed naming pattern like three letter Spp in the example. It can extent like App, Bpp, Cpp etc..</p>
<p>How can I improve this code?</p>
<pre><code>import sys
import re
def uniquelist(scaffold_names_list):
unique_names = []
for name in scaffold_names_list:
pattern_name = re.search(r"[A-Z]{1}[a-z]{2}", name)
unique_names.append(pattern_name.group())
unique_names = list(set(unique_names))
return unique_names
def uniquepattern(scaffold_names_list):
unique_names = uniquelist(scaffold_names_list)
dct = {}
for singlepattern in unique_names:
dct['%s' % singlepattern] = []
for singelelist in scaffold_names_list:
number = re.search(r"[A-Z]{1}[a-z]{2}", singelelist)
number = number.group()
for singlepattern in unique_names:
if number == singlepattern:
dct[singlepattern].append(singelelist)
return dct
scaffold_names_list = ['Spp1Aa1', 'Spp1Aa1', 'Spp2Aa1', 'Spp3Aa1', 'Spp4Aa1', 'Spp5Aa1']
patterns = uniquepattern(scaffold_names_list)
print(patterns)
{'Spp': ['Spp1Aa1', 'Spp1Aa1', 'Spp2Aa1', 'Spp3Aa1', 'Spp4Aa1', 'Spp5Aa1']}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T16:01:43.553",
"Id": "444769",
"Score": "1",
"body": "Are your patterns always the first three characters of the name?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T16:34:33.397",
"Id": "444771",
"Score": "0",
"body": "Yes. That's right."
}
] |
[
{
"body": "<p><strong>Naming</strong></p>\n\n<p>I have two problems with your naming: </p>\n\n<p>First, you don't use underscores to separate words. Instead of <code>uniquepattern</code>, use <code>unique_pattern</code>. </p>\n\n<p>Second, your names don't actually tell me anything! Functions, particularly non-method functions, should include a verb unless the verb is implicitly <code>get</code> or <code>is</code>. And implicit <code>is</code> needs to be used with some caution.</p>\n\n<p>So rather than <code>unique_pattern</code>, the name should be some phrase reflective of what your function does. Since you mention \"scaffold names\", perhaps that function should be <code>group_scaffold_names_by_unique_pattern</code>?</p>\n\n<p>Or maybe the unique pattern has another name? Like <code>prefix</code>? (See my question in the comments.) So perhaps it should be <code>group_scaffold_names_by_prefix</code>?</p>\n\n<p>Is that long? Yes. Does it says what happens? Also, yes. Clarity for the win!</p>\n\n<p><strong>Redundancy. Repetition. Duplication. Multiple Copies.</strong></p>\n\n<p>In coding, if you find yourself typing something for the second time, STOP! Whatever this is needs to be stored once and referenced from different places. Write a function. Store text in a variable. Create a class. Do whatever it takes, but DON'T REPEAT YOURSELF. (This is called the \"DRY\" principle.)</p>\n\n<p>This code is repeated:</p>\n\n<pre><code> pattern_name = re.search(r\"[A-Z]{1}[a-z]{2}\", name)\n</code></pre>\n\n<p>What does it do? Well, it appears to be used to extract the first matching pattern as the \"key\" for each name in the list.</p>\n\n<p>So let's write a function for this:</p>\n\n<pre><code>def extract_key(name):\n \"\"\" Extract unique pattern from a scaffold name. \n Apparently, patterns are just the first three characters,\n so don't use regexes, just grab the substring.\n \"\"\" \n return name[:3]\n</code></pre>\n\n<p><strong>Use the standard library</strong></p>\n\n<p>You have a separate function that pulls out the keys (unique patterns) from the names, and returns a uniquified list of them, which you apparently use only to initialize the keys of a dictionary.</p>\n\n<p>Instead of doing that, just use <a href=\"https://docs.python.org/3/library/collections.html?highlight=collections%20defaultdict#collections.defaultdict\" rel=\"nofollow noreferrer\"><code>collections.defaultdict</code></a> to create a dictionary that starts with empty lists:</p>\n\n<pre><code>import collections\n\ngroups = collections.defaultdict(list)\n</code></pre>\n\n<p>With that code, you can be sure that <code>groups[key]</code> is a list (unless you explicitly override it with some non-list value). So let's write your function again:</p>\n\n<pre><code>import collections\nfrom typing import Dictionary, Iterable, List\n\ndef group_scaffold_names_by_prefix(names: Iterable[str]) -> Dictionary[str, List[str]]:\n \"\"\" Given a list of scaffold names, return a dictionary that\n groups them together by their prefix.\n \"\"\"\n groups = collections.defaultdict(list)\n\n for name in names:\n groups[extract_key(name)].append(name)\n\n return groups\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T17:31:42.577",
"Id": "444776",
"Score": "0",
"body": "Thank you very much. Let me read and understand."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T16:47:56.690",
"Id": "228856",
"ParentId": "228851",
"Score": "4"
}
},
{
"body": "<p>Naming: According to PEP8, you should make all these names snake_case. This is good, but the important bits here are:</p>\n\n<ol>\n<li>Do the same thing consistently</li>\n<li>Have a clear word seperator.</li>\n</ol>\n\n<p>Basically, this means you can use snake_case, camelCase, or even TitleCase, but the last one is generally used only for classes. I'm personally partial to camelCase for functions/methods and snake_case for variables, but snake_case for both is more common, and that's what I'll be using here.</p>\n\n<p>Most important, naming should be meaningful. What does this function do? It parses a list of strings, and returns part of those strings. You've called these strings <code>names</code>, so we'll use something like that.</p>\n\n<p>Also, keep names short. This makes it easier to read.</p>\n\n<p>You first build a list, append to it, convert to a set, then convert to a list again to make them unique. In this case, I'd recommend to start out with a set. The role of this function is to figure out unique <em>prefixes</em> though - not full names. </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def get_prefixes(long_names):\n short_names = set() # set instead of list.\n for name in long_names:\n short_names.add(name[:3]) # Just slice a string if prefix length is constant.\n return list(unique_names) # Use sorted() instead of list if you care about that.\n # Can return right away. No need to reassign it first.\n</code></pre>\n\n<p>What else is easily noticeable? This is a rather straightforward loop. Python has a special tool to make this operation a bit easier: list/set/dict/generator comprehensions. Making this a set comprehension later cast to a list:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def get_prefixes(long_names):\n return list({name[:3] for name in long_names})\n# If you insist on regex:\ndef get_prefixes(long_names):\n return list({re.search(r\"[A-Z]{1}[a-z]{2}\", name) for name in long_names})\n</code></pre>\n\n<p>That's a lot more shorter, and others reading your code can read it easier.</p>\n\n<p>@Austin Hastings here goes into stdlib usage. If you're looking for performance, that's what you should do. If you're looking to write good production code, that's what you should do. However, I'm going to assume part of this is learning how to code, so I'll rewrite this function.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def uniquepattern(names):\n [other stuff happens]\n for singlepattern in unique_names:\n dct['%s' % singlepattern] = []\n</code></pre>\n\n<p>Why do string % formatting here? There's no reason, since that list already contains strings and only strings. You can just use it as key. Or even better, combine it with the dict declaration:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> dct = {key, [] for key in unique_names}\n</code></pre>\n\n<p>Now lets have a look at filling that dict:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> for singelelist in names: # Spelling error here. \n number = re.search(r\"[A-Z]{1}[a-z]{2}\", singelelist)\n number = number.group()\n\n for singlepattern in unique_names:\n if number == singlepattern:\n dct[singlepattern].append(singelelist)\n</code></pre>\n\n<p>That's a double iteration. I really can't figure out why we need that, since we can easily grab the prefixes from the names themselves:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> for name in names:\n dct[name[:3]].append(name)\n</code></pre>\n\n<p>And even if we need to use regexes to accomodate for variable prefix length, it's easy:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> for name in names:\n dct[re.search(r\"[A-Z]{1}[a-z]{2}\", name).group()].append(name)\n</code></pre>\n\n<p>This single loop means that we don't use <code>unique_names</code> more than once, which means we can merge it into where it's used.</p>\n\n<p>So for the entire function we get a much more modest:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def name_sorter(names):\n dct = {key: [] for key in get_prefixes(names)}\n for name in names:\n dct[name[:3]].append(name)\n return dct\n</code></pre>\n\n<p>And they say python code can't be concise...</p>\n\n<p>So our full script would become:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def get_prefixes(long_names):\n return list({name[:3] for name in long_names})\n\ndef name_sorter(names):\n dct = {key: [] for key in get_prefixes(names)}\n for name in names:\n dct[name[:3]].append(name)\n return dct\n\nif __name__ == \"__main__\":\n scaffold_names_list = ['Spp1Aa1', 'Spp1Aa1', 'Spp2Aa1', 'Spp3Aa1', 'Spp4Aa1', 'Spp5Aa1']\n patterns = name_sorter(scaffold_names_list)\n print(patterns)\n</code></pre>\n\n<p>Note that I included a <code>if __name__ == \"__main__\":</code> guard. This means that other scripts can import this file without actually running any code, only making the functions available. But if any script is executed directly, python sets the <code>__name__</code> variable to the string <code>\"__main__\"</code>, and it is executed. This is widely considered good practice.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T18:55:42.833",
"Id": "228863",
"ParentId": "228851",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "228856",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T15:55:40.730",
"Id": "228851",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"regex"
],
"Title": "Extract three letter pattern from a given list"
}
|
228851
|
Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served. Use this tag for questions related to CORS.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T16:20:39.300",
"Id": "228853",
"Score": "0",
"Tags": null,
"Title": null
}
|
228853
|
<p>I have my below prototyped script and it runs fine but I need to scale it out at large. So, wanted to get feedback if my script can be improved in terms of performance and if there are any non standard stuff am doing in it.</p>
<p>What is does: Script is to delete all the pods under defined namespaces and then also from kube-system namespace only certain pods. It also gives user 10sec to chose to cancel. Operation.</p>
<p>I am going to merge this to production but I want to assure am atleast in good shape to do coz there will be 1000s of pods in production. Am new to coding, if bash is best choice, please suggest how to proceed with it. </p>
<pre><code>#!/bin/bash
TT_NAMESPACES=(ambassador
argo-workflow-controller
webhook
)
#Pulling teamstest pods under teamstest service name namespace
printf "Deleting pods for teamstest Namespaces: %s\n" "${TT_NAMESPACES[@]}"
for nmspc in ${TT_NAMESPACES[@]}
do
printf "Terminate Jenkins Job in: %d seconds to cancel this operation\n" "10"
sleep 10
printf "Deleting PODS for Namespace: %s\n" "$nmspc"
kubectl -n $nmspc delete --all pods --force --grace-period 0
printf '\n'
done
#Pulling teamstest pods under Kube-system namespace
TT_SERVICES_KS_NMSPC=(local-volume-provisioner
registry-creds
tiller
)
printf "Deleting pods for teamstest services in kube-system Namespace: %s\n" "${TT_SERVICES_KS_NMSPC[@]}"
for ml_service_pod in ${TT_SERVICES_KS_NMSPC[@]}
do
printf "Deleting teamstest PODS for %s in Kube-System Namespace\n" "$ml_service_pod"
printf "Terminate Jenkins Job in: %d seconds to cancel this operation\n" "10"
sleep 10
kubectl -n kube-system get pods | grep $ml_service_pod | xargs -l1 -- sh -c 'kubectl -n kube-system delete pod $1 --force --grace-period 0' --
printf '\n'
done
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T18:34:01.033",
"Id": "444784",
"Score": "1",
"body": "Welcome to Code Review! Why is this question tagged with [tag:python]? There does not seem to be a single line of Python code in the whole post, but only bash?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T21:05:56.480",
"Id": "444798",
"Score": "0",
"body": "Oh I thought with Python Tag I can get Python code for similar func."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T21:07:56.777",
"Id": "444799",
"Score": "2",
"body": "That's not the purpose of this site! Code Review is a platform where you can get feedback on the code you have written, but *not* a code writing service."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T17:24:38.973",
"Id": "228858",
"Score": "0",
"Tags": [
"performance",
"bash"
],
"Title": "bash script at scale for kubernetes kubectl operations"
}
|
228858
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.