body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I have currently problem with discord bot, what is in Python programming language. This commands loading take so long, and I need help with optimization of this code. </p>
<pre class="lang-py prettyprint-override"><code>from fractions import Fraction
import discord
from discord.ext import commands
import asyncio
import asyncpg
import datetime
from aiohttp import web
import random
import json
import math
class Info(commands.Cog):
def __init__(self, bot):
self.bot = bot
with open('./poke/resources/pokemon_list.json') as pokemon_list_file:
global pokemon_list
pokemon_list = json.load(pokemon_list_file)
with open('./poke/resources/natures.json') as natures_file:
global natures
natures1 = json.load(natures_file)
global pokes
pokes = {}
for pokesm in pokemon_list['pokemons']:
name = pokesm['name']
pokes[name] = {}
pokes[name]['image_url'] = pokesm['image']
pokes[name]['hp'] = pokesm['hp']
pokes[name]['attack'] = pokesm['attack']
pokes[name]['defense'] = pokesm['defense']
pokes[name]['special_attack'] = pokesm['special_attack']
pokes[name]['special_defense'] = pokesm['special_defense']
pokes[name]['speed'] = pokesm['speed']
global natures
natures = {}
for naturesm in natures1['natures']:
nature = naturesm['name']
natures[nature] = {}
natures[nature]['boost'] = naturesm['boost']
natures[nature]['remove'] = naturesm['remove']
@commands.command(name="info", aliases=['i'])
async def info(self, ctx, poke):
con = await self.bot.pool.acquire()
fetch_id = await con.fetchval("SELECT pokes[{0}] FROM users WHERE u_id = {1}".format(poke, ctx.message.author.id))
name = await con.fetchval("SELECT name FROM pokes WHERE id = {0}".format(fetch_id))
hpiv = await con.fetchval("SELECT hpiv FROM pokes WHERE id = {0}".format(fetch_id))
atkiv = await con.fetchval("SELECT atkiv FROM pokes WHERE id = {0}".format(fetch_id))
defiv = await con.fetchval("SELECT defiv FROM pokes WHERE id = {0}".format(fetch_id))
spatkiv = await con.fetchval("SELECT spatkiv FROM pokes WHERE id = {0}".format(fetch_id))
spdefiv = await con.fetchval("SELECT spdefiv FROM pokes WHERE id = {0}".format(fetch_id))
speediv = await con.fetchval("SELECT speediv FROM pokes WHERE id = {0}".format(fetch_id))
hpev = await con.fetchval("SELECT hpev FROM pokes WHERE id = {0}".format(fetch_id))
atkev = await con.fetchval("SELECT atkev FROM pokes WHERE id = {0}".format(fetch_id))
defev = await con.fetchval("SELECT defev FROM pokes WHERE id = {0}".format(fetch_id))
spatkev = await con.fetchval("SELECT spatkev FROM pokes WHERE id = {0}".format(fetch_id))
spdefev = await con.fetchval("SELECT spdefev FROM pokes WHERE id = {0}".format(fetch_id))
speedev = await con.fetchval("SELECT speedev FROM pokes WHERE id = {0}".format(fetch_id))
lvl = await con.fetchval("SELECT lvl FROM pokes WHERE id = {0}".format(fetch_id))
exp = await con.fetchval("SELECT exp FROM pokes WHERE id = {0}".format(fetch_id))
nature = await con.fetchval("SELECT nature FROM pokes WHERE id = {0}".format(fetch_id))
ability = await con.fetchval("SELECT ability FROM pokes WHERE id = {0}".format(fetch_id))
hp_base = pokes[name]['hp']
atk_base = pokes[name]['attack']
def_base = pokes[name]['defense']
spatk_base = pokes[name]['special_attack']
spdef_base = pokes[name]['special_defense']
speed_base = pokes[name]['speed']
hp = math.floor((int((2 * hp_base + hpiv + int(hpev / 4)) * lvl) / 100) + lvl + 10)
self.attack = int((int((2 * atk_base + atkiv + int(atkev / 4)) * lvl) / 100) + 5)
self.defense = int((int((2 * def_base + defiv + int(defev / 4)) * lvl) / 100) + 5)
self.special_attack = int((int((2 * spatk_base + spatkiv + int(spatkev / 4)) * lvl) / 100) + 5)
self.special_defense = int((int((2 * spdef_base + spdefiv + int(spdefev / 4)) * lvl) / 100) + 5)
self.speed = int((int((2 * speed_base + speediv + int(speedev / 4)) * lvl) / 100) + 5)
total = int(hpiv) + int(atkiv) + int(defiv) + int(spatkiv) + int(spdefiv) + int(speediv)
iv_percentage = 100 * (total/186)
if natures[nature]['boost'] == "Attack":
attack_initial = self.attack
self.attack = int(attack_initial) * 1.1
elif natures[nature]['boost'] == "Defense":
defense_initial = self.defense
self.defense = int(defense_initial) * 1.1
elif natures[nature]['boost'] == "Special Attack":
special_attack_initial = self.special_attack
self.special_attack = int(special_attack_initial) * 1.1
elif natures[nature]['boost'] == "Special Defense":
special_defense_initial = self.special_defense
self.special_defense = int(special_defense_initial) * 1.1
elif natures[nature]['boost'] == "Speed":
speed_initial = self.speed
self.speed = int(speed_initial) * 1.1
if natures[nature]['remove'] == "Attack":
attack_initial = self.attack
self.attack = int(attack_initial) * 0.9
elif natures[nature]['remove'] == "Defense":
defense_initial = self.defense
self.defense = int(defense_initial) * 0.9
elif natures[nature]['remove'] == "Special Attack":
special_attack_initial = self.special_attack
self.special_attack = int(special_attack_initial) * 0.9
elif natures[nature]['remove'] == "Special Defense":
special_defense_initial = self.special_defense
self.special_defense = int(special_defense_initial) * 0.9
elif natures[nature]['remove'] == "Speed":
speed_initial = self.speed
self.speed = int(speed_initial) * 0.9
embed = discord.Embed(title="Level {0} {1}".format(lvl, name), description="""
**Ability**: {0}
**Exp**: {1}
**Nature**: {2}
**HP**: {3} | {4} IVs | {5} EVs
**Attack**: {6} | {7} IVs | {8} EVs
**Defense**: {9} | {10} IVs | {11} EVs
**Special Attack**: {12} | {13} IVs | {14} EVs
**Special Defense**: {15} | {16} IVs | {17} EVs
**Speed**: {18} | {19} IVs | {20} EVs
**IV %**: {21}""".format(ability, exp, nature, hp, hpiv, hpev, int(self.attack), atkiv, atkev, int(self.defense), defiv, defev, int(self.special_attack), spatkiv, spatkev, int(self.special_defense), spdefiv, spdefev, int(self.speed), speediv, speedev, round(iv_percentage, 2)))
embed.set_image(url=pokes[name]['image_url'])
await ctx.send(embed=embed)
await self.bot.pool.release(con)
def setup(bot):
bot.add_cog(Info(bot))
</code></pre>
<p>Just I can't release beta, when this responses take 20 sec sometimes. I want this respond in max 2 sec.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T07:48:24.480",
"Id": "447432",
"Score": "0",
"body": "Just a hint: Why are you doing almost 20 separate database queries when it could be done with one?"
}
] | [
{
"body": "<p>Almost certainly the largest slow-down is that you are getting each individual value on its own. Instead get all information at once:</p>\n\n<pre><code>poke_query = \"\"\"\nSELECT\nhpiv, atkiv, defiv, spatkiv, spdefiv, speediv, \nhpev, atkev, defev, spatkev, spdefev, speedev,\nlvl, exp, nature\nFROM pokes\nWHERE id = {}\"\"\"\n\npoke_info = await con.execute(poke_query.format(fetch_id)).fetchone()\n</code></pre>\n\n<p>Note that the parameters you pass to <code>str.format</code> are put into the placeholders in the order you pass them, so e.g. <code>\"{0} {1} {2}\".format(1, 2, 3)</code> is equivalent to <code>\"{} {} {}\".format(1, 2, 3)</code>.</p>\n\n<p>You should be able to access the individual columns with their names (e.g. <code>poke_info.hpiv</code>) or like a tuple (e.g. <code>poke_info[0]</code>).</p>\n\n<p>In addition, most SQL packages allow using parameters. This prevents <a href=\"https://en.wikipedia.org/wiki/SQL_injection\" rel=\"nofollow noreferrer\">SQL injections</a>, which you should be vary of, because the user of the bot controls the value of <code>poke</code>. I think in your case it would be as easy as</p>\n\n<pre><code>poke_query = \"\"\"\nSELECT\nhpiv, atkiv, defiv, spatkiv, spdefiv,\nspeediv, hpev, atkev, defev, speedev,\nlvl, exp, nature\nFROM pokes\nWHERE id = ?\"\"\"\n\npoke_info = await con.execute(poke_query, fetch_id).fetchone()\n</code></pre>\n\n<p>For the poke ID it is similarly:</p>\n\n<pre><code>fetch_id = await con.fetchval(\"SELECT pokes[?] FROM users WHERE u_id = ?\",\n poke, ctx.message.author.id)\n</code></pre>\n\n<p>These are assuming you are using <a href=\"https://github.com/mkleehammer/pyodbc/wiki/Getting-started\" rel=\"nofollow noreferrer\">pyodbc</a>, but there are equivalent ways to achieve the same thing in other packages.</p>\n\n<p>For example with <a href=\"https://magicstack.github.io/asyncpg/current/index.html\" rel=\"nofollow noreferrer\">asyncpg</a> it would be <code>$1</code> instead of <code>?</code>:</p>\n\n<pre><code>poke_query = \"\"\"\nSELECT\nhpiv, atkiv, defiv, spatkiv, spdefiv,\nspeediv, hpev, atkev, defev, speedev,\nlvl, exp, nature\nFROM pokes\nWHERE id = $1\"\"\"\n\npoke_info = await con.fetchrow(poke_query, fetch_id)\n</code></pre>\n\n<p>Where each value can be accessed as <code>poke_info['hpiv']</code> or <code>poke_inf[0]</code>.</p>\n\n<hr>\n\n<p>There is no need for <code>pokes</code> and <code>natures</code> to be <code>global</code> values. The way you currently define them they are class variables and you can access them both with <code>Info.pokes</code> and <code>self.pokes</code>. Beware that these are initialized at class definition time. So if you change the config files you need to restart the script/bot/interpreter. If you put that code into the constructor <code>__init__</code> it would be read everytime a new instance of <code>Info</code> is created and <code>pokes</code> becomes an attribute so can only be accessed via <code>self.pokes</code>.</p>\n\n<p>You can also use dictionary expressions to make this a bit easier.</p>\n\n<pre><code>class Info(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n with open('./poke/resources/pokemon_list.json') as pokemon_list_file:\n pokemon_list = json.load(pokemon_list_file)\n self.pokes = {p['name']: {'image_url': p['image'],\n 'hp': p['hp'],\n 'attack': p['attack'],\n 'defense': p['defense'],\n 'special_attack': p['special_attack'],\n 'special_defense': p['special_defense'],\n 'speed': p['speed']}\n for p in json.load(pokemon_list_file)}\n\n with open('./poke/resources/natures.json') as natures_file:\n self.natures = {n['name']: {'boost': n['boost'],\n 'remove': n['remove']}\n for n in json.load(natures_file)}\n</code></pre>\n\n<p>Things get even easier if you don't care that the inner dictionaries also contain the name (and any additional keys) and that the name of the image url changes:</p>\n\n<pre><code>class Info(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n with open('./poke/resources/pokemon_list.json') as pokemon_list_file:\n pokemon_list = json.load(pokemon_list_file)\n self.pokes = {p['name']: p for p in json.load(pokemon_list_file)}\n\n with open('./poke/resources/natures.json') as natures_file:\n self.natures = {n['name']: n for n in json.load(natures_file)}\n</code></pre>\n\n<hr>\n\n<p>I can't say I completely understand all the calculations of the actual stats from the IVs, EVs and base stats. But try to save each stat as its natural type. If a thing is an <code>int</code>, save it as an <code>int</code> from the beginning and don't continuously cast it to an <code>int</code>. This will not save a lot of runtime but make it a lot easier to read.</p>\n\n<p>Another thing you could to for this is put the calculations into their own functions, which you can give a name and docstring explaining what the function does. It also makes it immediately clear that the actual calculation is the same in all cases.</p>\n\n<pre><code>def calc(base, iv, ev, lvl):\n \"\"\"Calculate the actual stat from the base value, IV, EV and current level.\"\"\"\n return int((int((2 * base + iv + int(ev / 4)) * lvl) / 100) + 5)\n\nself.attack = calc(atk_base, atk_iv, atk_ev, lvl)\nself.defense = calc(def_base, def_iv, def_ev, lvl)\n...\n</code></pre>\n\n<p>For the boosts and removes, you can shorten it a bit using a mapping from the name to the internal name and in-place operations:</p>\n\n<pre><code>mapping = {\"Attack\": \"attack\", \"Defense\": \"defense\",\n \"Special Attack\": \"special_attack\", \"Special Defense\": \"special_defense\"}\n\nnature = self.natures[nature]\nself.__dict__[mapping[nature['boost']]] *= 1.1\nself.__dict__[mapping[nature['remove']]] *= 0.9\n</code></pre>\n\n<p>Instead of this dict you can also use the fact that there is an easy way to convert from one to the other:</p>\n\n<pre><code>def nature_to_attr(name):\n return name.lower().replace(\" \", \"_\")\n\nnature = self.natures[nature]\nself.__dict__[nature_to_attr(nature['boost'])] *= 1.1\nself.__dict__[nature_to_attr(nature['remove'])] *= 0.9\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T14:23:46.643",
"Id": "447344",
"Score": "0",
"body": "One note: Asyncpg doesn't have fetchone feature, and when you use fetch, you get result like this:\n`[<Record ability=None>, <Record ability=None>]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T14:25:33.287",
"Id": "447346",
"Score": "0",
"body": "@ks1001 It does have [`fetchrow`](https://magicstack.github.io/asyncpg/current/api/index.html#asyncpg.cursor.Cursor.fetchrow), though, which is what I used in the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T14:29:33.510",
"Id": "447347",
"Score": "0",
"body": "I am not really familiar with `asyncpg`, so you might have to call it slightly differently (obviously I could not test the code). Maybe it is actually `con.cursor(poke_query, fetch_id).fetchrow()` or something similar."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T14:34:06.877",
"Id": "447350",
"Score": "0",
"body": "I'll try to move psycopg2, but only when I can get pool over the Cogs (different files)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T14:06:42.633",
"Id": "229849",
"ParentId": "229842",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "229849",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T10:24:01.407",
"Id": "229842",
"Score": "0",
"Tags": [
"python",
"postgresql",
"automation"
],
"Title": "Discord.py Pokemon Bot performance problems"
} | 229842 |
<p>This problem is from [CCC2019]: <a href="https://dmoj.ca/problem/ccc19s5/" rel="nofollow noreferrer">https://dmoj.ca/problem/ccc19s5/</a> (Canadian Computing Contest 2019) and I have implemented it in C++.</p>
<p>I used sequence [A054237]: <a href="https://oeis.org/A054237/table" rel="nofollow noreferrer">https://oeis.org/A054237/table</a> to compute the indexes of sub-triangles.</p>
<blockquote>
<p>In a parallel universe, the most important data structure in computer science is the triangle. A triangle of size M M consists of M M rows, with the i t h i^{th} row containing i i elements. Furthermore, these rows must be arranged to form the shape of an equilateral triangle. That is, each row is centred around a vertical line of symmetry through the middle of the triangle. For example, the diagram below shows a triangle of size 4:</p>
<p>A triangle contains sub-triangles. For example, the triangle above contains ten sub-triangles of size 1, six sub-triangles of size 2 (two of which are the triangle containing ( 3 , 1 , 2 ) (3,1,2) and the triangle containing ( 4 , 6 , 1 ) (4,6,1) ), three sub-triangles of size 3 (one of which contains ( 2 , 2 , 1 , 1 , 4 , 2 ) (2,2,1,1,4,2) ). Note that every triangle is a sub-triangle of itself.</p>
<p>You are given a triangle of size N N and must find the sum of the maximum elements of every sub-triangle of size K K .</p>
</blockquote>
<p>Please review and suggest edits.</p>
<pre><code>#include<stdio.h>
int rec(int x)
{
return (x*(x+1))/2; //sum of n natural numbers
}
int main()
{ int n,k; //n=height of triangle k=height of sub-triangles ne= number of elements
int t1=0;
int t2=0;
std::scanf("%d %d",&n,&k);
int ne=rec(n);
int rk=rec(k); //rk=number of elements in sub-triangle
int nt=ne-rk-1; //ior[]=array to store index of row nt=number of sub-triangles
unsigned long int e[ne],gval,sum=0; //e[]=array to store elements gval=greatest element of sub-triangle sum=sum of gvals
gval=0;
for(int i=0;i<ne;i++)
scanf("%ld",&e[i]);
for(int rt=0,ior=0;ior<nt;rt++)
{
for(int ioc,r=0; r<=rt && ior<nt; r++,ior++)
{ ioc=0;
for(int ct=0;ioc<rk;ct++)
{
for(int c=0;c<=ct && ioc<rk;ioc++,c++,t2++)
{
if(gval<e[t2])gval=e[t2];
}
t2+=rt;
}
sum+=gval;
t1++;
t2=t1;
gval=0;
}
}
std::printf("%ld",sum);
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T10:56:32.607",
"Id": "447333",
"Score": "0",
"body": "Please review and suggest improvements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T11:11:43.563",
"Id": "447334",
"Score": "1",
"body": "I can't see any c++ specific code in your question besides _`using namespace std;`_, which is discouraged anyways."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T11:14:23.423",
"Id": "447335",
"Score": "1",
"body": "@πάνταῥεῖ are you saying this isn't c++? I am high schooler and still learning. Why is using namespace std discouraged?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T11:19:46.640",
"Id": "447336",
"Score": "0",
"body": "This isn't c++ but merely c code. Regarding the `using namespace std;` read up [here](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) please."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T11:23:34.420",
"Id": "447337",
"Score": "0",
"body": "@πάνταῥεῖ I am using code blocks as my IDE and gcc as compiler. It states the language as c++11 instead of c. Keeping language aside, I am just asking for algorithmic optimization and that I think is kinda universal for all languages."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T11:27:01.127",
"Id": "447338",
"Score": "0",
"body": "@πάνταῥεῖ using namespace omitted"
}
] | [
{
"body": "<p>Welcome to Code Review.</p>\n\n<p>As stated in the comments, the code is the C programming language, not C++. C is a procedural language and C++ is an object oriented lanugage originally based on C. We can tell from the first line,</p>\n\n<pre><code>#include <stdio.h>\n</code></pre>\n\n<p>In C++ this file would be <code><cstdio></code> but generally we would not be using it because represents an older form of input/output that has been replaced in C++.</p>\n\n<p>C++ generally uses </p>\n\n<pre><code>#include <iostream>\n</code></pre>\n\n<p>which provides <code>std::cin</code> as input and <code>std::cout</code> as output.</p>\n\n<p>The functions <code>printf()</code> and <code>scanf()</code> generally are not used in C++. FYI <code>scanf()</code> and <code>printf()</code> are not members of the std namespace and <code>std::scanf()</code> does not compile in many compilers.</p>\n\n<p><strong>Complexity</strong><br>\nIt might be better if there was a function to get the input and another function to process the input. This would lead to less variables being declared in <code>main()</code> and functions that are shorter, easier to read debug and maintain.</p>\n\n<p><strong>Variable Declarations</strong><br>\nThe line of code:</p>\n\n<pre><code> unsigned long int e[ne],gval,sum=0;\n</code></pre>\n\n<p>Is difficult to maintain, it would be better if it was multiple lines.</p>\n\n<pre><code> unsigned long e[ne];\n unsigned long gval;\n unsigned long sum=0;\n</code></pre>\n\n<p>Also one should choose either <code>long</code> or <code>int</code> but not both. It would be best if <code>gval</code> was also initialized.</p>\n\n<p>Variables should be declared as needed, for instance the variable <code>gval</code> should be defined inside the first inner for loop as shown below:</p>\n\n<p><strong>Variable Names</strong><br>\nRather than providing comments to explain what the variables are, give the variables meaningful names longer than 2 characters.</p>\n\n<p>This makes the code much easier to read, debug and modify.</p>\n\n<p><strong>Spacing</strong><br>\nThe vertical and horizontal spacing of the code is all crammed together which makes it very difficult to read add vertical spacing after declarations and after logic blocks.</p>\n\n<p>In expressions there should be spaces around binary operators as shown below.</p>\n\n<pre><code>int main()\n{ int n,k; //n=height of triangle k=height of sub-triangles ne= number of elements\n int t1=0;\n int t2=0;\n\n scanf(\"%d %d\", &n, k);\n\n int ne=rec(n);\n int rk=rec(k);\n int nt=ne-rk-1;\n\n unsigned long e[ne];\n unsigned long sum=0;\n\n for(int i = 0; i < ne; i++)\n {\n scanf(\"%ld\",&e[i]);\n }\n\n for(int rt = 0, ior = 0; ior < nt; rt++)\n {\n for(int r=0; r<=rt && ior<nt; r++,ior++)\n {\n int ioc = 0;\n unsigned long gval = 0;\n for(int ct=0; ioc <rk; ct++)\n {\n for(int c = 0; c <= ct && ioc < rk; ioc++, c++, t2++)\n {\n if(gval < e[t2])\n {\n gval = e[t2];\n }\n }\n t2+=rt;\n }\n sum += gval;\n t1++;\n t2 = t1;\n }\n }\n printf(\"%ld\", sum);\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T14:25:31.530",
"Id": "447345",
"Score": "0",
"body": "Thanks for your answer, I was loosing hope for answer. I used scanf because it has lower buffer then cin"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T14:32:33.887",
"Id": "447348",
"Score": "0",
"body": "@JashmanSinghBrar There are currently 2 votes to close this question as off-topic. Because you are a very beginner I explained things for you, otherwise I would have voted to close as well. We can only review working code here and it's not clear that your code works. StackOverflow.com does answer questions about code that isn't working."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T14:32:41.087",
"Id": "447349",
"Score": "0",
"body": "I have edited the code as you mentioned"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T14:35:18.257",
"Id": "447351",
"Score": "0",
"body": "Please dont' edit a question after it has been answered. See the code review rulls at https://codereview.stackexchange.com/help/someone-answers. You might want to look at all the help there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T14:35:22.217",
"Id": "447352",
"Score": "1",
"body": "my code works and I am not that beginner, the thing is that the information among hackerrank community is being contradicted here"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T14:37:48.893",
"Id": "447353",
"Score": "0",
"body": "I just need to reduce the processing time to 4 seconds or less. I came up with this solution after wrecking my brain for 2 3 hours and now I cannot find faster way to do it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T14:44:30.573",
"Id": "447354",
"Score": "0",
"body": "@JashmanSinghBrar In C use pointers rather than indexes to improve performance. Loops nested 3 deep could be the main problem. Please see the code review help page."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T14:45:50.237",
"Id": "447355",
"Score": "0",
"body": "I never knew that I was coding in c, my textbook says c++."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T14:46:19.597",
"Id": "447356",
"Score": "0",
"body": "4 loops are necessary in this solution"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T15:24:15.187",
"Id": "447358",
"Score": "0",
"body": "@JashmanSinghBrar If this is C++ it would be better to use std::vector or std::array."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T14:20:41.197",
"Id": "229850",
"ParentId": "229843",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T10:54:51.063",
"Id": "229843",
"Score": "2",
"Tags": [
"c++",
"beginner",
"programming-challenge",
"time-limit-exceeded",
"complexity"
],
"Title": "CCC '19 S5:Triangle: The Data Structure"
} | 229843 |
<p>I am new in machine learning methods and I am trying to use a Random Forest regression. I want to explain the influence of my variables on the variable "one" and I have the following code:</p>
<pre><code>library (raster)
library(caret)
library(randomForest)
facts= trainControl(method="cv", number=10,savePredictions = TRUE)
in_train= createDataPartition(example_data, p=.66, list=FALSE)
train_dt=example_data[in_train,]
test_dt=example_data[-in_train,]
dt_cor<-cor(in_train)
hcor<-findCorrelation(dt_cor,0.90)
train_dt_clean=train_dt[, -hcor]
test_dt_clean=test_dt[, -hcor]
my_model = train(one ~ .,
data=train_dt_clean,ntree=800,method="rf",metric="Rsquared",trControl=facts,importance = TRUE)
my_model$resample[with(my_model$resample, order(Resample)), ]
</code></pre>
<p>Apart from removing the multicollinearity and removing/adding parameters, what can I do to improve my model? How can I understand if my model can further be improved?</p>
<p><a href="https://drive.google.com/file/d/1RIGrtI2FmQmTPc139ebSRVOrQbS-0BBr/view?usp=sharing" rel="nofollow noreferrer">Example data here</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T21:22:20.333",
"Id": "447398",
"Score": "3",
"body": "Please revise the title of your post: per the [help center](https://codereview.stackexchange.com/help/how-to-ask), the title should _\"State what your code does in your title, not your main concerns about it.\"_."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T06:39:57.167",
"Id": "447422",
"Score": "1",
"body": "@VisualMelon, thank you for your notice. I will learn how to better ask questions!"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T11:04:17.683",
"Id": "229844",
"Score": "1",
"Tags": [
"performance",
"algorithm",
"r"
],
"Title": "Random Forest model"
} | 229844 |
<p>I wrote some Java code to look up all files in a chosen directory (like it's showing in the Windows Explorer), and to display the results, but it seems to be slow. Can you tell me, how to speed up it?</p>
<pre class="lang-java prettyprint-override"><code>import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Objects;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Main extends SimpleFileVisitor<Path> {
HashMap<Path, CarsAndSizes> map = new HashMap<>();
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
if (!map.containsKey(dir)) {
map.put(dir, new CarsAndSizes(dir, 0, 0));
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Path p = file.getParent();
long a = file.toFile().length();
while (p != null && map.containsKey(p)) {
map.get(p).incCar().addSize(a);
p = p.getParent();
}
return FileVisitResult.CONTINUE;
}
// If there is some error accessing
// the file, let the user know.
// If you don't override this method
// and an error occurs, an IOException
// is thrown.
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
return FileVisitResult.CONTINUE;
}
public static void main(String[] args) throws IOException {
JFileChooser j = new JFileChooser();
j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
j.showOpenDialog(null);
Main m = new Main();
Files.walkFileTree(j.getSelectedFile().toPath(), m);
Object[][] oa = new Object[m.map.size()][3];
int i = 0;
for (Entry<Path, CarsAndSizes> e : m.map.entrySet()) {
oa[i][0] = e.getKey().toString();
oa[i][1] = e.getValue().car;
oa[i][2] = e.getValue().size;
i++;
}
DefaultTableModel model = new DefaultTableModel(oa, new String[] { "Path", "Cars", "Sizes" }) {
private static final long serialVersionUID = 1L;
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public Class getColumnClass(int column) {
switch (column) {
case 0:
return String.class;
case 1:
return Integer.class;
case 2:
return Long.class;
default:
return String.class;
}
}
};
for (int k = model.getRowCount() - 1; k >= 0; k--) {
if ((Integer) model.getValueAt(k, 1) == 0)
model.removeRow(k);
}
JTable table = new JTable(model);
JScrollPane scroll = new JScrollPane(table);
table.setAutoCreateRowSorter(true);
JFrame frame = new JFrame();
frame.add(scroll);
frame.setSize(800, 800);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}
}
class CarsAndSizes implements Comparable<CarsAndSizes> {
Path p;
int car;
long size;
CarsAndSizes(Path p, int car, long size) {
super();
this.p = p;
this.car = car;
this.size = size;
}
CarsAndSizes incCar() {
car++;
return this;
}
CarsAndSizes addSize(long a) {
size += a;
return this;
}
@Override
public int hashCode() {
return Objects.hash(p);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CarsAndSizes other = (CarsAndSizes) obj;
return Objects.equals(p, other.p);
}
@Override
public int compareTo(CarsAndSizes o) {
if (car == o.car) {
if (size == o.size)
return p.compareTo(o.p);
else
return Long.compare(o.size, size);
}
return Integer.compare(o.car, car);
}
@Override
public String toString() {
return String.format("CarsAndSizes [p=%s, car=%10s, size=%10s]", p, car, size);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T03:23:02.630",
"Id": "448604",
"Score": "0",
"body": "First step is to put in timers and start pin pointing what exactly is slow."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T12:45:40.040",
"Id": "229847",
"Score": "1",
"Tags": [
"java",
"performance",
"file-system",
"file-structure",
"visitor-pattern"
],
"Title": "Recursively look up directories, (a little bit) slow"
} | 229847 |
<p>I am generating a 9x9 grid on which I will play sudoku later by setting click listeners to each square on the grid.</p>
<p>I first have a .xml file that represents a single square in the grid. This consists of the possible pencil marks someone ussually uses.</p>
<p>The important thing I need feedback on is just the last piece of code (the activity one). I just provide these .xml for completeness in case somebody wants to run it.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/cellValue"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintDimensionRatio="1:1"
android:gravity="center"
android:visibility="invisible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/pencilOne"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintDimensionRatio="1:1"
android:text="1"
android:textSize="10sp"
android:gravity="center"
android:visibility="invisible"
app:layout_constraintBottom_toTopOf="@+id/pencilFour"
app:layout_constraintEnd_toStartOf="@+id/pencilTwo"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/pencilTwo"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintDimensionRatio="1:1"
android:text="2"
android:textSize="10sp"
android:gravity="center"
android:visibility="invisible"
app:layout_constraintBottom_toTopOf="@+id/pencilFive"
app:layout_constraintEnd_toStartOf="@+id/pencilThree"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="@+id/pencilOne"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/pencilThree"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintDimensionRatio="1:1"
android:text="3"
android:textSize="10sp"
android:gravity="center"
android:visibility="invisible"
app:layout_constraintBottom_toTopOf="@+id/pencilSix"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="@+id/pencilTwo"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/pencilFour"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintDimensionRatio="1:1"
android:text="4"
android:textSize="10sp"
android:gravity="center"
android:visibility="invisible"
app:layout_constraintBottom_toTopOf="@+id/pencilSeven"
app:layout_constraintEnd_toStartOf="@+id/pencilFive"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/pencilOne" />
<TextView
android:id="@+id/pencilSix"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintDimensionRatio="1:1"
android:text="6"
android:textSize="10sp"
android:gravity="center"
android:visibility="invisible"
app:layout_constraintBottom_toTopOf="@+id/pencilNine"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="@+id/pencilFive"
app:layout_constraintTop_toBottomOf="@+id/pencilThree" />
<TextView
android:id="@+id/pencilSeven"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintDimensionRatio="1:1"
android:text="7"
android:textSize="10sp"
android:gravity="center"
android:visibility="invisible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/pencilEight"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/pencilFour" />
<TextView
android:id="@+id/pencilEight"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintDimensionRatio="1:1"
android:text="8"
android:textSize="10sp"
android:gravity="center"
android:visibility="invisible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/pencilNine"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="@+id/pencilSeven"
app:layout_constraintTop_toBottomOf="@+id/pencilFive" />
<TextView
android:id="@+id/pencilNine"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintDimensionRatio="1:1"
android:text="9"
android:textSize="10sp"
android:gravity="center"
android:visibility="invisible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="@+id/pencilEight"
app:layout_constraintTop_toBottomOf="@+id/pencilSix" />
<TextView
android:id="@+id/pencilFive"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintDimensionRatio="1:1"
android:text="5"
android:textSize="10sp"
android:gravity="center"
android:visibility="invisible"
app:layout_constraintBottom_toTopOf="@+id/pencilEight"
app:layout_constraintEnd_toStartOf="@+id/pencilSix"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="@+id/pencilFour"
app:layout_constraintTop_toBottomOf="@+id/pencilTwo" />
</android.support.constraint.ConstraintLayout>
</code></pre>
<p>I then have my principal layout (just a table layout). In here I want to insert the previous layout 81 times forming a 9x9 grid.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/solverTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="@string/solver"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TableLayout
android:id="@+id/sudokuGrid"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:divider="@drawable/row_divider"
android:showDividers="middle"
app:layout_constraintDimensionRatio="1:1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/solverTitle">
</TableLayout>
</android.support.constraint.ConstraintLayout>
</code></pre>
<p>And finally I have my activity where I programmatically inflate the cell layout 81 times into the table</p>
<pre><code>@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.solver_principal);
TableLayout sudokuGrid = (TableLayout) findViewById(R.id.sudokuGrid);
sudokuGrid.setShrinkAllColumns(true);
sudokuGrid.setStretchAllColumns(true);
TableRow.LayoutParams paramsRow = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);
TableLayout.LayoutParams paramsLayout = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT);
for(int i = 0; i < 9; ++i)
{
TableRow tableRow = new TableRow(SolverActivity.this);
tableRow.setDividerDrawable(getResources().getDrawable(R.drawable.column_divider));
tableRow.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
for(int j = 0; j < 9; ++j)
{
View cell = getLayoutInflater().inflate(R.layout.cell_layout, sudokuGrid, false);
cell.setLayoutParams(paramsRow);
tableRow.addView(cell);
}
tableRow.setLayoutParams(paramsLayout);
sudokuGrid.addView(tableRow);
}
}
</code></pre>
<p>The code works, and I generate the grid as expected. I would then be able to simulate pencil marks, and notes via changing the visibility of the views inside each cell.</p>
<p>What do you think about my method for generating the sudoku grid? My concerns are that it is taking a lot for the app to start the activity. In the log I get that the thread is doing many things, and some frames are skipped.</p>
<p>Are there any improvements you can suggest to make the process faster? Or even a totally different method?</p>
<p>Thanks</p>
<p><strong>Edit</strong></p>
<p>I tried to generate the xml file manually to test if the problem was due to inflating many times.</p>
<pre><code><TableLayout
android:id="@+id/sudokuGrid"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:divider="@drawable/row_divider"
android:showDividers="middle"
android:shrinkColumns="*"
android:stretchColumns="*"
app:layout_constraintDimensionRatio="1:1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/solverTitle">
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:divider="@drawable/column_divider"
android:showDividers="middle">
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</TableRow>
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:divider="@drawable/column_divider"
android:showDividers="middle">
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</TableRow>
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:divider="@drawable/column_divider"
android:showDividers="middle">
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</TableRow>
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:divider="@drawable/column_divider"
android:showDividers="middle">
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</TableRow>
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:divider="@drawable/column_divider"
android:showDividers="middle">
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</TableRow>
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:divider="@drawable/column_divider"
android:showDividers="middle">
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</TableRow>
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:divider="@drawable/column_divider"
android:showDividers="middle">
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</TableRow>
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:divider="@drawable/column_divider"
android:showDividers="middle">
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</TableRow>
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:divider="@drawable/column_divider"
android:showDividers="middle">
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<include
layout="@layout/cell_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</TableRow>
</TableLayout>
</code></pre>
<p>But I still get the same situation. It seems that 810 text views is in fact too much work. All I do is load this layout, there is no more code in my app at the moment.</p>
<p>Anyone has any idea how can I do what I want? I have seen lot of sudoku apps that have these 3x3 grid in each cell where you write pencil marks, but they must be implementing it in a different way.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T08:02:01.510",
"Id": "447435",
"Score": "0",
"body": "That is all the code my application has. All it does is to open the activity from a click button and load de UI. So the problem has to be de to loading the UI. I don´t know enough about the subject to tell if 810 text view is a lot for the UI to handle, but from past experience I wouldn´t think so."
}
] | [
{
"body": "<p>I have a few recommendations to give you.</p>\n\n<p>Firstly, you should try to use flat layouts when you are using a lot of view components. Try changing your <code>TableLayout</code> to a <code>ConstraintLayout</code> which is flat and has been proven to be generally a quicker solution. You can even use included <code>ConstraintLayout</code> layouts as you are within your parent, although that is a bit unnecessary as all layouts are just translated back into one. </p>\n\n<p>Secondly, I want to ask if there's a reason for you to create the views dynamically. If you are after animations, you could easily and beautifully do it with some Libraries both from the OS as third-party. Inflating so many views almost at the same time is bound to freeze up your UI and make the user wait, which is definitely not desired. You can create a single 9-box layout and include it multiple times through xml inside your parent layout and avoid inflating all the views at run-time.</p>\n\n<p>Lastly, If you absolutely must inflate programmatically, try doing it as one <code>ConstraintLayout</code> 9 times adding the 9 layouts within a parent <code>ConstraintLayout</code> and <strong>not</strong> a <code>TableLayout</code> (generally this is an outdated ViewGroup which has stopped being used because of its terrible loading time). To reduce even more the loading time you could look into loading in a background thread while you show a smart animation or progress bar in the main thread. </p>\n\n<p>I hope this helped, Panos.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T12:24:20.667",
"Id": "230368",
"ParentId": "229853",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T15:15:43.593",
"Id": "229853",
"Score": "2",
"Tags": [
"java",
"android",
"sudoku",
"user-interface"
],
"Title": "Creating an empty Sudoku grid"
} | 229853 |
<p>I needed a lot of data for a tensorflow project so I made a web scraper to get all of the text and links off of websites then to repeat the process at all of those links.</p>
<p>I left it on overnight and it did not get much done, so I spent the day optimizing it. I can't find any ways to optimize it more (If anyone knows a way I would like to hear it.) I used it on CNN and now I have a 9 gig text file.</p>
<p>BTW: I used faster_than_requests and selectolax because they are faster then urllib3 and bs4 and you should check them out</p>
<pre><code>import cython # helps speed up code
from selectolax.parser import HTMLParser #bs4 but faster
import faster_than_requests #urllib but faster
import _pickle as pickle #saving code
from colorama import init #just makes error messages stand out
from colorama import Fore, Back, Style
init() #colorama thing
#cdef is a cython thing, helping speed up code
cdef int i = 0
cdef list urls
cdef list text
cdef set visits #is a set for efficiency
cdef str mainsite = "https://www.cnn.com" #The main site keeps the scraper
#from straying too far from its original site.
cdef str source
parsing = True
try:
with open('visits.pickle', 'rb') as f:
visload = pickle.load(f)
visits = visload[1]
i = visload[0]
except Exception as e:
print(Back.RED + "Error loading Visits: " + str(e))
visits = set('')
i = 0
try:
with open('txt.pickle', 'rb') as f:
txt = pickle.load(f)
except Exception as e:
print(Back.RED + "Error loading txt: " + str(e))
txt = []
try:
with open('links.pickle', 'rb') as f:
urls = pickle.load(f)
except Exception as e:
print(Back.RED + "Error loading urls: " + str(e))
urls = ["https://www.cnn.com"]
while parsing:
try:
if urls[0][0] == "/": #checks to see if it can go
# to the site directly or it needs to add
#the main site to the front
source = faster_than_requests.get2str(mainsite + urls[0])
dom = HTMLParser(source)
print(Back.BLACK + mainsite + urls[0])
else:
source = faster_than_requests.get2str(urls[0])
dom = HTMLParser(source)
print(Back.BLACK + urls[0])
for tag in dom.tags('p'):
txt.append(str(dom.text())) #finds text and saves it
for tag in dom.tags('a'):
attrs = tag.attributes
if 'href' in attrs:
urls.append(attrs['href']) #finds links and saves them
except:
print(Back.RED + f"Error: {urls[0]}") # it will through up an error
# if it tries to go to a sub-page
# of another site, but this is
# an intended feature
visits.add(urls[0])
#visits keeps track of visites web pages
i = i + 1
clean = True
#clean make shure that it does not repeat a webpage.
while clean:
if urls[0] in visits:
del(urls[0])
else:
clean = False
print(Back.BLACK + f"urls:{len(urls)}, i:{i}, text lang:{len(txt)}")
if i % 10000 == 0:
#Save every 10000 webpages
with open('txt.pickle', 'wb') as f:
pickle.dump(txt, f, pickle.HIGHEST_PROTOCOL)
with open('links.pickle', 'wb') as f:
pickle.dump(urls, f, pickle.HIGHEST_PROTOCOL)
with open('visits.pickle', 'wb') as f:
pickle.dump([i, visits], f, pickle.HIGHEST_PROTOCOL)
if 0 == len(urls):
parsing = False
print(txt)
with open('txt.pickle', 'wb') as f:
pickle.dump(txt, f, pickle.HIGHEST_PROTOCOL)
with open('links.pickle', 'wb') as f:
pickle.dump(urls, f, pickle.HIGHEST_PROTOCOL)
with open('visits.pickle', 'wb') as f:
pickle.dump([i, visits], f, pickle.HIGHEST_PROTOCOL)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T01:38:15.140",
"Id": "447413",
"Score": "0",
"body": "Is there a good alternative to pickle that A- does not take three hours to save huge files, and B- compacts files better"
}
] | [
{
"body": "<p>If you want absolute performance</p>\n\n<ol>\n<li><p>You could avoid printing anything at all. Since that can be slow in some cases. If you absolutly need to know at least what happened you could try flushing at the end of the process.</p></li>\n<li><p>I know with python is delicated, but you could try visiting multiple pages at the same time? Threads or the equivalent in python</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T20:42:19.877",
"Id": "447394",
"Score": "0",
"body": "I was wondering, if print was slowing it down. I might only do it when the file saves."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T20:11:36.623",
"Id": "229871",
"ParentId": "229854",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "229871",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T16:39:26.057",
"Id": "229854",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x",
"web-scraping",
"cython"
],
"Title": "High Speed Python Web Scraper Optimised"
} | 229854 |
<p>This is a problem set from the MIT online course :</p>
<blockquote>
<p>Suppose you want to set a particular goal, e.g. to be able to afford
the down payment in three years. How much should you save each month
to achieve this? In this problem, you are going to write a program
to answer that question. To simplify things, assume: 3</p>
<ol>
<li>Your semiannual raise is .07 (7%)</li>
<li>Your investments have an annual return of 0.04 (4%) </li>
<li>The down payment is 0.25 (25%) of the cost of the house </li>
<li>The cost of the house that you are saving for is $1M. </li>
</ol>
<p>You are now going to try to find the best rate of savings to achieve a down
payment on a $1M house in 36 months. Since hitting this exactly is a
challenge, we simply want your savings to be within $100 of the
required down payment. </p>
<p>In ps1c.py, write a program to calculate the
best savings rate, as a function of your starting salary.</p>
<ul>
<li>You should use bisection search to help you do this efficiently. </li>
<li>You should keep track of the number of steps it takes your bisections search to
finish. </li>
<li>You should be able to reuse some of the code you wrote for
part B in this problem. </li>
</ul>
<p>Because we are searching for a value that is
in principle a float, we are going to limit ourselves to two decimals
of accuracy (i.e., we may want to save at 7.04% or 0.0704 in
decimal – but we are not going to worry about the difference between
7.041% and 7.039%). </p>
<p>This means we can search for an integer between 0 and 10000 (using integer division), and then convert it to a decimal
percentage (using float division) to use when we are calculating the
current_savings after 36 months. By using this range, there are only a
finite number of numbers that we are searching over, as opposed to the
infinite number of decimals between 0 and 1. This range will help
prevent infinite loops. </p>
<p>The reason we use 0 to 10000 is to account for
two additional decimal places in the range 0% to 100%. Your code
should print out a decimal (e.g. 0.0704 for 7.04%). Try different
inputs for your starting salary, and see how the percentage you need
to save changes to reach your desired down payment. </p>
<p>Also keep in mind
it may not be possible for to save a down payment in a year and a half
for some salaries. In this case your function should notify the user
that it is not possible to save for the down payment in 36 months
with a print statement. Please make your program print results in the
format shown in the test cases below.</p>
</blockquote>
<p>here is how I managed to do this:</p>
<pre><code>############## Inilize varibles ####################
current_savings = 0
salary = 201
intial_salary = salary
total_cost = 7200
#add in the bank return and the semi annual rasie
# and don't forget to inilaize the varibles with each loop
# also add a way for your program to escape the infinite loop when it's not possible
# to save for the total cost in two years
########################## Rate #####################
low = 0
high = 1
rate = (low + high) / 2
print ("rate =", rate)
######################################################
while True :
########### re-inilaizing varibles for a new loop ######
# rate is being re-iniliazed first because the deposit amount depends on it ###
rate = (low+high)/2
salary = intial_salary
deposit = rate * salary
current_savings = 0
bank_return = 0
##########################################################
####### looping the savings vs total_cost calculations 36 times for 36 months ##########
print ("rate=", rate)
for var in range (1,38) :
current_savings += deposit
bank_return = current_savings * 0.04 / 12
current_savings += bank_return
print ("current_savings=",current_savings)
###### semi_annual_raise #######################
if var % 6 == 0 :
print (var)
print ("salary=" , salary )
salary = salary + (salary * 0.07)
deposit = rate * salary
###########################################################
##### modifying the rate value based on the diffrence between the ####
##### current_savings and total_cost ############################
if current_savings < total_cost :
low = rate
elif current_savings > total_cost:
high = rate
# two ways to break the loop , first is that current_savings is equal to total_cost and in this case the rate is the pefect match
# the second way is that the rate is alreay 1 (whole salary) but still the current_savings are not equal to the total_cost so the
# the break is there to escape the infinite loop
# elif current_savings == total_cost : #( was working just fine until i introduced the semi_annual raise to the code )
if abs(current_savings - total_cost ) < 0.000001 :
break
if rate == 1 : #and current_savings < total_cost : ( an additonal unndeeded condition , kept here in case needed later )
print ("not possible")
break
print ("current_savings=",current_savings)
print (rate * salary * 36)
print ("rate=", rate)
</code></pre>
<p>Can you please tell me how this code can be improved?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T17:09:26.270",
"Id": "447364",
"Score": "4",
"body": "This is not your first question here, but nevertheless let me remind you of some things: 1. [The title should state what to programm accomplishes](/help/how-to-ask). 2. [We can only review code that you have written or that is maintained by you.](https://codereview.meta.stackexchange.com/a/1295/92478). So reviewing the GitHub piece (where you should at least link to the source to give proper credit!) is likely off-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T17:27:22.453",
"Id": "447366",
"Score": "2",
"body": "discussed in meta: https://codereview.meta.stackexchange.com/questions/9353/requesting-a-comparative-review-of-own-code-with-third-party-code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T17:32:55.023",
"Id": "447367",
"Score": "2",
"body": "I did edit the question to include credits to the original code owner, if this kind of practice was deemed to be off-topic then i will edit the second set of code off the question. As for the title to include what the program should do; I did try that to no avail, due to the limit of characters in the title."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T19:45:18.040",
"Id": "447389",
"Score": "4",
"body": "I removed the referenced code and updated the question as per the meta response."
}
] | [
{
"body": "<h1>Magic Numbers</h1>\n\n<pre><code>for var in range (1, 38):\n</code></pre>\n\n<p>What is <code>1</code> and <code>38</code> supposed to represent? You should make it clear what these are by declaring in variables/CONSTANTS.</p>\n\n<h1>Spacing</h1>\n\n<pre><code>print (var)\nif current_savings < total_cost :\nrate = (low+high)/2\n</code></pre>\n\n<p>should instead be</p>\n\n<pre><code>print(var)\nif current_savings < total_cost:\nrate = (low + high) / 2\n</code></pre>\n\n<p>You don't separate <code>()</code> from their function names, <code>:</code> from their statements, and arithmetic operators should be spaced out to increase readability.</p>\n\n<h1>Printing</h1>\n\n<p>Instead of this</p>\n\n<pre><code>print (\"current_savings=\",current_savings)\n</code></pre>\n\n<p>use an <code>f\"\"</code> string to directly incorporate your variables into the string, like so:</p>\n\n<pre><code>print(f\"current_savings={current_savings}\")\n</code></pre>\n\n<h1>Naming</h1>\n\n<p>Constants like</p>\n\n<pre><code>intial_salary = salary\ntotal_cost = 7200\n</code></pre>\n\n<p>should be uppercase to show that they are:</p>\n\n<pre><code>INITIAL_SALARY = salary\nTOTAL_COST = 7200\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T16:58:35.523",
"Id": "447642",
"Score": "0",
"body": "So basically we're saving up money for 36 months , this is what the problem set states. I do get the spacing and I will work on it, thanks ! But I don't see why these variables should be uppercase?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T19:03:30.167",
"Id": "447687",
"Score": "0",
"body": "@Elbasel These are variables that never change. You use `INITIAL_SALARY` to reset the value of `salary`, and you use `TOTAL_COST` to determine savings rate. Since you don't want these to be changed mid program, they should be `UPPERCASE`. This lets you know not to change them after declaring them at the top of your program."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T06:21:01.793",
"Id": "229953",
"ParentId": "229858",
"Score": "2"
}
},
{
"body": "<p>This may be but a small point, but this:</p>\n\n<pre><code>salary = 201\nintial_salary = salary\n</code></pre>\n\n<p>Makes more sense the other way around:</p>\n\n<pre><code>INITIAL_SALARY = 201\nsalary = INITIAL_SALARY\n</code></pre>\n\n<p>The initial is there first, or it wouldn't be the initial value. Setting the initial after the current value seems, odd.</p>\n\n<p>For short scripts like this, it doesn't matter much. But debugging & maintainability becomes a little easier if you put your declarations and assignments in an order that makes sense. It's a good habit to get into early.</p>\n\n<p>Also, the following has the potential for disaster:</p>\n\n<pre><code>if abs(current_savings - total_cost ) < 0.000001 : \n break\nif rate == 1 :\n print (\"not possible\")\n break\n</code></pre>\n\n<p>What if neither becomes true? You're in a <code>while True</code> loop. It's going to run forever if by some bug neither of the conditions become true (those are the only options your program has to <code>break</code>). You may want to consider a fail-safe of sorts, or change your loop altogether. <code>while</code> loops often look like an easy way out, but in Python, there's often a better way.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T16:55:26.700",
"Id": "447641",
"Score": "0",
"body": "Thanks for the input, but one value HAS to eventually be true, since this is bisectional search and eventually the rate is going to be equal to 1. Also , the initial salary value is there just so that I can re-intialize the salary variable after each loop so it I think it makes more sense to have it as intitial salary."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T07:10:18.077",
"Id": "229956",
"ParentId": "229858",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "229953",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T17:01:02.493",
"Id": "229858",
"Score": "5",
"Tags": [
"python",
"programming-challenge",
"finance"
],
"Title": "Calculating the necessary contribution to attain a savings goal with compound interest"
} | 229858 |
<p><strong>tl;dr</strong> </p>
<p>I tried to write some as general and as feasible as possible code where entities are able to communicate with other entities of the same type or of different types, allowing for the recipient to reply to the sender.</p>
<p><strong>Details :</strong></p>
<ul>
<li>Trying to work with some of the new contextual abstractions e.g. given and extension methods</li>
<li>Have a general Entity type to enable sending and receiving messages </li>
<li>To be able to send message types different from what I can receive.</li>
<li>To have the ability to reply to a received message</li>
<li>To be able to send messages between 2 instances of the same type <code>T</code> given the presence of <code>Entity[T, TMsg]</code></li>
<li>To be able to send messages between different types <code>T</code> and <code>U</code> given the presence of both <code>Entity[T, TMsg]</code> and <code>Entity[U, UMsg]</code></li>
<li>Have a <code>Person</code> example capable of receiving Strings that can do all this</li>
</ul>
<p><strong>Concerns I have regarding the code :</strong></p>
<ul>
<li>Feels more complex, more difficult to understand than it needs to be</li>
<li>Type parameters are often just single character ones, but I felt like it would render the code totally unreadable, now however I have very long type signatures</li>
</ul>
<p><strong>The code</strong></p>
<pre><code>trait Entity[Me, InMsg]
def (me: Me) send[Receiver, OutMsg] (receiver: Receiver, msg: OutMsg) (given Entity[Receiver, OutMsg], Entity[Me, InMsg]): Unit
def (me: Me) receive[Sender, ReplyMsg] (sender: Sender, msg: InMsg) (given Entity[Sender, ReplyMsg]): Unit
def (me: Me) name(): String
class Person(private val name: String)
object Person
given Entity[Person, String]
def (me: Person) send[Receiver, OutMsg] (receiver: Receiver, msg: OutMsg) (given Entity[Receiver, OutMsg], Entity[Person, String]): Unit =
receiver.receive[Person, String](me, msg)
def (me: Person) receive[Sender, ReplyMsg] (sender: Sender, msg: String) (given Entity[Sender, ReplyMsg]): Unit =
println(f"I'm ${me.name} and I just RECEIVED a msg saying $msg from ${sender.name()}")
def (me: Person) name () =
me.name
@main def m = Person("AAA").send(Person("BBB"), "Hi")
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T13:11:20.197",
"Id": "447613",
"Score": "0",
"body": "What is your code supposed to achieve? It isn't clear in your post, you should edit it to explain well... why you wrote this code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T20:28:47.893",
"Id": "447858",
"Score": "0",
"body": "@IEatBagels added a short description, do you find it clearer now? Thx"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T20:32:41.060",
"Id": "447861",
"Score": "0",
"body": "I have a couple more questions that'll make the post clearer, if you don't mind. You say \"What I attempted\", did it work? The phrasing makes it sound like you didn't achieve your goal and the code doesn't work. Do you feel like your title is as precise as it could be? Do you think there's a specific pattern that exists that does the same thing you're trying to do (I think there is) that you could name that would help pinpoint the exact goal?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T20:45:47.833",
"Id": "447865",
"Score": "0",
"body": "Yes, it did work, although not extensively tested I've seen it work. I didn't realise that I'm implying that it might not have worked, feel free to suggest better wording."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T20:46:01.553",
"Id": "447866",
"Score": "0",
"body": "The title describes an aspect of what's in the code, of course I'd like to get reviews that are not limited to this single aspect, such as how idiomatic the code is, or the concerns I listed that are not directly linked to the title."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T20:46:17.617",
"Id": "447867",
"Score": "0",
"body": "This can be done in multiple ways, I don't see any specific pattern coupled with the issue. I went for this typeclass-like one, for this exercises the new syntax I wanted to try out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T20:57:48.443",
"Id": "447868",
"Score": "0",
"body": "Alright this looks good! Good job on your first post and, especially, good job on being to keen to answer and edit your post, this shows an openness that is important on StackExchange :)"
}
] | [
{
"body": "<p>First, a minor thing here:</p>\n\n<pre><code>def (me: Me) send[Receiver, OutMsg] (receiver: Receiver, msg: OutMsg) (given Entity[Receiver, OutMsg], Entity[Me, InMsg]): Unit\n</code></pre>\n\n<p>The second <code>given</code> parameter is actually redundant - it's literally the same type as <code>this</code>, and with contextual parameters, there shouldn't be any other instance.</p>\n\n<p>In fact, implementation of <code>send</code> in <code>Person</code> shows that you can have a default impl:</p>\n\n<pre><code>def (me: Me) send[Receiver, OutMsg] (receiver: Receiver, msg: OutMsg) (given Entity[Receiver, OutMsg]): Unit =\n receiver.receive(me, msg)(given this)\n</code></pre>\n\n<hr>\n\n<p>Next, something more subtle:</p>\n\n<pre><code>def (me: Me) receive[Sender, ReplyMsg] (sender: Sender, msg: InMsg) (given Entity[Sender, ReplyMsg]): Unit\n</code></pre>\n\n<p>Whoever is implementing this will have to support <em>any</em> <code>ReplyMsg</code>, and therefore won't be able to create one (without breaking type system by casting or nulls). Try implementing it in a way that sends something back - you won't be able to make a call to <code>send</code> compile with normal code. If it's desirable, you can simplify the signature using existentials:</p>\n\n<pre><code>def (me: Me) receive[Sender] (sender: Sender, msg: InMsg) (given Entity[Sender, ?]): Unit\n</code></pre>\n\n<p>But I think it's not, as you wanted to reply to things. You'll have to work out a way to make it work - the simplest one being having 3 parameters - <code>Entity[Me, In, Out]</code> and accepting something that has <code>Me[Other, Out, In]</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T14:22:50.003",
"Id": "230165",
"ParentId": "229864",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T18:16:41.537",
"Id": "229864",
"Score": "3",
"Tags": [
"scala",
"extension-methods"
],
"Title": "Dotty 0.19 (Scala 3) features: contextual abstractions"
} | 229864 |
<p>I wanted to implement a selection sort and wanted to make sure that I'm doing it correctly. I wanted to do it in a way that's efficient and use recursion. Please let me know if I am doing this correctly or if there is a better way for me to do it.</p>
<pre><code> /**
* selectionSort
* @param toSort
* @param sorted
* @returns {Array}
*/
function selectionSort(toSort, sorted=[]) {
if (!toSort.length) {
return sorted;
}
let minIndex = findMinimum(toSort);
sorted.push(...toSort.splice(minIndex, 1))
return selectionSort(toSort, sorted);
}
function findMinimum(arr) {
let minIndex=0;
arr.forEach(function (item, index) {
if(item < arr[minIndex]) {
minIndex = index;
}
})
return minIndex;
}
const testCase = [64, 25, 12, 22, 11]
const answer = selectionSort(testCase);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T18:31:34.527",
"Id": "447380",
"Score": "0",
"body": "Is this code using node.js?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T19:18:36.120",
"Id": "447385",
"Score": "1",
"body": "Why use recursion when a loop would do just fine? Recursion is just going to have a lot of stack buildup for large arrays and extra function calls."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T19:19:37.517",
"Id": "447386",
"Score": "0",
"body": "A `for` loop is generally more efficient than `.forEach()` as there's no function call and new scope involved. Probably best to use `for/of`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T23:48:57.863",
"Id": "447407",
"Score": "0",
"body": "@jfriend00 I'm trying to familiarize myself with recursion more. I didn't know that it's better to use loops in some cases. Thanks for the tip with the `for/of` also"
}
] | [
{
"body": "<h3>Review</h3>\n\n<ul>\n<li><code>findMinimum</code> means to me that you find the minimum <em>value</em> in an array of items. Since your function returns the <em>index</em> instead, call it <code>indexOfMinimum</code>.</li>\n<li>Prefer the use of <code>const</code> over <code>let</code> if you only assign a variable once: <code>let minIndex = findMinimum(toSort);</code> -> <code>const minIndex = findMinimum(toSort);</code>.</li>\n<li>Use arrow notation to write more compact functions: <code>function (item, index)</code> -> <code>(item, index) =></code>.</li>\n<li>Your documentation seems like wasted space. If you document a public function (which is a good thing), put in some effort to write a clear description of the function, not just the name of the method copied.</li>\n<li>Use whitespace to write more idiomatic javascript:\n\n<ul>\n<li><code>let minIndex=0;</code> -> <code>let minIndex = 0;</code></li>\n<li><code>if(item < arr[minIndex])</code> -> <code>if (item < arr[minIndex])</code></li>\n</ul></li>\n</ul>\n\n<p>Rewritten:</p>\n\n<pre><code>function selectionSort(toSort, sorted=[]) {\n if (!toSort.length) {\n return sorted;\n }\n const minIndex = indexOfMinimum(toSort);\n sorted.push(...toSort.splice(minIndex, 1))\n return selectionSort(toSort, sorted);\n}\n\nfunction indexOfMinimum(arr) {\n let minIndex = 0;\n arr.forEach((item, index) => {\n if (item < arr[minIndex]) {\n minIndex = index;\n }\n })\n return minIndex;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T23:51:32.057",
"Id": "447408",
"Score": "0",
"body": "Those are good suggestions. Thank you.\n\nWhat do you mean by more idiomatic javascript?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T04:17:21.217",
"Id": "447414",
"Score": "1",
"body": "I mean by following more standard practices, or in this case conventions and style guides."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T18:46:47.400",
"Id": "229866",
"ParentId": "229865",
"Score": "5"
}
},
{
"body": "<p>I'd suggest the following changes:</p>\n\n<ol>\n<li>Use a loop instead of recursion</li>\n<li>Use <code>for/of</code> instead of <code>.forEach()</code></li>\n<li>push a single value instead of using an array with one element in it</li>\n<li>cache the lowest value so far so you don't have to constantly refetch it on every comparison</li>\n<li>Use a temporary array for the sort so the function is non-destructive to the source array (consistent with most array methods)</li>\n<li>Use <code>const</code> where you can.</li>\n</ol>\n\n<p>Code:</p>\n\n<pre><code> /**\n * selectionSort\n * @param toSort (not modified)\n * @param sorted (new sorted array)\n * @returns {Array}\n */\n function selectionSort(toSort, sorted = []) {\n if (!toSort.length) {\n return sorted;\n }\n // make copy so we don't modify source\n const sortData = toSort.slice();\n\n while (sortData.length) {\n const minIndex = findMinimum(sortData);\n sorted.push(sortData[minIndex]);\n // remove min item from data left to be sorted\n sortData.splice(minIndex, 1);\n }\n return sorted;\n }\n\n function findMinimum(arr) {\n let minIndex = 0, minValue = arr[0];\n for (const [index, item] of arr.entries()) {\n if (item < minValue) {\n minIndex = index;\n minValue = item;\n }\n }\n return minIndex;\n }\n\n\n const testCase = [64, 25, 12, 22, 11]\n const answer = selectionSort(testCase);\n console.log(answer);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T11:36:16.067",
"Id": "447450",
"Score": "0",
"body": "I disagree with `for...of...entries` though. There is nothing wrong with using normal `for` when the use case is exactly what it was designed for. JS communitie's overuse of new constructs where they bring no benefit over the old ones is harmful for code readability and consistency."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T15:23:20.107",
"Id": "447490",
"Score": "0",
"body": "@TomášZato - I have no problem with a regular `for` loop. The OP was using `.forEach()` which I did not think was as good as some type of a `for` loop. In this case, the OP actually needs both the index and the value which `for/of` and `.entries()` hands you on a silver platter, thus why I used it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T15:27:13.730",
"Id": "447491",
"Score": "0",
"body": "I apologize, I read the post again and noticed that I misread `arr.entries` for `Object.entries(arr)`. `arr.entries` is great."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T19:55:24.170",
"Id": "229870",
"ParentId": "229865",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T18:23:15.207",
"Id": "229865",
"Score": "6",
"Tags": [
"javascript",
"algorithm",
"sorting",
"recursion",
"node.js"
],
"Title": "Selection Sort Algorithm (Node.js)"
} | 229865 |
<p>Instead of using the null checks I tried using <code>Optional</code> and safely unwrapping the optional.</p>
<p><strong>Approach 1</strong></p>
<p>My first approach of unwrapping the <code>Optional</code> is using <code>map()</code> followed by <code>orElseThrow()</code>.</p>
<p><strong>Approach 2</strong></p>
<p>My second approach if unwrapping the <code>Optional</code> is using <code>orElseThrow()</code> and setting the value to a variable and using it.</p>
<p><strong>Service</strong></p>
<pre><code>@Inject
private UserConfigurationRepository userConfigurationRepository;
public UserConfiguration updateConfigUsingOrElseThrow(User user, String value) {
UUID configurationId = user.getConfigurationId().orElseThrow();
UserConfiguration userConfiguration = userConfigurationRepository
.findById(configurationId).orElseThrow();
return updateUserConfiguration(userConfiguration, value); // Performs update operation
}
public UserConfiguration updateConfigUsingMapOrElseThrow(User user, String value) {
return user.getConfigurationId().map(configurationId ->{
return userConfigurationRepository.findById(configurationId).map(userConfiguration -> {
return updateUserConfiguration(userConfiguration, value); // Performs update operation
}).orElseThrow();
}).orElseThrow();
}
private UserConfiguration updateUserConfiguration(UserConfiguration userConfiguration, String value)
{
userConfiguration.setValue(value);
// Business Logics
return userConfigurationRepository.save(userConfiguration);
}
</code></pre>
<p><strong>Repository</strong></p>
<pre><code>public interface UserConfigurationRepository extends JpaRepository<UserConfiguration, UUID>{}
</code></pre>
<p><strong>Model</strong></p>
<pre><code>public class User {
private int id;
private String name;
private String email;
private UUID configurationId;
public Optional<UUID> getConfigurationId() {
return Optional.ofNullable(configurationId);
}
public void setConfigurationId(UUID configurationId) {
this.configurationId = configurationId;
}
//Ignored getters and setters of other properties those are not used in this part of code
}
public class UserConfiguration {
private UUID id;
private String value;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
</code></pre>
<p>I am used to using null check using <code>if</code> statement and since I am new to this style of programming I am not sure which one is the best approach and gives more readability, Or is there any other recommended way to do this?</p>
<p>The task of this service is to get the configuration id and a configuration message from front end and update the data in the configuration table. And returns the updated configuration information. Not all the users will have an entry in the configuration so there is a possibility of getting null value for configurationId in the User model thats is why the getter returns the optional of configurationId.</p>
<p>Since this is my client code I am unable to expose the complete code, So I provided the structure of the model, services and repository. Hope I have provided necessary information.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T19:09:41.407",
"Id": "447383",
"Score": "4",
"body": "You have explained technically what you are after, but could you also provide some functional description and perhaps also include the source code of the classes you are using in this question?"
}
] | [
{
"body": "<ul>\n<li>I think you want <code>flatMap</code>. </li>\n<li>Those <code>return</code>s and braces are unnecessary noise.</li>\n<li><p>I would consider not throwing but returning <code>Optional<UserConfiguration></code> instead. Part of learning this style is realising that unwrapping is rarely necessary. At the call site, you can do something along the lines of <code>update(user).ifPresentOrElse(...)</code>. [*]</p>\n\n<pre><code>public Optional<UserConfiguration> update(User user) {\n return user.getConfigurationId() // Optional<UUID>\n .flatMap(configurationId -> userConfigurationRepository.findById(configurationId)) // Optional<UserConfiguration>\n .map(userConfiguration -> updateUserConfiguration(userConfiguration)); // Optional<UserConfiguration>\n}\n</code></pre></li>\n<li><p>However, if you insist on unwrapping, nothing's stopping you, technically.</p>\n\n<pre><code>public UserConfiguration update(User user) {\n return user.getConfigurationId() // Optional<UUID>\n .flatMap(configurationId -> userConfigurationRepository.findById(configurationId)) // Optional<UserConfiguration>\n .map(userConfiguration -> updateUserConfiguration(userConfiguration)) // Optional<UserConfiguration>\n .orElseThrow();\n}\n</code></pre></li>\n<li><p>consider method references. Sometimes they make code more readable, other times they don't. But mostly yes.</p>\n\n<pre><code>public Optional<UserConfiguration> update(User user) {\n return user.getConfigurationId() // Optional<UUID>\n .flatMap(userConfigurationRepository::findById) // Optional<UserConfiguration>\n .map(this::updateUserConfiguration); // Optional<UserConfiguration>\n}\n</code></pre></li>\n</ul>\n\n<p>[*] - Getting into this mindset would help you a lot when you will start working with other wrapper types that rely on the same abstractions, such as the standard library's <a href=\"https://www.baeldung.com/java-streams\" rel=\"nofollow noreferrer\">Stream</a>, <a href=\"http://reactivex.io/\" rel=\"nofollow noreferrer\">RxJava</a>, <a href=\"https://spring.io/\" rel=\"nofollow noreferrer\">Spring 5-reactive stack</a> / <a href=\"https://projectreactor.io/\" rel=\"nofollow noreferrer\">Project Reactor</a>, or classes provided by the <a href=\"https://www.vavr.io/\" rel=\"nofollow noreferrer\">vavr</a> library. Although possible, unwrapping some of these is considered a very bad idea, e.g. in case of RxJava and Reactor it is a blocking action which you want to avoid at all costs when writing reactive software. But even in the case of Optional, why not have the fact that the value might be missing captured by the type system rather that throwing Exceptions around that might be invisible up the stack until there is actually an issue.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T04:32:35.950",
"Id": "447416",
"Score": "0",
"body": "Invoking updateUserConfiguration(_) using the flatmap provides an Optional<UserConfiguration> as parameter. But the updateUserConfiguration(_) needs the parameter of type UserConfiguration."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T06:52:38.450",
"Id": "447423",
"Score": "0",
"body": "@RikudouSennin thanks, I edited my answer. Should be correct now(?) Can't code without a compiler providing feedback..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T19:20:26.690",
"Id": "229868",
"ParentId": "229867",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "229868",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T19:08:19.993",
"Id": "229867",
"Score": "4",
"Tags": [
"java",
"comparative-review"
],
"Title": "The best way to unwrap the optional in java"
} | 229867 |
<p>I am super proud of this python bingo game I wrote. I am posting it here to make get some help reviewing it to make sure I'm using the best practices. This is for a class, and my professor is a stickler for using best practices. I went above and beyond what the assignment called for so I need a little more helping making sure the code is okay. Any help is appreciated!</p>
<p>Here is the code:</p>
<pre class="lang-py prettyprint-override"><code># Author: Helana Brock
# Homework 2, problem 3
import random
random_draw_list = random.sample(range(1, 76), 75)
def generate_card():
"""
Generates a bingo card and stores the numbers in a dictionary.
"""
card = {
"B": [],
"I": [],
"N": [],
"G": [],
"O": [],
}
min = 1
max = 15
for letter in card:
card[letter] = random.sample(range(min, max), 5)
min += 15
max += 15
if letter == "N":
card[letter][2] = "X" # free space!
return card
def print_card(card):
"""
Prints the bingo card.
Arguments:
card (dictionary): The card to be printed out.
"""
for letter in card:
print(letter, end="\t")
for number in card[letter]:
print(number, end="\t")
print("\n")
print("\n")
def draw(card, list):
"""
Pops a number off a list of random numbers. Using the pop method ensures no duplicate
numbers will be drawn.
Arguments:
card (dictionary): The card to to check for the number that was drawn.
list (list): The list of random numbers to be drawn from.
"""
number_drawn = random_draw_list.pop()
for letter in card:
i = 0
for number in card[letter]:
if number == number_drawn:
card[letter][i] = "X"
i += 1
return number_drawn
def check_win(card):
"""
First checks for diagonal wins, then four-corner, then horizontal, and finally, vertical.
Arguments:
card (dictionary): The card to check for a win.
"""
win = False
if card["B"][0] == "X" and card["I"][1] == "X" and card["N"][2] == "X" and card["G"][3] == "X" and card["O"][4] == "X":
win = True
elif card["O"][0] == "X" and card["G"][1] == "X" and card["N"][2] == "X" and card["I"][3] == "X" and card["B"][4] == "X":
win = True
elif card["B"][0] == "X" and card["O"][4] == "X" and card["B"][4] == "X" and card["O"][0] == "X":
win = True
for letter in card:
if(len(set(card[letter]))==1):
win = True
for i in range(5):
cnt = 0
for letter in card:
if card[letter][i] == "X":
cnt += 1
print(cnt)
if cnt == 5:
win = True
break
return win
def main():
"""
Main method for the program. Generates a card, prints it, and loops through drawing
and printing until the check_win method returns True or the user enters "quit".
"""
print("Let's play bingo!")
card = generate_card()
print("\nHere is your card:\n")
print_card(card)
print("\nKeep pressing enter to continue or type quit to exit.\n")
user_input = input()
win = check_win(card)
balls_till_win = 0
while win == False and user_input != "quit":
number_drawn = draw(card, random_draw_list)
balls_till_win += 1
print(f"\nNumber drawn: {number_drawn}.")
print(f"Total balls drawn: {balls_till_win}.\n")
print_card(card)
win = check_win(card)
user_input = input()
if win == True:
print(f"\nBingo! Total balls to win: {balls_till_win}.")
else:
print("Goodbye! Thanks for playing!")
main()
</code></pre>
| [] | [
{
"body": "<p>Some low-hanging fruit:</p>\n\n<pre><code>if win == True \n</code></pre>\n\n<p>can be written as </p>\n\n<pre><code>if win:\n</code></pre>\n\n<p>Know that <code>print</code> delimits by a newline by default; you don't need to explicitly add <code>\\n</code> unless you want two newlines. </p>\n\n<p>You can use classes to make <code>card</code> a class on its own. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T12:29:29.427",
"Id": "447459",
"Score": "0",
"body": "Thank you so much! I will change that, I didnt think about it. Also yes I wanted to two newlines haha"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T20:47:19.993",
"Id": "229874",
"ParentId": "229872",
"Score": "3"
}
},
{
"body": "<h1>Style</h1>\n\n<p>Python comes with an \"official\" <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a> (aka PEP 8) which is a widely accepted standard for naming conventions and the like. Since you say your professor is keen on using best practices, I'd recommend to have a look at those guidelines. There is also a variety of tools that can help you to check for those best practices automatically. A non-exhaustive list (including <a href=\"https://www.pylint.org/\" rel=\"nofollow noreferrer\">Pylint</a>) can be found in <a href=\"https://codereview.meta.stackexchange.com/a/5252/92478\">this meta-post</a> here on Code Review.</p>\n\n<p>From what I have seen, your code looks quite good in that regard. I especially like your docstrings. The most prevalent issue in your code would be that <a href=\"https://www.python.org/dev/peps/pep-0008/#blank-lines\" rel=\"nofollow noreferrer\">there are usually two blank lines between different function definitions</a> in order to make their separation more clear.</p>\n\n<h1>Code</h1>\n\n<h2>Idiomatic Python</h2>\n\n<p>As <a href=\"https://codereview.stackexchange.com/users/138084\">@nz_21</a> already <a href=\"https://codereview.stackexchange.com/a/229874/92478\">mentioned</a>, <code>if sth == True:</code> and also <code>if sth == False:</code> can be expressed in a more idiomatic way as <code>if sth:</code> and <code>if not sth:</code> (Note: Pylint would also catch this particular \"mistake\".)</p>\n\n<h2>Redefining built-ins</h2>\n\n<p>Some of the variable names you have chosen (<code>min</code>, <code>max</code>, <code>list</code>) redefine <a href=\"https://docs.python.org/3/library/functions.html\" rel=\"nofollow noreferrer\">built-in functions</a> from the Python core. You should avoid that. The simplest way is to append a single trailing underscore, e.g. <code>list_</code>, in order to avoid that issue. Also the parameter <code>list</code> seems to be unused in <code>draw(...)</code>.</p>\n\n<h2>Random number generation</h2>\n\n<p><strike><code>card[letter] = random.sample(range(min_, max_), 5)</code> could also be rewritten as <code>card[letter] = [random.randrange(min_, max_) for _ in range(5)]</code>. Although I don't think that it will make a big difference in your case. The <a href=\"https://docs.python.org/3/library/random.html#random.randrange\" rel=\"nofollow noreferrer\">documentation</a> explicitly list them as alternatives:</p>\n\n<blockquote>\n <p><code>random.randrange(start, stop[, step])</code></p>\n \n <p>Return a randomly selected element from range(start, stop, step). This\n is equivalent to choice(range(start, stop, step)), but doesn’t\n actually build a range object.</p>\n</blockquote>\n\n<p>From that it seems that the later approach would make more sense for a large range of values to choose from.</strike></p>\n\n<p>Edit: removed after hint in the comments with regard to sampling with and without replacement. Thanks to <a href=\"https://codereview.stackexchange.com/users/196041/\">@Wombatz</a>.</p>\n\n<h2>Global variables</h2>\n\n<p><code>random_draw_list</code> is used as a global variable, but unfortunately not as a constant as one might expect, but as a mutable global variable. That makes it <a href=\"https://stackoverflow.com/a/16011147/5682996\">harder to reuse code</a>. Since <code>draw(...)</code> is the only function using this variable, it makes no sense to have it as a global variable. Instead, it should defined in <code>main()</code> after you have changed <code>draw(...)</code> to accept it as parameter (maybe that's what <code>list</code> was supposed to do in the first place?) and passed when calling <code>draw(...)</code> from <code>main()</code>.</p>\n\n<h2>Top-level script environment</h2>\n\n<p>In order to show what part of the file is actually supposed to be run as a script, Python defines the concept of a <a href=\"https://docs.python.org/3/library/__main__.html\" rel=\"nofollow noreferrer\"><em>top-level script environment</em></a>. Although the name sounds daunting at first, it's quite likely that you have seen it in someone else's Python code: <code>if __name__ == \"__main__\":</code> This tells the Python interpreter to only run that part of code if the file is used as a script. In your case all there is to do is to do add the above right before calling the <code>main</code>-function:</p>\n\n<pre><code>if __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>That also helps you to avoid the issue that Python always starts a new bingo game whenever you try to <code>import</code> a function from your file ;-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T12:30:09.087",
"Id": "447460",
"Score": "0",
"body": "Oh my gosh! Thank you so much for your awesome answer. I will definitely adopt all of this into my code!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T16:53:28.857",
"Id": "447505",
"Score": "1",
"body": "`random.randrange` is not an alternative to `random.sample` and neither does the documentation say so. The alternative to `random.randrange` is `random.choice(range(...))`. The thing is: `random.sample` samples **without** replacement while `random.choices` and your list comprehension sample **with** replacement. In other words: your listcomprehension can include duplicates while `random.sample` can not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T18:05:43.290",
"Id": "447515",
"Score": "0",
"body": "@Wombatz: I \"invalidated\" that part of the answer. Thanks for pointing it out."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T22:03:35.413",
"Id": "229877",
"ParentId": "229872",
"Score": "8"
}
},
{
"body": "<h1>Initializing your bingo card</h1>\n\n<p>You don't need to initialize your dictionary with lists, since <code>random.sample</code> returns a list by default. Just iterate through the string <code>\"BINGO\"</code> to set your keys. Also, the <code>if</code> check doesn't need to happen, you know that you will be replacing the 3rd element of the list at the key <code>'N'</code> every time, so just have that be an instruction at the end:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def generate_card():\n \"\"\"\n Generates a bingo card and stores the numbers in a dictionary.\n \"\"\"\n # just start with a plain dictionary, random.sample\n # returns a new list, so no need to pre-allocate lists\n # you won't be using in the future\n card = {}\n\n # min and max are builtin functions, so use\n # underscores to avoid name shadowing\n _min = 1\n _max = 15\n\n for letter in 'BINGO':\n card[letter] = random.sample(range(_min, _max), 5)\n _min += 15\n _max += 15\n\n # You know which letter this needs to be, no need for the if block\n card[\"N\"][2] = \"X\" # free space!\n return card\n</code></pre>\n\n<h1>Checking the win condition</h1>\n\n<p>To check over the diagonals, you can use <code>zip</code> for your keys and the indices to validate. For horizontals iterate over <code>card.values()</code> and check <code>all(item == 'X' for item in row)</code>. For columns, you can zip together the rows using argument unpacking.</p>\n\n<p>By iterating over a dictionary, it returns the keys by default, which is why <code>enumerate(dict)</code> is the desired structure here. To check the opposite direction, <code>zip(reversed(range(5)), card)</code> will give you <code>(idx, key)</code> pairs in opposite order in a pythonic way, since <code>dict</code> cannot be reversed:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># down to the right\n# iterating over the dictionary yields the keys\nif all(card[k][idx]=='X' for idx, key in enumerate(card)):\n print('win!')\n return True\n\n# up to the right\nelif all(card[k][idx]=='X' for idx, key in zip(reversed(range(5)), card)):\n print('win!')\n return True\n\n# horizontal condition\nfor row in card.values():\n if all(item=='X' for item in row):\n return True\n\n# vertical condition\nfor column in zip(*card.values()):\n if all(item=='X' for item in column):\n return True\n</code></pre>\n\n<p>To show how this works:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import random\n\nd = {k: random.sample(range(10), 3) for k in 'abc'}\n# {'a': [5, 3, 7], 'b': [1, 8, 7], 'c': [4, 5, 8]}\n\n# diagonal\nfor idx, key in enumerate(d):\n print(key, d[key][idx])\na 5\nb 8\nc 8\n\n\n# opposite diagonal\nfor idx, key in zip(reversed(range(3)), d):\n print(key, d[key][idx])\na 7\nb 8\nc 4\n\n\n# rows\nfor row in d.values():\n print(row)\n\n[5, 3, 7]\n[1, 8, 7]\n[4, 5, 8]\n\nfor col in zip(*d.values()):\n print(col)\n\n(5, 1, 4)\n(3, 8, 5)\n(7, 7, 8)\n</code></pre>\n\n<p>Also, the <code>return True</code> on all of the conditions means that the function will stop once a winning condition is hit, rather than going through all of the conditions when you really don't need to. This is called short-circuiting, meaning that you only evaluate up to the desired condition.</p>\n\n<p>Looking at this a bit further, I'd probably refactor the row and column check into a different function:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def check_line(values):\n \"\"\"\n values is an iterable over either rows or columns\n of the card. Should be iterable(str)\n\n returns boolean\n \"\"\"\n for line in values:\n if all(val=='X' for val in values):\n return True\n\n# the last two loops then look like:\nelif check_line(card.values()):\n return True\n\nelif check_line(zip(*card.values())):\n return True\n\nreturn False\n\n</code></pre>\n\n<h1>Class?</h1>\n\n<p>The fact that you're passing <code>card</code> around to a lot of functions says (to me) that you could probably use a class here. The <code>generate_card</code> method can be done on <code>__init__</code>, and everything else takes a <code>self</code> rather than a <code>card</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>\nclass BingoCard:\n\n def __init__(self, _min=1, _max=15):\n \"\"\"\n Generates a bingo card and stores the numbers in a dictionary.\n _min and _max are integers that default to 1 and 15\n if a default game is desired\n \"\"\"\n\n # just start with a plain dictionary, random.sample\n # returns a new list, so no need to pre-allocate lists\n # you won't be using in the future\n self.card = {}\n\n for letter in 'BINGO':\n self.card[letter] = random.sample(range(_min, _max), 5)\n _min += 15\n _max += 15\n\n # You know which letter this needs to be, no need for the if block\n self.card[\"N\"][2] = \"X\" # free space!\n # __init__ doesn't return anything\n\n # this makes your card printable\n # and requires you return a string\n def __str__(self):\n return '\\n'.join('\\t'.join((letter, *map(str, values))) for letter, values in self.card.items())\n\n\n def draw(self, random_draw_list):\n \"\"\"\n Pops a number off a list of random numbers. Using the pop method ensures no duplicate\n numbers will be drawn.\n\n Arguments:\n self (dictionary): The card to to check for the number that was drawn.\n list (list): The list of random numbers to be drawn from.\n \"\"\"\n number_drawn = random_draw_list.pop()\n for letter in self.card:\n # don't track an index here, use enumerate\n for i, number in enumerate(self.card[letter]):\n if number == number_drawn:\n self.card[letter][i] = \"X\"\n return number_drawn\n\n\n def check_win(self):\n # down to the right\n if all(self.card[k][idx]=='X' for idx, key in enumerate(self.card)):\n print('win!')\n return True\n\n # up to the right\n elif all(self.card[k][idx]=='X' for idx, key in zip(reversed(range(5)), self.card)):\n print('win!')\n return True\n\n # horizontal condition\n elif self.check_line(self.card.values()):\n return True\n\n # vertical condition\n elif self.check_line(zip(*self.card.values())):\n return True\n\n return False\n\n\n @staticmethod\n def check_line(values):\n \"\"\"\n values is an iterable over either rows or columns\n of the card. Should be iterable(str)\n\n returns boolean\n \"\"\"\n for line in values:\n if all(val=='X' for val in values):\n return True\n\n\n\n# then, your bingo card is an instance of this class\n\ncard = BingoCard()\n\ncard.check_win()\n# False\n</code></pre>\n\n<p>The <code>__str__</code> function is outlined in the <a href=\"https://docs.python.org/3/reference/datamodel.html#object.__str__\" rel=\"nofollow noreferrer\">python data model</a>, but the gist of it is that <code>__str__</code> allows you to redefine what the informal string representation of an object looks like. </p>\n\n<h1><code>random_draw_list</code></h1>\n\n<p>To make this work, I'd add it as a condition on your <code>while</code> loop. You <code>pop</code> elements off of it, but what happens when there's nothing else to <code>pop</code>? You will get an <code>IndexError</code> for attempting to <code>pop</code> from an empty list. To make the game re-playable, I'd have the user choose to re-play, and generate that new list on each play, just as you re-create the bingo card on each play:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def generate_random_list():\n return random.sample(range(1, 76), 75)\n\n\ndef main():\n card = BingoCard()\n # generate the draw list here, on each play of the game\n # that way if you run out of balls, you can handle that by restarting\n # the game\n random_draw_list = generate_random_list()\n\n print(f\"This is your card:\\n {card}\")\n\n # you don't need the user input here, I think it might\n # be better to include it elsewhere, before generating the\n # card. Instead, keep going while there are numbers to draw\n while random_draw_list:\n number_drawn = card.draw(random_draw_list)\n # this variable is better named balls_drawn\n balls_drawn += 1\n\n print(f\"You drew {number_drawn}\")\n print(f\"Total balls drawn: {balls_drawn}\")\n\n if check_win(card):\n print(f\"You won after drawing {balls_drawn} balls!\")\n break\n\n # if you were to check for user input during the game,\n # it would make more sense to do that after you've at least\n # checked one round\n keep_playing = input(\"Keep playing? (y/n)\").strip().lower()\n if keep_playing == 'n':\n print(\"Ok, thanks for playing\")\n break\n else:\n print(\"Sorry, there are no more balls to draw\")\n\n\n# This is where you prompt the user to play:\nif __name__ == \"__main__\":\n while True:\n play = input(\"Would you like to play bingo? (y/n)\")\n if play.strip().lower() == 'y':\n main()\n else:\n break\n\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T12:31:19.613",
"Id": "447462",
"Score": "0",
"body": "Amazing answer! I like the class idea :) I will definitely refactor that and look at what you have here when I improve my code!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T13:06:10.990",
"Id": "447466",
"Score": "0",
"body": "@AlexV fair point on the class name. In the comments on that code snippet, I do explain why `_min` and `_max` were changed :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T13:55:05.313",
"Id": "447471",
"Score": "0",
"body": "@HelanaBrock quick note, I changed the diagonal check condition since `dict` is not reversible"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T22:17:25.903",
"Id": "229879",
"ParentId": "229872",
"Score": "5"
}
},
{
"body": "<p>Nice job. Here's two comments to add to what other's have said.</p>\n\n<h3>range() excludes the stop point</h3>\n\n<p>The built-in function <code>range(start, stop, step)</code> does not include <code>stop</code> in the items it returns. So in <code>generate_card()</code>:</p>\n\n<pre><code>min_ = 1\nmax_ = 15\n...\nrandom.sample(range(min_, max_), 5)\n</code></pre>\n\n<p>only selects from the numbers 1, 2, 3, ..., 14. <code>max_</code> should be 16. I sometimes write code with an explicit <code>+1</code> like this:</p>\n\n<pre><code> random.sample(range(min_, max_+1), 5)\n</code></pre>\n\n<p>to remind myself that I intended to include <code>max_</code> in the range.</p>\n\n<h3>Separation of concerns</h3>\n\n<p>When a function in a program does multiple unrelated things, it may make the program more difficult to debug, modify, or enhance. For example, <code>draw()</code> gets the next numbered ball and adds it to the BINGO card. If a the player could have multiple bingo cards, each card would be drawing it's own random balls. Clearly, that wouldn't work. It would be better if the ball was drawn separately and then checked against each card. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T16:00:00.730",
"Id": "447496",
"Score": "0",
"body": "I like the separation of concerns point a lot, +1. To drive that home, I'd argue that `drawing` is a function of the game, not the card, so it should not be implemented at the card level. Instead, draw should take a `number` rather than a `number_list` as an argument, and *that* should be checked against the card"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T15:07:48.093",
"Id": "229914",
"ParentId": "229872",
"Score": "4"
}
},
{
"body": "<p>Tried the BINGO game. Encountered a few errors. One of them is an <code>IndexError</code> in the <code>random.pop()</code> function after 26 draws.</p>\n<pre><code><ipython-input-1-16d606983ecb> in draw(card, list)\n 53 list (list): The list of random numbers to be drawn from.\n 54 """\n---> 55 number_drawn = random_draw_list.pop()\n 56 for letter in card:\n 57 i = 0\n\nIndexError: pop from empty list\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-29T03:15:14.353",
"Id": "261361",
"ParentId": "229872",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "229877",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T20:20:21.360",
"Id": "229872",
"Score": "10",
"Tags": [
"python",
"game",
"homework"
],
"Title": "Python Bingo game that stores card in a dictionary"
} | 229872 |
<p>I like to help people on StackOverflow, matter of fact nowadays it depends on how quick you are when answering question.
With that being said, I can't always keep a tab and an eye to refresh the browser to view new questions.</p>
<p>I made a very basic script to send me a notification (OSX) whenever there's a new question.</p>
<pre><code>import requests, os, threading, time
from bs4 import BeautifulSoup
from timeloop import Timeloop
from datetime import timedelta
tl = Timeloop()
SE_REALTIME = "https://stackexchange.com/questions?tab=realtime"
WATCHED_TAG = "swift"
QUE_LI = []
# The notifier function
def notify(title, subtitle, message, link):
t = '-title {!r}'.format(title)
s = '-subtitle {!r}'.format(subtitle)
m = '-message {!r}'.format(message)
l = '-open {!r}'.format(link)
os.system('terminal-notifier {}'.format(' '.join([m, t, s, l])))
def fetch():
# The SOUP
soup = BeautifulSoup(requests.get(SE_REALTIME).content, "html.parser")
# List of Questions with the sid: Stackoverflow.com
li = soup.find_all('div', {'data-sid': 'stackoverflow.com'})
# Loop Through
for child in li:
id = child['class'][2]
all_tags = child.find("span", attrs={'class': 'realtime-tags'}).text.strip()
tags = all_tags.split()
if WATCHED_TAG in tags:
if id not in QUE_LI:
question = child.find("a", attrs={'class': 'realtime-question-url realtime-title'})
QUE_LI.append(id)
notify(title = 'New Question {}'.format(' '.join([WATCHED_TAG])),
subtitle = 'Stackoverflow.com',
message = question.text.strip(),
link = question['href'])
@tl.job(interval=timedelta(seconds=2))
def fetch_questions_every_2s():
fetch()
if __name__ == "__main__":
tl.start(block=True)
</code></pre>
<p>Ok, This code works well. But I'm looking for:</p>
<ol>
<li>A way to listen for changes on the div tree (without making a request every 2 second)</li>
<li>Less code. </li>
</ol>
<p>Dependencies: </p>
<pre class="lang-none prettyprint-override"><code>Terminal-Notifier
BeautifulSoup
TimeLoop
Requests
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T22:12:32.963",
"Id": "447399",
"Score": "0",
"body": "Welcome to Code Review! I trimmed your question description a little bit in order to make it more succinct. If you don't agree with this, feel free to [revert these changes](https://codereview.stackexchange.com/posts/229875/revisions)."
}
] | [
{
"body": "<p>Why would you use <code>stackexchange.com</code> and only take ones with the title of <code>stackoverflow.com</code>? That's a huge waste. </p>\n\n<p>You could change your url from <code>https://stackexchange.com/questions?tab=realtime</code> to <code>https://stackoverflow.com/questions?tab=realtime</code>.</p>\n\n<p>However, actually visiting the website the way you are is hacky and overkill. Instead of web scraping, use the <a href=\"https://api.stackexchange.com/docs\">Stackexchange API</a>.</p>\n\n<p>There is no way to get a notification when a new question is posted. You will have to make a call every time you want the latest results.</p>\n\n<p><strong>Edit:</strong> there may be a way to get notifications, see <a href=\"https://codereview.stackexchange.com/questions/229875/get-a-notification-when-questions-get-posted/229878#comments-229878\">vogel612's comment</a>:</p>\n\n<blockquote>\n <p>there is websockets to receive notifications when a new question is\n posted. To my knowledge these are very much undocumented and easier to\n get access to with a userscript (which would imply changing to\n javascript), but it's not like there's no way to receive notifications\n from SE directly.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T00:18:02.090",
"Id": "447409",
"Score": "2",
"body": "there is websockets to receive notifications when a new question is posted. To my knowledge these are very much undocumented and easier to get access to with a userscript (which would imply changing to javascript), but it's not like there's no way to receive notifications from SE directly."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T22:07:33.167",
"Id": "229878",
"ParentId": "229875",
"Score": "5"
}
},
{
"body": "<p>Apart from using the SE API (for example via some module like <a href=\"https://pypi.org/project/py-stackexchange/\" rel=\"nofollow noreferrer\">py-stackexchange</a>), there are some other optimizations possible.</p>\n\n<p>In your <code>notify</code> function you could use the new f-strings to simplify building the command:</p>\n\n<pre><code>def notify(title, subtitle, message, link):\n os.system(f\"terminal-notifier -title {title!r}\"\n f\" -subtitle {subtitle!r} -message {message!r} -open {link!r}\")\n</code></pre>\n\n<p>Note that strings on multiple lines like here are automatically joined.</p>\n\n<p>Alternatively you could use the <a href=\"https://docs.python.org/3/library/subprocess.html\" rel=\"nofollow noreferrer\"><code>subprocess</code> module</a>, which has a lot more advanced features, which are not needed here, though:</p>\n\n<pre><code>from subprocess import run\n\ndef notify(title, subtitle, message, link):\n run([\"terminal-notifier\", \"-title\", repr(title), \"-subtitle\", repr(subtitle),\n \"-message\", repr(message), \"-open\", repr(link)])\n</code></pre>\n\n<p>In your <code>fetch</code> function you have a possible slow-down. Since <code>QUE_LI</code> (not the most informative name, btw, should also probably be lowercase since it is not a global <em>constant</em>) is a <code>list</code>, checking <code>in</code> is <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>. Just make it a <code>set</code> instead to get <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span> <code>in</code>. I would also <code>and</code> the two <code>if</code> conditions. This saves one level of indentation.</p>\n\n<p>Instead of using <code>\"html.parser\"</code>, consider using <code>\"lxml\"</code> (you might have to <a href=\"https://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser\" rel=\"nofollow noreferrer\">install it first</a>). It is usually faster.</p>\n\n<p>Also note that you are shadowing the built-in function <code>id</code> here and the way you call <code>notify</code> does not conform to Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>. It took me a while to realize that the following lines are all part of the call and its keyword arguments, and not just new lines. It is arguable whether the keywords are needed here at all.</p>\n\n<p>It is also unclear if <code>WATCHED_TAG</code> is supposed to be one tag or multiple tags. If it is just one, as the name suggests, then <code>' '.join([WATCHED_TAG])</code> is quite pointless, since it is just <code>WATCHED_TAG</code>. If it is multiple, then that command won't join them properly and <code>if WATCHED_TAG in tags</code> will only return true if the order of the tags is the same.</p>\n\n<pre><code>seen_ids = set()\n\ndef fetch():\n r = requests.get(SE_REALTIME)\n # r.raise_for_status() # to enable failing if the request fails\n soup = BeautifulSoup(r.content, \"lxml\")\n for child in soup.find_all('div', {'data-sid': 'stackoverflow.com'}):\n question_id = child['class'][2]\n tags = child.find(\"span#\", attrs={'class': 'realtime-tags'}).text.strip()\n if WATCHED_TAG in tags.split() and question_id not in seen_ids:\n seen_ids.add(question_id)\n question = child.find(\"a\", attrs={'class': 'realtime-question-url realtime-title'})\n notify(f'New Question {WATCHED_TAG}', 'Stackoverflow.com',\n question.text.strip(), question['href'])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T09:39:10.830",
"Id": "229899",
"ParentId": "229875",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "229899",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T21:28:22.363",
"Id": "229875",
"Score": "3",
"Tags": [
"python",
"web-scraping",
"stackexchange",
"beautifulsoup"
],
"Title": "Get a notification when questions get posted"
} | 229875 |
<p>I would like to improve the naive matrix transpose algorithm by using a cache friendly algorithm.</p>
<p>So far there are 4 variants.</p>
<p><em>Iterate over the source matrix</em>:</p>
<pre><code> MatrixXd transposeSrc() const
{
MatrixXd At(m_cols, m_rows);
for (int i = 0; i < m_rows; i++) {
for (int j = 0; j < m_cols; j++) {
At(j, i) = (*this)(i, j);
}
}
return At;
}
</code></pre>
<p><em>Iterate over the destination matrix</em>:</p>
<pre><code> MatrixXd transposeDst() const
{
MatrixXd At(m_cols, m_rows);
for (int i = 0; i < m_cols; i++) {
for (int j = 0; j < m_rows; j++) {
At(i, j) = (*this)(j, i);
}
}
return At;
}
</code></pre>
<p><em>A "tiling" version found on <a href="https://stackoverflow.com/a/21548079/6055233">StackOverflow</a></em>:</p>
<pre><code> MatrixXd transposeTilingSO(int tileSize = 16) const
{
MatrixXd out(m_cols, m_rows);
for (int i = 0; i < m_rows; i += tileSize) {
for (int j = 0; j < m_cols; ++j) {
for (int b = 0; b < tileSize && i + b < m_rows; ++b) {
out.m_data[j*m_rows + i + b] = (*this).m_data[(i + b)*m_cols + j];
}
}
}
return out;
}
</code></pre>
<p><em>A block tiling version</em>:</p>
<pre><code> MatrixXd transposeTiling(int tileSize = 16) const
{
MatrixXd At(m_cols, m_rows);
for (int i = 0; i < m_rows;) {
for (; i <= m_rows - tileSize; i += tileSize) {
int j = 0;
for (; j <= m_cols - tileSize; j += tileSize) {
for (int k = i; k < i + tileSize; k++) {
for (int l = j; l < j + tileSize; l++) {
At(l, k) = (*this)(k, l);
}
}
}
for (int k = i; k < i + tileSize; k++) {
for (int l = j; l < m_cols; l++) {
At(l, k) = (*this)(k, l);
}
}
}
for (; i < m_rows; i++) {
for (int j = 0; j < m_cols; j++) {
At(j, i) = (*this)(i, j);
}
}
}
return At;
}
</code></pre>
<p>Experimentally, I thought I have found how to choose which variant is preferable depending on the input matrix size:</p>
<pre><code> MatrixXd transposeOptim(int tileSize = 16) const
{
if (m_rows > 2 * m_cols && m_cols <= 64) {
return transposeSrc();
} else if (m_cols > 2 * m_rows && m_rows <= 64) {
return transposeDst();
} else if (m_rows % tileSize == 0) {
return transposeTilingSO();
} else {
return transposeTiling();
}
}
</code></pre>
<p>And the essential information about the <code>MatrixXd</code> class (full <a href="https://gist.github.com/catree/33942c1b4dd5ed2581e29de147030a1a" rel="nofollow noreferrer">source code</a>):</p>
<pre><code>class MatrixXd {
public:
MatrixXd() :
m_data(), m_rows(0), m_cols(0) {}
MatrixXd(int row, int col) :
m_data(row*col), m_rows(row), m_cols(col) {}
double& operator() (int row, int col)
{
return m_data[row*m_cols + col];
}
double operator() (int row, int col) const
{
return m_data[row*m_cols + col];
}
std::vector<double> m_data;
int m_rows;
int m_cols;
};
</code></pre>
<p>On one computer, I have found that:</p>
<ul>
<li>for <code>Nx6</code> it was preferable to iterate over the source matrix</li>
<li>for <code>6xN</code> the opposite</li>
<li>when the first dimension was divisible by 16 (the tile size), the SO tiling variant was better</li>
<li>otherwise the block tiling was better</li>
</ul>
<p>It is interesting for me to optimize <code>Nx6</code> size that corresponds to problem that involves N samples and 6 variables.</p>
<p>On another computer, the results are a little bit different that makes me think I have probably overengineered the problem (<code>block tiling</code> seems to be the best overall).</p>
<p>Moreover, on <a href="http://quick-bench.com/nhUWfBnHSYemOqx0KR0Bdkd67ok" rel="nofollow noreferrer">quick-bench</a>, I don't have the same conclusion (<code>block tiling</code> performs the worst).</p>
<p>Any idea how to have a fast matrix transpose that performs well on any matrix size and specifically for matrices of <code>Nx6</code> size?</p>
<p>How to choose the optimal tile size? I have used 16 experimentally.</p>
<p>I target classical architecture that has 32 kB of L1-cache, 8-way associative and 64 bytes of cache line size.</p>
<p>Full source code and log are <a href="https://gist.github.com/catree/33942c1b4dd5ed2581e29de147030a1a" rel="nofollow noreferrer">here</a>. I use Catch2 for micro-benchmarking.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T20:15:38.463",
"Id": "447522",
"Score": "0",
"body": "The \"best performance\" is always bound to the specific platform you're running code on, so you will have to benchmark. That said, there are some easy general optimizations you can do if `N` is known at compile time. Is that the case? Or can `N` only be known at runtime?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T11:43:44.960",
"Id": "447599",
"Score": "0",
"body": "`N` is not known at compile time. An example is a computer vision application where you extract some features from a video stream. I am interested to know what optimization could be done with for instance `N=1000` or a large number."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-12T06:36:40.093",
"Id": "449343",
"Score": "0",
"body": "The problem is that this code is very platform/compiler/hardware dependent. Normally, there is no need to optimize matrix transposition lest initially a big mistake was made - as this is neither a bottle neck nor is a frequently used operation. At most, I'd consider adding support for MatrixExpression a class or rather a concept that behaves matrix-like. So instead of transposing a matrix you make a MatrixExpression with reference to the original matrix, and make its operator () swap the indexes (i,j) when you access data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T23:51:46.353",
"Id": "451217",
"Score": "0",
"body": "@ALX23z \nI am not convince about using a MatrixExpression and swaping the indexes. At least for my use case where I can potentially need to iterate over the matrix. MatrixExpression à la Eigen for lazy evaluation is for sure a good solution. But I am more interest in the theoretical optimisation for this specific operation, to understand more about memory cache topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-27T04:27:22.153",
"Id": "451226",
"Score": "0",
"body": "@Catree speed of memory manipulations depends heavily on the cache lines. If you somehow manage to transform in into exchange of cache lines or close to it then the code should be faster. So, if matrix rows memory are 64bit aligned then it should be most efficient to use tiled-like version with parameter 4 or 8. But at long as it is not aligned you'll surely get random results."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-29T21:37:21.020",
"Id": "229876",
"Score": "1",
"Tags": [
"c++",
"performance",
"comparative-review",
"matrix",
"cache"
],
"Title": "Fast matrix transpose"
} | 229876 |
<p><strong>Problem</strong></p>
<p>Write a function that replaces the words in <code>raw</code> with the words in <code>code_words</code> such that the first occurrence of each word in <code>raw</code> is assigned the first unassigned word in <code>code_words</code>. If the <code>code_words</code> list is too short, raise an error. <code>code_words</code> may contain duplicates, in which case the function should ignore/skip them.</p>
<p>Examples:</p>
<pre><code>encoder(["a"], ["1", "2", "3", "4"]) → ["1"]
encoder(["a", "b"], ["1", "2", "3", "4"]) → ["1", "2"]
encoder(["a", "b", "a"], ["1", "1", "2", "3", "4"]) → ["1", "2", "1"]
</code></pre>
<p><strong>Solution</strong></p>
<pre><code>def encoder(raw, code_words):
cw = iter(code_words)
code_by_raw = {} # map of raw item to code item
result = []
seen = set() # for ignoring duplicate code_words
for r in raw:
if r not in code_by_raw:
for code in cw: # cw is iter(code_words), "persistent pointer"
if code not in seen:
seen.add(code)
break
else: # nobreak; ran out of code_words
raise ValueError("not enough code_words")
code_by_raw[r] = code
result.append(code_by_raw[r])
return result
</code></pre>
<p><strong>Questions</strong></p>
<p>My main concern is the use of <code>cw</code> as a "persistent pointer". Specifically, might people be confused when they see <code>for code in cw</code>?</p>
<p>What should be the typical best practices in this case?</p>
<p>Might it be better if I used the following instead?</p>
<pre><code>try:
code = next(cw)
while code in seen:
code = next(cw)
except StopIteration:
raise ValueError("not enough code_words")
else:
seen.add(code)
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p>My main concern is the use of cw as a \"persistent pointer\". Specifically, might people be confused when they see for code in cw?</p>\n</blockquote>\n\n<p>No. Instead, you can just remove the line <code>cw = iter(code_words)</code> as long as it's a native iterable. \"Persistent Pointer\" isn't a thing in python, because all python knows are Names. </p>\n\n<blockquote>\n <p>What should be the typical best practices in this case?</p>\n</blockquote>\n\n<p>That would be building a dictionary and using it for the actual translation. You're basically already doing this with your <code>code_by_raw</code>, if a bit more verbose than others might. The only real difference would be that, in my opinion, it would be better to first establish the translation, and then create the result. </p>\n\n<p>Except for your premature result generation, I would say your current function isn't bad. It does what it needs to do, it does it well without stupid actions, but it's not very readable. It's said often, I think you need to factor out a bit of code. Specifically, the bit that handles the fact that your inputs don't have to yield unique values, and how you need to handle duplicates. </p>\n\n<p>I would suggest a <a href=\"https://docs.python.org/3/tutorial/classes.html#generators\" rel=\"nofollow noreferrer\">generator</a> to handle that. This simplifies the main function a ton. (A comment pointed me towards the <a href=\"https://docs.python.org/3/library/itertools.html#itertools-recipes\" rel=\"nofollow noreferrer\">unique_everseen</a> recipe, which is a slightly broader function. We don't quite need all it's functionality, but it might be worth the effort if you need some more flexibility.)</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def unique(iterable):\n \"\"\" Generator that \"uniquefies\" an iterator. Subsequent values equal to values already yielded will be ignored. \"\"\"\n past = set()\n for entry in iterable:\n if entry in past:\n continue\n past.add(entry)\n yield entry\n\ndef encoder(raw_words, code_words):\n # Create mapping dictionary:\n code_by_raw = dict(zip(unique(raw_words), unique(code_words))\n # Check if we had sufficient code_words:\n if len(code_by_raw) < len(raw_words):\n raise ValueError(\"not enough code_words\")\n # Do translation and return the result\n return [code_by_raw[raw] for raw in raw_words]\n</code></pre>\n\n<p>I can't completely tell your experience level with python. For result creation, I'm using <a href=\"https://docs.python.org/3/tutorial/datastructures.html?highlight=list%20comprehension#list-comprehensions\" rel=\"nofollow noreferrer\">comprehensions</a> here.</p>\n\n<blockquote>\n <p>Might it be better if I used the following instead?</p>\n</blockquote>\n\n<p>It would not be bad functionally to use a structure like that, but it's still ugly (but opinions may differ). It basically does the same as my unique() generator up there.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T07:40:20.360",
"Id": "447426",
"Score": "0",
"body": "Also it might be worth it to have a look at the [`unique_everseen` function in the `itertools` recipes](https://docs.python.org/3/library/itertools.html#itertools-recipes), which has some performance improvements and an optional key by which to determine uniqueness (but is otherwise the same as your `unique` function)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T07:44:46.857",
"Id": "447430",
"Score": "1",
"body": "Yeah, that's worth mentioning. I put it in. I'll keep my `unique()` around for ease spotting of what it does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T07:48:08.500",
"Id": "447431",
"Score": "1",
"body": "Beware that it is just a recipe, though. Unfortunately you cannot just do `from itertools import unique_everseen`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T07:50:23.663",
"Id": "447433",
"Score": "0",
"body": "Ah, OK. Didn't pay attention to the header."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T15:45:59.210",
"Id": "447492",
"Score": "0",
"body": "This makes a lot of sense, thanks! By the way, I think you need another `len` in `if len(code_by_raw) < raw_words`. But this is great, and definitely a lot more readable!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T19:09:21.147",
"Id": "447519",
"Score": "0",
"body": "You're right... I clearly wasn't in good shape today. Glad to have it still be of use despite my mistakes :)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T21:23:48.877",
"Id": "447535",
"Score": "1",
"body": "I think `dict.fromkeys(iterable)` serves more or less the same functionality (for Python version >= 3.6) as `unique(iterable)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T05:07:35.340",
"Id": "447562",
"Score": "0",
"body": "I'm not sure why, but that feels... icky. It should work perfectly fine. Perhaps I'm just not used enough to dicts preserving insertion order. It's not a purpose of the dict class."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T07:06:19.290",
"Id": "229893",
"ParentId": "229891",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "229893",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T06:31:45.950",
"Id": "229891",
"Score": "7",
"Tags": [
"python",
"iterator",
"iteration",
"generator"
],
"Title": "Map unique raw words to a list of code words"
} | 229891 |
<p>I had some XSS protection code I wanted to add into my Web API/MVC application, the model that was used to bind was <code>EditLocationViewModel</code> as below.<br>
My initial plan was to add <code>safeName = AntiXssEncoder.HtmlEncode(locationName, false)</code> into the controller but that would leave the controller littered with <code>AntiXssEncoder</code> code. I figured it could be encapsulated better within the model class, see <code>UpdateLocationViewModel</code>. </p>
<p>I have a small voice saying to me that the XSS code is more than just validation so perhaps should not be on the model class but in fact back in the controller.</p>
<p>Which would be the better approach?<br>
Any other changes that would be recommended?</p>
<p>Before changes...</p>
<pre><code>using System.ComponentModel.DataAnnotations;
namespace SomeNameSpace
{
public class EditLocationViewModel
{
public int LocationId { get; set; }
[Required(ErrorMessage = "Please enter a Location name.")]
[MaxLength(50, ErrorMessage = "Location name has exceeded the maximum length of 50 characters.")]
public string NewLocationName { get; set; }
public string NewAddress { get; set; }
public string NewPhoneNumber { get; set; }
public string NewFaxNumber { get; set; }
}
}
</code></pre>
<p>After changes...</p>
<pre><code>using System.ComponentModel.DataAnnotations;
using System.Web.Security.AntiXss;
namespace SomeNameSpace
{
public class UpdateLocationViewModel
{
private string locationName;
private string address;
private string phoneNumber;
private string fax;
public int LocationId { get; set; }
[Required(ErrorMessage = "Please enter a Location name.")]
[MaxLength(50, ErrorMessage = "Location name has exceeded the maximum length of 50 characters.")]
public string LocationName
{
get { return AntiXssEncoder.HtmlEncode(locationName, false); }
set { locationName = value.Trim(); }
}
public string Address
{
get { return AntiXssEncoder.HtmlEncode(address, false); }
set { address = value?.Trim(); }
}
public string PhoneNumber
{
get { return AntiXssEncoder.HtmlEncode(phoneNumber, false); }
set { phoneNumber = value?.Trim(); }
}
public string FaxNumber
{
get { return AntiXssEncoder.HtmlEncode(fax, false); }
set { fax = value?.Trim(); }
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T11:04:35.643",
"Id": "447445",
"Score": "2",
"body": "It's not a model. It's a view model. So it's perfectly valid to have some presentation concerns her. i.e. XSS protection"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T15:02:28.180",
"Id": "447805",
"Score": "0",
"body": "That was my thinking, nice to have it seconded"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T09:44:11.157",
"Id": "229900",
"Score": "1",
"Tags": [
"c#",
"object-oriented"
],
"Title": "Anti XSS code encapsulated inside model class, does it belong there?"
} | 229900 |
<p>The backup script itself. Make it executable and place it somewhere in your path:</p>
<pre class="lang-bsh prettyprint-override"><code>#!/bin/bash
# Debug:
# set -x
# export PS4='$LINENO:'
TAR_BACKUP_VERSION="1.01"
# Stop on errors:
set -e
set -o pipefail
# Run as root:
if [ "$EUID" -ne 0 ]
then echo "We need root (administrator) privileges to run this..."
sudo bash -c "${0}"
echo ""
read -p "Press [enter] to terminate. " asomevar
exit
fi
# Functions:
function finish {
rm -rf "${PART_LOCATION}"
}
store_partition_layout () {
if [ "${BACKUP_TYPE,,}" == "full" ] && [ ! -z "${PART_LOCATION}" ]; then
# Check if the directory/file already exists:
if [[ -e ${PART_LOCATION} ]] ; then
echo "Error! ${PART_LOCATION} already exists. Please rename or remove it."
exit 1
fi
# Store the partition layout:
trap finish EXIT
mkdir "${PART_LOCATION}"
PIPE_TARGET="${PART_LOCATION}/partition-layout.txt"
echo "##################################################################" >| "${PIPE_TARGET}"
echo "### Partitionals via: lsblk -o name,mountpoint,label,size,uuid ###" >> "${PIPE_TARGET}"
echo "##################################################################" >> "${PIPE_TARGET}"
lsblk -o name,mountpoint,label,size,uuid >> "${PIPE_TARGET}"
echo "" >> "${PIPE_TARGET}"
echo "" >> "${PIPE_TARGET}"
echo "##################################################################" >> "${PIPE_TARGET}"
echo "### Partitionals via: fdisk -l ###" >> "${PIPE_TARGET}"
echo "##################################################################" >> "${PIPE_TARGET}"
fdisk -l >> "${PIPE_TARGET}"
# echo "Created text file with new partition layout: ${PIPE_TARGET}"
STORE_PARTITION_LAYOUT_OUTPUT+="Created text file with new partition layout: ${PIPE_TARGET} in the archieve"
STORE_PARTITION_LAYOUT_OUTPUT+=$'\n'
if [ ! -z "${BOOT_SECTORS}" ]; then
for BOOTSEC in ${BOOT_SECTORS}
do
PNAME="${BOOTSEC##*/}"
BSNAME="${PART_LOCATION}/${PNAME}_boot-sector.bak"
dd if=${BOOTSEC} of=${BSNAME} bs=512 count=1 status=none
# echo "Created backup of boot sector from ${BOOTSEC} as ${BSNAME}"
STORE_PARTITION_LAYOUT_OUTPUT+="Created backup of boot sector from ${BOOTSEC} as ${BSNAME} in the archieve"
STORE_PARTITION_LAYOUT_OUTPUT+=$'\n'
done
fi
# Store UEFI boot stuff (and NVRAM partition), if wanted:
if [ "${STORE_UEFI_BOOT,,}" == "yes" ]; then
efibootmgr -v >| "${PART_LOCATION}/UEFI_boot-entries.txt"
dd if=/dev/nvram of="${PART_LOCATION}/nvram.bin"
fi
fi
}
output_time_it_took () {
END=$(date +%s)
DIFF=$(( $END - $START ))
printf "Operation took: %02d:%02d:%02d (hours:minutes:seconds)" $(($DIFF/3600)) $(($DIFF%3600/60)) $(($DIFF%60))
echo ""
}
suspend_to_disk_yes_no () {
if [ -z "${1}" ]
then
OPERATION="backup"
else
OPERATION="${1}"
fi
echo ""
echo "Suspend to computer to disk after ${OPERATION}? [y/n]"
echo ""
while true; do
read -p "Please enter y or n: " wtd
case $wtd in
[Yy] ) SUSPEND_TO_DISK_AFTERWARDS="1"; break;;
[Nn] ) SUSPEND_TO_DISK_AFTERWARDS=""; break;;
* ) echo "Please answer with y or n.";;
esac
done
echo ""
}
perform_backup () {
FULL_BACKUP_FILENAME="`ls -d ${TAR_BACKUP_BACKUP_LOCATION}`/${BACKUP_FILENAME}"
suspend_to_disk_yes_no
START=$(date +%s)
CUTOFF=$((${#TAR_BACKUP_COMPRESSOR}+4))
FULL_CHECKSUM_FILENAME="${FULL_BACKUP_FILENAME:0:-${CUTOFF}}${TAR_BACKUP_CHECKSUM_COMMAND}"
# FULL_CHECKSUM_FILENAME="${FULL_BACKUP_FILENAME}.${TAR_BACKUP_CHECKSUM_COMMAND}"
SNAR_FULL_FILENAME="`ls -d ${TAR_BACKUP_BACKUP_LOCATION}`/${BACKUP_FILENAME:0:-${CUTOFF}}snar"
# Build the exclude list:
OLDIFS=${IFS}
EXCLUDE_NE=""
while IFS= read -r line; do
if [ ! -z "${line}" ] && [[ $line != //* ]]; then
EXCLUDE_NE=( "${EXCLUDE_NE[@]}" "--exclude=${line}" )
fi
done <<< "${EXCLUDE_THESE}"
IFS=${OLDIFS}
EXCLUDE_NE=`echo "${EXCLUDE_NE[@]}"`
STORE_PARTITION_LAYOUT_OUTPUT=""
TAR_BACKUP_SOURCES=( "${TAR_BACKUP_SOURCE}" "${PART_LOCATION}" )
if [ "${1,,}" == "full" ]; then
# Doing a full backup:
BACKUP_TYPE="$1"
store_partition_layout
if [ "${REMOVE_SNAR_OF_OLD_FULL_BACKUPS,,}" = "yes" ]; then
NO_SNAR="yes"
fi
else
# Doing a differential backup:
BACKUP_TYPE="differential"
OLD_SNAR_FULL_FILENAME="`ls -d ${TAR_BACKUP_BACKUP_LOCATION}`/${LAST_FULL_BACKUP:0:-${CUTOFF}}snar"
if [ "${REMOVE_SNAR_OF_DIFFERENTIAL_BACKUPS,,}" = "yes" ]; then
# User does not want to keep the snar file of the differential backup, so put it into /tmp:
NO_SNAR="yes"
SNAR_TMPDIR=$(mktemp -d -t snar_of_differntial_backup-XXXXXXXXXX)
SNAR_FULL_FILENAME="${SNAR_TMPDIR}/${SNAR_FULL_FILENAME##*/}"
fi
cp -n "${OLD_SNAR_FULL_FILENAME}" "${SNAR_FULL_FILENAME}"
fi
echo "Doing a ${BACKUP_TYPE} backup of ${TAR_BACKUP_SOURCE[@]}"
tar -cpf - ${TAR_BACKUP_OPTIONS} -g "${SNAR_FULL_FILENAME}" ${EXCLUDE_NE} "${TAR_BACKUP_SOURCES[@]}" \
| ${TAR_BACKUP_COMPRESSOR} ${TAR_BACKUP_COMPRESSION_LEVEL} \
| tee >(CHECKSUM=$(mbuffer ${BUFFER_PARAMETERS} | "${TAR_BACKUP_CHECKSUM_COMMAND}" "${TAR_BACKUP_CHECKSUM_PARAM}");echo "${CHECKSUM:0:-1}${BACKUP_FILENAME}" > "${FULL_CHECKSUM_FILENAME}" )\
| mbuffer ${BUFFER_PARAMETERS} > "${FULL_BACKUP_FILENAME}"
# Get the archive size:
ARCHIVE_SIZE=`ls -lLh "${FULL_BACKUP_FILENAME}" | cut -f 5-5 -d ' '`
if [ "${NO_SNAR}" != "yes" ]; then
# Add the checksum of the snar file as well:
cd "${TAR_BACKUP_BACKUP_LOCATION}"
eval "${TAR_BACKUP_CHECKSUM_COMMAND} ${TAR_BACKUP_CHECKSUM_PARAM} ${BACKUP_FILENAME:0:-${CUTOFF}}snar >> ${FULL_CHECKSUM_FILENAME}"
cd - > /dev/null
else
# Remove old snar files of full backups:
if [ "${BACKUP_TYPE,,}" == "full" ]; then
if [ ! -z "${LAST_FULL_BACKUP}" ]; then
cd "${TAR_BACKUP_BACKUP_LOCATION}"
SNAR_TMP=$(mktemp -d -t snar_of_old_full_backup-XXXXXXXXXX)
for i in ????????-??????_${TAR_BACKUP_NAME}_full-backup.snar; do
[ -f "$i" ] || break
if [ "${i}" != "${BACKUP_FILENAME:0:-${CUTOFF}}snar" ]; then
mv -f "${i}" "${SNAR_TMP}"
fi
done
cd - > /dev/null
fi
fi
fi
echo ""
# Output partition layout info:
if [ ! -z "${STORE_PARTITION_LAYOUT_OUTPUT}" ]; then
echo "${STORE_PARTITION_LAYOUT_OUTPUT}"
fi
echo "Finished doing a ${BACKUP_TYPE} backup."
echo "Backup name is: ${BACKUP_FILENAME} (${ARCHIVE_SIZE} in size)"
# Execute post-backup command:
if [ ! -z "${TAR_BACKUP_POST_COMMAND}" ]
then
eval ${TAR_BACKUP_POST_COMMAND}
fi
}
perform_FULL_backup () {
BACKUP_FILENAME="`date +%Y%m%d-%H%M%S`_${TAR_BACKUP_NAME}_full-backup.tar.${TAR_BACKUP_COMPRESSOR}"
TAR_BACKUP_COMPRESSION_LEVEL="${TAR_BACKUP_COMPRESSION_LEVEL_FULL}"
perform_backup "full"
}
perform_DIFFERENTIAL_backup () {
if [ -z "${LAST_FULL_BACKUP}" ]
then
echo "There are no full backups. Can't make a differential backup."
echo "Make a full backup first!"
exit 1
fi
CUT_END=$((${#TAR_BACKUP_COMPRESSOR}+5))
BASED_NAME="${LAST_FULL_BACKUP:0:-$CUT_END}"
BACKUP_FILENAME="`date +%Y%m%d-%H%M%S`_${TAR_BACKUP_NAME}_diff-backup_based_on_${BASED_NAME}.tar.${TAR_BACKUP_COMPRESSOR}"
TAR_BACKUP_COMPRESSION_LEVEL="${TAR_BACKUP_COMPRESSION_LEVEL_DIFF}"
perform_backup "diff"
}
VERIFY_backup () {
suspend_to_disk_yes_no "verify"
echo "Verifying backup"
BACKUP_TO_VERIFY=`( cd ${TAR_BACKUP_BACKUP_LOCATION}; zenity --title="Select backup file to verify, the compressed \".tar\"-archieve and not the checksum file:" --file-selection 2> /dev/null )`
START=$(date +%s)
# Set the type of backup:
if [[ ${BACKUP_TO_VERIFY} == *"_diff-backup_based_on"* ]]; then
BACKUP_TYPE="differential"
if [ "${REMOVE_SNAR_OF_DIFFERENTIAL_BACKUPS,,}" = "yes" ]; then
NO_SNAR="yes"
fi
else
BACKUP_TYPE="full"
if [ "${REMOVE_SNAR_OF_OLD_FULL_BACKUPS,,}" = "yes" ]; then
NO_SNAR="yes"
fi
fi
# SUMFILE_TO_VERIFY="`ls -d "${BACKUP_TO_VERIFY}".*`"
SUMFILE_TO_VERIFY="`ls -d ${BACKUP_TO_VERIFY}`"
SUMFILE_TO_VERIFY=${SUMFILE_TO_VERIFY%%.*}
SUMCOMMAND="${SUMFILE_TO_VERIFY:$((${#BACKUP_TO_VERIFY}+1))}"
DECOMPRESS_COMMAND="${BACKUP_TO_VERIFY##*.} ${TAR_BACKUP_DECOMPRESS_OPTION}"
echo ""
echo "Testing checksum and archieve integrity"
TMPFILE=`mktemp /tmp/chksumout.XXXXXXXXXX`
mbuffer ${BUFFER_PARAMETERS} -i "${BACKUP_TO_VERIFY}" \
| tee >(CHECKSUM=`"${TAR_BACKUP_CHECKSUM_COMMAND}" "${TAR_BACKUP_CHECKSUM_PARAM}"`;echo "${CHECKSUM}" >| ${TMPFILE}) \
| eval "${DECOMPRESS_COMMAND}" | tar tf - && export ARCPASS="OK" || export ARCPASS="FAIL"
CHKCALC=`cat "${TMPFILE}"`
CHKCALC="${CHKCALC%%\ *}"
CHKFILE=`cat "${SUMFILE_TO_VERIFY}.${TAR_BACKUP_CHECKSUM_COMMAND}"`
readarray -t CHECKSUM_ARRAY <<<"${CHKFILE}"
ARCHIEVE_CHECKSUM="${CHECKSUM_ARRAY[0]%%\ *}"
# echo "calculated ac: $CHKCALC"
# echo "stored archic: $ARCHIEVE_CHECKSUM"
if [ "${NO_SNAR}" != "yes" ]; then
SNAR_CHECKSUM="${CHECKSUM_ARRAY[1]%%\ *}"
CHKCALCSNAR=`"${TAR_BACKUP_CHECKSUM_COMMAND}" "${TAR_BACKUP_CHECKSUM_PARAM}" "${BACKUP_TO_VERIFY%%.*}.snar"`
CHKCALCSNAR="${CHKCALCSNAR%%\ *}"
# echo "calculated sc: $CHKCALCSNAR"
# echo "stored snarck: $SNAR_CHECKSUM"
fi
if [ "${CHKCALC}" == "${ARCHIEVE_CHECKSUM}" ]; then
CHKPASS="OK"
else
CHKPASS="FAIL"
CORRUPTED="YES"
fi
rm -f "${TMPFILE}"
echo ""
echo "Checksum test: ${CHKPASS}"
echo "Archieve test: ${ARCPASS}"
if [ "${ARCPASS}" != "OK" ]; then
CORRUPTED="YES"
fi
if [ ! -z "${CORRUPTED}" ]; then
echo "The archieve has probably been corrupted!"
fi
if [ "${NO_SNAR}" != "yes" ]; then
if [ "${CHKCALCSNAR}" == "${SNAR_CHECKSUM}" ]; then
echo "snar file test: OK"
else
echo "snar file test: FAIL"
echo "The snar file has probably been corrupted!"
fi
fi
echo ""
}
PRINT_HELP () {
HELP_STRING='
Instructions for restoring your system from a backup:
First of all a word of warning: If you do not know what you
are doing, you can easily erase all your data and seriously
fuck-up your system by mistake! You can do so even when you
know what you are doing, by being careless.
First, make sure to have everything backed up!
Your Linux system should let you click on the archives and
view their contents in a GUI. This can also be used to
extract only certain folders and files. As the archives are
usually big, this can take a lot of time.
You may consider the alternative of simply mounting the
archives to a folder. You can then treat the folder (and its
content) normally, read-only, of course. For instance, you
could run the "find" command to look for something
particular.
In order to mount an archive to a folder, use the
"archivemount" command (you may have to install it first).
The usage is straightforward. You create a directory where
you want the contents of the archive to appear virtually and
then:
archivemount your-archive.tar.xz your-directory
Don not forget to "unmout" the directory afterwards.
When extracting a full backup for restoration, you can
choose two methods.
Method 1: extract everything into a directory and afterwards
move the contents to the right locations (which may need to
be mounted to the correct folders).
Method 2: Go to your empty root partition and mount all
partitions needed to the correct folders (/boot, for
instance). Now extract everything, excluding stuff you do
not want to extract (/boot/efi for instance). Note that the
"--numeric-owner" flag is important when restoring from
live-CD/DVD:
cd /
DECOMPRESS_COMMAND -d -c your-full-archive-name.tar.compressor | tar xvpf - --exclude=/boot/efi --numeric-owner
Note that the "DECOMPRESS_COMMAND" is the compressor (named
in the extension as well). You start with the full backup,
of course. Then you add the latest differential (if that
is the newest backup):
DECOMPRESS_COMMAND -d -c your-latest-differential-backup-name.tar.compressor | tar xvpf - -g /dev/zero --exclude=/boot/efi --numeric-owner
You can find the layout of your partitions in each full(!)
backup under the folder named by the PART_LOCATION variable
in your config file (/partition-layout by default).
There you can see the partitions, the partition types and
sizes (and their names). You can restore them automatically
or manually via "fdisk". Read up on how to do so properly by
searching for something like "how to use fdisk to manage
partitions on linux".
This is only needed, if you are looking to install to a new
system or your old system went completely blank, of course.
If you added the proper locations of your boot partitions to
the BOOT_SECTORS variable, you will also find a backup of
those boot (or root/MBR) sectors there.
An example for restoring (Warning: this can kill your
system, when not knowing what you are doing!), after having
extracted the folder named in PART_LOCATION from your full
backup archive:
Suppose you want to restore your MBR and the drive was and
still is /dev/sda. Suppose that you did not change anything
and thus HAVE IDENTICALLY SIZED PARTITIONS and you are in
the folder of the partition backup:
dd if=sda_boot-sector.bak of=/dev/sda bs=512 count=1
This will restore the entire 512 bytes of your MBR.
Suppose you want to restore the boot block of partition
/dev/sda3, but you have changed the size of that partition
on your new system:
dd if=sda3_boot-sector.bak of=/dev/sda3 bs=446 count=1
Here we restore the boot-sector to a partition WITH A
DIFFERENT SIZE. If they have the same size, you can use the
code from above (with the 512 bytes).
For those having UEFI systems:
If you added (and mounted) the EFI partition, when you made
a backup, you can find it in there as well (/boot/efi). This
will then contain the backup of that FAT-partition with the
UEFI compliant boot loaders.
If you set the STORE_UEFI_BOOT to "yes", then you will also
find the UEFI boot entries in the PART_LOCATION folder as
"UEFI_boot-entries.txt", while "nvram.bin" will contain a
backup of your NVRAM.
"efibootmgr" can be used to manipulate (restore) the boot
entries, "efivar" for all the other variables (normally you
should not need this).
I hope that this has been somewhat helpful. You can find
more in-depth help on the Internet.
'
echo "${HELP_STRING}" | more
}
check_prog_existance () {
command -v "${1}" >/dev/null 2>&1 || { echo >&2 "I require \"${1}\" but it is not installed. Aborting."; exit 1; }
}
# Read in the configuration (source it):
source "${HOME}/.config/tar_backup_config.sh"
# Check for programms needed:
check_prog_existance "tr"
check_prog_existance "dd"
check_prog_existance "cut"
check_prog_existance "tar"
check_prog_existance "tee"
check_prog_existance "sed"
check_prog_existance "fdisk"
check_prog_existance "lsblk"
check_prog_existance "zenity"
check_prog_existance "printf"
check_prog_existance "mbuffer"
check_prog_existance "${TAR_BACKUP_COMPRESSOR}"
check_prog_existance "${TAR_BACKUP_CHECKSUM_COMMAND}"
if [ "${STORE_UEFI_BOOT,,}" == "yes" ]; then
check_prog_existance "efibootmgr"
fi
#echo ""
# Looking for a bug here that causes a freeze. Pre-running possibly culprits:
echo "test" | mbuffer -q > /dev/null
echo "test" | ${TAR_BACKUP_CHECKSUM_COMMAND} > /dev/null
# Execute pre-backup command:
if [ ! -z "${TAR_BACKUP_PRE_COMMAND}" ]
then
eval ${TAR_BACKUP_PRE_COMMAND}
fi
# Get the last full and differential backup names:
LAST_BACKUP=`( cd ${TAR_BACKUP_BACKUP_LOCATION}; ls ) | grep -v 'sum' | grep -e '^[0-9]\{8\}-[0-9]\{6\}_'${TAR_BACKUP_NAME}'_\(full\|diff\)-backup\(\?\:_based_on\)\?.*\.tar\..*' | tail -1 || true`
LAST_FULL_BACKUP=`( cd ${TAR_BACKUP_BACKUP_LOCATION}; ls ) | grep -v 'sum' | grep -e '^[0-9]\{8\}-[0-9]\{6\}_'${TAR_BACKUP_NAME}'_full-backup\.tar\..*' | tail -1 || true`
LAST_DIFF_BACKUP=`( cd ${TAR_BACKUP_BACKUP_LOCATION}; ls ) | grep -v 'sum' | grep -e '^[0-9]\{8\}-[0-9]\{6\}_'${TAR_BACKUP_NAME}'_diff-backup_based_on.*\.tar\..*' | tail -1 || true`
if [ -z "${LAST_FULL_BACKUP}" ]
then
echo "No backups (no full backup) found."
LAST_DIFF_BACKUP=""
LAST_BACKUP=""
else
echo "Last full backup: ${LAST_FULL_BACKUP}"
if [ -z "${LAST_DIFF_BACKUP}" ]
then
echo "No differential backups."
else
echo "Last differential backup: ${LAST_DIFF_BACKUP}"
fi
LAST_BACKUP_AGE="${LAST_BACKUP:0:8}"
LAST_SECONDS=`date -d $LAST_BACKUP_AGE '+%s'`
AGE=$(( $(date +%s) - $LAST_SECONDS ))
printf "Last backup is %d days old." $(($AGE/86400))
fi
# Ask the user what to do:
echo ""
echo ""
echo "tar_backup.sh V${TAR_BACKUP_VERSION}"
echo "==================="
echo "Perform [f]ull, [d]ifferencial, [v]erify a backup or [p]rint help for restoring?"
echo ""
while true; do
read -p "Please enter f, d, v or p: " wtd
case $wtd in
[Ff] ) perform_FULL_backup; break;;
[Dd] ) perform_DIFFERENTIAL_backup; break;;
[Vv] ) VERIFY_backup; break;;
[Pp] ) PRINT_HELP; break;;
* ) echo "Please answer f, d or v.";;
esac
done
output_time_it_took
# Suspend to disk, if user wishes so:
if [ ! -z "${SUSPEND_TO_DISK_AFTERWARDS}" ]
then
echo "Suspending system to disk in ${TAR_BACKUP_SUSPEND_WAIT} seconds..."
sleep ${TAR_BACKUP_SUSPEND_WAIT}
eval ${TAR_BACKUP_SUSPEND_COMMAND}
fi
exit 0
</code></pre>
<hr>
<p>The configuration file. Edit this to your liking. Place it in <code>$HOME/.config/tar_backup_config.sh</code>. Make sure that you set the path to the backup output folder and add that to the excluded folders:</p>
<pre class="lang-bsh prettyprint-override"><code># This is the configuration file of the "tar_backup" shell script.
# It is usually located in "~/.config/tar_backup_config.sh"
echo ""
# Backup location (directory):
# make sure that this is within the excluded directories!!!!!!!!!!!!!
#TAR_BACKUP_BACKUP_LOCATION="/home/*/tmp/backups"
TAR_BACKUP_BACKUP_LOCATION="/media/*/*"
echo "The backups will be written to: ${TAR_BACKUP_BACKUP_LOCATION}"
# My name for backups (keep this short!):
#
# This will then become something like this:
# date-time_name_type-backup.tar.your_compressor
# Example: 20190920-175933_linux_full-backup.tar.xz
# or: 20190920-181103_linux_diff-backup_based_on_20190920-175933_linux_full-backup.tar.xz
TAR_BACKUP_NAME="myname"
# What to backup:
#
# Make sure to add all the mouted file systems, as we are using the "--one-file-system"
# option with tar! Make sure to mount them in the TAR_BACKUP_PRE_COMMAND.
# Typically /boot is on a different filesystem. If you are on a UEFI system and want
# your UEFI variables backed up as well, add /boot/efi (and mount it).
# Examples:
# "/" = when you got it all on one partition
# "/ /boot /boot/efi /home" = backup the root partition, the boot partition, the UEFI vars and your home (when all have their own seperate partitions)
# ${HOME} = only your home directory
# Note: no trailing slash!
# Note #2: These have precedence over the excluded folders.
# Hence, if you wish to exclude /var/tmp, but add /var/tmp/important - add it here.
TAR_BACKUP_SOURCE="/"
echo "This will be backed up: ${TAR_BACKUP_SOURCE}"
# These directories or files are excluded.
# directory/* will exclude the contents, but store the empty directory in the archive.
# Thus, */.cache/* will exclude all .cache directory's contents, while keeping the
# directories. /lost+found will exclude both directory and contents from the backup.
# Only C++ style comments starting with double slashes (//) are allowed.
# Emtpy lines are allowed as well.
EXCLUDE_THESE='
// These will be excluded, while the archive will contain the empty directories:
/dev/*
/proc/*
/sys/*
/mnt/*
/media/*
/run/*
/var/run/*
/var/log/*
/var/lock/*
/home/*/.gvfs/*
/home/*/.thumbnails/*
/home/*/.local/share/Trash/*
/home/*/.local/share/Steam/*
// Exclude all cache directories, while keeping the empty directories:
*/.cache/*
*/.Cache/*
*/caches/*
*/Caches/*
*/cache/*
*/Cache/*
// Exclude all tmp directories, while keeping the empty directories.
// Note: This already excludes /tmp and /var/tmp
*/tmp/*
// Exclude the lost+found folder in root and do not store the empty directory:
/lost+found
'
# Backup the partition layout and boot sector(s) (only on full backups).
# Leave this empty ="", if you don't want this.
# Make sure that this is NOT within the excluded directores!
# PART_LOCATION="/partition-layout"
PART_LOCATION="/partition-layout"
# List the partitions for which to backup the boot(/root) sector(s) here.
# If you don't want this, leave it empty ="".
# BOOT_SECTORS="/dev/sda1 /dev/sda3"
BOOT_SECTORS="/dev/sda /dev/sda1"
# If you wish to add a dump of your UEFI boot settings (note that you need
# to have an UEFI system for this) you can set this to "yes".
# Note that for convenience this will also store a backup of the NVRAM
# partition (both very small)!
STORE_UEFI_BOOT="yes"
# Set the program used for compression:
#
# xz = high compression, slow (with "-9 -e" it can be impossibly slow)
# bzip2 = slightly less good
# lzip = a lot faster
# gzip = bad crompression ratio
#
#TAR_BACKUP_COMPRESSOR="xz"
TAR_BACKUP_COMPRESSOR="plzip"
# Option for decompression to stdout:
TAR_BACKUP_DECOMPRESS_OPTION="-d -c"
# Set the compression level:
# 0-9, where 0 ist the fastest (bad compression ratio)
# and 9 is the slowest (best compression, most memory usage).
# Adding "-e" (extreme) to some compressors (xz) will increase
# compression ratio, but it may double compression time.
# Adding "-T X" will use X threads (xz), where "-T 0"
# defaults to the number of available cores.
#TAR_BACKUP_COMPRESSION_LEVEL="-T 0 -9 -e"
TAR_BACKUP_COMPRESSION_LEVEL_FULL="-9"
TAR_BACKUP_COMPRESSION_LEVEL_DIFF="-9"
echo "The command for compression will be: \"${TAR_BACKUP_COMPRESSOR} ${TAR_BACKUP_COMPRESSION_LEVEL_FULL}\" [full backup] or \"${TAR_BACKUP_COMPRESSOR} ${TAR_BACKUP_COMPRESSION_LEVEL_DIFF}\" [differential]"
# We don't need the snar files for restoring backups.
# Hence, snar files of old full backups can be deleted:
REMOVE_SNAR_OF_OLD_FULL_BACKUPS="yes"
# We don't need the snar files for restoring backups.
# Hence, snar files from differential backups can be deleted:
REMOVE_SNAR_OF_DIFFERENTIAL_BACKUPS="yes"
# Checksum program:
# Example: "sha512sum -b"
TAR_BACKUP_CHECKSUM_COMMAND="sha512sum"
# Parameters:
TAR_BACKUP_CHECKSUM_PARAM="-b"
# buffer parameters:
BUFFER_PARAMETERS="-b 5 -m 40m -p 75"
# Seconds to wait, before suspending to disk (if wanted):
TAR_BACKUP_SUSPEND_WAIT="30"
# Command to execute for suspending to disk:
# Example: "systemctl hibernate"
TAR_BACKUP_SUSPEND_COMMAND="systemctl hibernate"
# Commands to execute before and after backup
# (for mounting devices and such):
TAR_BACKUP_PRE_COMMAND="echo '' || true"
TAR_BACKUP_POST_COMMAND="echo '' || true"
# tar options (except for some weird exclude szenarios you should
# not have change these:
# --one-file-system --exclude-backups -v
TAR_BACKUP_OPTIONS="--acls --xattrs --exclude-caches --no-wildcards-match-slash --sparse"
</code></pre>
<hr>
<p>I hope that someone can find this useful. If you have any suggestions for improvement or otherwise, feel free to comment.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T09:44:55.830",
"Id": "229901",
"Score": "4",
"Tags": [
"bash",
"linux",
"unix"
],
"Title": "tar-backup V1.01 - backup script for Linux (full and differential backups)"
} | 229901 |
<blockquote>
<p>Q: I have a <code>Bank</code> class containing multiple loan accounts (<code>LoanAccount</code> class). I've create a <code>LoanAccountService</code> that have the CRUD functionalities. My concerns are about how I implemented the update functionality.</p>
</blockquote>
<p><strong>Bank</strong></p>
<pre><code>public class Bank {
private List<LoanAccount> loanAccounts;
}
</code></pre>
<p><strong>Loan account</strong></p>
<pre><code>public class LoanAccount {
private String id;
private Integer numberOfInstallments;
private LoanAccountType type;
private Date creationDate;
private BigDecimal loanAmount;
}
</code></pre>
<p><strong>Service</strong></p>
<pre><code>public class LoanAccountService{
private Bank bank;
public LoanAccountService(Bank bank) {
this.bank = bank;
}
public LoanAccount update(LoanAccount loanAccount) {
Optional<LoanAccount> account = bank.getLoanAccounts()
.stream()
.filter(la -> la.getId().equals(loanAccount.getId()))
.findAny();
if (account.isPresent()) {
account.get().setCreationDate(loanAccount.getCreationDate());
account.get().setLoanAmount(loanAccount.getLoanAmount());
account.get().setNumberOfInstallments(loanAccount.getNumberOfInstallments());
account.get().setType(loanAccount.getType());
} else {
throw new IllegalArgumentException("The object does not exist.");
}
return loanAccount;
}
}
</code></pre>
<p>When the method <code>update</code> is called with a <code>LoanAccount</code> containing an <code>id</code> that already exists in <code>loanAccounts</code> list, I want to update the existing object with the object <code>loanAccount</code> given as parameter.</p>
<p>Above is my implementation, but I feel like there should be better ways to do it.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T11:19:53.510",
"Id": "447447",
"Score": "1",
"body": "Hello, from your implementation it seems me that you can create a `loanaccount` instance with the same id of an existing one and after use the newer to update the older (you are also updating the creation date field). I expect instead to have all `loanaccounts` have at least different ids, is this the expected behaviour ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T14:09:46.433",
"Id": "447473",
"Score": "1",
"body": "_Why_ would you ever want to copy a `LoanAccount`? Please provide some context."
}
] | [
{
"body": "<p>I would suggest following:</p>\n\n<ol>\n<li>Place operations to the objects that contain data for this operation. It will improve encapsulation and allow more flexible code reuse.\nAlso it will be easy to test such implementation because of small methods. </li>\n<li>Use more convenient structure. In this case <code>Map<String, LoanAccount></code> (map id to loanAccount) instead of <code>List<LoanAccount></code></li>\n</ol>\n\n<p>As you can see in this case service contains only required logic (how to react on loan absence). It is easy to read, test and understand.</p>\n\n<p><strong>LoanAccountService.java</strong></p>\n\n<pre><code>public class LoanAccountService{\n\n private Bank bank;\n\n public LoanAccountService(Bank bank) {\n this.bank = bank;\n }\n\n public LoanAccount update(LoanAccount loanAccount) {\n if (!bank.updateLoanAccount(loanAccount)) {\n throw new IllegalArgumentException(\"The object does not exist.\");\n }\n return loanAccount;\n }\n}\n</code></pre>\n\n<p><strong>Bank.java</strong></p>\n\n<pre><code>@Getter\n@Setter\npublic class Bank {\n private Map<String, LoanAccount> loanAccounts;\n\n public boolean updateLoanAccount(LoanAccount loanAccount) {\n LoanAccount loan = loanAccounts.get(loanAccount.getId());\n if (loan != null) {\n loan.update(loanAccount);\n return true;\n }\n return false;\n }\n}\n</code></pre>\n\n<p><strong>LoanAccount.java</strong></p>\n\n<pre><code>@Getter\n@Setter\npublic class LoanAccount {\n private String id;\n private Integer numberOfInstallments;\n private LoanAccountType type;\n private Date creationDate;\n private BigDecimal loanAmount;\n\n public void update(LoanAccount loanAccount) {\n this.setCreationDate(loanAccount.getCreationDate());\n this.setLoanAmount(loanAccount.getLoanAmount());\n this.setNumberOfInstallments(loanAccount.getNumberOfInstallments());\n this.setType(loanAccount.getType());\n }\n}\n</code></pre>\n\n<p>If you can't use this approach, you could made a small refactoring of the service (less code and \"if conditions\" are good things):</p>\n\n<pre><code>public LoanAccount update(LoanAccount loanAccount) {\n LoanAccount account = bank.getLoanAccounts()\n .stream()\n .filter(la -> la.getId().equals(loanAccount.getId()))\n .findAny()\n .orElseThrow(() -> new IllegalArgumentException(\"The object does not exist.\"));\n account.setCreationDate(loanAccount.getCreationDate());\n account.setLoanAmount(loanAccount.getLoanAmount());\n account.setNumberOfInstallments(loanAccount.getNumberOfInstallments());\n account.setType(loanAccount.getType());\n return account;\n}\n</code></pre>\n\n<p>Also I think you should return updated loan account.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T12:22:38.810",
"Id": "447602",
"Score": "0",
"body": "In your last example it should be `acount.set...` not `account.get().set` (`account` is not a `Optional`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T12:37:20.653",
"Id": "447604",
"Score": "0",
"body": "Fixed. Thank you. Pasted not final version."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T07:07:30.837",
"Id": "229955",
"ParentId": "229902",
"Score": "1"
}
},
{
"body": "<h1><a href=\"https://refactoring.guru/smells/feature-envy\" rel=\"nofollow noreferrer\">Feature Envy</a></h1>\n\n<p>The <code>LoanAccountService</code> needs to know all fields from <code>LoanAccount</code> that gets updated:</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>account.get().setCreationDate(loanAccount.getCreationDate());\naccount.get().setLoanAmount(loanAccount.getLoanAmount());\naccount.get().setNumberOfInstallments(loanAccount.getNumberOfInstallments());\naccount.get().setType(loanAccount.getType());\n</code></pre>\n</blockquote>\n\n<p>Now imagine <code>LoanAccount</code> would get a few more fields and they are updateable too but you forgot to change <code>LoanAccountService</code>.. This means <code>LoanAccountService</code> depends on <code>LoanAccount</code>..</p>\n\n<p>A solution would be to add a new method to <code>LoanAccount</code>:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public LoanAccount updateBy(LoanAccount other) {\n this.creationDate = other.creationDate();\n this.loanAmount = other.loanAmount();\n this.numberOfInstallments = other.numberOfInstallments();\n this.type = other.type();\n return this;\n}\n</code></pre>\n\n<h1><a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#map-java.util.function.Function-\" rel=\"nofollow noreferrer\">Optional#map</a></h1>\n\n<p>The if-statement </p>\n\n<blockquote>\n <p><code>if (account.isPresent()) {</code></p>\n</blockquote>\n\n<p>can be replaced by the method <code>map</code> on Optional. With adding the new <code>updateBy</code> method:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public LoanAccount updateBy(LoanAccount other) {\n bank.getLoanAccounts()\n .stream()\n .filter(la -> la.getId().equals(other.getId()))\n .findAny()\n .map(loanAccount -> loanAccount.updateBy(other))\n .orElseThrow(() -> new IllegalArgumentException(\"The object does not exist.\"));\n return other;\n}\n</code></pre>\n\n<h1>Further Improvement</h1>\n\n<p>A second <a href=\"https://refactoring.guru/smells/feature-envy\" rel=\"nofollow noreferrer\">Feature Envy</a> is in the following snipped:</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>bank.getLoanAccounts()\n .stream()\n .filter(la -> la.getId().equals(loanAccount.getId()))\n</code></pre>\n</blockquote>\n\n<p>Not the <code>LoanAccountService</code> should filter the data but the <code>Bank</code> itself should filter it:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>// in Bank.java\n\npublic Optinal<List<LoanAccount> findBy(int id) {\n return loanAccounts.stream()\n .filter(la -> la.getId().equals(id))\n .collect(Collectors.toList())\n}\n</code></pre>\n\n<h1>All together</h1>\n\n<pre class=\"lang-java prettyprint-override\"><code>// LoanAccountService.java\n\npublic LoanAccount updateBy(LoanAccount other) {\n bank.findBy(other.getId())\n .findAny()\n .map(loanAccount -> loanAccount.updateBy(other))\n .orElseThrow(() -> new IllegalArgumentException(\"The object does not exist.\"));\n return other;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T12:31:22.870",
"Id": "447603",
"Score": "0",
"body": "In `Bank::findBy` you have the wrong return type in the signature. Also `LoadAccountService::updateBy` is assuming `Bank::findBy` is returning a `Stream`. I'd also like to suggest to have `Bank::findBy` directly return a single (optional) `LoanAccount` by moving `.findAny()` there instead of building an unneeded `List`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T08:44:37.660",
"Id": "229959",
"ParentId": "229902",
"Score": "1"
}
},
{
"body": "<p>I'd like to focus on a different aspect:</p>\n\n<p>I find it dangerous using the same class <code>LoanAccount</code> both as a storage class inside Bank and as a data transfer class in the API, because if by accident the code on the outside gets an storage instance then it could change it's data bypassing the service.</p>\n\n<p>I'd suggest to make <code>LoanAccount</code> an interface containing only getters and use this in the API methods. Then <code>Bank</code> and the caller would have their own implementations that can't be modified by the other side.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T13:02:01.077",
"Id": "447610",
"Score": "1",
"body": "Nice point! Alternatively it is possible to introduce LoanAccountDTO and use it on Service API and outside (it has clear name). Also mapstruct can be used for transformation."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T12:51:59.120",
"Id": "229970",
"ParentId": "229902",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T09:48:48.897",
"Id": "229902",
"Score": "2",
"Tags": [
"java"
],
"Title": "update object in list"
} | 229902 |
<p>here is my issue when trying to override my equals method. </p>
<p>this is what I have currently</p>
<pre><code> @Override
public boolean equals(Object o) {
if (this.name.equals(((Animal) o).getName())) {
System.out.println("True");
return true;
} else {
System.out.println("False");
return false;
}
}
</code></pre>
<p>I'm trying to compare the names of objects which extend the Animal class is there a better way to create this equals method without the explicit casting to compare the names of each object?, I was messing around with Generics but just couldn't get it to work properly. below is what I attempted with generics but when I tried to pass an object in the parenthesis it was just using the super equals method. (The get method literally just returns the name)</p>
<pre><code>public boolean equals(Class<? extends Animal>o) {
if (this.name.equals(o.getName())) {
System.out.println("True");
return true;
} else {
System.out.println("False");
return false;
}
}
</code></pre>
<p>any help is really appreciated.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T11:15:30.470",
"Id": "447446",
"Score": "2",
"body": "Welcome to Code Review; however, there is not enough context here for us to provide a meaningful review, and this site is not the place to ask for help with producing working code. Please consult the [help center](https://codereview.stackexchange.com/help/asking), to find out how to make the most of this resource."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T11:51:18.143",
"Id": "447453",
"Score": "0",
"body": "Ive edited the code, hopefully this meets the standards."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T14:31:09.187",
"Id": "447481",
"Score": "0",
"body": "There isn't enough code here for us to give a good review, it might be better if you posted the entire class."
}
] | [
{
"body": "<p>You could try something like the following in The Animal Class:</p>\n\n<pre><code> @Override\n public boolean equals(Object obj) {\n Animal animal = null;\n if(obj == null || this ==null) {\n return false;\n }\n if(obj instanceof Animal) {\n animal = (Animal) obj;\n }\n if(this.name.equals(animal.getName())) {\n return true;\n }\n\n return super.equals(obj);\n }\n</code></pre>\n\n<p>Now if you have a Cat and a Dog which extend Animal\nand you check</p>\n\n<pre><code>private Cat cat = new Cat(\"Pipsy\");\nprivate Dog dog = new Dog(\"Pupsy\");\n</code></pre>\n\n<p><code>if(cat.equals(dog))</code> will return false because you check the name, and they have a different one.</p>\n\n<p>I do not think you have to use Generics, Object is generic enough :). Hope this helped</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T12:09:32.047",
"Id": "447454",
"Score": "0",
"body": "Ah this seems to be what I was looking for, thank you very much =)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T13:27:46.957",
"Id": "447468",
"Score": "0",
"body": "This will cause a NPE if the `obj` is not an Animal. I'm surprised the compiler doesn't warn you about it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T13:57:48.333",
"Id": "447472",
"Score": "0",
"body": "How could `this` ever be `null`?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T12:00:40.660",
"Id": "229907",
"ParentId": "229905",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "229907",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T10:39:59.677",
"Id": "229905",
"Score": "0",
"Tags": [
"java",
"generics"
],
"Title": "using a cast in an overriden equals method should I use generics and if so, how?"
} | 229905 |
<p>Below there is a function eating all strings and convert it to Unicode. It works fine. But is it the best way to do so? Is there maybe already an existing function for it?</p>
<p>The reason was a German Windows version which prints German ä ö ü - error-messages which are retrieved from popen/communicate etc. There must have been someone before me with the same issue.</p>
<pre><code># python2.7
def all_eating_unicode_converter(input_string):
test1 = 'äöü'
test2 = b'\xe4\xf6\xfc'
test3 = u'äöü'
"""
Converts every input to unicode. tested with testcases abouve!
:param input_string: may be a string or unicode or bytes.
:return: returns unicode
"""
l.debug("type: %s\n message:%s" % (type(input_string), input_string))
if type(input_string) is not unicode:
# i don't need to decode unicode. because it already is!
output_string = input_string.decode("utf-8") # converts bytes to unicode
else:
output_string = input_string
return output_string
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T13:00:29.603",
"Id": "447465",
"Score": "2",
"body": "While you say it works for the three test strings, it actually raises an exception for `test2`: `b'\\xe4\\xf6\\xfc'.decode(\"utf-8\") -> UnicodeDecodeError: 'utf8' codec can't decode byte 0xe4 in position 0: invalid continuation byte`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T13:14:46.710",
"Id": "447467",
"Score": "1",
"body": "Although that is just because that is not a valid UTF-8 string. Maybe use `b'\\xc3\\xa4\\xc3\\xb6\\xc3\\xbc'` instead."
}
] | [
{
"body": "<p>First, you should not be using Python 2 anymore, if at all possible. <a href=\"https://pythonclock.org/\" rel=\"noreferrer\">It will reach end of support at the end of the year</a>.</p>\n\n<p>In Python 3 your code would just be:</p>\n\n<pre><code>def all_eating_unicode_converter(input_string):\n \"\"\"\n Converts every input to unicode.\n :param input_string: may be a string or unicode or bytes.\n :return: returns unicode\n\n Tested with: 'äöü', b'\\xc3\\xa4\\xc3\\xb6\\xc3\\xbc', u'äöü'\n \"\"\"\n if isinstance(input_string, bytes):\n return input_string.decode(\"utf-8\")\n return input_string\n</code></pre>\n\n<p>Note that I used <code>isinstance</code> instead of <code>type</code>, to also allow derived types of <code>bytes</code> to work properly.</p>\n\n<p>I also shortened the logic by not insisting on having a single <code>return</code> from the function. Here it is clear enough what is happening, and I am in general a fan of early returns.</p>\n\n<p>Docstrings only work when they are actually right after the function header, so I moved the testcases inside the docstring. </p>\n\n<p>In addition, one reason the <code>logging</code> module is so powerful is that it allows you to write log messages which are costly to print and never print them. In other words the replacement of the placeholders is only performed if the message is actually being printed, i.e. if the log level is high enough. So you should always do this:</p>\n\n<pre><code>l.debug(\"type: %s\\n message:%s\", type(input_string), input_string)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T14:12:18.383",
"Id": "447474",
"Score": "1",
"body": "thank you for your effort and detailed explanation and comments to the performance. I've learnde a lot and one time I'll be a great python programmer =)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T13:15:30.380",
"Id": "229910",
"ParentId": "229909",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "229910",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T12:39:44.107",
"Id": "229909",
"Score": "6",
"Tags": [
"python",
"python-2.x",
"unicode"
],
"Title": "Universal string conversion"
} | 229909 |
<p>I often have data stored in a Map that I need to retrieve by something other than the Key, so wanted to write a generic class that lets you define up to N keys (with the possibility of each key having a different class). Methods are definied to retrieve both the first matching result, and all matching results.</p>
<p>I achieved this by internally creating an ID which is mapped to the data, and keys which are mapped to a list of their matching IDs. Here's my implementation:</p>
<pre><code>public class MultiKeyMap<T> {
private Map<Long, T> dataMap = new HashMap<>();
private Map<Class<?>, Map<Object, List<Long>>> keyMaps = new HashMap<>();
private long id = 0;
/**
* Construct a data map with the given data and key function(s)
*
* @param data
* @param keyFunctions
*/
@SafeVarargs
public MultiKeyMap(Collection<T> data, Function<T, ?>... keyFunctions) {
addAll(data);
for (Function<T, ?> f : keyFunctions) {
addKey(f);
}
}
/**
* Add an additional key function to this data map.
*
* @param keyFunction
* @return
*/
public <K> MultiKeyMap<T> addKey(Function<T, K> keyFunction) {
if (keyFunction == null) {
throw new RuntimeException("Key function must not be null");
}
Map<Object, List<Long>> keyMap = new HashMap<>();
Class<?> keyClass = keyFunction.apply(dataMap.values().iterator().next()).getClass();
if (keyMaps.containsKey(keyClass)) {
keyMap = keyMaps.get(keyClass);
}
for (Entry<Long, T> e : dataMap.entrySet()) {
K key = keyFunction.apply(e.getValue());
if (!keyMap.containsKey(key)) {
List<Long> l = new ArrayList<>();
l.add(e.getKey());
keyMap.put(key, l);
} else {
keyMap.get(key).add(e.getKey());
}
}
keyMaps.put(keyClass, keyMap);
return this;
}
/**
* Add a single element to this data map
*
* @param data
*/
public void add(T data) {
if (data == null) {
throw new RuntimeException("Data must not be null");
}
dataMap.put(id++, data);
}
/**
* Add a collection to this data map
*
* @param data
*/
public void addAll(Collection<T> data) {
if (data == null || data.isEmpty()) {
throw new RuntimeException("Data must not be empty or null");
}
for (T t : data) {
dataMap.put(id++, t);
}
}
/**
* Returns true if there is a mapping for the given key
*
* @param key
* @return
*/
public boolean containsKey(Object key) {
return keyMaps.get(key.getClass()).containsKey(key);
}
/**
* Get a single result from the given key
*
* @param key
* @return
*/
public T get(Object key) {
return dataMap.get(keyMaps.get(key.getClass()).get(key).get(0));
}
/**
* Get a list of results from the given key
*
* @param key
* @return
*/
public List<T> getAll(Object key) {
return keyMaps.get(key.getClass()).get(key).stream().map(a -> dataMap.get(a)).collect(Collectors.toList());
}
/**
* Return the size of the map
*
* @return
*/
public int size() {
return dataMap.size();
}
/**
* Returns true if the map is empty
*
* @return
*/
public boolean isEmpty() {
return dataMap.isEmpty();
}
/**
* Return true if this map contains the given value
*
* @param value
* @return
*/
public boolean containsValue(Object value) {
return dataMap.containsValue(value);
}
/**
* Clear this map of all of its data
*/
public void clear() {
dataMap = new HashMap<>();
keyMaps = new HashMap<>();
id = 0;
}
/**
* Return a list of all key sets generated for this map
*
* @return
*/
public List<Set<Object>> keySets() {
return keyMaps.values().stream().map(a -> a.keySet()).collect(Collectors.toList());
}
/**
* Return the key set for the given class
*
* @param keySetClass
* @return
*/
public Set<Object> keySet(Class<?> keySetClass) {
return keyMaps.get(keySetClass).keySet();
}
/**
* Return all values in this map
*
* @return
*/
public Collection<T> values() {
return dataMap.values();
}
}
</code></pre>
<p>Internally the class of the key is used to to populate the key map, for a faster retrieval of the data, since almost always the keys that are defined will be of a different class. In the case that they are not, this may produce additional search results, but this is acceptable (for example, if for a Person, a key is defined to be a the firstName (String.class), and a second to be lastName (String.class), when searching for "Smith", all matching first and last names of Smith will be returned, e.g. "John Smith" and "Smith Jones")</p>
<p>Given a Person class as an example:</p>
<pre><code>public class Person {
private String firstName;
private String lastName;
private String streetName;
private int doorNumber;
}
</code></pre>
<p>The MultiKeyMap could be initialised like this,</p>
<pre><code>MultiKeyMap<Person> map = new MultiKeyMap<>(data, Person::getLastName, Person::getDoorNumber);
</code></pre>
<p>which would allow for retrieval of the data by their last name, or the door number.</p>
<p>I tested it compared to a traditional nested Map approach, and this seems to run in about the same time or less (comparing only the retrival time as initialisation time is not a problem here).</p>
<p>My questions: Could this code be improved? Are there cases when it may not work?</p>
<p>[EDIT] Added a unit test (based on the same Person class as before) to show how this might be used, and what results are expected below.</p>
<pre><code>@Test
public void tester() {
List<Person> data = new ArrayList<>();
Person p1 = new Person("John", "Smith", "Street", 6);
Person p2 = new Person("Smith", "Jones", "Road", 7);
Person p3 = new Person("Alex", "Brown", "Street", 6);
Person p4 = new Person("Jane", "Smith", "Road", 8);
data.add(p1);
data.add(p2);
data.add(p3);
data.add(p4);
MultiKeyMap<Person> map = new MultiKeyMap<>(data, Person::getDoorNumber, Person::getLastName);
// get where doorNumber=7
Assert.assertEquals(p2, map.get(7));
List<Person> expected = new ArrayList<>();
expected.add(p1);
expected.add(p4);
// get where lastName="Smith"
Assert.assertEquals(expected, map.getAll("Smith"));
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T14:36:06.417",
"Id": "447483",
"Score": "0",
"body": "expected is the first argument in `assertEquals`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T14:41:55.337",
"Id": "447484",
"Score": "0",
"body": "Thanks, updated accordingly."
}
] | [
{
"body": "<ol>\n<li>I would drop </li>\n</ol>\n\n<pre><code>private Map<Long, T> dataMap = new HashMap<>();\nprivate long id = 0;\n</code></pre>\n\n<p>And use directly </p>\n\n<pre><code>private Map<Class<?>, Map<Object, List<T>>> keyMaps = new HashMap<>();\n</code></pre>\n\n<p>You are already storing pointers to objects, you aren't saving any memory with dataMap.</p>\n\n<ol start=\"2\">\n<li>I would expect that add() method adds new item also to keyMaps.</li>\n<li>Why not allow for multiple keys of same type? Maybe change the API to something like:</li>\n</ol>\n\n<pre><code>MultiKeyMap<Person> map = new MultiKeyMap<>(data);\nMap<String, List<Person>> byLast = map.by(Person::getLastName);\nMap<String, List<Person>> byFirst = map.by(Person::getFirstName);\n</code></pre>\n\n<p>On the other hand you could just use built in Streams:</p>\n\n<pre><code>List<Person> data;\n...\nMap<String, List<Person>> byLast = data.stream().collect(Collectors.groupingBy(Person::getLastName));\nMap<String, List<Person>> byFirst = data.stream().collect(Collectors.groupingBy(Person::getFirstName));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T18:13:07.133",
"Id": "447516",
"Score": "0",
"body": "Thanks for the feedback! You're right, I'll scrap the ID and the add function definitely should add the new key - that was an oversight, although this would mean storing the Function passed to the mapping function which I wanted to avoid so might just remove it altogether since I don't really need it.\nThanks for some interesting further exercises to do but it doesn't really fit my use case - although my fault for not explaining what it is!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T16:28:25.443",
"Id": "229920",
"ParentId": "229911",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T14:03:11.400",
"Id": "229911",
"Score": "2",
"Tags": [
"java"
],
"Title": "Storing data in a map that can be retrieved by N keys"
} | 229911 |
<p>I wrote a very rudimentary code that counts sentences and words in the arbitrary text.</p>
<p>Code:</p>
<pre><code>class analyse():
def __init__(self,text):
self.text = text
def sentence_count(self):
punctuation_marks = ['\.','\?','!', '\."','\.”']
space_newline_end = [' ', '\n', '$']
combine = ['({}({}|{}|{}))'.format(x,*space_newline_end) for x in punctuation_marks]
pattern_string = '|'.join(combine)
sentence_search = re.compile(r'{}'.format(pattern_string))
count = len(sentence_search.findall(self.text))
return count
def word_search(self):
'''Returns all words in the text (repetitions are included)'''
word_pattern = re.compile(r'(\w+)((\’\w+)|(-\w+)|(\'\w+))?')
find_all = word_pattern.findall(self.text)
return [''.join(x[:2]).lower() for x in find_all]
def unique_words(self):
return set(self.word_search())
def unique_words_count(self):
return {x : (self.word_search()).count(x) for x in self.unique_words()}
def most_frequent(self,n,reverse):
'''Returns n most (reverse == False) / least (reverse == True) frequent words.'''
uniq_words = self.unique_words_count()
if n > len(uniq_words):
print("Number of unique words is less than {}.".format(n))
return None
words = list(uniq_words.keys())
count = [[list(uniq_words.values())[x],x] for x in range(len(uniq_words))]
count_sorted = sorted(count,key = lambda x: x[0],reverse=True)
words_sorted = [words[x[1]] for x in count_sorted]
if reverse == False:
for y in range(n):
print('Word: {}. {} \t \t |||| Count: {}'.format(y+1,words_sorted[y],count_sorted[y][0]))
if reverse == True:
iterator = 1
for y in range(len(uniq_words)-1,len(uniq_words)-n-1,-1):
print('Word: {}. {} \t \t |||| Count: {}'.format(iterator,words_sorted[y],count_sorted[y][0]))
iterator+=1
def search_specific_word_count(self,word):
if word in self.unique_words_count():
print('Word: {} || Count: {}'.format(word,self.unique_words_count()[word]))
else:
print('"{}" is not found.'.format(word))
</code></pre>
<p>What can be improved?</p>
<hr>
<p><em>If you don't need an example, you can skip following part.</em></p>
<p>Example:</p>
<p>Consider following passage:</p>
<blockquote>
<p>When Matt Radwell, a customer support officer for a small local
authority in the UK, first started answering queries from the area’s
residents, it was a frustrating and time-consuming business. If a
resident contacted Aylesbury Vale District Council, 40 miles north of
London, about an issue like housing benefit in which he lacked
expertise, Mr Radwell might keep the caller waiting as long as 20
minutes. He had to find someone who could give him the relevant
information.</p>
</blockquote>
<p>Let the variable that hold the passage above be called <code>passage</code></p>
<p>Firstly we instantiate class</p>
<p><code>p1 = analyse(passage)</code></p>
<p>Now let's have a look at each function:</p>
<pre><code>Input: p1.sentence_count()
Output: 3
Input: p1.word_search()
Output: ['when', 'matt', 'radwell', 'a', 'customer', 'support', 'officer', 'for', 'a', 'small', 'local', 'authority', 'in', 'the', 'uk', 'first', 'started', 'answering', 'queries', 'from', 'the', 'area’s', 'residents', 'it', 'was', 'a', 'frustrating', 'and', 'time-consuming', 'business', 'if', 'a', 'resident', 'contacted', 'aylesbury', 'vale', 'district', 'council', '40', 'miles', 'north', 'of', 'london', 'about', 'an', 'issue', 'like', 'housing', 'benefit', 'in', 'which', 'he', 'lacked', 'expertise', 'mr', 'radwell', 'might', 'keep', 'the', 'caller', 'waiting', 'as', 'long', 'as', '20', 'minutes', 'he', 'had', 'to', 'find', 'someone', 'who', 'could', 'give', 'him', 'the', 'relevant', 'information']
Input: p1.unique_words()
Output: {'20', '40', 'a', 'about', 'an', 'and', 'answering', 'area’s', 'as', 'authority', 'aylesbury', 'benefit', 'business', 'caller', 'contacted', 'could', 'council', 'customer', 'district', 'expertise', 'find', 'first', 'for', 'from', 'frustrating', 'give', 'had', 'he', 'him', 'housing', 'if', 'in', 'information', 'issue', 'it', 'keep', 'lacked', 'like', 'local', 'london', 'long', 'matt', 'might', 'miles', 'minutes', 'mr', 'north', 'of', 'officer', 'queries', 'radwell', 'relevant', 'resident', 'residents', 'small', 'someone', 'started', 'support', 'the', 'time-consuming', 'to', 'uk', 'vale', 'waiting', 'was', 'when', 'which', 'who'}
Input: p1.unique_words_count()
Output: {'was': 1, 'queries': 1, 'radwell': 2, 'the': 4, 'caller': 1, 'waiting': 1, 'area’s': 1, 'and': 1, 'first': 1, 'north': 1, 'a': 4, 'give': 1, 'like': 1, 'housing': 1, 'as': 2, 'him': 1, 'from': 1, 'he': 2, 'might': 1, 'someone': 1, 'who': 1, 'it': 1, 'issue': 1, 'miles': 1, 'lacked': 1, 'started': 1, 'benefit': 1, '20': 1, 'minutes': 1, 'an': 1, 'council': 1, 'time-consuming': 1, 'resident': 1, 'officer': 1, 'uk': 1, 'expertise': 1, 'had': 1, 'support': 1, 'small': 1, 'answering': 1, 'which': 1, 'customer': 1, 'matt': 1, 'if': 1, 'mr': 1, 'in': 2, 'aylesbury': 1, 'london': 1, 'frustrating': 1, 'long': 1, 'when': 1, 'contacted': 1, 'district': 1, 'relevant': 1, '40': 1, 'could': 1, 'information': 1, 'residents': 1, 'about': 1, 'keep': 1, 'of': 1, 'to': 1, 'find': 1, 'authority': 1, 'local': 1, 'business': 1, 'for': 1, 'vale': 1}
Input: p1.most_frequent(1,reverse=False)
Output: 'Word: 1. the |||| Count: 4'
Input: p1.most_frequent(2,reverse=False)
Output: 'Word: 1. the |||| Count: 4
Word: 2. a |||| Count: 4'
Input: p1.most_frequent(100,reverse=False)
Output: 'Number of unique words is less than 100.'
</code></pre>
<p>If you want words that occur least often, set reverse for True</p>
<pre><code>Input: p1.most_frequent(1,reverse=True)
Output: 'Word: 1. vale |||| Count: 1'
</code></pre>
<p>You can also check frequency of the specific word, for example:</p>
<pre><code>Input: p1.search_specific_word_count('customer')
Output: 'Word: customer || Count: 1'
</code></pre>
<p>If you want to check the word that is not in the text, then output will be</p>
<pre><code>Input: p1.search_specific_word_count('president')
Output: '"president" is not found.'
</code></pre>
| [] | [
{
"body": "<h3>Redundant processing</h3>\n\n<p>Some of the code processes the text multiple times. For example:</p>\n\n<pre><code>def unique_words_count(self):\n return {x : (self.word_search()).count(x) for x in self.unique_words()}\n</code></pre>\n\n<p>scans the text twice and scans a list of all the words:</p>\n\n<ol>\n<li><code>self.word_search()</code> calls <code>word_pattern.findall()</code></li>\n<li><code>.count(x)</code> scans the list of words</li>\n<li><code>self.unique_words()</code> calls <code>word_search()</code> which calls <code>word_pattern.findall()</code> </li>\n</ol>\n\n<p>All of the analysis can be obtained by processing the text once to build a dictionary of items in the text. The various methods can the return information based on the dictionary.</p>\n\n<h3>collections module</h3>\n\n<p>The <code>collections</code> library provides a <code>Counter</code> class designed for counting things.</p>\n\n<pre><code>counts = Counter(sequence) # counts items in the sequence\n</code></pre>\n\n<h3>regex</h3>\n\n<p>The regex patterns can be simplified:</p>\n\n<pre><code>word_pattern = r\"\\w+(?:[-’']\\w+)?\"\n\nsentence_ending = r'[.?!](?=\\s|\"|”|$)' # .?! only if followed by white space, quote, or end-of-string.\n</code></pre>\n\n<p>I also added a regex to catch a few abbreviations, so they won't be picked up as sentence endings. Obviously, this can be expanded.</p>\n\n<h3>Separate viewing from processing</h3>\n\n<p>Rather than directly printing out some data, it is often better for a class to return a string representation of the data. This makes the class more flexible. For example, if you want to use the Analysis class as part of a web server. The string should be sent to the web browser, not printed on the server's screen. (Although, some web frameworks take care of this for you).</p>\n\n<h3>revised code</h3>\n\n<pre><code>import re\nimport itertools as it\n\nfrom collections import Counter, deque\n\n\nclass Analyse:\n\n def __init__(self, text):\n self.text = text\n\n abbreviations = r\"Dr\\.|Mr\\.|Mrs\\.\"\n\n word_pattern = r\"\\w+(?:[-’']\\w+)?\"\n\n sentence_ending = r'[.?!](?=\\s|\"|”|$)'\n\n pattern_string = '|'.join([abbreviations, word_pattern, sentence_ending])\n\n search_pattern = re.compile(pattern_string)\n\n self.counts = Counter(match[0].lower() for match in search_pattern.finditer(text))\n\n # pulls sentence endings out of self.counts, so the methods don't need\n # to filter them out\n self.sentence_endings = sum(self.counts.pop(p, 0) for p in '.?!')\n\n # length of longest word\n self.maxlen = max(len(w) for w in self.counts) \n\n\n def sentence_count(self):\n return self.sentence_endings\n\n\n def all_words(self):\n '''Returns all words in the text (repetitions are included)'''\n return list(self.counts.elements())\n\n\n def unique_words(self):\n return list(self.counts.keys())\n\n\n def word_counts(self, word=None):\n if word:\n return self.counts[word]\n else:\n return dict(self.counts)\n\n\n def most_frequent(self, n):\n '''Returns n most frequent words.'''\n return self.counts.most_common(n)\n\n\n def least_frequent(self, n):\n return self.counts.most_common()[-n:]\n\n\n def most_frequent_as_str(self, n):\n s = [f\"Word {i}: {word:{self.maxlen}} |||| Count: {count}\" for i, (word, count) in enumerate(self.most_frequent(n))]\n return '\\n'.join(s)\n\n\n def least_frequent_as_str(self, n):\n s = [f\"Word {i}: {word:{self.maxlen}} |||| Count: {count}\" for i, (word, count) in enumerate(self.least_frequent(n))]\n return '\\n'.join(s)\n</code></pre>\n\n<p>Several of the methods end with <code>return list(...)</code> or <code>return dict(...)</code>. The calls to <code>list</code> or <code>dict</code> are probably not needed, but I put them in to match the data structures returned by your code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T05:22:54.083",
"Id": "447565",
"Score": "0",
"body": "Thanks for the review! One question: you wrote `word_pattern = r\"\\w+(?:[-’']\\w+)?\"` What is `?:` for?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T05:47:54.927",
"Id": "447570",
"Score": "0",
"body": "One more thing: the name of my class was called \"analyse\", but you instead wrote \"Analyse\". Is there a reason for that? (Like, for example, convention for writing names of the classes)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T05:53:52.983",
"Id": "447571",
"Score": "0",
"body": "And one more: `sentence_ending = r'[.?!](?=\\s|\"|”|$)'` I get everything except `?=` part. What is it for?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T06:17:34.733",
"Id": "447572",
"Score": "0",
"body": "And one more: you imported `deque` from `collections`, but I haven't seen you using it anywhere. Why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T09:21:17.760",
"Id": "447584",
"Score": "2",
"body": "@Nelver It is `Analysis` because of [PEP8](https://www.python.org/dev/peps/pep-0008/), the import is probably an oversight (maybe they used it instead of `pop` for `self.sentence_endings`?). `?=` is a [positive look ahead](https://www.regular-expressions.info/lookaround.html). So it matches only of the pattern will come afterwards. `?:` is [quite similar, but not quite the same](https://stackoverflow.com/a/10804846/4042267)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T09:38:48.687",
"Id": "447586",
"Score": "1",
"body": "@Graipher I see, thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T22:19:56.050",
"Id": "447732",
"Score": "1",
"body": "`(?:...)` is like using `(...)`, but the regex engine doesn't save the results. So you can't get it using `.group()`. As Graipher said classes should start with a capital letter. `p1(?=p2)` means that p1 matches if p2 would match next, but it doesn't \"use up\" the p2. `deque` was left over from a previous version of the code."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T18:08:57.007",
"Id": "229923",
"ParentId": "229916",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "229923",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T15:50:41.627",
"Id": "229916",
"Score": "3",
"Tags": [
"python",
"regex"
],
"Title": "Word frequency analysis: Python"
} | 229916 |
<p>I am having a hard time speeding up a function that I use to compute angular distances between data points in a matrix. More precisely, I want to compute <span class="math-container">$$\sum_{r=1}^n|\pi - \arccos\left(\frac{(X_{i}-X_{j})'(X_j-X_r)}{|X_{i}-X_{j}|\ |X_j-X_r|}\right) \times \frac{\pi^{(0.5k - 1)}}{\Gamma(0.5k + 1)}| $$</span>… where <span class="math-container">\$X_i\$</span> is a a <span class="math-container">\$k\$</span>-dimensional vector.</p>
<p>Speeding this up is somehow crucial for me when sample size is around 10,000.</p>
<pre><code>omega_w <- function(X){
X <- as.matrix(X)
n <- dim(X)[1]
kdim <- dim(X)[2]
omega <- matrix(0, nrow = n, ncol = n) # n x n
for (j in 1:n){
for (l in 1:j){
for (r in 1:n){
x.jr <- ((X[j,])-(X[r,]))
x.lr <- ((X[l,])-(X[r,]))
if (l==r && j==r){
omega[j,l] <- omega[j,l] + 2*pi }
else if ((l==r || j==r) && j!=l){
omega[j,l] <- omega[j,l] + pi }
else if (l==j && j!=r){
omega[j,l] <- omega[j,l] + pi }
else {
omega[j,l] <- omega[j,l] + abs(pi - acos(cor(x.jr,x.lr)))
}
}
}
}
omega <- (omega + t(as.matrix(Matrix::tril(omega,-1)))) * pi^(kdim/2-1)/gamma(kdim/2 +1)
return(omega)
}
x <- as.matrix(rnorm(10000*20),n,20)
w <- omega_w(x)
</code></pre>
<p>I would really appreciate any guidance on to make this function "better" and more computationally efficient. I am not really that worried about large matrices, as I will use this with sample sizes approximately the same as the one in the example.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T17:22:04.013",
"Id": "447512",
"Score": "0",
"body": "Just did. Hope now is a bit clearer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T23:13:41.263",
"Id": "447883",
"Score": "0",
"body": "I don't think your code is matching the provided formula. For instance, where the formula says `X_i - X_j`, your code seems to use `X_i - X_r`. Also your formula is of the form `sum(abs(pi - a * b))` but your code does `sum(abs(pi-a)) * b`. If you have an outside reference (wikipedia, online article, etc.) for your formula, maybe you could include it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T00:25:27.503",
"Id": "447892",
"Score": "0",
"body": "Note that you meant to use `matrix`, not `as.matrix` when creating the fake data to test your code."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T15:57:03.163",
"Id": "229918",
"Score": "2",
"Tags": [
"performance",
"matrix",
"r",
"computational-geometry"
],
"Title": "Compute angular distances between data points in a matrix"
} | 229918 |
<p>A Binary Tree Sort is an algorithm that builds a binary search tree from the elements to be sorted, and then traverses the tree (in-order) so that the elements come out in sorted order. </p>
<p>Average Case Time Complexity : O(N log N) adding one element to a Binary Search Tree on average takes O(log N) time (height of a tree). Therefore, adding n elements will take O(N log N) time. </p>
<p>Worst Case Time Complexity : O(N^2). The worst case can be improved by using a self-balancing binary search tree, which will take O(N log N) time to sort the array in worst case.</p>
<hr>
<p>Just for practicing, I've implemented the Binary Tree Sort algorithm, and if you'd like to review the code and provide any change/improvement recommendations, please do so, and I appreciate that.</p>
<hr>
<h3>Code</h3>
<pre><code>"""
This module creates a Binary Sort Tree ascendingly using In Order Tree Traverse;
Stable Sort;
Worst Case Time Complexity (For if the tree would be a chain Tree): O(N^2)
Average Case Time Complexity: O(N^Log N)
Memory Complexity: Not in place O(N)
"""
import random
from typing import List, TypeVar
T = TypeVar('T')
# Not sure how to design and handle the exceptions here yet
class ExceptionHandling(Exception):
pass
class Node(object):
def __init__(self, node_value: int) -> None:
"""
Initializes a node with three attributes;
`node_value` (Node Value): Must be an integer/float;
`right_child` (Right Child): Initializes to `None`; Its value must be larger than the Root Node;
`left_child` (Left Child): Initializes to `None`; Its value must be smaller than the Root Node;
"""
self.node_value = node_value
self.right_child = None
self.left_child = None
class BinarySearchTree(object):
def __init__(self) -> None:
"""
Initializes the Root Node of the Binary Tree to None;
"""
self.root = None
def is_empty(self) -> bool:
"""
Returns True if the tree doesn't have a node;
"""
return self.root == None
def insert(self, new_node: int) -> None:
"""
Inserts an integer-value Node in the Tree;
"""
self.root = self._insert(self.root, new_node)
def _insert(self, parent: int, new_node: int) -> int:
"""
Inserts an integer value in the left or right Node;
Returns the parent Node;
"""
# If tree is empty
if parent is None:
parent = Node(new_node)
# If the new Node value is smaller than its parent Node value
elif new_node < parent.node_value:
parent.left_child = self._insert(parent.left_child, new_node)
# If the new Node value is bigger than its parent Node value
else:
parent.right_child = self._insert(parent.right_child, new_node)
return parent
def inorder(self) -> None:
"""
Calls the _inorder traversing method;
"""
self._inorder(self.root)
def _inorder(self, parent: int) -> None:
"""
Traverses the tree inorder (Left Node, Root Node, Right Node)
"""
if parent is None:
return
self._inorder(parent.left_child)
print(f'{parent.node_value}')
self._inorder(parent.right_child)
if __name__ == '__main__':
tree = BinarySearchTree()
for i in range(random.randint(20, 30)):
tree.insert(random.uniform(-10, 10))
tree.inorder()
</code></pre>
<h3>Sources</h3>
<ul>
<li><p><a href="https://en.wikipedia.org/wiki/Tree_sort" rel="nofollow noreferrer">Tree Sort - Wiki</a></p></li>
<li><p><a href="https://www.geeksforgeeks.org/tree-sort/" rel="nofollow noreferrer">Tree Sort - Geeks for Geeks</a></p></li>
</ul>
| [] | [
{
"body": "<h2>Exceptions</h2>\n\n<pre><code># Not sure how to design and handle the exceptions here yet\n</code></pre>\n\n<p>Your syntax is more or less fine, though you'll obviously want to rename the exception class. The purpose of an exception like this is to allow you to <code>raise</code> something specific to your application that consumer code might be interested in catching. One place you could potentially raise:</p>\n\n<pre><code> if parent is None:\n return\n</code></pre>\n\n<p>It's unlikely that silent-fail is the right thing to do, here.</p>\n\n<h2><code>is None</code></h2>\n\n<p>This:</p>\n\n<pre><code>return self.root == None\n</code></pre>\n\n<p>should probably be</p>\n\n<pre><code>return self.root is None\n</code></pre>\n\n<h2>Member types</h2>\n\n<p>These assignments:</p>\n\n<pre><code> self.right_child = None\n self.left_child = None\n</code></pre>\n\n<p>should receive type hints, since it's not obvious what they'll eventually receive. My guess is</p>\n\n<pre><code>self.right_child: Node = None\nself.left_child: Node = None\n</code></pre>\n\n<h2>English is not C;</h2>\n\n<p>You have a funny habit of terminating your comments with semicolons. That isn't necessary.</p>\n\n<h2>Node value types</h2>\n\n<blockquote>\n <p><code>node_value</code> (Node Value): Must be an integer/float</p>\n</blockquote>\n\n<p>So which is it - an integer, or a float? Given that your usage of this value only requires that it be comparable, I'd suggest <code>float</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T21:45:50.577",
"Id": "229931",
"ParentId": "229921",
"Score": "2"
}
},
{
"body": "<h2>Type Hints</h2>\n\n<p>From these lines:</p>\n\n<pre><code>from typing import List, TypeVar\n\nT = TypeVar('T')\n</code></pre>\n\n<p>it looks like you intend to add type-hints for a type <code>T</code> to you code. But nowhere are you using <code>T</code> as a type hint. You probably wanted to actually use <code>T</code>, such as like:</p>\n\n<pre><code>def __init__(self, node_value: T) -> None\n</code></pre>\n\n<p>Either that, or delete the <code>typing</code> code.</p>\n\n<h2>Exception Handling</h2>\n\n<p>You have:</p>\n\n<pre><code>class ExceptionHandling(Exception):\n pass\n</code></pre>\n\n<p>but nowhere are you actually executing <code>raise ExceptionHandling(\"Your error message\")</code>. Moreover, nowhere do I actually see a need to raise an exception; you aren't doing anything that could fail. Until you have a need for raising your own custom exception, you could remove this code.</p>\n\n<h2>class Node(object):</h2>\n\n<p>Since you are using f-strings, it is clear, you are using Python 3. In Python 3+, you don't need to inherit from <code>object</code>; it is automatically implied.</p>\n\n<h2>Names & Types</h2>\n\n<pre><code>def insert(self, new_node: int) -> None:\n</code></pre>\n\n<p>Is <code>new_node</code> a <code>Node</code> or an <code>int</code>? The variable name suggests it would be a <code>Node</code>, but it is typed as an <code>int</code>. When you use it, you are passing in an int. Maybe <code>new_value</code> would be clearer?</p>\n\n<pre><code>def _insert(self, parent: int, new_node: int) -> int:\n</code></pre>\n\n<p>Now we're definitely confused. Is <code>parent</code> an <code>int</code>? Does this function return an <code>int</code>? Both seem to be a definite \"no\". Those types should be <code>Node</code>. And again, <code>new_node</code> should be renamed, because it isn't a <code>Node</code>.</p>\n\n<h2>Method naming (and docstrings)</h2>\n\n<p>What does <code>inorder</code> do? I'd expect it to return the contents of the tree \"in order\". But the type-hint says it returns <code>None</code>, so that is not correct. Let's consult help:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>>>> help(BinarySearchTree.inorder)\nHelp on function inorder in module __main__:\n\ninorder(self) -> None\n Calls the _inorder traversing method;\n\n>>>\n</code></pre>\n\n<p>Well, that's entirely unhelpful. It calls a private <code>_inorder</code> traversing method. Ok, but what does it do???</p>\n\n<p>Name functions based on what they do. Your <code>inorder</code> function <strong>prints</strong> the tree in order, so name it with <code>print</code> in its name, such as <code>print_inorder</code>.</p>\n\n<p>Also, write docstrings to tell a caller what the function does. Use a high-level description. Include any requirements, preconditions and/or postconditions. Do not include implementation details. The caller cares only about what it does and how to use the function properly; they only care the function works, not how it works.</p>\n\n<pre><code>def print_inorder(self) -> None:\n \"\"\"\n Print the tree in ascending order, one element per line, to sys.stdout\n \"\"\"\n self._inorder(self.root)\n</code></pre>\n\n<p>Finally, your class is named <code>BinarySearchTree</code>, yet it provides no methods for searching. Hmm.</p>\n\n<h2>Pointless f-string</h2>\n\n<p>The statement:</p>\n\n<pre><code>print(f'{parent.node_value}')\n</code></pre>\n\n<p>is a complicated way of writing:</p>\n\n<pre><code>print(parent.node_value)\n</code></pre>\n\n<h2>Algorithm</h2>\n\n<p>Your <code>insert</code> / <code>_insert</code> functions are overly complicated. There is no need to use recursion. Moreover, returning the <code>parent</code> from <code>_insert</code> is mostly useless, because the caller is passing <code>parent</code> to the function; it only matters when the caller passes <code>None</code> in as the parent.</p>\n\n<p>A non-recursive approach:</p>\n\n<pre><code>def insert(self, new_value: int) -> None:\n\n new_node = Node(new_value)\n\n if self.root:\n parent = self.root\n while True:\n if new_value < parent.node_value:\n if parent.left_child:\n parent = parent.left_child\n else:\n parent.left_child = new_node\n break\n else:\n if parent.right_child:\n parent = parent.right_child\n else:\n parent.right_child = new_node\n break\n else:\n self.root = new_node\n</code></pre>\n\n<h2>Possible Improvements</h2>\n\n<h3>Encapsulation</h3>\n\n<p><code>Node</code> is an internal detail of the <code>BinarySearchTree</code>. You could make it an internal class:</p>\n\n<pre><code>class BinarySearchTree:\n\n class Node:\n def __init__(self, node_value:T ) -> None:\n self.node_value = node_value\n self.right_child = None\n self.left_child = None\n\n def __init__(self) -> None\n self.root = None\n\n ...\n\n\n parent = BinarySearchTree.Node(new_node)\n\n ...\n</code></pre>\n\n<h3>Iterator</h3>\n\n<p>Instead of the method <code>inorder</code> printing the contents of the tree, perhaps it could return an iterator which would traverse the tree returning elements one at a time. The caller could then print them, or perform whatever operation they desired.</p>\n\n<pre><code>for value in tree.inorder():\n print(value)\n</code></pre>\n\n<p>Instead of naming this iterator creating function <code>inorder</code>, it could be named <code>__iter__</code>, in which case, the caller would just need to write:</p>\n\n<pre><code>for value in tree:\n print(value)\n</code></pre>\n\n<p>You'd create this iterator in one of two ways. The \"hard way\", returning a new iterator object, with a <code>__next__</code> method. Or the \"easy way\" using a generator function, using <code>yield</code> and <code>yield from</code> statements.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T22:46:57.273",
"Id": "229934",
"ParentId": "229921",
"Score": "5"
}
},
{
"body": "<p>I don't know about this typevar but it seems over complicated. Why are you specifying the type and using two classes when you need only one. Here's my solution.</p>\n<pre><code>class Node:\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n def add(self, val):\n if val < self.val:\n if self.left == None:\n self.left = Node(val)\n else:\n self.left.add(val)\n else:\n if self.right == None:\n self.right = Node(val)\n else:\n self.right.add(val)\n def sort(self):\n a = []\n b = [self.val]\n c = []\n if self.left:\n a = self.left.sort()\n if self.right:\n c = self.right.sort()\n return a+b+c\n def str(self):\n a, b = "", ""\n if self.left:\n a = self.left.str()\n if self.right:\n b = self.right.str()\n return "({}, {}, {})".format(self.val, a, b)\ndef tree_sort(s):\n node = Node(s[0])\n for val in s[1:]:\n node.add(val)\n return node.sort()\n\nl=[123, 48, 23, 100, 56,2, 10, 273, 108, 398, 100, 2651, 12]\nprint(tree_sort(l))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T09:54:59.430",
"Id": "481023",
"Score": "2",
"body": "Welcome to Code Review. Your answer does focus on an alternative implementation, while answers should preferably focus on a review of the code/approach provided. There are many binary-sort questions on Code Review, what makes your answer specific to this question?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T09:26:14.907",
"Id": "244988",
"ParentId": "229921",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "229934",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T16:43:23.727",
"Id": "229921",
"Score": "4",
"Tags": [
"python",
"beginner",
"algorithm",
"object-oriented",
"sorting"
],
"Title": "Binary Tree Sort Algorithm (Python)"
} | 229921 |
<p>I'm trying to flatten a binary tree into a linked list.</p>
<p>I have a working, correct solution:</p>
<pre><code># Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def insert(root, node):
if root.right is None:
root.right = node
return None
else:
insert(root.right, node)
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
if root is None:
return None
if root.left is None and root.right is None:
return root
left = self.flatten(root.left)
right = self.flatten(root.right)
root.left = None
if left:
root.right = left
insert(root.right, right)
else:
root.right = right
return root
</code></pre>
<p>I'm not certain, but I think the time complexity is <span class="math-container">\$O(n^2)\$</span>. How do I make it run faster? Specifically, how do I modify it so that it runs in optimal time complexity (linear time)?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T16:57:18.220",
"Id": "447507",
"Score": "1",
"body": "Not enough for a review, but note you shouldn't be returning anything (\"Do not return anything, modify root in-place instead.\", `-> None:`), yet you are (`return root`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T18:26:04.433",
"Id": "447517",
"Score": "4",
"body": "I wouldn't go so far as to say that it isn't working, but it's certainly not complete. Please show the source code for `TreeNode`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T03:11:35.537",
"Id": "447559",
"Score": "0",
"body": "Why is flatten in its own class called Solution? Is this a requirement for some online test? I'd think it makes more sense as a method on TreeNode if not a standalone function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T06:27:13.277",
"Id": "447573",
"Score": "0",
"body": "I've once tried it to, perhaps the answer could give you some insights: https://codereview.stackexchange.com/questions/226781/convert-a-binary-tree-to-doubly-linked-list"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T13:15:55.093",
"Id": "447616",
"Score": "0",
"body": "@bullseye The code works fine (especially now that the class was uncommented). Also, I believe you know you can't VTC if you don't have 3k rep"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T17:07:41.303",
"Id": "447643",
"Score": "0",
"body": "@Turksarama That's a dumb requirement for Leetcode challenges (https://leetcode.com/problems/flatten-binary-tree-to-linked-list/)."
}
] | [
{
"body": "<h2>Encapsulating the wrong things</h2>\n\n<p><code>insert</code> and <code>flatten</code> should be methods on <code>TreeNode</code>. <code>Solution</code> doesn't particularly need to exist as a class. Those two methods can assume that <code>self</code> is the root.</p>\n\n<h2>Return types</h2>\n\n<p>As @Carcigenicate suggested: what do you return from <code>flatten</code>? Probably the return type hint should be changed to <code>TreeNode</code>, and you should modify your comment to describe the circumstances under which <code>None</code> will or won't be returned.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T17:09:14.007",
"Id": "447644",
"Score": "2",
"body": "I'll just note, this is a Leetcode challenge, which necessitates the useless `Solution` class and the method signature requirements and the included docstring. I agree with your suggestions, but I think Leetcode set them off on the wrong foot here. https://leetcode.com/problems/flatten-binary-tree-to-linked-list/"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T02:56:01.910",
"Id": "229946",
"ParentId": "229922",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T16:44:06.123",
"Id": "229922",
"Score": "1",
"Tags": [
"python",
"algorithm",
"linked-list",
"time-limit-exceeded",
"tree"
],
"Title": "Flatten binary tree to linked list"
} | 229922 |
<p>I'm working on a project where I needed to extract the indices for the headers of a CSV file to initialise objects. I thought that I should work on my documentation process and learn how to document code, seeing as I'm always reading about people not documenting code.</p>
<pre><code>/**
* Returns the indices of searched for headers, e.g. if the file looks like this: (Name Email
* Phone Age) and we call the method: findIndices("Name", "Age", "Email", "Phone"), if returns
* [0,3,1,2].
*
* Ignores case of letters, i.e. Age and AGE "is" the same.
*
* @param input Strings to search for in the header
* @return int[] with indices for the columns
*/
public int[] findIndices(String... input) throws IllegalArgumentException {
int[] indices = new int[input.length];
if (input.length > this.headers.length) {
throw new IllegalArgumentException("Amount of searched for headers, " + input.length
+ ", exceeded the actual amount of headers: " + this.headers.length);
}
boolean found = true; // Assume we will find all headers.
int k = 0; // Counter variable.
for (int i = 0; i < this.headers.length; i++) {
for (String s : input) {
if (s.equalsIgnoreCase(this.headers[i])) {
indices[k++] = i;
found = true;
} else {
found = false;
}
}
}
if (!found) {
throw new IllegalArgumentException(
"One or more of input arguments could not be found in the headers.");
}
return indices;
}
</code></pre>
<p>My own thoughts:</p>
<ol>
<li>The found flag seems poorly handled.</li>
<li>This is part of a custom CSV-reader class, with a headers private field. This seems a bit weird to me, this could maybe be static and take a String[] as input as well.</li>
<li>Should this actually throw an exception or should it just return a "bad" index? But I'm using an array to represent it. Null, maybe?</li>
</ol>
<p>Edit: Found a bug which did not show up in my unit tests due to a misunderstanding of the JUnit api, found -> !found.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T20:16:28.983",
"Id": "447523",
"Score": "0",
"body": "Could you post your tests as well? It might be beneficial to code review the tests as well. I don't think you're testing properly"
}
] | [
{
"body": "<p>Since you mentioned unit tests, here are 2 unit tests that proves your code does not work (Based on <code>name, age, email, phone</code> header):</p>\n\n<pre><code>@Test\npublic void testFindIndicesThrowsException()\n{\n ClassName x = new ClassName();\n\n try\n {\n int[] result = x.findIndices(\"Name\", \"age\", \"FieldThatDoesNotExist\", \"Phone\");\n fail(\"expected exception was not thrown!\");\n }\n catch (IllegalArgumentException exception)\n {\n assertEquals(\"One or more of input arguments could not be found in the headers.\", exception.getMessage());\n }\n}\n\n@Test\npublic void testFindIndices()\n{\n ClassName x = new ClassName();\n\n int[] result = x.findIndices(\"Email\", \"Phone\", \"Name\", \"age\");\n assertEquals(4, result.length);\n assertEquals(2, result[0]);\n assertEquals(3, result[1]);\n assertEquals(0, result[2]);\n assertEquals(1, result[3]);\n}\n</code></pre>\n\n<p>Explanation: You are setting a boolean <strong>in a loop.</strong> This means it could be set to false on one iteration, then set to true on the next.</p>\n\n<p>Instead, you can set the index to the one found, and if it's not found, throw an error:</p>\n\n<pre><code>int k = 0;\n\nfor (String s : input) \n{\n indices[k] = -1;\n\n for (int i = 0; i < this.headers.length; i++)\n {\n if (s.equalsIgnoreCase(this.headers[i])) \n {\n indices[k] = i;\n }\n }\n\n // If we never found the item\n if (indices[k] == -1)\n {\n throw new IllegalArgumentException(\n \"One or more of input arguments could not be found in the headers.\");\n }\n\n k++;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T05:15:35.060",
"Id": "447564",
"Score": "0",
"body": "Thank you. My test had the failing header as last argument, which obviously then causes faulty behaviour. I have changed my code to this solution, but I will be going with the HashMap solution above. Thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T20:02:16.860",
"Id": "229926",
"ParentId": "229924",
"Score": "1"
}
},
{
"body": "<p>Too me the biggest thing to look at in your code is the complexity. Right now it's O(n²). This is very inefficient and can be greatly improved upon, by taking a step back and changing the <code>headers</code> to a <code>HashMap<String, Integer></code>. Now, since lookups for <code>HashMap</code> is O(1) you only need to count the loop through the input array, which will give a complexity of O(n). The code could look something like this:</p>\n\n<pre><code>HashMap<String, Integer> headers = new HashMap<>();\n\npublic int[] findIndices(String... input) throws IllegalArgumentException {\n int headerSize = headers.size();\n if (input.length > headerSize) {\n throw new IllegalArgumentException(\"Amount of searched for headers, \" + input.length\n + \", exceeded the actual amount of headers: \" + headerSize);\n }\n int[] indices = new int[input.length];\n int index = 0;\n for (String s : input) {\n if (headers.containsKey(s)) {\n indices[index++] = headers.get(s);\n } else {\n throw new IllegalArgumentException(\"One or more of input arguments could not be found in the headers.\");\n }\n }\n return indices;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T05:10:32.870",
"Id": "447563",
"Score": "0",
"body": "This is great - thank you. Of course, the HashMap is better suited for this particular problem. Is containsKey(s) O(1)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T06:44:52.667",
"Id": "447574",
"Score": "0",
"body": "Yes, all the lookup functions are O(1)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T22:51:16.803",
"Id": "447737",
"Score": "0",
"body": "Careful, this changes it to be case sensitive -- though it's easily fixed."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T04:02:42.177",
"Id": "229948",
"ParentId": "229924",
"Score": "1"
}
},
{
"body": "<pre class=\"lang-java prettyprint-override\"><code> if (input.length > this.headers.length) {\n throw new IllegalArgumentException(\"Amount of searched for headers, \" + input.length\n + \", exceeded the actual amount of headers: \" + this.headers.length);\n }\n</code></pre>\n\n<p>Why is this needed? At the moment I get <code>[0,1,0]</code> for <code>findIndices(\"name\", \"age\", \"name\")</code>, but <code>IllegalArgumentException</code> when I call <code>findIndices(\"name\", \"age\", \"name\", \"email\", \"phone\")</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T23:07:17.137",
"Id": "230004",
"ParentId": "229924",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "229926",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T18:28:53.610",
"Id": "229924",
"Score": "4",
"Tags": [
"java",
"csv"
],
"Title": "Finding indices of CSV headers in Java"
} | 229924 |
<p>I'm making an app that creates pdfs of images layed out in a grid. I know the size of each grid element and how many fit on a page, it works out to a 5x6 grid.
The syntax is not the real focus, but the logic for how I determine when to start a new row or page.</p>
<pre><code>const pageconstants = {
grid:{
x: 5,
y: 4,
}
}
const griditems = []//an array containing 35 elements
</code></pre>
<pre><code>const doc = new PDFDocument(
{
layout : 'portrait',
width: 612,
height: 792,
autoFirstPage: false
}
);
let gridx = 0;
let gridy = 0;
let pagenum = 1;
createNewPage(doc);//create new page and elements like header and footer
griditems.forEach((item) => {
var x = 100 * gridx;//The actual equation has more parts, I'm simplifying here
var y = 100 * gridy;
addGridItem(doc, { x: x, y: y }, item)//places the image on the grid
if( gridx == pageconstants.grid.x ){
gridx = 0;
if( gridy == pageconstants.grid.y ){
subjecty = 0;
pagenum++;
createNewPage(doc)
}
else{
subjecty++;
}
}
else{
subjectx++;
}
})
</code></pre>
<p>So basically, it checks if the current gridx has reached the max of 5 (6 because it starts at zero), and if so, resets gridx, and increments gridy to start the next row.</p>
<p>If gridy reaches it's maximum, gridx and gridy are reset and a new page is created again, so it can go again until there are no items left.
This all works, but it feels really word, I really hate having nested if's like this, and incrementing all these numbers. Is there a more elegant way to achieve this?</p>
| [] | [
{
"body": "<p>So essentially, you want to layout an array of items in a 2D grid. This problem can be solved by using division and remainder operations to calculate the coordinates.</p>\n\n<ul>\n<li><code>x</code> is the remainder of dividing the index by <code>maxX</code></li>\n<li><code>y</code> is the remainder of dividing by <code>maxY</code> the result of dividing the index by <code>maxX</code>.</li>\n<li>A new page made is when both <code>x</code> and <code>y</code> are <code>0</code></li>\n</ul>\n\n<p>Here's a rough sketch of how it looks:</p>\n\n<pre><code>let i = item index\nlet maxX = 5\nlet maxY = 6\nlet x = i % maxX \nlet y = (i / maxX) % maxY \nlet p = !(i % (maxX * maxY))\n\ni: 0 1 2 3 4 5 6 7 8 9 ... 29 30 31 32 33 34 35\nx: 0 1 2 3 4 0 1 2 3 4 ... 4 0 1 2 3 4 0\ny: 0 0 0 0 0 1 1 1 1 1 ... 5 0 0 0 0 0 1\np: 1 0 0 0 0 0 0 0 0 0 ... 0 1 0 0 0 0 0\n</code></pre>\n\n<p>In code, this would be:</p>\n\n<pre><code>const griditems = []\n\nconst pageconstants = {\n grid:{\n x: 5, // 5 across\n y: 6, // 6 down\n }\n}\n\nconst doc = new PDFDocument({\n layout : 'portrait',\n width: 612,\n height: 792,\n autoFirstPage: false\n})\n\nconst getX = i => i % pageconstants.grid.x\nconst getY = i => Math.floor((i / pageconstants.grid.x) % pageconstants.grid.y)\nconst isNewPage = i => !(i % (pageconstants.grid.x * pageconstants.grid.y))\n\nconst positions = griditems.forEach((item, index) => {\n const x = 100 * getX(index)\n const y = 100 * getY(index)\n\n if (isNewPage(index)) createNewPage(doc)\n\n addGridItem(doc, { x, y }, item)\n})\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T17:49:55.243",
"Id": "447664",
"Score": "0",
"body": "Wow thats pretty slick. thanks for the explanation."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T00:02:43.530",
"Id": "229937",
"ParentId": "229925",
"Score": "3"
}
},
{
"body": "<p>You state <em>"The syntax is not the real focus..."</em> but I can not ignore style and syntax because they are the most important parts of any good code.</p>\n<h2>Style</h2>\n<ul>\n<li><p>More use of <code>const</code>. For example the line <code>var x = 100 * gridx;</code> should be <code>const x = 100 * gridx</code>;</p>\n</li>\n<li><p>Use property shorthand when creating objects. For example defining the object literal <code>{ x: x, y: y }</code> can be shorthanded with <code>{x, y}</code></p>\n</li>\n<li><p>Use the JavaScript layout conventions.</p>\n<ul>\n<li>Spaces <code>if(</code> as <code>if (</code>, also <code>if () {</code>, <code>} else {</code></li>\n<li>No space <code>if ( foo</code> as <code>if (foo</code> and at start and end of object <code>{x: foo, y: bar}</code></li>\n<li><code>else</code> on same line as closing <code>}</code> eg <code>} else {</code></li>\n</ul>\n</li>\n<li><p>Use camelCase consistently. e.g. <code>pageconstants</code> to <code>pageConstants</code> and <code>gridItems</code>, <code>gridX</code>, <code>pageNum</code>, <code>subjectY</code> and so on. If you mix them you end up always having to look up the variable as humans do not include the capitalization in the mnemonic,</p>\n</li>\n<li><p>Be consistent in the style you use. E.g. you sometimes don't use semicolons to end a line and other times you do. Either do or do not. Spend some time investigating semicolon use to know the pros and cons.</p>\n</li>\n<li><p>Nested object and array opening lines are more readable if opened on the same line. e.g. <code>foo(\\n\\t{\\n\\t\\tbar: 0,\\n\\t}\\n);\\n</code> as <code>foo({\\n\\tbar: 0,\\n});\\n</code> (CodeReview clarity is escape chars <code>\\n</code> newline <code>\\t</code> tag)</p>\n</li>\n</ul>\n<h2>Code and logic</h2>\n<p>As pointed out in the answer Joseph you can use remainder to reduce the logic.</p>\n<p>On top of that the need to floor the values can use a bitwise operation to reduce the verbosity of <code>const foo = Math.floor(bar / width)</code> to <code>const foo = bar / width | 0;</code> converts the result into a signed 32 bit integer. Note that you should only use this to floor values if <code>foo</code> is a positive and less than <code>2**31 - 1</code>. Example <code>2**31 - 1 | 0 === 2147483647</code> while <code>2**31 | 0 1== 2147483648</code>, it is in fact <code>-2147483648</code></p>\n<p>Rather than define the rows and columns of page items. It may be preferable to define the width and height of page items and then calculate the rows and columns from them. See example.</p>\n<p>You have the property <code>autoFirstPage</code> as <code>false</code> in the doc. Yet the code does not consider this when it creates pages. If you change this value then you will end up with an empty page. Add some logic to determine if the first page needs to be created.</p>\n<p>The same is true for the <code>layout</code> of the PDF (I am not sure if the doc swaps width and height if not <code>portrait</code> and guessing that they are not swapped in the example.</p>\n<p>You are generating x and y coordinates but it is unclear if they are relative to the page, or relative to some centering construct and thus relative to a top left coordinate. In the example I have added a top left to the calculations that will auto center the grid coordinates. In effect the coordinates are relative to the page top left corner.</p>\n<p>Your code is obviously not the code you use, so I don't know if you have it as part of a function, or it is actually flat code in the global names space. If it is flat global code it should be wrapped in a function to encapsulate it, or use modules. See example of IIF to encapsulate the scope.</p>\n<h2>Example</h2>\n<p>The example is somewhat longer than your original, however is is more flexible and less prone to layout error if the document setup is changed.</p>\n<p>Note...</p>\n<ol>\n<li><p>that I freeze the objects created for layout. I have come to consider this as standard practice as it forces better object encapsulation code, and prevents object state mutation. It is a bit wordy but if you use it you can add an alias to the global space.</p>\n</li>\n<li><p>that the function <code>layout.grid.indexPos</code> takes a second optional argument <code>pos</code> that defaults to an empty <code>object</code>. This is a general optimization and lets you reuse objects rather than create and deference an object every call. This technique (called pre allocation) can significantly reduce the memory management overhead. IE if you had a 1000 items, that is 999 less allocations and GC cleanups needed to process them all.</p>\n</li>\n<li><p>I have made some name changes <code>doc</code> to <code>PDF</code> and <code>pageconstants</code> to <code>layout</code> and <code>x</code>, <code>y</code> for grid size to <code>rows</code> and <code>cols</code> (cols is columns using the common abbreviation)</p>\n</li>\n<li><p>the line <code>addGridItem(doc, {...pos.coord}, items[i++]);</code> may be written without the need to copy the object <code>pos.coord</code>. If the function <code>addGridItems</code> makes a copy of the object or transfers the properties then use <code>addGridItem(doc, pos.coord, items[i++]);</code></p>\n</li>\n</ol>\n<p>The code</p>\n<pre><code>;(() => { // to encapsulate the scope away from the global scope.\n "use strict";\n \n const PDF = new PDFDocument( {\n layout : 'portrait',\n width: 612,\n height: 792,\n autoFirstPage: false,\n });\n\n const gridItems = [];\n const AUTO_CENTER_GRID_ITEMS = true;\n const ITEM_WIDTH = 120;\n const ITEM_HEIGHT = 200;\n const PAGE_WIDTH = PDF.layout === 'portrait' ? PDF.width : PDF.height;\n const PAGE_HEIGHT = PDF.layout === 'portrait' ? PDF.height : PDF.width;\n\n const layout = Object.freeze({\n grid: Object.freeze({\n cols: PAGE_WIDTH / ITEM_WIDTH | 0,\n rows: PAGE_HEIGHT / ITEM_HEIGHT | 0,\n left: (PAGE_WIDTH - (PAGE_WIDTH / ITEM_WIDTH | 0) * ITEM_WIDTH) / 2,\n top: (PAGE_HEIGHT - (PAGE_HEIGHT / ITEM_HEIGHT | 0) * ITEM_HEIGHT) / 2, \n indexPos(idx, pos = {}) {\n const grid = layout.grid;\n const c = pos.coord = pos.coord ? pos.coord : {};\n const col = idx % grid.cols;\n const row = idx / grid.cols | 0;\n pos.page = row / grid.rows | 0; \n c.x = col * ITEM_WIDTH;\n c.y = (row % grid.rows) * ITEM_HEIGHT;\n pos.newPage = !c.x && !c.y;\n if (AUTO_CENTER_GRID_ITEMS) {\n c.x += grid.left;\n c.y += grid.top;\n }\n return pos;\n },\n }),\n });\n\n function addGridedItems(doc, items) {\n const autoP = doc.autoFirstPage;\n var i = 0, pos;\n while (i < items.length) {\n pos = layout.grid.indexPos(i, pos);\n if (pos.newPage && (!autoP || (autoP && pos.page))) { createNewPage(doc) }\n addGridItem(doc, {...pos.coord}, items[i++]); \n }\n }\n \n addGridItems(PDF, gridItems);\n})();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T13:08:21.427",
"Id": "229973",
"ParentId": "229925",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "229937",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T19:59:20.270",
"Id": "229925",
"Score": "5",
"Tags": [
"javascript"
],
"Title": "Creating pages containing grids"
} | 229925 |
<p>I'm making a simple program that generates a random password of some length with or without special characters, just for the sake of learning the C language. Finally I've got this working very well based on the outputs below:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
char *generate_random_password(int password_lenght, int has_special_characters)
{
const char *letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
const char *digits = "0123456789";
const char *special_characters = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
char *random_password = malloc(sizeof(char) * (password_lenght+1));
srandom(time(NULL));
if(has_special_characters)
{
char to_be_used[95] = "\0";
strcat(to_be_used, letters);
strcat(to_be_used, digits);
strcat(to_be_used, special_characters);
for(int i = 0; i < password_lenght; i++)
{
const int random_index = random() % strlen(to_be_used);
const char random_character = to_be_used[random_index];
random_password[i] = random_character;
}
}
else
{
char to_be_used[63] = "\0";
strcat(to_be_used, letters);
strcat(to_be_used, digits);
for(int i = 0; i < password_lenght; i++)
{
const int random_index = random() % strlen(to_be_used);
const char random_character = to_be_used[random_index];
random_password[i] = random_character;
}
}
return random_password;
free(random_password);
}
int main(void)
{
printf("%s\n", generate_random_password(17, 1));
printf("%s\n", generate_random_password(17, 0));
return 0;
}
</code></pre>
<p>The output is:</p>
<pre class="lang-none prettyprint-override"><code>|ZzN>^5}8:i-P8197
vPrbfzBEGzmSdaPPP
</code></pre>
<p>It's working!</p>
<p>But I'm completely in doubt about these strings, pointers, char arrays, etc. I have no idea if this is written "the right way" or how it could be better. I'm concerned if I allocated the right amount for each string/char array, and if it can break or crash in some future.</p>
<p>PS: I'm new at C programming, that's why I don't know much about pointers and memory management yet.</p>
<p>If can anyone give me some feedback about it I will be very grateful!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T20:26:29.060",
"Id": "447528",
"Score": "2",
"body": "Welcome to CodeReview, maverick. Your code is currently not platform independent due to the use of `srandom` and `random`. If this is intended, please [edit] your post to include your target and host programming platform, as reviewers can add platform dependent notes. You might also add relevant tags. If you intended to create platform independent code, feel free to also [edit] your post to indicate this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T14:49:10.740",
"Id": "447799",
"Score": "0",
"body": "@Mast: this version does have some of the bug fixes pointed out in SO comments. (e.g. `to_be_used` is now initialized before the first `strcat` reads it. I would have used `strcpy` instead of zeroing that local on the stack and then using strcat. Or really I would have [done what @Baldrickk suggests](https://codereview.stackexchange.com/questions/229927/my-first-random-password-generator/230026#230026) and not done any copying). But anyway, this is a repost with some of the bugs fixed. I guess still a crosspost but I was wondering why nobody was mentioning the things from the SO comments)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T08:54:21.133",
"Id": "447917",
"Score": "1",
"body": "I know you're doing it only for excercise, but see [Why shouldn't we roll our own?](https://security.stackexchange.com/q/18197/32019) on security stack."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T11:25:17.477",
"Id": "447928",
"Score": "0",
"body": "@MooingDuck: I see a double-backslash \\\\ inside the double quoted string, so there's a backslash in the character literal. Or were you typing a space as special char?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T20:28:43.957",
"Id": "448000",
"Score": "0",
"body": "@PeterCordes: I swear I checked it three times before posting. But it doesn't seem to have been edited, so I must have lost my mind"
}
] | [
{
"body": "<h2>Typo</h2>\n\n<p><code>lenght</code> is spelled <code>length</code>.</p>\n\n<h2>Magic numbers</h2>\n\n<p>What does <code>95</code> signify? You'll want to put this in a named <code>#define</code> or a <code>const</code>.</p>\n\n<h2>Allocation failure</h2>\n\n<p>After calling <code>malloc</code>, always check that you've been given a non-null pointer. Allocation failure does happen in real life.</p>\n\n<h2>Indentation</h2>\n\n<p>You'll want to run this through an autoformatter, because your <code>if</code> block has wonky indentation and needs more columns to the right.</p>\n\n<h2>Inaccessible statement</h2>\n\n<pre><code>\n return random_password;\n\n free(random_password);\n</code></pre>\n\n<p>This <code>free</code> will never be called; delete it.</p>\n\n<h2><code>Random</code></h2>\n\n<p>The larger conceptual problem with this program is that it uses a very cryptographically weak pseudorandom number generator. This is a large and fairly complex topic, so you'll need to do some reading, but asking for random data from an entropy-controlled system source will already be better than using C <code>rand</code>.</p>\n\n<p>That aside: you aren't calling <code>rand</code>, you're calling <a href=\"https://linux.die.net/man/3/random\" rel=\"noreferrer\"><code>random</code></a>:</p>\n\n<blockquote>\n <p>The random() function uses a nonlinear additive feedback random number generator employing a default table of size 31 long integers to return successive pseudo-random numbers in the range from 0 to RAND_MAX. The period of this random number generator is very large, approximately 16 * ((2^31) - 1). </p>\n</blockquote>\n\n<p>It's probably not appropriate for cryptographic purposes. Have a read through this:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/822323/how-to-generate-a-random-int-in-c/39475626#39475626\">https://stackoverflow.com/questions/822323/how-to-generate-a-random-int-in-c/39475626#39475626</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T20:38:48.913",
"Id": "447531",
"Score": "7",
"body": "Thank you for the accept, but I suggest that you instead unaccept, upvote, and wait a while for other suggestions to come in for other users before you decide on an accepted answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T20:42:20.970",
"Id": "447532",
"Score": "0",
"body": "Thanks, I will write the Allocation Failure test for the malloc().\nAbout the free(), I read that after using malloc() to manual allocate some memory, I also need to manualy free the memory after using it. I put free() after the return because when I put it before, the string \"random_password\" was returned empty, I don't know why, maybe the free() before \"deleted\" the variable in some way.\nThe random() function is Linux only."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T20:44:20.270",
"Id": "447533",
"Score": "2",
"body": "`return` terminates the function, so nothing after it will be run. But you're correct to identify that, in general, allocated memory should be `free`d. In this case, it would be the responsibility of `main` to do that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T00:03:51.590",
"Id": "447546",
"Score": "1",
"body": "Agreed that the C library `rand` function is cryptographically weak, but this isn't cryptography. Even knowing the exact random algorithm used it wouldn't help you crack the password, particularly as you don't know any of it. Taking the remainder of the generated number mod the length of the character set would further obfusticate things. Knowing nothing more, you would still have to run through all RAND_MAX possibilities."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T01:39:56.473",
"Id": "447549",
"Score": "4",
"body": "@PeterJennings Key and password generation are *absolutely* activities requiring cryptographic strength. Given that password generation requires a tiny amount of data and only needs to occur once, the marginal added cost and complexity are more than worth it - even if it brings password attacks from \"infeasible\" to \"extremely infeasible\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T09:44:31.153",
"Id": "447587",
"Score": "5",
"body": "@PeterJennings The `srandom` function is initialized with the return from `time`. If we know the year the password is generated, there are fewer than 32 million possible passwords. You are also wrong about the \"knowing the exact random algorithm won't help you crack the password\" - there are many, *many* passwords that using `random` cannot generate even if the initial seed is adequate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T16:10:31.857",
"Id": "447639",
"Score": "1",
"body": "There's also the age old `random() % <some random number >` error."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T16:13:36.580",
"Id": "447640",
"Score": "1",
"body": "@Peter There've been successful real-world attacks on people using a weak crytographic RNG that was initialized based on the current time (even when they added the PID to it). What Martin is talking about is an absolutely practical attack."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T04:07:12.240",
"Id": "447750",
"Score": "2",
"body": "Using srandom(time(NULL)) is clearly the limiting bug; if used server-side, it opens the barn door for attackers to ask for a password reset and try just a handful of options before succeeding. Client or server-side, it means instantly pwning a new sign-up. A better source of entropy, even if you don't resort to OS/hardware sources, is clearly preferred, but using rand alone isn't a problem given the huge range of rand mapped to a tiny range of symbols, unless the lib implementation of rand is *horribly* broken. The point of a password generator is just reasonable entropy, not maximum."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T16:23:26.597",
"Id": "447820",
"Score": "0",
"body": "Given that the program is intended \"just for the sake of learning the C language\", I wouldn't focus too much on the entropy issue. But yeah, definitely choose a better RNG seed than `time(NULL)` if you intend to actually use the program to generate passwords."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T11:17:08.490",
"Id": "447927",
"Score": "1",
"body": "@SilverbackNet Huge range of rand? Rand_Max is only guaranteed to give 32767 unique values which is trivial to hack. The whole function specification is horribly broken, don't blame implementations that don't want to change a broken function just to marginally improve security."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T12:27:14.233",
"Id": "447930",
"Score": "0",
"body": "I guess I've used gcc too long, I didn't realize VC still defines it as 32767."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T20:33:42.960",
"Id": "229928",
"ParentId": "229927",
"Score": "29"
}
},
{
"body": "<p>Whilst your code works, there are a number of simplifications that you might try.</p>\n\n<ol>\n<li><p>As Reinderien says, get rid of \"magic\" numbers </p></li>\n<li><p>Having done that, declare a single string containing all 95 characters with the special ones last. This does away with all the <code>strcat</code> code.</p></li>\n<li><p>It's good practice to declare <code>has_special_characters</code> as type <code>bool</code>. You will have to include <code><stdbool.h></code>.</p></li>\n<li><p>You can then test it to set an integer variable, <code>modulus_divider</code>, to the correct <code>const</code> or <code>#define</code> value as in 1).</p></li>\n<li><p>You can then take the modulus of the random number with <code>modulus_divider</code> That way you don't need to keep using <code>strlen(to_be_used)</code> and you only need one generating loop.</p></li>\n<li><p>You don't really need all the intermediate variables in your <code>for</code> loop. Assuming you have set up <code>char_set</code> as the full 94 character array as in 2), your entire <code>for</code> loop could become:</p>\n\n<pre><code>for(int i = 0; i < password_lenght; i++)\n{\n random_password[i] = char_set[random() % modulus_divider];\n}\n</code></pre></li>\n</ol>\n\n<hr>\n\n<p>Later</p>\n\n<p>I'm not claiming this is perfect, but here is my version. I don't currently have a C compiler installed but this does compile and run with the online compiler at <a href=\"https://www.onlinegdb.com/\" rel=\"noreferrer\">onlinegdb.com</a></p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n#include <stdbool.h>\n\nchar *generate_random_password(const int password_length, bool has_special_characters)\n{\n const int alphamerics = 64; /* length of alphameric character set */\n const int alphamerics_plus = 94; /* length of alphameric character set plus special chatacters */\n const char character_set[] = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\\\"#$%&'()*+,-./:;<=>?@[\\\\]^_`{|}~\"; /* full character set */\n int n = has_special_characters ? alphamerics_plus : alphamerics; /* set the length of character_set to be used */\n\n char *random_password = malloc(sizeof(char) * (password_length + 1)); /* allocate memory for password */\n\n srandom(time(NULL)); /* initialise random number generator, srandom(clock()); works just as well*/\n for (int i = 0; i < password_length; i++)\n {\n random_password[i] = character_set[random() % n]; /* get a character from character_set indexed by the remainder when random() os divided by n */\n }\n random_password[password_length] = '\\0'; /* append terminating null to string */\n\n return random_password;\n}\n\nint main(void)\n{\n printf(\"%s\\n\", generate_random_password(17, true));\n printf(\"%s\\n\", generate_random_password(17, false));\n\n return 0;\n}\n</code></pre>\n\n<p>Typical output is</p>\n\n<pre><code>W$Mg-tT?oTwa~EF$S\nxGLMrqJBS6IB96xvp \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T15:39:43.330",
"Id": "447638",
"Score": "2",
"body": "Instead of commenting the description of a variable, why not use descriptive names? The compiler does not care if the varaible has a long name like `alphanumerics_plus_special_characters` or `length_of_characters_to_be_used`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T22:18:09.597",
"Id": "447731",
"Score": "4",
"body": "@dustytrash It's a matter of personal preference to some extent. Long variable names are a double edged weapon. Yes they are descriptive, but they can become unwieldy and make lines of code excessively long and awkward to read. My take is to use fairly short but descriptive names and expand on their use in the comments to allay any doubt. As for comments, I'm old school. I've been writing C on and off for over 35 years (Kernighan and Ritchie was my text book) and have always adhered to the idea of commenting most important lines to aid the next guy who needs to edit the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T22:25:27.097",
"Id": "447735",
"Score": "2",
"body": "@dustytrash I admit that 'n' instead of 'length_of_characters_to_be_used' was a slip of the pen! It should, at least , have been a bit more descriptive. Another reason I've been liberal with the comments is to help the OP, an learner, understand the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T23:14:11.427",
"Id": "447884",
"Score": "0",
"body": "The suggested code leaks memory"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T00:13:26.287",
"Id": "447891",
"Score": "0",
"body": "@MooingDuck I never said it was perfect. I like some variation on Ronald's idea of declaring the memory in the calling function (main) and passing a pointer. That should fix it. If this were some full blown password generator you would take user input for the password length, malloc the memory, call this function and free up the memory in the calling function once you have used the password,"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T01:01:04.427",
"Id": "229938",
"ParentId": "229927",
"Score": "11"
}
},
{
"body": "<p>You could get away without all the complicated memory allocation if you simply require that the calling code passes you the memory for the password. It could look like this:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include <stdio.h>\n#include <stdlib.h>\n\nvoid generate_password(char *password, size_t password_size) {\n for (size_t i = 0; i < password_size - 1; i++) {\n password[i] = alphabet[rnd_int(alphabet_len)];\n }\n password[password_size - 1] = '\\0';\n}\n</code></pre>\n\n<p>The <code>char *</code> means \"a pointer to a character\". In C, a pointer to a character can also mean \"a pointer to a character and some memory beyond\". This is commonly used to refer to strings. The <code>char *</code> then points to the first character of the string, and the string continues until it reaches the character <code>'\\0'</code>, which is binary 0. Not to be confused with the character <code>'0'</code>, which is the digit zero.</p>\n\n<p>Of course, the variables <code>alphabet</code> and <code>alphabet_len</code> are undeclared in the above code. Same as the <code>rnd_int</code> function that generates a random number from the range <code>[0, n)</code>.</p>\n\n<p>The code would be called like this:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>int main(void) {\n char password[80];\n\n generate_password(password, sizeof password);\n fprintf(\"password: %s\\n\", password);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T03:16:46.167",
"Id": "447744",
"Score": "2",
"body": "That's an excellent point; creating a contract where one doesn't need to exist is a bad idea. Expect callers always forget and leak memory, or worse use the wrong kind of free, even if you tell them to call deallocate_password(). That said, for security reasons requiring a call to wipe the password from memory might be necessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T15:02:10.850",
"Id": "447804",
"Score": "1",
"body": "Do you mean \"without\" in the first line?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T15:36:16.250",
"Id": "447811",
"Score": "0",
"body": "@Baldrickk Thanks"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T22:23:07.953",
"Id": "230002",
"ParentId": "229927",
"Score": "7"
}
},
{
"body": "<p>It's been touched on (e.g. fixed in Peter's example) but not explicitly stated by anyone - but to me, the most obvious issue is in the duplication of code.</p>\n\n<p>You have the following <code>if</code> statement:</p>\n\n<pre><code>if(has_special_characters)\n{\n //codeblock 1\n}\nelse\n{\n //codeblock 2\n}\n</code></pre>\n\n<p>where <code>codeblock 1</code> and <code>codeblock 2</code> are almost exactly identical. In fact it seems that the only difference is that you have this line in <code>codeblock 1</code>:</p>\n\n<pre><code>strcat(to_be_used, special_characters);\n</code></pre>\n\n<p>You can completely remove the duplication of code and wrap only that line in an <code>if</code> block.</p>\n\n<p>Although, I'd also suggest using Peter's second point, and not using strcat at all. You can put all the characters into one string from the start and use the <code>if</code> to determine the range which you will cover:</p>\n\n<pre><code>//adjacent strings are concatenated by the compiler\nconst char* characters = \"abcdefghijklmnopqrstuvwxyz\"\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n \"0123456789\"\n \"!\\\"#$%&'()*+,-./:;<=>?@[\\\\]^_`{|}~\";\nconst unsigned int alphanumerics_len = 62;\nconst unsigned int all_character_len = 96;\n\nint char_range_max;\nif (has_special_characters)\n{\n char_range_max = all_character_len;\n} \nelse\n{\n char_range_max = alphanumerics_len;\n}\n\n//...intermediate code\n\nconst int random_index = random() % char_range_max;\n\n//...more code\n\n</code></pre>\n\n<p>We can then improve upon this further by having the compiler handle the string lengths for us with a little pre-processor use to prevent anything needing repeating:</p>\n\n<pre><code>#define AN \"abcdefghijklmnopqrstuvwxyz\"\\\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\\\n \"0123456789\"\n#define SP \"!\\\"#$%&'()*+,-./:;<=>?@[\\\\]^_`{|}~\"\nconst int alphanumerics_len = sizeof (AN);\nconst int all_character_len = sizeof (AN SP);\nconst char* characters = AN SP;\n</code></pre>\n\n<p>I'd personally also prefer to replace the verbose if-block with the more concise:</p>\n\n<pre><code>const int char_range_max = has_special_characters ? all_character_len : alphanumerics_len;\n</code></pre>\n\n<p>which also has the advantage that it can be defined as const too.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T14:54:15.477",
"Id": "447800",
"Score": "0",
"body": "Too bad C doesn't make it easy to put labels part way through a string so you could have the compiler calculate `alphanumerics_len` for you. That would be easy in assembly language: just put a label after those bytes, and another label at the end of the string, so you can do `end1-start` or `end2-start` instead of hardcoding either length. (You could have used an array so you could at least use `sizeof` for `all_character_len` though.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T14:57:29.043",
"Id": "447802",
"Score": "0",
"body": "If you put the special chars *first*, you could use `strchr(characters, 'a')` to find a new start position (and a smart compiler could optimize that to pointer += constant). But choosing just a different length with the same start is most efficient. I guess you could `strrchr` at runtime if you wanted to avoid hardcoding lengths that match the string contents. Or `memrchr` if you use an array so total length is a compile-time constant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T15:01:02.103",
"Id": "447803",
"Score": "0",
"body": "@PeterCordes you can use sizeof (see https://stackoverflow.com/a/5022113/4022608) but only to find the maximum length, so you would need to have a hard-coded value regardless... There is probably something a little more inventive that can do it, but would possibly impact readability, or memory use. I can think of a readable alternative using the preprocessor, but it would rely on the compiler optimising out the creation of unused arrays, which is a little dirty."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T15:08:26.380",
"Id": "447806",
"Score": "0",
"body": "That's what I said: you can use `sizeof` for `all_character_len` but not `alphanumerics_len`. Good idea though; with macros you could concat everything for the actual definition, or just the alphanumeric part for `sizeof(\"abcdefg...\")` as a compile-time-constant integer. Yes that works: https://godbolt.org/z/ikLz_3 I thought I was going to have to cast it to an anonymous array or something. (Just using a string literal as an operand to `sizeof` doesn't make it part of your program so it doesn't even need to be \"optimized away\") Oh, another answer on the Q you linked points that out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T15:25:45.863",
"Id": "447809",
"Score": "0",
"body": "https://godbolt.org/z/T8-gm_ demonstrates this working in the context of this question :) @PeterCordes worth editing into the answer do you think?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T15:43:06.063",
"Id": "447812",
"Score": "1",
"body": "Yes, I'd put that in. Hard-coding a length requires updating 2 things if you ever add another special character, so it's highly frowned-upon and usually only justifiable for performance reasons. An answer that recommends hard-coding lengths / magic numbers isn't very good for coding-style. Since macros allow us to get just as efficient machine code without hard-coding lengths, we should use that. (And as a bonus, it's no worse to read than a runtime `strcat` + `strlen`). Your method (selecting a different length) is clearly more elegant and doesn't offend the reader's sense of efficiency."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T10:29:45.170",
"Id": "230026",
"ParentId": "229927",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "229928",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T20:11:43.970",
"Id": "229927",
"Score": "28",
"Tags": [
"beginner",
"c"
],
"Title": "My first random password generator"
} | 229927 |
<p>I am working with a 3th party library which has following interface defined for a processing task:</p>
<pre><code>public interface IProcessor {
void Execute( FileContent fileContent );
}
</code></pre>
<p>Such an <code>IProcessor</code> gives me the possibility to change the <code>FileContent</code> before it gets written to the database. For legacy reasons, and for integration reasons with an unnamed ERP, its unique identifiers are string identifiers which have a limitation in length, and they are padded on the left with padding char <code>'0'</code>.</p>
<p>Names will therefore always have the form of <code>00100</code> or <code>02301</code> or <code>10179</code> for a 5 digit identifier.</p>
<p>Sometimes, we need to add new content inside the <code>fileContent.Components</code>, but we are not allowed to change the existing identifiers. Theoretically any number of items could be added to the components, but for the question at hand, I simplified it to just adding 20 items.</p>
<p>The existing identifiers do not have any order to them, nor can I be sure that the highest number inside the string would be lower than the theoretical maximum number for this identifier.</p>
<p>To handle this addition, I thought I could use a <code>IEnumerator<string></code> function (not class) as an iterator, that creates the next number starting from the theoretical minimum value to the theoretical maximum value, and throw when it exceeds the maximum value.</p>
<pre><code>public static class GapHelper {
public static IEnumerator<string> GetNextName( int maxSize, IEnumerable<string> items, Func<int, string> transform ) {
var maxLength = (long)Math.Pow( maxSize, 10 );
var hashSet = new HashSet<string>( items );
for (var i = 0; i < maxLength; i++) {
var text = transform(i);
if (hashSet.Contains( text )) {
continue;
}
yield return text;
}
throw new ArgumentOutOfRangeException( "Iteration exceeded maximum numbers of items at " + maxSize );
}
public static IEnumerator<string> GetNextName( int maxSize, IEnumerable<string> items) {
return GetNextName( maxSize, items, i => i.ToString().PadLeft( maxSize, '0' ) );
}
}
</code></pre>
<p>and this would be used inside such an <code>IProcessor</code> in the following way:</p>
<pre><code>public class ProcessingTask : IProcessor {
public void Execute( FileContent fileContent ) {
using (var nameGenerator = GapHelper.GetNextName( 5, fileContent.Components.Select( c => c.Name ) ) ) {
for (var i = 0; i < 20; i++) {
nameGenerator.MoveNext();
fileContent.Components.Add( new Component {
Name = nameGenerator.Current, Content = "Foo"
} );
}
}
}
}
</code></pre>
<p>What I cannot change:</p>
<ul>
<li>How the processor is called, and with which parameters</li>
<li>How the file is processed afterwards, and might have been processed before</li>
<li>My bracket positioning, we have them at the end of each line</li>
<li>I am aware I didn't add documentation to the methods</li>
</ul>
<p>A full simplified example can be found in <a href="https://dotnetfiddle.net/HyTQmK" rel="nofollow noreferrer">this dotnetfiddle</a>.</p>
<p>I am interested in how this code looks from maintainability perspective, and what other potential options I might have overlooked. I am also curious if having an <code>IEnumerator<string></code> implemented as a method rather than a class makes a big difference, either for this implementation or from an iterator perspective.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T17:14:25.540",
"Id": "447984",
"Score": "0",
"body": "I vote to close this question because of this: _Theoretically any number of items could be added to the components, but for the question at hand, I simplified it to just adding 20 items._ - it makes it difficult to figure out whether the result **must** have `n` number of items or **can** have. In other words do you add _fake_ items to the result as you are doing here or do you stop when there are no more items to add."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T20:28:22.970",
"Id": "447999",
"Score": "0",
"body": "@t3chb0t That's a good point, it was hard to know how much I could simply the question without oversimplifying the process. It is indeed a bit more complex as the number of items I would add is undefined at compilation time, I get it from another file, and there are 3 dependent counters on top of it, one for subitems of the component, and two for the component. I chose not to do it that complex for the questions, but maybe I should"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T07:29:11.603",
"Id": "448056",
"Score": "0",
"body": "Do you have any tests for this code? It helps reviewers to be able to build and run the code, and experiment with it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T10:42:40.580",
"Id": "448084",
"Score": "0",
"body": "@TobySpeight well I did add a link to a dotnetfiddle"
}
] | [
{
"body": "<h2>Possible Bug</h2>\n\n<p>Since <code>Func<int, string> transform</code> is not guarded against collisions (different <code>int</code> values may yield the same string <code>result</code>), the next line is wrong. It only checks for unique elements in the already available data <code>items</code>, not in the new results fetched from <code>transform</code>.</p>\n\n<blockquote>\n<pre><code> if (hashSet.Contains( text )) {\n</code></pre>\n</blockquote>\n\n<p>This could be solved by trying to add each element to the set instead:</p>\n\n<pre><code>if (!hashSet.Add( text )) {\n</code></pre>\n\n<h2>LINQ</h2>\n\n<p>Furthermore, I would use an <code>IEnumerable</code> to allow for some LINQ chaining.</p>\n\n<pre><code>public static IEnumerable<string> GetNextName(\n int maxSize, IEnumerable<string> items, Func<int, string> transform) {\n</code></pre>\n\n<p>So we could just call:</p>\n\n<pre><code>public class ProcessingTask : IProcessor {\n public void Execute( FileContent fileContent ) {\n GapHelper.GetNextName(5, fileContent.Components\n .Select(c => c.Name)).Take(20).Select(x \n => new Component { Name = x, Content = \"Foo\" })\n .ToList().ForEach(fileContent.Components.Add);\n }\n}\n</code></pre>\n\n<p>Which yields better readability. Also a fun fact about <a href=\"https://blogs.msdn.microsoft.com/kcwalina/2005/01/07/the-reason-why-ienumerator-extens-idisposable/\" rel=\"nofollow noreferrer\">disposing an enumerator</a> from the initial code:</p>\n\n<blockquote>\n<pre><code> using (var nameGenerator = // ..\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T08:10:57.357",
"Id": "447580",
"Score": "1",
"body": "Ha, good one on the bug, I had actually refactored that for the question, but didn't test it with anything else ^_^ before that the padding was done in the method, but it didn't feel right :) On the topic of chaining, that would be nice, but I am iterating an external file given to me (I know that the question didn't reflect that, so sorry), and I will have 3 different iterators there"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T08:29:19.307",
"Id": "447581",
"Score": "0",
"body": "I only don't get the comment on disposing an enumerator, I honestly don't mind it, it makes sense to have it disposed since I will probably never really iterate the full list, so having it in a using feels like second nature to me, as it implements the `IDisposable`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T09:33:35.080",
"Id": "447585",
"Score": "0",
"body": "Eric Lippert suggests not to bother with disposing enumerators, since its only purpose is to for some interop. But it can't hurt ether if you keep using it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T07:03:44.473",
"Id": "448323",
"Score": "0",
"body": "mhmm... have you seen [this](https://stackoverflow.com/a/21337552/235671) post of him? He says the opposite: _**Always dispose your enumerators.** They implement `IDisposable` for a reason._ which the linked article confirms."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T08:58:31.447",
"Id": "448330",
"Score": "0",
"body": "@t3chb0t He has a more recent post where he argued otherwise."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T06:20:08.893",
"Id": "229952",
"ParentId": "229933",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "229952",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-30T22:07:35.290",
"Id": "229933",
"Score": "1",
"Tags": [
"c#",
"iterator",
"generator"
],
"Title": "A GapHelper static class to create unique (non-existing) size restricted names"
} | 229933 |
<p>I have two sets of points in lists list1 and list2 given below</p>
<pre><code>list1 = [['a',[1.2,3.6,4.5]],['b',[3.2,-5.4,6.6]],['c',[1.1,2.2,9.9]],['d',[5.5,12.5,2.9]],['e',[3.5,6.5,22.9]]]
list2 = [['v',[11.2,3.6,4.5]],['x',[13.2,-5.4,6.6]],['y',[11.1,2.2,9.9]],['z',[15.5,12.5,2.9]]]
</code></pre>
<p>If all the points in list1 are rotated and/or translated, points <code>a</code>, <code>b</code>, <code>c</code> and <code>d</code> align with points <code>v</code>, <code>x</code>, <code>y</code> and <code>z</code> respectively. Currently I have written Python code that can output the groups of pairs provided two input lists using a pairwise distance comparison method. It computes intra-list combinatorial distances within <code>list1</code> and <code>list2</code> and compares these distances between the lists to identify the pairs. For e.g. <code>distance(ab) ~= distance(vx), distance(ac) ~= distance(vy)</code> and so on. The code is given below. My code works but is slow for larger lists. I would like to know if there is any faster or easier way to solve this problem.</p>
<p>Thanks</p>
<pre><code>def calculate_distance(point1,point2):
#function calculates distance
dis = 0
dis += math.pow((point2[0]-point1[0]),2)
dis += math.pow((point2[1]-point1[1]),2)
dis += math.pow((point2[2]-point1[2]),2)
distance = math.sqrt(dis)
return distance
def make_masterdict(list1,list2):
# calculate interalist combinitorial pairs of points with
# their distances and store into dicts
list1pairs = {}
list2pairs = {}
for i in range(len(list1)):
p1 = list1[i][1]
for p2 in list1[i:]:
if list1[i][0] != p2[0]:
dist = calculate_distance(p1,p2[1])
#store both the pairs in the dictionary
list1pairs.update({list1[i][0]+'_'+p2[0]:dist})
list1pairs.update({p2[0]+'_'+list1[i][0]:dist})
for i in range(len(list2)):
p1 = list2[i][1]
for p2 in list2[i:]:
if list2[i][0] != p2[0]:
dist = calculate_distance(p1,p2[1])
list2pairs.update({list2[i][0]+'_'+p2[0]:dist})
list2pairs.update({p2[0]+'_'+list2[i][0]:dist})
# calculate interlist pairs between list1 and list2
masterlist = []
for i in list1:
for j in list2:
masterlist.append([i[0],j[0]])
masterdict = {}
# for each combinatorial pair in masterlist
for i in range(len(masterlist)-1):
c1 = masterlist[i]
key1 = c1[0]+'_'+c1[1]
masterdict.update({key1:[]})
for j in range(i+1,len(masterlist)):
c2 = masterlist[j]
# if the same point is not repeated in the pairs
if c1[0] != c2[0] and c1[1] != c2[1]:
#collect and compare the distances
p1 = c1[0]+'_'+c2[0]
p2 = c1[1]+'_'+c2[1]
dis1 = list1pairs[p1]
dis2 = list2pairs[p2]
if abs(dis1-dis2) < 0.1:
#if same distance, then store in masterdict
key2 = c2[0]+'_'+c2[1]
masterdict[key1].append(key2)
return masterdict
def recursive_finder(p1,list1,masterdict,d,ans):
# if lenght of d is more than 2, store that list in ans
if len(d) > 2:
ans.append(d)
# if lenght of list is 0, do not do anything
if len(list1) == 0:
pass
else:
other = []
nextlist = []
#loop through each value in list1 as p1
for i in list1:
if i in masterdict[p1]:
#make empty list
newl = []
#store old group in newl
newl.extend(d)
#add new member to old group
newl.append(i)
#store this list
other.append(newl)
#store new member
nextlist.append(i)
#repeat for each successful value in nextlist
for i in range(len(nextlist)):
#collect p1 and dnew
p1 = nextlist[i]
dnew = other[i]
#repeat process
recursive_finder(p1,nextlist[i+1:],masterdict,dnew,ans)
def find_groups(list1,list2):
#make master dictionary from input lists
masterdict = make_masterdict(list1,list2)
ans = []
#use recursive function to identify groups
for mainkey in masterdict:
if len(masterdict[mainkey]) > 1:
for i in range(len(masterdict[mainkey])):
p1 = masterdict[mainkey][i]
recursive_finder(p1,masterdict[mainkey][i+1:],masterdict,[mainkey,p1],ans)
return ans
#define two lists with a,b,c and d matching v,x,y, and z respectively
list1 = [['a',[1.2,3.6,4.5]],['b',[3.2,-5.4,6.6]],['c',[1.1,2.2,9.9]],['d',[5.5,12.5,2.9]],['e',[3.5,6.5,22.9]]]
list2 = [['v',[11.2,3.6,4.5]],['x',[13.2,-5.4,6.6]],['y',[11.1,2.2,9.9]],['z',[15.5,12.5,2.9]]]
answer = find_groups(list1,list2)
print(answer)
</code></pre>
<p>Upon running the code, the correct answer is output. Groups larger than size of 3 are output.</p>
<pre><code>[['a_v', 'b_x', 'c_y'], ['a_v', 'b_x', 'c_y', 'd_z'], ['a_v', 'b_x', 'd_z'], ['a_v', 'c_y', 'd_z'], ['b_x', 'c_y', 'd_z']]
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T02:02:25.560",
"Id": "447550",
"Score": "2",
"body": "Can you provide simple examples of input and desired output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T02:26:57.353",
"Id": "447553",
"Score": "0",
"body": "input lists list1 and list2 are given in the beginning and output is given at the end of the question. list1 = [['a',[1.2,3.6,4.5]],['b',[3.2,-5.4,6.6]],['c',[1.1,2.2,9.9]],['d',[5.5,12.5,2.9]],['e',[3.5,6.5,22.9]]]\nlist2 = [['v',[11.2,3.6,4.5]],['x',[13.2,-5.4,6.6]],['y',[11.1,2.2,9.9]],['z',[15.5,12.5,2.9]]]. Output is [['a_v', 'b_x', 'c_y'], ['a_v', 'b_x', 'c_y', 'd_z'], ['a_v', 'b_x', 'd_z'], ['a_v', 'c_y', 'd_z'], ['b_x', 'c_y', 'd_z']]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T12:38:15.833",
"Id": "447605",
"Score": "0",
"body": "How large would a \"large\" list be? Would it be possible to share an example of a large list, maybe using a GitHub gist or something similar?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T17:32:35.277",
"Id": "447657",
"Score": "0",
"body": "Large lists refer to more than 10,000 points in list1 and list2"
}
] | [
{
"body": "<h1>Calculate Distance</h1>\n\n<p>To check the distance between points, you can <code>zip</code> together two points to get corresponding coordinates. Every point is denoted by X, Y, Z, so <code>zip(point1, point2)</code> will give you pairs <code>(X1, X2), (Y1, Y2), (Z1, Z2)</code>. Furthermore, you can use <code>sum</code> to get the total of any iterable, rather than hard-coding indices. Applying this to your distance function:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import math\n\ndef calculate_distance(p1, p2):\n \"\"\"\n Takes the euclidean distance between two points. They are assumed\n to be of equal length:\n\n p1 = [a1, a2, ..., an]\n p2 = [b1, b2, ..., bn]\n\n Where n is any integer\n \"\"\"\n sq_dist = sum((a - b)**2 for a, b in zip(p1, p2))\n return math.sqrt(sq_dist)\n</code></pre>\n\n<p>This allows you to handle any point, and cleanly pairs up corresponding points.</p>\n\n<h1>Generating Combinations of Distances</h1>\n\n<p>There's no need to re-create a combinatorics function, one exists for you in <a href=\"https://docs.python.org/3.7/library/itertools.html#itertools.combinations\" rel=\"nofollow noreferrer\"><code>itertools.combinations</code></a>. They also include a sample recipe if you want to try it on your own, but theirs is great. It has the added benefit that you don't store the combinations in memory by default, that's totally up to you.</p>\n\n<p>It looks like you are trying to find pairs of points across both lists that share the same distance. You have <em>lots</em> of nested loops here, so let's look at it one step at a time. A <code>dict</code> is a great way to group these points together, with the keys being distance and the values being the pairs of points. </p>\n\n<p>To keep track of where sets of points come from, we can return separate dictionaries for fast membership testing:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def combine(l1, l2):\n \"\"\"\n Create your master dictionary by using the dict\n constructor on the list of key: value pairs (key is str, val is list)\n \"\"\"\n d = dict(l1)\n d2 = dict(l2)\n\n return d, d2\n</code></pre>\n\n<p>Ok, using itertools to generate pairs, you want to group based on the euclidean distance between points. Let's do that. We will use a <code>defaultdict</code> of <code>set</code> to hold our list of names based on a distance key. The <code>set</code> will make sure that the names pairs are unique:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from collections import defaultdict\nfrom itertools import combinations\n\n\ndef get_pairs(d1, d2):\n \"\"\"\n p1 and p2 are dictionaries of points\n we will construct a defaultdict that will take the combinations\n of points and construct the euclidean distance as our key, and a set of\n names as the values\n \"\"\"\n groups = defaultdict(set)\n\n # unpack the names and the points using dict.items()\n pairs_dict = {**d1,**d2}\n for (name1, p1), (name2, p2) in combinations(pairs_dict.items(), 2):\n check_1 = name1 in d1 and name2 in d1\n check_2 = name1 in d2 and name2 in d2\n if check_1 or check_2:\n # skip since they lie in the same dictionary\n continue\n dist = calculate_distance(p1, p2)\n\n for k in groups:\n # this will give you that tolerance you are looking for\n if math.isclose(dist, k, rel_tol=0.1):\n groups[k].add((name1, name2))\n groups[dist].add((name1, name2))\n\n return groups\n\n</code></pre>\n\n<p>Why do it this way? Well, you avoid most of your nested loops, and you are returned pairs of names based on the distances. The reason I say most is that you want to check against existing distances in your group dictionary to pair up approximately equal distances. Then you are grouping not only by exact distance, but also by approximate distance. Now, as the dictionary grows, this will be an O(N) operation, and you aren't necessarily going to avoid that. Add that to an O(M) loop, where M is the number of combinations, and N*M can get quite big, but comparing to your recursive function:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def recursive_finder(p1,list1,masterdict,d,ans):\n # if lenght of d is more than 2, store that list in ans\n if len(d) > 2:\n ans.append(d)\n\n # if lenght of list is 0, do not do anything\n if len(list1) == 0:\n pass\n else:\n other = []\n nextlist = []\n #loop through each value in list1 as p1\n for i in list1:\n if i in masterdict[p1]:\n #make empty list\n newl = []\n #store old group in newl\n newl.extend(d)\n #add new member to old group\n newl.append(i)\n #store this list\n other.append(newl)\n #store new member\n nextlist.append(i)\n #repeat for each successful value in nextlist \n for i in range(len(nextlist)):\n #collect p1 and dnew \n p1 = nextlist[i]\n dnew = other[i]\n #repeat process\n # can't get this to line up, indentation should be the same \n recursive_finder(p1,nextlist[i+1:],masterdict,dnew,ans)\n</code></pre>\n\n<p>You have a recursive function containing an O(N) loop inside another O(N) loop, so the O(M*N) is no worse than the existing code. Furthermore, while this may <em>look</em> like I'm modifying a dict while iterating over it, I'm really not. The state of the keys is constant while I iterate the keys, and I only inject a key after the loop. Your outer <code>build_master_dict</code> function, however, does modify a dict while iterating over the keys, since the recursive function is nested inside that loop.</p>\n\n<p>This makes it <em>really</em> easy to look them up from your master dictionary:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># assume list1 and list2 are the same and in the namespace already\nimport math\nimport json # for formatting\nfrom collections import defaultdict\n\nd1, d2 = combine(list1, list2)\n\ngroups = get_pairs(d1, d2)\n\n# to look up your points\npoints = groups[5.579426493825329]\n\nfor p1, p2 in points:\n print(d[p1], d[p2])\n[1.2, 3.6, 4.5] [1.1, 2.2, 9.9]\n[11.2, 3.6, 4.5] [11.1, 2.2, 9.9]\n</code></pre>\n\n<p>Or, to show in a more succinct way:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for dist, points in groups.items():\n print(dist)\n for p1, p2 in points:\n print(p1, d[p1], p2, d[p2])\n\n9.455686120002081\na [1.2, 3.6, 4.5] b [3.2, -5.4, 6.6]\nv [11.2, 3.6, 4.5] x [13.2, -5.4, 6.6]\n5.579426493825329\na [1.2, 3.6, 4.5] c [1.1, 2.2, 9.9]\nv [11.2, 3.6, 4.5] y [11.1, 2.2, 9.9]\n...\n</code></pre>\n\n<p>It's now easy to filter <code>groups</code> by <code>len</code> as well:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>res = dict(filter(lambda x: len(x[1]) >= 3, groups.items()))\n\n{10.0: {('c', 'y'), ('a', 'v'), ('b', 'x'), ('d', 'z'), ('d', 'v')}, 15.146286673637205: {('e', 'y'), ('c', 'x'), ('a', 'x'), ('d', 'y')}, 11.363538181394032: {('b', 'v'), ('b', 'y'), ('a', 'y'), ('c', 'v'), ('d', 'v')}, 12.223338332877807: {('c', 'v'), ('b', 'v'), ('b', 'y')}, 11.448143954370945: {('c', 'v'), ('d', 'v'), ('b', 'y')}, 22.03156826011258: {('e', 'z'), ('e', 'v'), ('e', 'x'), ('d', 'x'), ('b', 'z')}, 14.664924138910505: {('e', 'y'), ('c', 'x'), ('d', 'y')}, 19.03811965504997: {('e', 'v'), ('d', 'x'), ('c', 'z')}}\n\n</code></pre>\n\n<p>And to get your values:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>res = list(map(list, dict(filter(lambda x: len(x[1]) >= 3, groups.items())).values()))\n\n[[('c', 'y'), ('a', 'v'), ('b', 'x'), ('d', 'z'), ('d', 'v')], \n [('e', 'y'), ('c', 'x'), ('a', 'x'), ('d', 'y')], \n [('b', 'v'), ('b', 'y'), ('a', 'y'), ('c', 'v'), ('d', 'v')], \n [('c', 'v'), ('b', 'v'), ('b', 'y')], \n [('c', 'v'), ('d', 'v'), ('b', 'y')], \n [('e', 'z'), ('e', 'v'), ('e', 'x'), ('d', 'x'), ('b', 'z')], \n [('e', 'y'), ('c', 'x'), ('d', 'y')], [('e', 'v'), ('d', 'x'), ('c', 'z')]]\n\n# to format your keys:\npairs = [['_'.join(x) for x in sub] for sub in res]\n\n[['c_y', 'a_v', 'b_x', 'd_z', 'd_v'], \n ['e_y', 'c_x', 'a_x', 'd_y'], \n ['b_v', 'b_y', 'a_y', 'c_v', 'd_v'], \n ['c_v', 'b_v', 'b_y'], \n ['c_v', 'd_v', 'b_y'], \n ['e_z', 'e_v', 'e_x', 'd_x', 'b_z'], \n ['e_y', 'c_x', 'd_y'], \n ['e_v', 'd_x', 'c_z']]\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T03:37:41.150",
"Id": "447560",
"Score": "0",
"body": "Thanks for the reply. I think it's my mistake not explaining the problem properly. I need to identify groups of pairs that have equal intra-list distances. For example, if list1 = [['a',[0,0,0]],['b',[1,0,0]],['c',[0,3.5,0]]] and list2 = [['v',[0,0,5]],['x',[0,0,6]],['y',[0,3.5,5]]] then the solution will be [['a_v', 'b_x', 'c_y']]. As you will notice, dis(a,b) = dis(v,x) , dis(a,c) = dis(v,y) and dis(b,c) = dis(x,y). If I had to identify a group of four pairs from much larger input lists, then I would need 6 distance equalities."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T18:58:21.983",
"Id": "447686",
"Score": "0",
"body": "Thanks for the edit. The edited version you provided still outputs the wrong answer for list1 = [['a',[0,0,0]],['b',[1,0,0]],['c',[0,3.5,0]]] and list2 = [['v',[0,0,5]],['x',[0,0,6]],['y',[0,3.5,5]]]. The right answer is [['a_v', 'b_x', 'c_y']]. I think the issue is in the usage of distances as keys in the dictionary since the aim is not to identify groups that have the same inter-pair distance but inter-list pairs that have the same combinatiorial intra-pair distances."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T19:04:36.710",
"Id": "447688",
"Score": "0",
"body": "Hm, I'm misunderstanding the question, then. I'll take some time with it. I'm not sure what you mean by *inter-list pairs that have the same combinatorial intra-pair distances*. Let's take your answer, `['a_v', 'b_x', 'c_y']`. Putting it in simple language, is it that `a_v, b_x, and c_y` share a distance? What *exactly* do they share that causes them to be grouped? *inter-list pairs* implies pairs across the two lists while *intra-pair distances* implies the distance between the pair of points must be the same. Am I off base here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T19:21:50.903",
"Id": "447697",
"Score": "0",
"body": "I think I see the problem now, like I said, I'll take some time to revise it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T19:46:50.263",
"Id": "447708",
"Score": "0",
"body": "For the solution, a_v, b_x and c_y means that the points in one list can be moved and/or rotated collectively to match those from other list. Hence 'a' would align/occupy/meet 'v', 'b' to 'x' and 'c' to 'y'. Without doing any actual movements or rotations, I am using pairwise distance checks to find the groups. Hence for the solution a_v, b_x and c_y, distance(a,b) = distance(v,x) , distance(a,c) = distance(v,y) and distance(b,c) = distance(x,y). Thanks for the continuing help. I appreciate it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T15:15:29.807",
"Id": "447962",
"Score": "0",
"body": "@Pythonprotein Let me see if this phrasing of your question makes sense. You have a collection of points between two lists. A collection of three or more points is a plane, mathematically speaking. You want to know if there is a series of linear transformations that can be applied to a plane in `list1` to create a plane in `list2`? And this should list all such planes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T15:28:08.940",
"Id": "447965",
"Score": "0",
"body": "Though the *distance* requirement highlights only translations in this particular example"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T01:44:34.573",
"Id": "448021",
"Score": "0",
"body": "It does not need to be only three points (minimum of three) and not only linear transformations. For eg. for the input lists list1 = [['a',[0,0,0]],['b',[1,0,0]],['c',[0,3.5,0]]] and list2 = [['v',[0,0,5]],['x',[0,0,6]],['y',[0,3.5,5]]], both rotation and translation are involved to coincide points a to v, b to x and c to y. The first example I gave required only translations."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T02:18:57.460",
"Id": "229943",
"ParentId": "229940",
"Score": "6"
}
},
{
"body": "<h2>Sum generator</h2>\n\n<pre><code> dis = 0\n dis += math.pow((point2[0]-point1[0]),2)\n dis += math.pow((point2[1]-point1[1]),2)\n dis += math.pow((point2[2]-point1[2]),2)\n</code></pre>\n\n<p>can be</p>\n\n<pre><code> dis = sum((p2 - p1)**2 for p1, p2 in zip(point1, point2))\n</code></pre>\n\n<h2>Type hints</h2>\n\n<p>PEP484 type hints will help the static analysis and readability of your code. For example,</p>\n\n<pre><code>def calculate_distance(point1: Sequence[float], point2: Sequence[float]) -> float:\n</code></pre>\n\n<h2>Variable naming</h2>\n\n<p>Never call anything <code>list1</code> or <code>list2</code>. What do the lists actually contain? What are they for? Are they full of license plates? Death certificates? Deeds to property on the moon?</p>\n\n<h2>Typo</h2>\n\n<p><code>interalist</code> = <code>intra-list</code>.</p>\n\n<h2>Point tuples</h2>\n\n<p>From what I can tell, many of your sequences are actually three-dimensional points. There are easier or at least more legible ways to represent this, perhaps as a namedtuple:</p>\n\n<pre><code>from collections import namedtuple\n\nPoint = namedtuple('Point', ('x', 'y', 'z'))\n# ...\nlist1 = [['a', Point(1.2,3.6,4.5)] ...\n</code></pre>\n\n<h2>f-strings</h2>\n\n<p><code>p2[0]+'_'+list1[i][0]</code></p>\n\n<p>can be</p>\n\n<pre><code>f'{p2[0]}_{list1[i][0]}'\n</code></pre>\n\n<p>or, if you use named tuples - and assuming that this is a <code>Point</code> -</p>\n\n<pre><code>f'{p2.x}_{list1[i].x}'\n</code></pre>\n\n<h2>Loop like a native</h2>\n\n<pre><code> for i in range(len(list1)):\n p1 = list1[i][1]\n</code></pre>\n\n<p>can become</p>\n\n<pre><code>for item1 in list1:\n p1 = item1[1]\n</code></pre>\n\n<p>In other words, don't use C-style indexing when you can just iterate over the items in an iterable.</p>\n\n<h2>Use <code>isclose</code></h2>\n\n<pre><code>if abs(dis1-dis2) < 0.1:\n</code></pre>\n\n<p>is better represented with a call to <a href=\"https://docs.python.org/3/library/math.html#math.isclose\" rel=\"nofollow noreferrer\"><code>isclose</code></a>.</p>\n\n<h2>Null conditions</h2>\n\n<p>Don't do this:</p>\n\n<pre><code> if len(list1) == 0:\n pass\n else:\n</code></pre>\n\n<p>Just write</p>\n\n<pre><code>if len(list1) != 0:\n # ...\n</code></pre>\n\n<h2>List creation</h2>\n\n<p>This:</p>\n\n<pre><code> #make empty list\n newl = []\n #store old group in newl\n newl.extend(d)\n</code></pre>\n\n<p>should simply be</p>\n\n<pre><code>new1 = list(d)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T02:33:38.347",
"Id": "447557",
"Score": "1",
"body": "Wouldn't `if list:` make more sense, since any list that is length 0 won't pass this check?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T02:34:41.600",
"Id": "447558",
"Score": "2",
"body": "Depends on whether the OP also cares about `None` references, which are also falsy."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T02:26:43.213",
"Id": "229944",
"ParentId": "229940",
"Score": "4"
}
},
{
"body": "<h1>Indentation</h1>\n\n<p>Use four (4) spaces for indentation, not eight (8).</p>\n\n<h1>Checking List Existence</h1>\n\n<p>This</p>\n\n<pre><code>if len(list1) == 0:\n pass\nelse:\n</code></pre>\n\n<p>should be this (Thanks to @Reinderien for pointing this out)</p>\n\n<pre><code>if list1:\n ...\n</code></pre>\n\n<h1>Parameter Spacing</h1>\n\n<p>There should be spaces between parameters and the commas. For example, from this</p>\n\n<pre><code>def recursive_finder(p1,list1,masterdict,d,ans):\n</code></pre>\n\n<p>to this</p>\n\n<pre><code>def recursive_finder(p1, list1, masterdict, d, ans):\n</code></pre>\n\n<h1>Type Hints</h1>\n\n<p>This allows you to show what functions are accepting/returning. These are added to function headers. For example, from this</p>\n\n<pre><code>def find_groups(list1, list2):\n</code></pre>\n\n<p>to this</p>\n\n<pre><code>def find_groups(list1: list, list2: list) -> list:\n</code></pre>\n\n<h1>String Formatting</h1>\n\n<p>Doing this</p>\n\n<pre><code>p1 = c1[0]+'_'+c2[0]\np2 = c1[1]+'_'+c2[1]\n</code></pre>\n\n<p>can be simplified using an <code>f\"\"</code> stringike so</p>\n\n<pre><code>p1 = f\"{c1[0]}_{c2[0]}\"\np2 = f\"{c1[1]}_{c2[1]}\"\n</code></pre>\n\n<h1>Operator Spacing</h1>\n\n<p>This</p>\n\n<pre><code>dis += math.pow((point2[0]-point1[0]),2)\ndis += math.pow((point2[1]-point1[1]),2)\ndis += math.pow((point2[2]-point1[2]),2)\n</code></pre>\n\n<p>should be spaced out like this</p>\n\n<pre><code>dis += math.pow((point2[0] - point1[0]),2)\ndis += math.pow((point2[1] - point1[1]),2)\ndis += math.pow((point2[2] - point1[2]),2)\n</code></pre>\n\n<h1>Simplification</h1>\n\n<p>The above can even be reduced to one statement</p>\n\n<pre><code>dis = math.pow((point2[0] - point1[0]), 2) + \\\n math.pow((point2[1] - point1[1]), 2) + \\\n math.pow((point2[2] - point1[2]), 2)\n</code></pre>\n\n<p>The <code>\\</code> allows the addition to span multiple lines, increasing readability.</p>\n\n<p>Your <code>calculate_distance</code> function can now be reduced to one statement:</p>\n\n<pre><code>def calculate_distance(point1: list, point2: list) -> float:\n \"\"\"\n Returns the distance between the two points\n \"\"\"\n return math.sqrt(\n math.pow((point2[0] - point1[0]), 2) + \\\n math.pow((point2[1] - point1[1]), 2) + \\\n math.pow((point2[2] - point1[2]), 2)\n )\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T02:32:32.470",
"Id": "447556",
"Score": "1",
"body": "@Reinderien Thanks for the `if not` suggestion, I realize that's much better. And I used `line` and `statement` intermittently. I meant to use `statement` both times."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T09:21:00.110",
"Id": "447583",
"Score": "0",
"body": "IMHO you should not need \\ in `calculate_distance`, Python's implicit line continuation/joining should take care of this. [PEP 8 also recommends](https://www.python.org/dev/peps/pep-0008/#should-a-line-break-before-or-after-a-binary-operator) putting binary operators, e.g. `+`, at the beginning of the next line, not at the end of the last one."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T02:28:15.513",
"Id": "229945",
"ParentId": "229940",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T01:30:18.407",
"Id": "229940",
"Score": "5",
"Tags": [
"python",
"performance",
"mathematics"
],
"Title": "identify groups of congruent points"
} | 229940 |
<p>Sometimes some tasks can be taken a lot of time to end up.
This code is created in order to play a random radio music in background while the script is running another task until to finish up and the music will stop too.</p>
<p>The code is working well, just i'm waiting for any suggestion to improve this code, like to add a progress bar or something else ?
So what do you think ?</p>
<pre><code>'**********************************Description in English***********************************
'This vbscript is created by Hackoo on 29/09/2019
'Sometimes some tasks can be taken a lot of time to end up.
'This code is created in order to play music in background while the script is running another
'task until to finish up and the music will stop too.
'So, the user can listen to the music playing while the script is running another task.
'**********************************Description en Français**********************************
'Parfois, certaines tâches peuvent prendre beaucoup de temps pour finir.
'Ceci est créé afin de jouer de la musique en arrière-plan pendant que,
'le script exécute une autre tâche jusqu’à la terminer et la musique s’arrêtera aussi.
'Ainsi, l'utilisateur peut écouter la musique pendant que le script exécute une autre tâche.
'*******************************************************************************************
Option Explicit
If AppPrevInstance() Then
MsgBox "The script is already Running" & vbCrlf &_
CommandLineLike(WScript.ScriptName),VbExclamation,"The script is already Running"
WScript.Quit
Else
Call Run_as_Admin()
Dim Title,EndUP,WS,fso,Temp,WSF_File,URL_Music,CMD,Process_Music,StartTime,Duration
Title = "Playing music while another task is running by "& Chr(169) &" Hackoo 2019"
EndUP = False
Set WS = CreateObject("wscript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
Temp = WS.ExpandEnvironmentStrings("%Temp%")
WSF_File = Temp & "\Music.wsf"
URL_Music = Random_Music
Call Create_WSF_Music_File()
CMD = "wscript.exe " & DblQuote(WSF_File) & " //job:PlayMusic "& DblQuote(URL_Music) &""
Set Process_Music = WS.Exec(cmd)
WS.Popup "Playing this Radio music "& DblQuote(URL_Music) & vbCrlf &_
"in the background while the script is running another task until to finish it"_
,5,Title,vbInformation + vbSystemModal
Do While Process_Music.Status = 0
If EndUP = False Then
'**********************************************************************************************************************
'Your Main Code goes Here
StartTime = Timer
Call RUN_CMD ( _
"echo.>%Tmp%\LogCMD.txt" &_
"& (Tracert.exe www.codereview.stackexchange.com" &_
"& Ping www.codereview.stackexchange.com" &_
"& Tracert.exe www.google.com" &_
"& Ping www.google.com" &_
"& NetStat -abnof)>>%Tmp%\LogCMD.txt" &_
"& Start /MAX %Tmp%\LogCMD.txt"_
)
Duration = FormatNumber(Timer - StartTime, 0)
WS.Popup "The task had taken a run time until its completion about :" & vbCrlf &_
vbTab & convertTime(Duration) & vbCrlf & _
vbTab & WScript.ScriptName,10,Title,vbExclamation + vbSystemModal
'**********************************************************************************************************************
Else
On Error Resume Next 'to ignore "invalid window handle" errors
Process_Music.Terminate
On Error Goto 0
EndUP = True
End If
Loop
End If
'----------------------------------------------------------------------------------------
Sub Create_WSF_Music_File()
Dim oWSF
Set oWSF = fso.OpenTextFile(WSF_File,2,True)
oWSF.WriteLine "<job id=""PlayMusic"">"
oWSF.WriteLine "<script language=""Vbscript"">"
oWSF.WriteLine "Dim URL_Music"
oWSF.WriteLine "URL_Music = WScript.Arguments(0)"
oWSF.WriteLine "Call Play(URL_Music)"
oWSF.WriteLine "Function Play(URL)"
oWSF.WriteLine "Dim Sound"
oWSF.WriteLine "Set Sound = CreateObject(""WMPlayer.OCX"")"
oWSF.WriteLine "Sound.URL = URL"
oWSF.WriteLine "Sound.settings.volume = 100"
oWSF.WriteLine "Sound.Controls.play"
oWSF.WriteLine "Do while Sound.currentmedia.duration = 0"
oWSF.WriteLine "wscript.sleep 100"
oWSF.WriteLine "Loop"
oWSF.WriteLine "End Function"
oWSF.WriteLine "</script>"
oWSF.WriteLine "</job>"
End Sub
'----------------------------------------------------------------------------------------
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'----------------------------------------------------------------------------------------
Function RUN_CMD(StrCmd)
Dim ws,MyCmd,Result
Set ws = CreateObject("wscript.Shell")
MyCmd = "CMD /C " & StrCmd & " "
Result = ws.run(MyCmd,0,True)
EndUP = True
End Function
'----------------------------------------------------------------------------------------
Function Random_Music()
Dim URL1,URL2,URL3,URL4,URL5,URL6,ListMusic,i,j,tmp
URL1 = "http://94.23.221.158:9197/stream"
URL2 = "http://www.chocradios.ch/djbuzzradio_windows.mp3.asx"
URL3 = "http://vr-live-mp3-128.scdn.arkena.com/virginradio.mp3"
URL4 = "http://185.52.127.168/fr/30201/mp3_128.mp3?origine=fluxradios"
URL5 = "http://icecast.skyrock.net/s/natio_mp3_128k"
URL6 = "http://185.52.127.173/fr/30601/mp3_128.mp3?origine=tunein"
ListMusic = array(URL1,URL2,URL3,URL4,URL5,URL6)
Randomize
For i = 0 To UBound(ListMusic)
j = Int((UBound(ListMusic) - i + 1) * Rnd + i)
tmp = ListMusic(i)
ListMusic(i) = ListMusic(j)
ListMusic(j) = tmp
Next
Random_Music=tmp
End Function
'----------------------------------------------------------------------------------------
Function AppPrevInstance()
With GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2")
With .ExecQuery("SELECT * FROM Win32_Process WHERE CommandLine LIKE " & CommandLineLike(WScript.ScriptFullName) & _
" AND CommandLine LIKE '%WScript%' OR CommandLine LIKE '%cscript%'")
AppPrevInstance = (.Count > 1)
End With
End With
End Function
'----------------------------------------------------------------------------------------
Function CommandLineLike(ProcessPath)
ProcessPath = Replace(ProcessPath, "\", "\\")
CommandLineLike = "'%" & ProcessPath & "%'"
End Function
'----------------------------------------------------------------------------------------
Function convertTime(seconds)
Dim ConvSec,ConvHour,ConvMin
ConvSec = seconds Mod 60
If Len(ConvSec) = 1 Then
ConvSec = "0" & ConvSec
End If
ConvMin = (seconds Mod 3600) \ 60
If Len(ConvMin) = 1 Then
ConvMin = "0" & ConvMin
End If
ConvHour = seconds \ 3600
If Len(ConvHour) = 1 Then
ConvHour = "0" & ConvHour
End If
convertTime = ConvHour & ":" & ConvMin & ":" & ConvSec
End Function
'----------------------------------------------------------------------------------------
Sub Run_as_Admin()
If Not WScript.Arguments.Named.Exists("elevate") Then
CreateObject("Shell.Application").ShellExecute DblQuote(WScript.FullName) _
, DblQuote(WScript.ScriptFullName) & " /elevate", "", "runas", 1
WScript.Quit
End If
End Sub
'----------------------------------------------------------------------------------------
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T16:26:40.827",
"Id": "449097",
"Score": "1",
"body": "In `Random_Music`, perhaps you can save the last played URL in the Registry and avoid the 1 out of 6 chance of playing the same URL twice in a row. Without randomizing it you could simply go down your list of URLs by saving such a variable."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T01:54:38.907",
"Id": "229941",
"Score": "4",
"Tags": [
"vbscript"
],
"Title": "Playing music in the background while another task is running"
} | 229941 |
<p>I am looking for a more elegant way to validate in an input word can be created from a list of letters.</p>
<pre class="lang-py prettyprint-override"><code># Necessary variables (change as needed to test your code).
user_word = 'BANANA'
letters = ['N', 'B', 'N', 'A', 'A', 'P', 'M', 'S', 'A']
# This function checks whether a word entered by the user contains appropriate letters.
# It receives the letters and the word as parameter values, and returns True or False.
def validate_word(word, letters):
from collections import Counter
Count = Counter(letters)
for letters in word:
if not Count[letters]:
return False
Count[letters] -= 1
return True
# Print the return value of the function to test it.
print(validate_word(user_word, letters))
</code></pre>
<p>As commented the function needs to return <code>True</code> if all the letters in the word are in the list, <code>False</code> otherwise.</p>
| [] | [
{
"body": "<h2>Imports</h2>\n\n<p>In general, imports should be listed at the top of the script, not inside function definitions. So instead of this:</p>\n\n<pre><code>def validate_word(words, letters):\n from collections import Counter\n ...\n</code></pre>\n\n<p>Write:</p>\n\n<pre><code>from collections import Counter\n\ndef validate_word(words, letters):\n ...\n</code></pre>\n\n<h2>Variable names</h2>\n\n<p>In Python, variable names should be <code>snake_case</code>. Words beginning with upper case letters are reserved from classes, like <code>Counter</code>, so <code>Count</code> should be called <code>count</code>.</p>\n\n<h2>Test Code</h2>\n\n<p><code>user_word</code> and <code>letters</code> are declared far from the code that uses them. They should be declared near where they are used, so at the bottom of the script, and ideally inside a <code>__name__ == '__main__'</code> guard:</p>\n\n<pre><code>from collections import Counter\n\ndef validate_word(word, letters):\n ...\n\nif __name__ == '__main__':\n user_word = 'BANANA'\n letters = ['N', 'B', 'N', 'A', 'A', 'P', 'M', 'S', 'A']\n print(validate_word(user_word, letters))\n</code></pre>\n\n<h2>A String is a List of Characters</h2>\n\n<p>The <code>Counter</code> class accepts an iterable for its construction argument, such as the list of letters you want to count. But a string is also an iterable list of characters, so instead of a list, you could simply pass in a string, and it would work just as well:</p>\n\n<pre><code>if __name__ == '__main__':\n user_word = 'BANANA'\n letters = 'NBNAAPMSA'\n print(validate_word(user_word, letters))\n</code></pre>\n\n<h2>Counters</h2>\n\n<p>You are counting up the counts of letters you are allowed to use. Why not count up the count of letters in the <code>user_word</code>?</p>\n\n<pre><code>>>> Counter('NBNAAPMSA')\nCounter({'A': 3, 'N': 2, 'B': 1, 'P': 1, 'M': 1, 'S': 1})\n>>> Counter('BANANA')\nCounter({'A': 3, 'N': 2, 'B': 1})\n</code></pre>\n\n<p>Then instead of looping over the letters of the user word, and subtracting 1 from the letter count, you could compare the letter counts directly.</p>\n\n<p>Or ... you could subtract one from the other ...</p>\n\n<pre><code>>>> counts = Counter('NBNAAPMSA')\n>>> counts.subtract('BANANA')\n>>> counts\nCounter({'P': 1, 'M': 1, 'S': 1, 'N': 0, 'B': 0, 'A': 0})\n>>> \n</code></pre>\n\n<p>As long as all values in the counter are non-negative, the word is valid.</p>\n\n<pre><code>>>> all(count >= 0 for count in counts.values())\nTrue\n</code></pre>\n\n<p>From this, a simpler function can be created. Left to student.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T04:58:05.500",
"Id": "229950",
"ParentId": "229947",
"Score": "9"
}
},
{
"body": "<p>There is a very short way to accomplish what you are trying to do:</p>\n\n<pre><code>def validate_word(word: str, letters: list) -> bool:\n \"\"\"\n Determines if the `word` can be made out of `letters`\n \"\"\"\n matched_word = \"\"\n for letter in word:\n for index, value in enumerate(letters):\n if value == letter:\n matched_word += value\n del letters[index]\n break\n return word == matched_word\n</code></pre>\n\n<p>What this does it loop through <code>word</code> and <code>letters</code>. It then matches up each <code>letter</code> in <code>word</code> and <code>letters</code>, and if they match, it adds it to the matched_word. It then returns if they are equal or not.</p>\n\n<p>The <code>break</code> is used to exit out of the inner loop, so multiple letters are not added if they match.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T05:45:02.167",
"Id": "447569",
"Score": "2",
"body": "Yuk. Ditch the inner loop, use `letters.remove(letter)`, and catch the `ValueError` exception and return `False` if the letter wasn't present. Return `True` if you were able to `list.remove(letter)` for all of the letters in `word`. No need for `matched_word`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T05:31:29.500",
"Id": "229951",
"ParentId": "229947",
"Score": "-1"
}
}
] | {
"AcceptedAnswerId": "229950",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T03:52:40.377",
"Id": "229947",
"Score": "6",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Determine if input word can be created from a list of letters"
} | 229947 |
<p><a href="https://i.stack.imgur.com/RVJ52.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RVJ52.jpg" alt="Main Menu"></a></p>
<p><a href="https://i.stack.imgur.com/QvogR.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QvogR.jpg" alt="Category Menu"></a></p>
<p><a href="https://i.stack.imgur.com/Q5zpo.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Q5zpo.jpg" alt="Category List"></a></p>
<p><a href="https://i.stack.imgur.com/0GZdZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0GZdZ.jpg" alt="Random Name Menu"></a></p>
<p><a href="https://i.stack.imgur.com/ylRWt.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ylRWt.jpg" alt="Pre-Joke"></a></p>
<p><a href="https://i.stack.imgur.com/31vf4.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/31vf4.jpg" alt="Joke"></a></p>
<p>I've created a command line joke teller which makes Chuck Norris jokes after communicating with the Chuck Norris API. </p>
<p>It also allows you to generate a random person by communicating to the names API and replaces Chuck Norris with that name.</p>
<p>Execution goes like:</p>
<p>1) Asks you if you want a joke</p>
<p>2) Asks you to pick a category</p>
<ol>
<li>Yes -> calls API/Reads file (acts like cache for me) -> shows list</li>
<li>No -> picks a random category</li>
</ol>
<p>3) Asks you to pick a random name</p>
<ol>
<li>Yes -> Calls API </li>
<li>No -> keeps the same chuck norris in joke</li>
</ol>
<p>4) Calls Joke API and replaces Chuck Norris if user asked for random name</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp1
{
class Program
{
// key and names allowed to remain as static global variable - not eligible for race condition
static char key; // monitor keyboard strokes
static Tuple<string, string, string> names;
const string CHUCK_NORRIS_API_BASE = "https://api.chucknorris.io";
const string NAME_API_BASE = "http://uinames.com/api/";
// create a multithreaded approach to speed up execution time
static async Task Main(String[] args)
{
// list of all categories - used to verify if user entered category is acceptable
string[] categoriesList = null;
string[] results = null;
int lastLoad = -1;
int calls_count = 0;
// counter to check API calls from both names API and joke API don't exceed certain number (set at 15)
while (calls_count < 15)
{
// Initial Screen
PrintScreen("Main");
validateAnswer("Main");
// Category Screen
PrintScreen("Category");
validateAnswer("CategoryOrName");
string userCategory = null;
// if category is selected
if (key == 'c')
{
Tuple<string[], int> catInfo = Tuple.Create(results, lastLoad);
catInfo = await getCategories(lastLoad);
lastLoad = (int)catInfo?.Item2;
categoriesList = parseCategories(catInfo?.Item1, categoriesList);
Console.WriteLine("\nChuckie askes you make a selection. Make sure it's written word for word...:");
userCategory = Console.ReadLine().ToLower();
validateCategory(userCategory, categoriesList);
}
//Randon Name screen
PrintScreen("Random Name");
validateAnswer("CategoryOrName");
// get random name
if (key == 'r')
{
await GetNames();
}
// get the joke and store into results
String[] joke = await GetRandomJokes(userCategory);
calls_count++;
//Pre-Joke Screen
PrintScreen("Pre-Joke");
// show joke
PrintJoke(joke);
}
// ends game
PrintScreen("End");
}
// print the joke
private static void PrintJoke(string[] joke)
{
Console.Clear();
Console.WriteLine(string.Join(",", joke));
Console.WriteLine("\nChuckie hopes you enjoyed your joke. Press any key to go back to main menu...");
GetEnteredKey(Console.ReadKey());
}
// checks user input
private static void validateAnswer(string stage)
{
// checks for valid answer
switch (stage)
{
case "Main":
// checks for valid answer
while (key != 'y' && key != 'e')
{
Console.WriteLine("\nChuckie is not pleased with your invalid answer. Pick 'y' or 'e'");
GetEnteredKey(Console.ReadKey());
}
break;
case "CategoryOrName":
while (key != 'c' && key != 'r' && key != 'e')
{
Console.WriteLine("\nChuckie is not pleased with your invalid answer. Pick 'c', 'r', or 'e'");
GetEnteredKey(Console.ReadKey());
}
break;
default:
break;
}
// check if user wants to exit
if (key == 'e')
{
Console.WriteLine("\nChuckie understands. Good day...");
Environment.Exit(0);
}
}
// different screen displays
private static void PrintScreen(string screen)
{
switch(screen)
{
// Main Menu
case "Main":
Console.Clear();
Console.WriteLine("========================================================");
Console.WriteLine("| =) Chuck Norris Joke Generator =) |");
Console.WriteLine("| Do you wish to be elightened by the great chuckie... |");
Console.WriteLine("| Press y for yes |");
Console.WriteLine("| Press e to exit |");
Console.WriteLine("========================================================");
Console.WriteLine(" Made by: Joke Company™ ");
GetEnteredKey(Console.ReadKey());
break;
// Category Menu
case "Category":
Console.Clear();
Console.WriteLine("========================================================");
Console.WriteLine("| =) Chuck Norris Joke Generator =) |");
Console.WriteLine("| Chuckie wonders if you want a category of joke... |");
Console.WriteLine("| Press c to pick a category |");
Console.WriteLine("| Press r to get a random category |");
Console.WriteLine("| Press e to exit |");
Console.WriteLine("========================================================");
Console.WriteLine(" Made by: Joke Company™ ");
GetEnteredKey(Console.ReadKey());
break;
// Name Menu
case "Random Name":
Console.Clear();
Console.WriteLine("========================================================");
Console.WriteLine("| =) Chuck Norris Joke Generator =) |");
Console.WriteLine("| Is the joke about chuckie or someone else... |");
Console.WriteLine("| Press c to make the joke about chuckie |");
Console.WriteLine("| Press r to get a random name |");
Console.WriteLine("| Press e to exit |");
Console.WriteLine("========================================================");
Console.WriteLine(" Made by: Joke Company™ ");
GetEnteredKey(Console.ReadKey());
break;
// Pre-Joke Screen
case "Pre-Joke":
Console.Clear();
Console.WriteLine("========================================================");
Console.WriteLine("| =) Chuck Norris Joke Generator =) |");
Console.WriteLine("| Chuckie has found your perfect joke... |");
Console.WriteLine("| Press any key to see it |");
Console.WriteLine("| |");
Console.WriteLine("| |");
Console.WriteLine("========================================================");
Console.WriteLine(" Made by: Joke Company™ ");
GetEnteredKey(Console.ReadKey());
break;
// Closing Screen
case "End":
Console.Clear();
Console.Write("\n Chuckie is out of jokes now. Please try again letter :)");
break;
default:
break;
}
}
// checks user input for categories
private static void validateCategory(string category, string[] categories)
{
// loop to confirm user enters correct category
while (!categories.Contains('"' + category + '"'))
{
Console.WriteLine("\nThis is not a category chuckie knows about. Please choose a category from the above list");
category = Console.ReadLine().ToLower();
}
}
//cleans category result into ordered list
private static string[] parseCategories(string[] results, string[] categories)
{
Console.Clear();
// checks if categories hasn't been previously populated - i.e if program ran before
if (categories == null) {
results = results[0].Split('[');
results = results[1].Split(']');
categories = results[0].Split(',');
}
Console.WriteLine("\nCategories are:");
//print ordered list of categories
for (int num_of_cat = 0; num_of_cat < categories.Length; num_of_cat++)
{
Console.WriteLine("\n" + num_of_cat.ToString() + "." + categories[num_of_cat]);
}
return categories;
}
// maps keystroke to standard character - removes error due to case
private static void GetEnteredKey(ConsoleKeyInfo consoleKeyInfo)
{
switch (consoleKeyInfo.Key)
{
case ConsoleKey.C:
key = 'c';
break;
case ConsoleKey.E:
key = 'e';
break;
case ConsoleKey.N:
key = 'n';
break;
case ConsoleKey.R:
key = 'r';
break;
case ConsoleKey.Y:
key = 'y';
break;
}
}
// Generates random joke from API
private static async Task<String[]> GetRandomJokes(string category)
{
// creates joke based on first name, and last name and category
string[] joke = JsonFeed.GetRandomJokes(CHUCK_NORRIS_API_BASE, names?.Item1, names?.Item2, category);
// fixes any incorrect pronouns based on random name generated
return GenderPronounReplace(joke);
}
// checks gender pronouns in joke
private static string[] GenderPronounReplace(string[] joke)
{
if (names?.Item3 == "female")
{
for (int i = 0; i < joke.Length; i++)
{
switch(joke[i])
{
case " He ":
joke[i] = " She ";
break;
case " he ":
joke[i] = " she ";
break;
case " His ":
joke[i] = " Her ";
break;
case " his ":
joke[i] = " her ";
break;
case " Him ":
joke[i] = " Her ";
break;
case " him ":
joke[i] = " her ";
break;
}
}
}
return joke;
}
// grabs categories
private static async Task <Tuple<String[], int>> getCategories(int lastLoad)
{
// save categories to a text file so don't have to call the
string[] cat;
// load categories from file
if (File.Exists("categories.txt") && lastLoad < 100)
{
// read all the categories and last line is count since the number of times text file has been used (in case API updates response to add more categories)
cat = await File.ReadAllLinesAsync("categories.txt");
int numLoaded = Int32.Parse(cat[cat.Length - 1]);
// increment the last updated count and updates the file with new count
cat[cat.Length - 1] = numLoaded++.ToString();
await File.WriteAllLinesAsync("categories.txt", cat);
return Tuple.Create(cat, numLoaded);
}
// File has not been created OR > 100 iterations since text file has been updated
else
{
// resets last loaded stat and calls API
lastLoad = 0;
cat = JsonFeed.GetCategories(CHUCK_NORRIS_API_BASE);
// writes list and last Updated from API to file
await File.WriteAllLinesAsync("categories.txt", cat);
await File.AppendAllTextAsync("categories.txt", lastLoad.ToString());
return Tuple.Create(cat, lastLoad);
}
// return JsonFeed.GetCategories(CHUCK_NORRIS_API_BASE);
}
// generates random name
private static async Task GetNames()
{
dynamic result = JsonFeed.Getnames(NAME_API_BASE);
// stores name, surname, gender
names = Tuple.Create(result.name.ToString(), result.surname.ToString(), result.gender.ToString());
}
}
}
</code></pre>
<p>It talks to a helper class which handles all the API calls called JsonFeed</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Text.RegularExpressions;
namespace ConsoleApp1
{
class JsonFeed
{
public static string[] GetRandomJokes(string jokeUrl, string firstName, string lastName, string category)
{
StringBuilder joke = new StringBuilder("");
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(jokeUrl);
// TODO: use stringbuilder for this....
StringBuilder url = new StringBuilder("jokes/random");
if (category != null)
{
if (url.ToString().Contains('?'))
url.Append("&");
else url.Append("?");
url.Append("category=");
url.Append(category);
}
//check if word was inside available categories - create array of categories
joke.Append(Task.FromResult(client.GetStringAsync(url.ToString()).Result).Result);
}
catch (HttpRequestException e)
{
Console.WriteLine("\nError");
Console.WriteLine(e);
Console.WriteLine("Error Message: {0}", e.Message);
Environment.Exit(-1);
}
if (firstName != null && lastName != null)
{
// replace all instances of "chuck" to the first name and "norris" with the last name
joke.Replace(joke.ToString(), (Regex.Replace(joke.ToString(), "(?i)Chuck", firstName)));
joke.Replace(joke.ToString(), (Regex.Replace(joke.ToString(), "(?i)Norris", lastName)));
}
return new string[] { JsonConvert.DeserializeObject<dynamic>(joke.ToString()).value };
}
/// <summary>
/// returns an object that contains name and surname
/// </summary>
/// <param name="client2"></param>
/// <returns></returns>
public static dynamic Getnames(string NameAPIUrl)
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(NameAPIUrl);
var result = client.GetStringAsync("").Result;
return JsonConvert.DeserializeObject<dynamic>(result);
}
catch (HttpRequestException e)
{
Console.WriteLine("\nError");
Console.WriteLine(e);
Console.WriteLine("Error Message: {0}", e.Message);
Environment.Exit(-1);
}
return " ";
}
public static string[] GetCategories(string jokeAPI)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(jokeAPI);
return new string[] { Task.FromResult(client.GetStringAsync("/jokes/categories").Result).Result };
}
}
}
</code></pre>
<p>I'm still semi-comfortable with best practices and clear documentation so any suggestions in that area or functionality wise, I'm all ears!</p>
| [] | [
{
"body": "<p>Your code is somewhat messy because almost everything is inside a single <code>Program</code> class. It can use some abstractions. Few things off the bat:</p>\n\n<p>1) Declare and implement a strongly typed api for your service. For example:</p>\n\n<pre><code>interface IChuckService\n{\n Joke[] GetRandomJokes(Category category);\n Category[] GetCategories();\n Name[] GetNames();\n //other json-related methods\n}\n</code></pre>\n\n<p>2) Declare and implement api for your screens, and create transitions. For example</p>\n\n<pre><code>interface IChuckScreen\n{\n void Show(IChuckService service);\n //this is an example of \"active\" state machine (you can use \"passive\" one instead)\n //return \"this\" to stay on the screen, or new state to transition away\n IChuckScreen ApplyInput(string input);\n}\n</code></pre>\n\n<p>Your program class should probably look like:</p>\n\n<pre><code>var service = new ChuckService();\nvar currentScreen = new MainScreen();\nwhile(true)\n{\n currentScreen.Show(service);\n var input = Console.ReadLine();\n currentScreen = currentScreen.ApplyInput(input);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T09:34:43.007",
"Id": "448344",
"Score": "1",
"body": "Good answer. You basically took the crude state machine that OP had in the one class and broke it out to interfaces. Maybe mention this pattern explicitly in the answer? A question: how do you propose to exit the while loop? Using ```Environment.Exit```? Could the IChuckScreen interface have a method flagging for exit that you could use as a condition in the loop? That way, one can easily do cleanup et cetera after the loop."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T08:47:19.927",
"Id": "230252",
"ParentId": "229954",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T06:27:47.473",
"Id": "229954",
"Score": "4",
"Tags": [
"c#",
"game",
"regex",
"api",
"thread-safety"
],
"Title": "Chuck Norris Joke Teller"
} | 229954 |
<p>I am translating a text into another language using Google APIs. </p>
<p>Sometimes the translated text returned from the API does not match the case of the text provided - e.g. when translating the text "Now Activated" to German, I get the translated text response as "jetzt aktiviert" instead of "Jetzt Aktiviert".</p>
<p>I wrote a function which can change the case of translated text to match the input text:</p>
<pre><code>public string MaintainCase(string text, string translatedText)
{
// Split the inputs provided into string arrays
var textStrArray = text.Split(' ');
var translatedTextStrArray = translatedText.Split(' ');
// Count the no of words of both the texts provided
var noOfWordsInText = textStrArray.Length;
var noOfWordsInTranslatedText = translatedTextStrArray.Length;
// Check if the word count matches
bool wordCountMatches =
noOfWordsInText == noOfWordsInTranslatedText
? true
: false;
// Start changing the case of translated text as per text
for (int i = 0; i < noOfWordsInText; i++)
{
// Take the word no i of text and translated text
var textWord = textStrArray[i];
var translatedTextWord = translatedTextStrArray[i];
// Using string builder to modify the first character of translated text
// based on the case identified of the first character of text
var strBuilder = new StringBuilder(translatedTextWord);
var changedChar =
char.IsUpper(textWord[0])
? char.ToUpper(translatedTextWord[0])
: char.ToLower(translatedTextWord[0]);
strBuilder[0] = changedChar;
translatedTextStrArray[i] = strBuilder.ToString();
// If the word count does not match, after changing the case of only first word, break the loop
if (!wordCountMatches)
{
break;
}
}
// Return the modified translated text
return string.Join(" ", translatedTextStrArray);
}
</code></pre>
<p>Kindly suggest if this can be made more efficient (usage of string builders etc) and if I need to add some additional checks which I may have missed.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T07:46:21.713",
"Id": "447575",
"Score": "2",
"body": "Frame challenge: is the result really what we want? E.g. translating German *mein Buch* to English, we normally want *my book*, not *my Book*. Similarly, when going the other way, we must respect the capitalisation that the rules of the language demand, rather than slavishly following the source language."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T07:52:25.923",
"Id": "447576",
"Score": "0",
"body": "In the application this can be made optional by providing a default bool parameter 'maintainCase = false'.\nHowever is the code fine for the scenario where we _do_ want to utilize this functionality?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T10:03:57.657",
"Id": "447589",
"Score": "2",
"body": "This looks like trouble to me and as a method that will never be good enough because of all strange possibilities in real world texts. Have you considered the functionality provided by `CultureInfo.TextInfo` for instance `ToTitleCase()` and the like?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T07:28:04.443",
"Id": "229957",
"Score": "2",
"Tags": [
"c#",
"performance",
"strings",
"google-translate"
],
"Title": "Function to match the case of a text as per another text"
} | 229957 |
<p>I frequently encounter the need for creating services that concurrently process messages from Redis queues. So I decided to share the knowledge I learned and help others easily bootstrap such a service. I would like a second opinion from code reviews of the library. Please do contribute if you feel like improving it!</p>
<p>Github repo: <a href="https://github.com/ikhoury/rstreamer" rel="nofollow noreferrer">https://github.com/ikhoury/rstreamer</a></p>
<h1>Sample usage</h1>
<p>You create <code>Worker</code> classes that processes incoming messages from a queue.</p>
<pre><code>public class SampleWorker implements Worker {
@Override
public void processSingleItem(String item) {
System.out.println("Got item: " + item);
}
}
</code></pre>
<p>You link workers to a task queue using a <code>WorkSubscription</code>:</p>
<pre><code>List<Worker> workers = new ArrayList();
workers.add(new SampleWorker());
WorkSubscription subscription = new WorkSubscription("my:task:queue", workers);
</code></pre>
<p>You add your <code>WorkSubscription</code> to a <code>SubscriptionManager</code> that handles the lifecycle of all subscriptions.</p>
<pre><code>subscriptionManager.addSubscription(subscription);
subscriptionManager.activateSubscriptions();
</code></pre>
<p>Background threads will spin up, continuously poll tasks, and process them using workers.</p>
| [] | [
{
"body": "<p>Really good library.</p>\n\n<p>Here are my proposals:</p>\n\n<p>1) Annotation mapping it would be really cool to use annotations (in spring boot application for example) like this:</p>\n\n<pre><code>@RstreamerProcessor\npublic class SampleWorker {\n\n @RstreamerListener(queue = \"my:task:queue\")\n public void processSingleItem(String item) {\n System.out.println(\"Got item: \" + item);\n }\n}\n</code></pre>\n\n<p>2) Add the library to maven central(<a href=\"https://dzone.com/articles/publish-your-artifacts-to-maven-central\" rel=\"nofollow noreferrer\">publish artifact</a>) or another repository and describe the usage on <code>README.md</code></p>\n\n<p>3) Consider to add Spring boot starter <a href=\"https://www.baeldung.com/spring-boot-custom-starter\" rel=\"nofollow noreferrer\">spring-boot-custom-starter</a></p>\n\n<p>4) Add version compatibility table rstreamer to jedis and resilience4j. </p>\n\n<p>5) It would be nice to have exception handling section with samples and description of errors and best practices to handle them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T15:11:58.287",
"Id": "447633",
"Score": "1",
"body": "Thank you! I will add your ideas to my roadmap. You're welcome to contribute as well."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T13:49:36.180",
"Id": "229977",
"ParentId": "229960",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "229977",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T09:19:55.780",
"Id": "229960",
"Score": "2",
"Tags": [
"java",
"library",
"redis"
],
"Title": "Redis work queue processor"
} | 229960 |
<p>I'd offer a couple of iterator accesses to the class member, both constant and non-constant. I came to the following solution, but it seems to me far more verbose than needed. I'd like somehow to merge the two function members <code>get_c</code>, <code>get_m</code> in some fashion, but I'm not sure if possible.</p>
<pre><code>#include <iostream>
#include <vector>
#include <cstdint>
using my_t = uint64_t;
// Own implementation of 3D-vector. size() == m_X * m_Y * m_Z
class Package
{
// 3D-strides
const size_t m_X = 10, m_Y = 2, m_Z = 4;
public:
std::vector<my_t> m_v;
template <class I>
typename std::enable_if<std::is_same<I, typename std::vector<typename std::iterator_traits<I>::value_type>::iterator>::value, std::vector<my_t>::iterator>::type
get_it(I i, size_t x, size_t y, size_t z)
{
return std::next(i, x * m_X * m_Y + y * m_Z + z);
}
template <class I>
typename std::enable_if<std::is_same<I, typename std::vector<typename std::iterator_traits<I>::value_type>::const_iterator>::value, std::vector<my_t>::const_iterator>::type
get_it(I i, size_t x, size_t y, size_t z) const
{
return std::next(i, x * m_X * m_Y + y * m_Z + z);
}
std::vector<my_t>::iterator
get_m(size_t x, size_t y, size_t z)
{
return get_it(m_v.begin(), x, y, z);
}
std::vector<my_t>::const_iterator
get_c(size_t x, size_t y, size_t z) const
{
return get_it(m_v.cbegin(), x, y, z);
}
Package() : m_v(m_X * m_Y * m_Z, 1)
{}
};
void f_const(const Package & pkg)
{
auto it = pkg.get_c(0, 1, 2);
std::cout << "const: " << *it << "\n";
}
void f_modif(Package & pkg)
{
auto it = pkg.get_m(0, 1, 2);
*it += 10;
std::cout << "modif: " << *it << "\n";
}
int main(int argc, char**argv)
{
Package p;
f_const(p);
f_modif(p);
}
</code></pre>
<p>In other words, I'd like some context-aware <em>single</em> method for access. A two-methods functionally-equivalent solution could be</p>
<pre><code>my_t & operator () (size_t x, size_t y, size_t z) {
return *(m_v.begin() + x * m_X * m_Y + y * m_Z + z);
}
my_t operator () (size_t x, size_t y, size_t z) const {
return *(m_v.cbegin() + x * m_X * m_Y + y * m_Z + z);
}
</code></pre>
<p>No surprise I'm still a novice in metaprogramming, but I'm wondering if this approach has some intrinstic fallacy.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T10:58:19.563",
"Id": "447593",
"Score": "3",
"body": "Could you explain a bit more about what you're trying to do here? It looks like there's no need for the `enable_if` stuff at all. Why not just go with the usual C++ approach of having a const function called `get` returning a `const_iterator`, and non-const function also called `get` returning a plain `iterator`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T11:20:52.237",
"Id": "447596",
"Score": "0",
"body": "I exactly need something akin, but perhaps, as suggested, over-complicated the boilerplate code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T12:58:03.893",
"Id": "447607",
"Score": "0",
"body": "What's the goal of the code? What problem should it solve?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T13:13:26.860",
"Id": "447614",
"Score": "0",
"body": "Code should offer two detailed accesses to 3D data (flattened in a `vector`), where arguments are a triple of coordinates. I'd enforce constness template selection inside functions not allowed to modify their `Package` argument"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T09:27:22.867",
"Id": "229961",
"Score": "1",
"Tags": [
"c++",
"c++11",
"template-meta-programming",
"overloading"
],
"Title": "Overloading both for (non) constant access"
} | 229961 |
<p>I am getting the probability of a string being similar to another string in Python using <code>fuzzywuzzy</code> lib.</p>
<p>Currently, I am doing this using a for loop and the search is time consuming.</p>
<p>Below is working code :</p>
<pre><code>from fuzzywuzzy import fuzz
with open('all_nut_data.csv', newline='') as csvfile:
spamwriter = csv.DictReader(csvfile)
mostsimilarcs = 0
mostsimilarns = 0
for rowdata in spamwriter:
mostsimilarns = fuzz.ratio(rowdata["Food Item"].lower(), name.lower())
if mostsimilarns > mostsimilarcs:
mostsimilarcs = mostsimilarns
row1 = rowdata
</code></pre>
<p>How I can optimize this code without for loop?</p>
<p>Note* CSV file contain 600,000 rows and 17 column</p>
<p><a href="https://i.stack.imgur.com/gd1tU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gd1tU.png" alt="Sample CSV file"></a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T10:04:54.927",
"Id": "447590",
"Score": "1",
"body": "Does the food-item column contain duplicates? Caching might help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T10:24:49.610",
"Id": "447591",
"Score": "0",
"body": "Could you include a snippet of the csv file for testing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T12:00:04.033",
"Id": "447600",
"Score": "0",
"body": "Also, what is `name`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T14:11:58.560",
"Id": "447622",
"Score": "0",
"body": "@AustinHastings Hastings food-item column not contain duplicates value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T14:15:27.590",
"Id": "447624",
"Score": "0",
"body": "@Graipher its any random value like : \"Test\" or \"John\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T14:16:21.383",
"Id": "447625",
"Score": "0",
"body": "@QuantumChris Sure"
}
] | [
{
"body": "<p>This will not be much faster, but more readable (IMO) and extendable. You are looking for the maximum (in similarity). So, use the built-in <code>max</code> function. You can also define a function that does the file reading (so you can swap it out for a list of dictionaries, or whatever, for testing) and a function to be use as <code>key</code>. I made it slightly more complicated than needed here to give some customizability. The word it is compared to is fixed, so it is passed to the outer function, but so is the column name (you could also hard-code that).</p>\n\n<pre><code>import csv\nfrom fuzzywuzzy.fuzz import ratio as fuzz_ratio\n\ndef get_rows(file_name):\n with open(file_name, newline='') as csvfile:\n reader = csv.DictReader(csvfile)\n yield from reader\n\ndef similarity_to(x, column_name):\n x = x.lower()\n def similarity(row):\n return fuzz_ratio(row[column_name].lower(), x)\n return similarity\n\nif __name__ == \"__main__\":\n items = get_rows('all_nut_data.csv')\n name = \"Hayelnut\"\n best_match = max(items, key=similarity_to(name, \"Food Item\"))\n match_quality = similarity_to(name, \"Food Item\")(best_match)\n</code></pre>\n\n<p><code>max</code> ensures that the <code>key</code> function is only called once per element (so no unnecessary calculations). However, since the similarity is not part of the row, you have to calculate it again at the end. On the other hand, I don't call <code>name.lower()</code> every loop iteration.\n Note that <code>get_rows</code> is a generator. This is very nice because you don't need to load the whole file into memory (just like in your code), but if you want to run it multiple times, you need to recreate the generator each time.</p>\n\n<p>In the end the code as currently written can not avoid having to call the function on each row, one at a time. With <code>max</code> at least the iteration is partially done in C and therefore potentially faster, but not by much. For some naive tests, the built-in <code>max</code> is about 30% faster than a simple <code>for</code> loop, like you have.</p>\n\n<p>The only way to get a significant speed increase would be to use a vectorized version of that function. After some digging I found out that internally the <code>fuzzywuzzy</code> just returns the Levenshtein ratio for the two words (after type and bound checking, and then applies some casting and rounding) from the <a href=\"https://pypi.org/project/python-Levenshtein/\" rel=\"nofollow noreferrer\"><code>Levenshtein</code> module</a>. So you could look for different modules that implemented this or try if directly using the underlying method is faster. Unfortunately I have not managed to find a vectorized version of the Levenshtein ratio (or distance) where one word is fixed and the other is not.</p>\n\n<p>However, there is <code>fuzzywuzzy.process.extractOne</code>, which lets you customize the scoring and processing. It might be even faster than the loop run by <code>max</code>:</p>\n\n<pre><code>from fuzzywuzzy import process, fuzz\n\ndef processor(x):\n return x[\"Food Item\"].lower()\n\ndef get_best_match(name, rows):\n name = {\"Food Item\": name}\n return process.extractOne(name, rows,\n scorer=fuzz.ratio, processor=processor)\n\nif __name__ == \"__main__\":\n rows = get_rows('all_nut_data.csv')\n name = \"Hayelnut\"\n best_match, match_quality = get_best_match(name, rows)\n print(best_match, match_quality)\n</code></pre>\n\n<p>The packing of the <code>name</code> in the dictionary is necessary, because the <code>processor</code> is called also on the query.</p>\n\n<p>Using a local dictionary (from the hunspell package), which contains 65867 words, I get the following timings for finding the closest match for <code>\"Hayelnut\"</code>:</p>\n\n<pre><code>OP: 207 ms ± 4.05 ms\nmax: 206 ms ± 8.33 ms\nget_best_match: 221 ms ± 3.77 ms\n</code></pre>\n\n<p>So no real improvement, in fact the last function is even slightly slower! But at least all three determine that <code>\"hazelnut\"</code> is the correct choice in this case.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T12:32:15.610",
"Id": "229967",
"ParentId": "229963",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "229967",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T09:48:37.750",
"Id": "229963",
"Score": "4",
"Tags": [
"python",
"performance"
],
"Title": "How to optimize the for loop for finding a matching 2 string using fuzzywuzzy"
} | 229963 |
<p>Any one suggest me right way to write mapping more then one table using spring-boot (jpa), i was done it, but its required more time to extract result,</p>
<p>Following are the Mapping of Pojo:</p>
<p>First:-</p>
<pre><code>@Entity
@Table(name="DIM_CORPORATE_AND_SERVICE_ATTRIBUTE_MAPPING")
public class ServiceAttributeMapping {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="N_CORPORATE_SERVICE_MAP_SKEY")
private long serviceMapSkey;
@Column(name="V_MAP_WITH")
private String mapWith;
@Column(name="F_LINKED_WITH_MAIN_SERVICE")
private String fLikedWithMainService;
@Column(name="V_STATUS")
private String status;
@Column(name="N_DIM_ATTRIBUTE_OPTION_SKEY")
private Long attOptionSkey;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "N_DIM_CORPORATE_SKEY", referencedColumnName = "N_DIM_CORPORATE_SKEY")
private CorporateServicesDetails corporateSericeDetails;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "N_DIM_ATTRIBUTE_SKEY", referencedColumnName = "N_DIM_ATTRIBUTE_SKEY")
private ServiceAttribute serviceAttribute;
}
</code></pre>
<p>Second Mapping :</p>
<pre><code>@Entity
@Table(name="DIM_CORPORATE_SERVICE_ATTRIBUTE")
public class ServiceAttribute {
@Id
@Column(name="N_DIM_ATTRIBUTE_SKEY")
@GeneratedValue(strategy = GenerationType.AUTO)
private long attributeSkey;
@Column(name="V_ATTRIBUTE_NAME")
private String attributeName;
@Column(name="F_FINAL_ELEMENT")
private String fFinalElement;
@Column(name="V_STATUS")
private Integer status;
@JsonIgnore
@OneToOne(mappedBy="serviceAttribute")
private ServiceAttributeMapping AttributeMapping;
@OneToMany(fetch = FetchType.EAGER,mappedBy="serviceAttribute")
private Set<ServiceAttributeOptions> serviceAttributeOptions;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "N_ATTRIBUTE_TYPE_ID", referencedColumnName = "N_ATTRIBUTE_TYPE_ID")
private AttributeType attributeType;
}
</code></pre>
<p>Third Pojo:</p>
<pre><code>@Entity
@Table(name="DIM_CORPORATE_SERVICE_ATTRIBUTE_OPTIONS")
public class ServiceAttributeOptions {
@Id
@Column(name="N_DIM_ATTRIBUTE_OPTION_SKEY")
@GeneratedValue(strategy=GenerationType.AUTO)
private long optionSkey;
@Column(name="N_ATTRIBUTE_TYPE_ID")
private long attributeTypeId;
@Column(name="V_ATTRIBUTE_OPTION_NAME")
private String optionName;
@Column(name="F_FINAL_ELEMENT")
private String finalElement;
@Column(name="V_STATUS")
private String status;
@ManyToOne(cascade= CascadeType.ALL)
@JoinColumn(name = "N_DIM_ATTRIBUTE_SKEY")
private ServiceAttribute serviceAttribute;
}
</code></pre>
<p>Query :-</p>
<pre><code>@SuppressWarnings("unchecked")
List<CorporateServicesDetails> corporateServiceslist = entityManager.createQuery(
"select r from ServiceAttributeMapping r INNER JOIN r.serviceAttribute i where r.mapWith=:mapWith and r.fLikedWithMainService='Y' and r.status='1' ")
.setParameter("mapWith", "MAIN").getResultList();
return corporateServiceslist;
</code></pre>
<p>Thanks in advance </p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T09:55:19.913",
"Id": "229964",
"Score": "1",
"Tags": [
"java",
"comparative-review",
"spring-mvc",
"jpa"
],
"Title": "Spring Boot - JPA query execution Time"
} | 229964 |
<p>I have the following dictionary:</p>
<pre><code>results_dict = {'Current model': {'Recall': 0.77,
'Precision': 0.1,
'F1_score': 0.18,
'Frauds': 94},
'New model': {'Recall': 0.96,
'Precision': 0.17,
'F1_score': 0.29,
'Frauds': 149}}
</code></pre>
<p>What I want is to make a comparison for each metric between the two models, and in case the one belonging to the new model is better, adding +1 to a variable i. So far, I have made this:</p>
<pre><code>recall_new = results_dict['New model']['Recall']
recall_current = results_dict['Current model']['Recall']
precision_new = results_dict['New model']['Precision']
precision_current = results_dict['Current model']['Precision']
F1_new = results_dict['New model']['F1_score']
F1_current = results_dict['Current model']['F1_score']
frauds_new = results_dict['New model']['Frauds']
frauds_current = results_dict['Current model']['Frauds']
i = 0
if recall_new > recall_current or recall_new > (recall_current-(0.1)):
i+=1
if precision_new > precision_current or precision_new > (precision_current-(0.1)):
i+=1
if F1_new > F1_current or F1_new > (precision_current-(0.1)):
i+=1
if frauds_new > frauds_current or frauds_new > int(round(frauds_current*1.2,0)):
i+=1
</code></pre>
<p>The code makes what is intended to do but it is very verbose and repetitive and I was wondering whether it could be simplified or not. Thank you!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T13:25:23.087",
"Id": "447618",
"Score": "0",
"body": "At your fourth comparison, you're using a variable \"frauds\" that isn't defined. I assume that should be frauds_current?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T13:26:42.687",
"Id": "447619",
"Score": "0",
"body": "Correct. I have edited the question"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T13:56:04.390",
"Id": "447620",
"Score": "2",
"body": "Why do you compare `F1_new > (precision_current-(0.1))`. Shouldn't it be `F1_new > (F1_current-(0.1))`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T15:20:05.253",
"Id": "447635",
"Score": "0",
"body": "Another mistake"
}
] | [
{
"body": "<h3>Index less</h3>\n\n<p>Also, you're indexing a lot. Perhaps it's better to seperate the two dicts:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>old, new = results_dict[\"Current model\"], results_dict[\"New model\"]\n</code></pre>\n\n<p>(And what's up with having an underscore in <code>Current_model</code> and a space in <code>New model</code>? That's asking for typos. You're not even consistent with it - in your first code they're both spaces, but in the assignment you use 3 underscores and a space for <code>Current</code>...)</p>\n\n<p>Also, with how you make the checks, one of your conditions always implies the other. You should remove the redundant comparisons. Change:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if recall_new > recall_current or recall_new > (recall_current-(0.1)):\n# Into:\nif recall_new > recall_current - 0.1:\n</code></pre>\n\n<p>The additional braces don't do anything, and if <code>recall_new</code> is bigger than <code>current-0.1</code>, then it is also bigger than <code>current</code>. </p>\n\n<h3>Loop</h3>\n\n<p>If you look closely, you'll see you're doing the same thing multiple times. So just make it a loop.</p>\n\n<p>Arguably you should make an outside variable for the keys to iterate over, or iterate over the keys of either new or old dict. But if hard-coding is appropriate, it could look a lot like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>new_better = 0 # i is a bad variable name. Names should have meaning.\nfor key in (\"Recall\", \"Precision\", \"F1_score\"):\n if new[key] > old[key]-0.1:\n new_better += 1\nif new[\"Frauds\"] > old[\"Frauds\"]*1.2:\n new_better += 1\n</code></pre>\n\n<p>Note that I removed your rounding. Python has no issues transforming a float to the closest integer by means of <code>int()</code>, but neither does it have a problem with comparing ints to floats. I did notice that your adjustments make it easier to score an increment for the first three variables, but harder for the fourth. Is this intentional?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T13:24:17.097",
"Id": "229974",
"ParentId": "229972",
"Score": "6"
}
},
{
"body": "<p>I'm not convinced your code is <em>too long</em>, but it is verbose in the sense that it's a bit hard to read. To make sense of it one must read many lines in detail and identify the repeated pattern between them. Wrapping things in functions can improve clarity just as much as using a more concise syntax or pattern</p>\n\n<p><a href=\"https://codereview.stackexchange.com/a/229974/200133\">Gloweye</a>'s concern about your choices of dictionary keys is sound. <strong>I'd go further and suggest that this is a good time to write a small <a href=\"https://docs.python.org/3/tutorial/classes.html\" rel=\"nofollow noreferrer\">class</a>.</strong></p>\n\n<p>There are different ways to think about classes and objects. Without getting too deep into the weeds, the thing they offer us here is the ability to express the <em>structure</em> of a \"dictionary\" variable in our code. </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Dict, Union\n\nclass MyModel:\n def __init__(self, recall: float, precision: float, f1: float, frauds: int):\n self.recall = recall\n self.precision = precision\n self.f1 = f1\n self.frauds = frauds\n\n def from_dict(data: Dict[str, Union[int, float]]) -> 'MyModel':\n return MyModel(data['Recall'], data['Precision'], data['F1_score'], data['Frauds'])\n\n def recall_surpassed(self, new: float) -> bool:\n return new > self.recall - 0.1\n\n def precision_surpassed(self, new: float) -> bool:\n return new > self.precision - 0.1\n\n def f1_surpassed(self, new: float) -> bool:\n return new > self.f1 - 0.1\n\n def frauds_surpassed(self, new: float) -> bool:\n return new > self.frauds\n\n def get_improvement_score(self, new: 'MyModel') -> int:\n return (\n int(self.recall_surpassed(new.recall))\n + int(self.precision_surpassed(new.precision))\n + int(self.f1_surpassed(new.f1))\n + int(self.frauds_surpassed(new.frauds))\n )\n</code></pre>\n\n<p>This isn't any more concise than what you'd written, but here the verbosity serves a purpose: it's easier to make sense of the behavior and to find any particular detail because the pieces are split up and labeled. For example, did I get the <code>frauds</code> check right, and if I didn't then how would you fix it?</p>\n\n<p>To use this with your existing nested dicts would be easy enough, because I included <code>from_dict</code> as a helper method:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>i = MyModel.from_dict(\n results_dict['Current model']\n).get_improvement_score(\n MyModel.from_dict(results_dict['New model'])\n)\nprint(i)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T17:58:25.963",
"Id": "447665",
"Score": "1",
"body": "I agree that a class *might* be a good solution, but be on guard for premature optimization. Still +1."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T15:24:06.447",
"Id": "229983",
"ParentId": "229972",
"Score": "4"
}
},
{
"body": "<p>As others have pointed out, your comparison operations are skewed between the <code>Frauds</code> fields and all other fields. Given that the data type appears to be different, I'm going to assume that you're doing the comparison correctly, and it's working as intended.</p>\n\n<p>That said, the numbers you are using to subtract (<code>0.1</code>) appear surprisingly large in relation to the values you are comparing them with. In one case, your initial value is 0.1, so subtracting 0.1 would result in comparing the new value > 0, which might not be what you intended.</p>\n\n<h3>Iterating the keys</h3>\n\n<p>You can use the <a href=\"https://docs.python.org/3/library/stdtypes.html?highlight=dict%20keys#dict.keys\" rel=\"nofollow noreferrer\"><code>dict.keys()</code></a> iterable to get all the keys for one of the dictionaries, and you can use Python's <a href=\"https://docs.python.org/3/reference/expressions.html?highlight=ternary#conditional-expressions\" rel=\"nofollow noreferrer\"><em>conditional expressions</em></a> to evaluate your score.</p>\n\n<p>Combine those together and you get:</p>\n\n<pre><code>def score_results(old, new):\n \"\"\" Return a score based on the number of \n 'improved' fields of the new results over \n the old.\n \"\"\"\n score = 0\n\n for k in new.keys():\n if k == 'Frauds':\n score += 1 if new[k] > int(old[k] * 1.2) else 0\n\n else:\n score += 1 if new[k] > old[k] - 0.1 else 0\n # NOTE: did you mean > old[k] * 0.9 ???\n\n return score\n</code></pre>\n\n<h3>Lambdas and defaults and iterables, oh my!</h3>\n\n<p>You can shorten this by putting your brain in Python-mode and <em>treating code as data</em> using Python's <a href=\"https://stackoverflow.com/a/245208/4029014\">first-class functions</a>. In this case, we'll make use of the <a href=\"https://docs.python.org/3/tutorial/controlflow.html?highlight=lambda#lambda-expressions\" rel=\"nofollow noreferrer\"><em>lambda expression</em></a> syntax, since the things we're doing are so short:</p>\n\n<pre><code>def score_results(old, new):\n \"\"\" Idem. \"\"\"\n\n minor_change = lambda o: o - 0.1 # could be o * 0.9??\n change_funcs = { 'Frauds': lambda o: int(o * 1.2) }\n\n return sum((1 if new[k] > change_funcs.get(k, minor_change)(old[k]) else 0) \n for k in new.keys())\n</code></pre>\n\n<p>In this version, I used the <em>conditional-expression</em> syntax from above to evaluate either 0 or 1 for each key <code>k</code>. I used the <a href=\"https://docs.python.org/3/library/functions.html?highlight=sum#sum\" rel=\"nofollow noreferrer\"><code>sum()</code> built-in</a> to add up the scores. This replaces the <code>for k in new.keys()</code> loop with an iterable. The iterable I chose was the <a href=\"https://www.python.org/dev/peps/pep-0289/#rationale\" rel=\"nofollow noreferrer\"><em>generator expression</em></a> that looped over the <code>k in new.keys()</code>. </p>\n\n<p>I could have used an <code>if</code> clause in the generator expression to skip over the <code>Frauds</code> key. But we don't want to skip it, we want to compute it differently. So instead I built a dictionary where I could look up the keys. Every key would have a default behavior, except for special keys, by using the <a href=\"https://docs.python.org/3/library/stdtypes.html?highlight=dict%20get#dict.get\" rel=\"nofollow noreferrer\"><code>dict.get(key, default)</code></a> method. The special keys in this case are <code>Frauds</code>:</p>\n\n<pre><code>change_funcs.get(k, minor_change)\n</code></pre>\n\n<p>Once I had the special function (for Frauds) or the default function (<code>minor_change</code> for everything except Frauds) I could call it:</p>\n\n<pre><code>change_funcs.get(...)(old[k])\n</code></pre>\n\n<p>And then put it into the comparison with the new key as part of the conditional-expression.</p>\n\n<h3>int(bool) -> {0, 1}</h3>\n\n<p>Another \"shortening\" that could be made is to note that Python converts Boolean values to integers by mapping <code>False</code> to <code>0</code> and <code>True</code> to <code>1</code>. So instead of the conditional expression:</p>\n\n<pre><code>1 if cond else 0\n</code></pre>\n\n<p>we could simply use:</p>\n\n<pre><code>int(cond)\n</code></pre>\n\n<p>This converts our sum expression to:</p>\n\n<pre><code> return sum(int(new[k] > change_funcs.get(k, minor_change)(old[k])) for k in new.keys())\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T07:45:07.943",
"Id": "447762",
"Score": "1",
"body": "You can even do without the `int` and just add booleans directly. bool is a subclass of int."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T18:34:13.933",
"Id": "229991",
"ParentId": "229972",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T13:05:00.430",
"Id": "229972",
"Score": "5",
"Tags": [
"python",
"hash-map"
],
"Title": "Comparison of values in dictionary"
} | 229972 |
<h1> Problem statement (<a href="https://leetcode.com/problems/letter-combinations-of-a-phone-number/" rel="nofollow noreferrer">online source</a>)</h1>
<blockquote>
<p>Given a digit string, return all possible letter combinations that the
number could represent.</p>
<p>A mapping of digit to letters (just like on the telephone buttons) is
given below.</p>
<p>Input: Digit string "23"</p>
<p>Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].</p>
<p>Note:</p>
<p>Although the above answer is in lexicographical order, your answer
could be in any order you want.</p>
</blockquote>
<p>I have seen and read the reviews for the above problem, and made the modifications suggested. I did see the comment on using LINQ, I am learning how to use them and don't fully understand it yet. I successfully submitted my answer to LeetCode, but I would like a review to see what else I can do to improve the code. I noticed the code uses more memory than most submissions on LeetCode and I wonder if I can find out why here. </p>
<p>My code is based on a tutorial I watched. While it was in Java, I typed my code in C#. It recursively calls the method that looks into the objects of a Dictionary and concatenates the data inside them in the desired format. I am new to programming so I looked up stuff online and made some assumptions on equivalent data structures in C#. For example, the original code used a <code>HashMap</code>, and saw a recommendation online to used <code>Dictionary<T, T></code> in C#. </p>
<pre><code>public class Solution {
public IList<string> LetterCombinations(string digits) {
List<String> result = new List<String>();
if (String.IsNullOrEmpty(digits)){
return result;
throw new ArgumentNullException(nameof(digits));
}
Dictionary<Char, Char[]> lettersMap = new Dictionary<Char, char[]>();
lettersMap.Add('1', null);
lettersMap.Add('2', new[] { 'a', 'b', 'c' });
lettersMap.Add('3', new[] { 'd', 'e', 'f' });
lettersMap.Add('4', new[] { 'g', 'h', 'i' });
lettersMap.Add('5', new[] { 'j', 'k', 'l' });
lettersMap.Add('6', new[] { 'm', 'n', 'o' });
lettersMap.Add('7', new[] { 'p', 'q', 'r', 's' });
lettersMap.Add('8', new[] { 't', 'u', 'v' });
lettersMap.Add('9', new[] { 'w', 'x', 'y', 'z' });
lettersMap.Add('0', null);
StringBuilder sb = new StringBuilder();
int pos = 0;
LetterCombinationsFunction(digits, sb, lettersMap, result, pos);
return result;
}
private static List<String> LetterCombinationsFunction(String digits, StringBuilder sb,
Dictionary<Char, Char[]> lettersMap, List<String> result, int pos)
{
if (sb.Length == digits.Count())
{
result.Add(sb.ToString());
return result;
}
lettersMap.TryGetValue(digits[pos], out char[] values);
foreach (var v in values)
{
sb.Append(v);
LetterCombinationsFunction(digits, sb, lettersMap, result, pos+1);
sb.Remove(sb.Length - 1, 1);
}
return result;
}
}
</code></pre>
| [] | [
{
"body": "<p>I have a few other minor thoughts, but the big one is: rather than building the lookup dictionary on each call, since it's the same static and read-only data, presumably forever, make it a class-level member and don't pass it around:</p>\n\n<pre><code> private static readonly IReadOnlyDictionary<char, char[]> _LettersMap = new Dictionary<char, char[]>\n {\n { '1', null },\n { '2', new[] { 'a', 'b', 'c' } },\n { '3', new[] { 'd', 'e', 'f' } },\n { '4', new[] { 'g', 'h', 'i' } },\n { '5', new[] { 'j', 'k', 'l' } },\n { '6', new[] { 'm', 'n', 'o' } },\n { '7', new[] { 'p', 'q', 'r', 's' } },\n { '8', new[] { 't', 'u', 'v' } },\n { '9', new[] { 'w', 'x', 'y', 'z' } },\n { '0', null }\n };\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T17:48:26.370",
"Id": "447663",
"Score": "0",
"body": "C Slicer-Thanks. I'll make the change. This is a great idea."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T15:35:14.833",
"Id": "229984",
"ParentId": "229976",
"Score": "7"
}
},
{
"body": "<h2>Review</h2>\n\n<ul>\n<li><code>LetterCombinations</code> returns an <code>IList<string></code> but I see no reason to return a modifiable collection. Consider returning <code>IEnumerable<string></code> instead.</li>\n<li>A method's name should be a verb. Change <code>LetterCombinations</code> to <code>GetLetterCombinations</code>, <code>FindLetterCombinations</code> or <code>PermutateLetterCombinations</code>.</li>\n<li>You did good by creating a private function that performs the recursion with intermediate parameters. This way, the user of this API only needs to think about the public endpoint. However, it could have used the same name as the public method. An overload would not resulted in a conflict. The postfix <code>*Function</code> is weird.</li>\n<li>Prefer the use of <code>var</code> if the type can be read from code: <code>var lettersMap = new Dictionary<char, char[]>();</code></li>\n<li>You are looking to get familiar with LINQ, however the next statement did not require the LINQ wrapper <code>Count()</code> of a string's <code>Length</code> property: <code>if (sb.Length == digits.Count())</code>.</li>\n<li>Use more consistent indentation for your class members.</li>\n<li>Having the opening curly brace on the same line is ok, but it's more a convention in Java than in C#, where the opening curly brace is usually on the next line.</li>\n<li>See Jesse C. Slicer's answer to move the static data out of the method.</li>\n</ul>\n\n<hr>\n\n<h2>Peculiarities</h2>\n\n<p>Did you plan to return the empty <code>result</code> list or throw an exception on this edge case?</p>\n\n<blockquote>\n<pre><code>if (String.IsNullOrEmpty(digits)){\n return result;\n throw new ArgumentNullException(nameof(digits));\n}\n</code></pre>\n</blockquote>\n\n<p>The next line is followed by a loop over <code>values</code> but doesn't care whether the operation succeeded:</p>\n\n<blockquote>\n<pre><code>lettersMap.TryGetValue(digits[pos], out char[] values);\n</code></pre>\n</blockquote>\n\n<p>Did you plan to write this instead?</p>\n\n<pre><code>if (lettersMap.TryGetValue(digits[pos], out char[] values)) \n{\n // ..\n}\n</code></pre>\n\n<p>You are using both <code>char</code> and <code>Char</code> in the next line. Is there a specific reason to use both these types?</p>\n\n<blockquote>\n<pre><code>Dictionary<Char, Char[]> lettersMap = new Dictionary<Char, char[]>();\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T17:43:30.373",
"Id": "447661",
"Score": "1",
"body": "dfhwze-Thanks. I meant to use Char; I'll change the other instances. re: Exception vs. empty result, I'll remove the empty result. I did see a comment on adding {}'s to if statements, and missed this one. I'll add it. I need to understand IEnumerables much better. I can use them, and in this instance it seems passing one IEnumerable object instead of an entire collection would save me memory space especially once I make the change Jesse C. Slicer mentioned also. I also need to really understand how yield works, beyond the example of MSN docs that is, and how it is used instead of IEnumerable."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T16:12:29.597",
"Id": "229985",
"ParentId": "229976",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "229984",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T13:48:22.050",
"Id": "229976",
"Score": "7",
"Tags": [
"c#",
"beginner",
"programming-challenge",
"recursion",
"combinatorics"
],
"Title": "Letter Combinations of a phone number using a Dictionary"
} | 229976 |
<p>I've just rewritten <a href="https://jsfiddle.net/zpenoyre/Lt0euym5/8/" rel="nofollow noreferrer">this code</a> (a simple gravitational restricted n-body simulation) to display using canvas, rather than SVG. The reason being that I'd like to be able to run it with many thousands of particles.</p>
<p>To my surprise I didn't see any sizable performance improvement after making the conversion. I'm wondering if I've missed some simple step in the implementation, or if I'm misidentifying the bottleneck?</p>
<pre><code> var width=0.5*window.innerWidth || document.body.clientWidth;
var height=width;
//var svg=d3.select("#sim").append("svg");
//svg.attr('width',width)
// .attr('height',height);
var canvas = d3.select('#sim').append('canvas').attr('width', width).attr('height', height);
var context = canvas.node().getContext('2d');
// instead of using svg and storing data in DOM we create a pseudo-DOM (maybe - https://www.freecodecamp.org/news/d3-and-canvas-in-3-steps-8505c8b27444/)
//var customBase = document.createElement('custom');
//var custom = d3.select(customBase); // This is your SVG replacement and the parent of all other elements
var custom = d3.select('#sim').append('custom');
function databind(data) {
var circles = custom.selectAll('custom.circle')
.data(data);
var enterSel = circles.enter()
.append('custom').attr('class', 'circle')
.attr('id',function(d) { return "particle" + d.id; })
.attr('r',function(d) { return d.r; })
.attr('cx', function(d) {return width*(d.x[0]+boxSize)/(2*boxSize);})
.attr('cy', function(d) {return width*(d.x[1]+boxSize)/(2*boxSize);})
.attr('fillStyle', function(d) {return d.c});
circles.merge(enterSel)
.transition()
.attr('cx', function(d) {return width*(d.x[0]+boxSize)/(2*boxSize);})
.attr('cy', function(d) {return width*(d.x[1]+boxSize)/(2*boxSize);})
.attr('fillStyle', function(d) {return d.c});
}
//var join = custom.selectAll('custom.circle') .data(data);
function draw(){
context.clearRect(0, 0, width, height);
var elements = custom.selectAll('custom.circle');
elements.each(function(d,i) {
var node = d3.select(this);
//console.log(node.attr('fillStyle'))
context.beginPath();
context.arc(node.attr('cx'), node.attr('cy'), node.attr('r'), 0, 2*Math.PI);
context.fillStyle = node.attr('fillStyle');
context.fill();
//context.lineWidth = 1;
//context.stroke();
})
}
var info = d3.select('body').append('div')
.style('position', 'absolute')
.style('top', '0')
.style('left', '0')
.style('padding', '5px')
.style('background-color', '#aaa');
var start = d3.now(), t0 = 0, sum = 0, cnt = 0;
var fmt = d3.format(",d");
var G=6.67e-11; // in SI
var mSun=2e30;
var kpc=3e19;
var Gyr=3.15e16;
var Galt=G*(mSun*(Gyr**2))/(kpc**3);
var rHat=[0,0,0];
var a1=[0,0,0];
var a2=[0,0,0];
function gravParticle(){
this.id=0;
this.m=1e6;
this.x=[0,0,0];
this.v=[0,0,0];
this.a=[0,0,0];
this.flag=0;
this.c='black';
this.r=2;
this.smooth=0.1;
}
function gravity(p1,p2){ // calculating and updating the acceleration of a pair of particles
var r=Math.sqrt((p2.x[0]-p1.x[0])**2 + (p2.x[1]-p1.x[1])**2 + (p2.x[2]-p1.x[2])**2 + p1.smooth**2 + p2.smooth**2);
rHat[0]=(p2.x[0]-p1.x[0])/r;
rHat[1]=(p2.x[1]-p1.x[1])/r;
rHat[2]=(p2.x[2]-p1.x[2])/r;
a1[0]=rHat[0]*Galt*p2.m/(r**2);
a1[1]=rHat[1]*Galt*p2.m/(r**2);
a1[2]=rHat[2]*Galt*p2.m/(r**2);
a2[0]=-rHat[0]*Galt*p1.m/(r**2);
a2[1]=-rHat[1]*Galt*p1.m/(r**2);
a2[2]=-rHat[2]*Galt*p1.m/(r**2);
p1.a[0]=p1.a[0]+a1[0];
p1.a[1]=p1.a[1]+a1[1];
p1.a[2]=p1.a[2]+a1[2];
p2.a[0]=p2.a[0]+a2[0];
p2.a[1]=p2.a[1]+a2[1];
p2.a[2]=p2.a[2]+a2[2];
}
function update(ps){
clearAcc(ps)
for (var i=0; i<nParticles; i++){
if (ps[i].flag == 1){
var index=ps[i].id;
for (var j=i+1; j<nParticles; j++){
gravity(ps[i],ps[j]);
}
}
}
}
var boxSize=30;
var ps=[];
var host = new gravParticle();
host.m=1e11;
host.flag=1;
host.c='red';
host.r=20;
host.smooth=1;
var sat = new gravParticle();
sat.m=1e10;
sat.id=1;
sat.flag=1;
sat.x=[20,0,0];
sat.v=[0,-200,0];
sat.r=10;
sat.c='blue';
sat.smooth=0.5;
host.v[1]=-(sat.m/host.m)*sat.v[1];
ps.push(host);
ps.push(sat);
rMin=1;
rMax=20;
var nPassive=100;
for (var i=0;i<nPassive;i++){
var pNew = new gravParticle();
pNew.m=1e11/nPassive;
pNew.id=i+2;
pNew.flag=0;
var theta=Math.PI*Math.random();
var phi=2*Math.PI*Math.random();
var r=rMin+Math.random()*(rMax - rMin);
pNew.x=[r*Math.cos(phi)*Math.sin(theta),r*Math.sin(phi)*Math.sin(theta),r*Math.cos(theta)];
var vTheta=Math.PI*Math.random();
var vPhi=2*Math.PI*Math.random();
var v=Math.sqrt(Galt*1e11/r);
pNew.v=[v*Math.cos(vPhi)*Math.sin(vTheta),v*Math.sin(vPhi)*Math.sin(vTheta),v*Math.cos(vTheta)];
//pNew.v=[150*randn_bm(),150*randn_bm(),150*randn_bm()];
pNew.smooth=0.1;
ps.push(pNew);
}
var nParticles=ps.length;
//var circles=custom.selectAll(".node")
// .data(ps)
// .enter()
// .append('circle')
// .attr('id',function(d) { return "particle" + d.id; })
// .attr('r',function(d) { return d.r; })
// .style("fill", function(d) {return d.c})
// .attr('cx', function(d) {return width*(d.x[0]+boxSize)/(2*boxSize);})
// .attr('cy', function(d) {return width*(d.x[1]+boxSize)/(2*boxSize);});
var dt=0.001;
update(ps);
databind(ps);
draw();
var t=0;
function evolve() {
for (var i=0; i< nParticles; i++){
ps[i].v[0]=ps[i].v[0]+ps[i].a[0]*dt/2;
ps[i].v[1]=ps[i].v[1]+ps[i].a[1]*dt/2;
ps[i].v[2]=ps[i].v[2]+ps[i].a[2]*dt/2;
ps[i].x[0]=ps[i].x[0]+ps[i].v[0]*dt;
ps[i].x[1]=ps[i].x[1]+ps[i].v[1]*dt;
ps[i].x[2]=ps[i].x[2]+ps[i].v[2]*dt;
}
update(ps); // finds new acceleration
for (var i=0; i < nParticles; i++){
ps[i].v[0]=ps[i].v[0]+ps[i].a[0]*dt/2;
ps[i].v[1]=ps[i].v[1]+ps[i].a[1]*dt/2;
ps[i].v[2]=ps[i].v[2]+ps[i].a[2]*dt/2;
//if (i>1000) {continue;}
var thisCircle=d3.select('#particle'+ps[i].id);
thisCircle
.attr('cx', function(d) {return width*(d.x[0]+boxSize)/(2*boxSize);})
.attr('cy',function(d) {return width*(d.x[1]+boxSize)/(2*boxSize);})
.style("fill", function(d) {
if (d.flag==0){ return d3.interpolateSpectral((d.x[2]+boxSize)/(2*boxSize))}
return d.c
})
}
draw();
t = d3.now();
var fps = 1000 / (t - t0);
info.html(fmt(fps) + " fps = " + fmt(fps) + ' frames/sec');
t0=t;
}
function clearAcc(ps){ // clearing old accelerations at each step
for (var i = 0; i < ps.length; i++) {
ps[i].a=[0,0,0];
}
}
var startStop=1
document.body.onkeyup = function(e){
if(e.keyCode == 32){
startStop=(startStop+1)%2
if (startStop==0) {timer.stop();}
if (startStop==1) {timer.restart(evolve,1000/60);}
}
}
var timer=d3.interval(evolve,1000/60);
// Standard Normal variate using Box-Muller transform.
function randn_bm() {
var u = 0, v = 0;
while(u === 0) u = Math.random(); //Converting [0,1) to (0,1)
while(v === 0) v = Math.random();
return Math.sqrt( -2.0 * Math.log( u ) ) * Math.cos( 2.0 * Math.PI * v );
}
</code></pre>
| [] | [
{
"body": "<p>Before anything else, the tutorial you're referencing is this: <a href=\"https://www.freecodecamp.org/news/d3-and-canvas-in-3-steps-8505c8b27444/\" rel=\"nofollow noreferrer\">https://www.freecodecamp.org/news/d3-and-canvas-in-3-steps-8505c8b27444/</a></p>\n\n<p>By reading the tutorial you'll see that the elements we'll create for manipulating the <code><canvas></code>...</p>\n\n<blockquote>\n <p>... don’t live in the DOM but only in memory (in a ‘virtual’ DOM) and describe the life-cycle of these elements in a known D3 way.</p>\n</blockquote>\n\n<p>However, this is what you did in your code:</p>\n\n<pre><code>var custom = d3.select('#sim').append('custom');\n</code></pre>\n\n<p>By doing that, you're <strong>actually appending</strong> a meaningless element called <code><custom></code> to the DOM! If you inspect your page you'll see thousands of them:</p>\n\n<pre><code><div class=\"sim\" id=\"sim\">\n <canvas width=\"615\" height=\"615\"></canvas>\n <custom>\n <custom class=\"circle\" id=\"particle0\" r=\"20\" cx=\"307.5\" cy=\"307.5\" fillstyle=\"red\"></custom>\n <custom class=\"circle\" id=\"particle1\" r=\"10\" cx=\"512.5\" cy=\"307.5\" fillstyle=\"blue\"></custom>\n <custom class=\"circle\" id=\"particle2\" r=\"2\" cx=\"313.23860812263854\" cy=\"267.5420080575814\" fillstyle=\"black\"></custom>\n <custom class=\"circle\" id=\"particle3\" r=\"2\" cx=\"210.56926409724912\" cy=\"223.62781812619318\" fillstyle=\"black\"></custom>\n etc...\n </custom>\n</div>\n</code></pre>\n\n<p>Because of that you're missing the whole point of using HTML canvas instead of SVG, and losing all its performance. In other words: you changed SVG for canvas but you're still appending and manipulating DOM elements, which is the very drawback of SVGs.</p>\n\n<h2>Using D3 with HTML canvas</h2>\n\n<p>Just like the tutorial you mentioned in your question, create an element <strong>without appending it</strong>:</p>\n\n<pre><code>var customBase = document.createElement('custom');\n\nvar custom = d3.select(customBase);\n</code></pre>\n\n<p>That's, by far, the most important change here. But there are other needed changes as well:</p>\n\n<p>You don't need to draw anything in your enter/update selection, therefore you don't need to set attributes to them. The important thing here is entering/updating the elements and binding data to them. </p>\n\n<p>That being said, it can be just:</p>\n\n<pre><code>function databind(data) {\n var circles = custom.selectAll('custom')\n .data(data);\n var enterSel = circles.enter()\n .append('custom');\n circles = circles.merge(enterSel);\n}\n</code></pre>\n\n<p>By the way, you're missing an exit selection here. I don't know if missed it on purpose or not.</p>\n\n<p>Then, after simplifying your selections, use the datum in the <code>draw</code> function itself:</p>\n\n<pre><code>function draw() {\n context.clearRect(0, 0, width, height);\n custom.selectAll('custom').each(function(d, i) {\n context.beginPath();\n context.arc(width * (d.x[0] + boxSize) / (2 * boxSize), width * (d.x[1] + boxSize) / (2 * boxSize), d.r, 0, 2 * Math.PI);\n context.fillStyle = d.c;\n context.fill();\n })\n}\n</code></pre>\n\n<p>With these changes we get a solid 30-35 fps, way better than your 13-14fps:</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>var width = window.innerWidth || document.body.clientWidth;\nvar height = width;\n\nvar canvas = d3.select('#sim').append('canvas').attr('width', width).attr('height', height);\nvar context = canvas.node().getContext('2d');\n\nvar customBase = document.createElement('custom');\n\nvar custom = d3.select(customBase);\n\nfunction databind(data) {\n var circles = custom.selectAll('custom')\n .data(data);\n var enterSel = circles.enter()\n .append('custom');\n circles = circles.merge(enterSel);\n}\n//var join = custom.selectAll('custom.circle') .data(data);\nfunction draw() {\n context.clearRect(0, 0, width, height);\n custom.selectAll('custom').each(function(d, i) {\n context.beginPath();\n context.arc(width * (d.x[0] + boxSize) / (2 * boxSize), width * (d.x[1] + boxSize) / (2 * boxSize), d.r, 0, 2 * Math.PI);\n context.fillStyle = d.c;\n context.fill();\n })\n}\n\nvar info = d3.select('body').append('div')\n .style('position', 'absolute')\n .style('top', '0')\n .style('left', '0')\n .style('padding', '5px')\n .style('background-color', '#aaa');\nvar start = d3.now(),\n t0 = 0,\n sum = 0,\n cnt = 0;\nvar fmt = d3.format(\",d\");\n\nvar G = 6.67e-11; // in SI\nvar mSun = 2e30;\nvar kpc = 3e19;\nvar Gyr = 3.15e16;\nvar Galt = G * (mSun * (Gyr ** 2)) / (kpc ** 3);\n\nvar rHat = [0, 0, 0];\nvar a1 = [0, 0, 0];\nvar a2 = [0, 0, 0];\n\nfunction gravParticle() {\n this.id = 0;\n this.m = 1e6;\n this.x = [0, 0, 0];\n this.v = [0, 0, 0];\n this.a = [0, 0, 0];\n this.flag = 0;\n this.c = 'black';\n this.r = 2;\n this.smooth = 0.1;\n}\n\nfunction gravity(p1, p2) { // calculating and updating the acceleration of a pair of particles\n var r = Math.sqrt((p2.x[0] - p1.x[0]) ** 2 + (p2.x[1] - p1.x[1]) ** 2 + (p2.x[2] - p1.x[2]) ** 2 + p1.smooth ** 2 + p2.smooth ** 2);\n\n rHat[0] = (p2.x[0] - p1.x[0]) / r;\n rHat[1] = (p2.x[1] - p1.x[1]) / r;\n rHat[2] = (p2.x[2] - p1.x[2]) / r;\n\n a1[0] = rHat[0] * Galt * p2.m / (r ** 2);\n a1[1] = rHat[1] * Galt * p2.m / (r ** 2);\n a1[2] = rHat[2] * Galt * p2.m / (r ** 2);\n\n a2[0] = -rHat[0] * Galt * p1.m / (r ** 2);\n a2[1] = -rHat[1] * Galt * p1.m / (r ** 2);\n a2[2] = -rHat[2] * Galt * p1.m / (r ** 2);\n\n p1.a[0] = p1.a[0] + a1[0];\n p1.a[1] = p1.a[1] + a1[1];\n p1.a[2] = p1.a[2] + a1[2];\n\n p2.a[0] = p2.a[0] + a2[0];\n p2.a[1] = p2.a[1] + a2[1];\n p2.a[2] = p2.a[2] + a2[2];\n}\n\nfunction update(ps) {\n clearAcc(ps)\n for (var i = 0; i < nParticles; i++) {\n if (ps[i].flag == 1) {\n var index = ps[i].id;\n for (var j = i + 1; j < nParticles; j++) {\n gravity(ps[i], ps[j]);\n }\n }\n }\n}\nvar boxSize = 30;\nvar ps = [];\nvar host = new gravParticle();\nhost.m = 1e11;\nhost.flag = 1;\nhost.c = 'red';\nhost.r = 20;\nhost.smooth = 1;\nvar sat = new gravParticle();\nsat.m = 1e10;\nsat.id = 1;\nsat.flag = 1;\nsat.x = [20, 0, 0];\nsat.v = [0, -200, 0];\nsat.r = 10;\nsat.c = 'blue';\nsat.smooth = 0.5;\nhost.v[1] = -(sat.m / host.m) * sat.v[1];\nps.push(host);\nps.push(sat);\nrMin = 1;\nrMax = 20;\nvar nPassive = 5000;\nfor (var i = 0; i < nPassive; i++) {\n var pNew = new gravParticle();\n pNew.m = 1e11 / nPassive;\n pNew.id = i + 2;\n pNew.flag = 0;\n var theta = Math.PI * Math.random();\n var phi = 2 * Math.PI * Math.random();\n var r = rMin + Math.random() * (rMax - rMin);\n pNew.x = [r * Math.cos(phi) * Math.sin(theta), r * Math.sin(phi) * Math.sin(theta), r * Math.cos(theta)];\n\n var vTheta = Math.PI * Math.random();\n var vPhi = 2 * Math.PI * Math.random();\n var v = Math.sqrt(Galt * 1e11 / r);\n pNew.v = [v * Math.cos(vPhi) * Math.sin(vTheta), v * Math.sin(vPhi) * Math.sin(vTheta), v * Math.cos(vTheta)];\n //pNew.v=[150*randn_bm(),150*randn_bm(),150*randn_bm()];\n pNew.smooth = 0.1;\n ps.push(pNew);\n}\n\nvar nParticles = ps.length;\n\nvar dt = 0.001;\n\nupdate(ps);\ndatabind(ps);\ndraw();\n\nvar t = 0;\n\nfunction evolve() {\n for (var i = 0; i < nParticles; i++) {\n ps[i].v[0] = ps[i].v[0] + ps[i].a[0] * dt / 2;\n ps[i].v[1] = ps[i].v[1] + ps[i].a[1] * dt / 2;\n ps[i].v[2] = ps[i].v[2] + ps[i].a[2] * dt / 2;\n\n ps[i].x[0] = ps[i].x[0] + ps[i].v[0] * dt;\n ps[i].x[1] = ps[i].x[1] + ps[i].v[1] * dt;\n ps[i].x[2] = ps[i].x[2] + ps[i].v[2] * dt;\n }\n update(ps); // finds new acceleration\n for (var i = 0; i < nParticles; i++) {\n ps[i].v[0] = ps[i].v[0] + ps[i].a[0] * dt / 2;\n ps[i].v[1] = ps[i].v[1] + ps[i].a[1] * dt / 2;\n ps[i].v[2] = ps[i].v[2] + ps[i].a[2] * dt / 2;\n //if (i>1000) {continue;}\n\n var thisCircle = d3.select('#particle' + ps[i].id);\n thisCircle\n .attr('cx', function(d) {\n return width * (d.x[0] + boxSize) / (2 * boxSize);\n })\n .attr('cy', function(d) {\n return width * (d.x[1] + boxSize) / (2 * boxSize);\n })\n .style(\"fill\", function(d) {\n return d.c\n })\n }\n draw();\n t = d3.now();\n var fps = 1000 / (t - t0);\n info.html(fmt(fps) + \" fps = \" + fmt(fps) + ' frames/sec');\n t0 = t;\n}\n\nfunction clearAcc(ps) { // clearing old accelerations at each step\n for (var i = 0; i < ps.length; i++) {\n ps[i].a = [0, 0, 0];\n }\n}\n\nvar startStop = 1\ndocument.body.onkeyup = function(e) {\n if (e.keyCode == 32) {\n startStop = (startStop + 1) % 2\n if (startStop == 0) {\n timer.stop();\n }\n if (startStop == 1) {\n timer.restart(evolve, 1000 / 60);\n }\n }\n}\nvar timer = d3.interval(evolve, 1000 / 60);\n\n// Standard Normal variate using Box-Muller transform.\nfunction randn_bm() {\n var u = 0,\n v = 0;\n while (u === 0) u = Math.random(); //Converting [0,1) to (0,1)\n while (v === 0) v = Math.random();\n return Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>div.container {\n display: flex;\n /* Magic begins */\n flex-direction: row;\n width: 100vw;\n height: 50vw;\n}\n\ndiv.sim {\n flex-grow: 1;\n width: 50%;\n}\n\ndiv .link {\n stroke: #bbb;\n}\n\n.node circle {\n stroke-width: 2px;\n r: 2px\n}\n\n* {\n margin: 0;\n padding: 0;\n}\n\ndiv.text {\n flex-grow: 1;\n width: 50%;\n padding-left: 5%;\n padding-right: 1%;\n align-self: flex-end;\n text-align: right;\n font-family: Futura, \"Trebuchet MS\", Arial, sans-serif;\n font-weight: bold;\n color: black;\n}\n\nh1 {\n margin: 3%;\n font-size: 32px;\n}\n\nh2 {\n margin: 3%;\n font-size: 14px;\n}\n\np {\n margin: 3%;\n font-size: 16px;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js\"></script>\n<div class=\"container\">\n <div class=\"sim\" id=\"sim\"> </div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Bear in mind that this is just the beginning, there is room for lots of improvements (both D3 related and general JavaScript good practices, like using <code>let</code> and <code>const</code>). For instance, if you remove that ID selection inside <code>evolve</code> (whose purpose is not clear for me), we get something around <strong>50 fps</strong>:</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>var width = window.innerWidth || document.body.clientWidth;\nvar height = width;\n\nvar canvas = d3.select('#sim').append('canvas').attr('width', width).attr('height', height);\nvar context = canvas.node().getContext('2d');\n\nvar customBase = document.createElement('custom');\n\nvar custom = d3.select(customBase);\n\n//var join = custom.selectAll('custom.circle') .data(data);\nfunction draw(data) {\n var circles = custom.selectAll('custom')\n .data(data);\n var enterSel = circles.enter()\n .append('custom');\n circles = circles.merge(enterSel);\n context.clearRect(0, 0, width, height);\n circles.each(function(d, i) {\n context.beginPath();\n context.arc(width * (d.x[0] + boxSize) / (2 * boxSize), width * (d.x[1] + boxSize) / (2 * boxSize), d.r, 0, 2 * Math.PI);\n context.fillStyle = d.c;\n context.fill();\n })\n}\n\nvar info = d3.select('body').append('div')\n .style('position', 'absolute')\n .style('top', '0')\n .style('left', '0')\n .style('padding', '5px')\n .style('background-color', '#aaa');\nvar start = d3.now(),\n t0 = 0,\n sum = 0,\n cnt = 0;\nvar fmt = d3.format(\",d\");\n\nvar G = 6.67e-11; // in SI\nvar mSun = 2e30;\nvar kpc = 3e19;\nvar Gyr = 3.15e16;\nvar Galt = G * (mSun * (Gyr ** 2)) / (kpc ** 3);\n\nvar rHat = [0, 0, 0];\nvar a1 = [0, 0, 0];\nvar a2 = [0, 0, 0];\n\nfunction gravParticle() {\n this.id = 0;\n this.m = 1e6;\n this.x = [0, 0, 0];\n this.v = [0, 0, 0];\n this.a = [0, 0, 0];\n this.flag = 0;\n this.c = 'black';\n this.r = 2;\n this.smooth = 0.1;\n}\n\nfunction gravity(p1, p2) { // calculating and updating the acceleration of a pair of particles\n var r = Math.sqrt((p2.x[0] - p1.x[0]) ** 2 + (p2.x[1] - p1.x[1]) ** 2 + (p2.x[2] - p1.x[2]) ** 2 + p1.smooth ** 2 + p2.smooth ** 2);\n\n rHat[0] = (p2.x[0] - p1.x[0]) / r;\n rHat[1] = (p2.x[1] - p1.x[1]) / r;\n rHat[2] = (p2.x[2] - p1.x[2]) / r;\n\n a1[0] = rHat[0] * Galt * p2.m / (r ** 2);\n a1[1] = rHat[1] * Galt * p2.m / (r ** 2);\n a1[2] = rHat[2] * Galt * p2.m / (r ** 2);\n\n a2[0] = -rHat[0] * Galt * p1.m / (r ** 2);\n a2[1] = -rHat[1] * Galt * p1.m / (r ** 2);\n a2[2] = -rHat[2] * Galt * p1.m / (r ** 2);\n\n p1.a[0] = p1.a[0] + a1[0];\n p1.a[1] = p1.a[1] + a1[1];\n p1.a[2] = p1.a[2] + a1[2];\n\n p2.a[0] = p2.a[0] + a2[0];\n p2.a[1] = p2.a[1] + a2[1];\n p2.a[2] = p2.a[2] + a2[2];\n}\n\nfunction update(ps) {\n clearAcc(ps)\n for (var i = 0; i < nParticles; i++) {\n if (ps[i].flag == 1) {\n var index = ps[i].id;\n for (var j = i + 1; j < nParticles; j++) {\n gravity(ps[i], ps[j]);\n }\n }\n }\n}\nvar boxSize = 30;\nvar ps = [];\nvar host = new gravParticle();\nhost.m = 1e11;\nhost.flag = 1;\nhost.c = 'red';\nhost.r = 20;\nhost.smooth = 1;\nvar sat = new gravParticle();\nsat.m = 1e10;\nsat.id = 1;\nsat.flag = 1;\nsat.x = [20, 0, 0];\nsat.v = [0, -200, 0];\nsat.r = 10;\nsat.c = 'blue';\nsat.smooth = 0.5;\nhost.v[1] = -(sat.m / host.m) * sat.v[1];\nps.push(host);\nps.push(sat);\nrMin = 1;\nrMax = 20;\nvar nPassive = 5000;\nfor (var i = 0; i < nPassive; i++) {\n var pNew = new gravParticle();\n pNew.m = 1e11 / nPassive;\n pNew.id = i + 2;\n pNew.flag = 0;\n var theta = Math.PI * Math.random();\n var phi = 2 * Math.PI * Math.random();\n var r = rMin + Math.random() * (rMax - rMin);\n pNew.x = [r * Math.cos(phi) * Math.sin(theta), r * Math.sin(phi) * Math.sin(theta), r * Math.cos(theta)];\n\n var vTheta = Math.PI * Math.random();\n var vPhi = 2 * Math.PI * Math.random();\n var v = Math.sqrt(Galt * 1e11 / r);\n pNew.v = [v * Math.cos(vPhi) * Math.sin(vTheta), v * Math.sin(vPhi) * Math.sin(vTheta), v * Math.cos(vTheta)];\n //pNew.v=[150*randn_bm(),150*randn_bm(),150*randn_bm()];\n pNew.smooth = 0.1;\n ps.push(pNew);\n}\n\nvar nParticles = ps.length;\n\nvar dt = 0.001;\n\nupdate(ps);\ndraw(ps);\n\nvar t = 0;\n\nfunction evolve() {\n for (var i = 0; i < nParticles; i++) {\n ps[i].v[0] = ps[i].v[0] + ps[i].a[0] * dt / 2;\n ps[i].v[1] = ps[i].v[1] + ps[i].a[1] * dt / 2;\n ps[i].v[2] = ps[i].v[2] + ps[i].a[2] * dt / 2;\n\n ps[i].x[0] = ps[i].x[0] + ps[i].v[0] * dt;\n ps[i].x[1] = ps[i].x[1] + ps[i].v[1] * dt;\n ps[i].x[2] = ps[i].x[2] + ps[i].v[2] * dt;\n }\n update(ps); // finds new acceleration\n for (var i = 0; i < nParticles; i++) {\n ps[i].v[0] = ps[i].v[0] + ps[i].a[0] * dt / 2;\n ps[i].v[1] = ps[i].v[1] + ps[i].a[1] * dt / 2;\n ps[i].v[2] = ps[i].v[2] + ps[i].a[2] * dt / 2;\n //if (i>1000) {continue;}\n }\n draw(ps);\n t = d3.now();\n var fps = 1000 / (t - t0);\n info.html(fmt(fps) + \" fps = \" + fmt(fps) + ' frames/sec');\n t0 = t;\n}\n\nfunction clearAcc(ps) { // clearing old accelerations at each step\n for (var i = 0; i < ps.length; i++) {\n ps[i].a = [0, 0, 0];\n }\n}\n\nvar startStop = 1\ndocument.body.onkeyup = function(e) {\n if (e.keyCode == 32) {\n startStop = (startStop + 1) % 2\n if (startStop == 0) {\n timer.stop();\n }\n if (startStop == 1) {\n timer.restart(evolve, 1000 / 60);\n }\n }\n}\nvar timer = d3.interval(evolve, 1000 / 60);\n\n// Standard Normal variate using Box-Muller transform.\nfunction randn_bm() {\n var u = 0,\n v = 0;\n while (u === 0) u = Math.random(); //Converting [0,1) to (0,1)\n while (v === 0) v = Math.random();\n return Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>div.container {\n display: flex;\n /* Magic begins */\n flex-direction: row;\n width: 100vw;\n height: 50vw;\n}\n\ndiv.sim {\n flex-grow: 1;\n width: 50%;\n}\n\ndiv .link {\n stroke: #bbb;\n}\n\n.node circle {\n stroke-width: 2px;\n r: 2px\n}\n\n* {\n margin: 0;\n padding: 0;\n}\n\ndiv.text {\n flex-grow: 1;\n width: 50%;\n padding-left: 5%;\n padding-right: 1%;\n align-self: flex-end;\n text-align: right;\n font-family: Futura, \"Trebuchet MS\", Arial, sans-serif;\n font-weight: bold;\n color: black;\n}\n\nh1 {\n margin: 3%;\n font-size: 32px;\n}\n\nh2 {\n margin: 3%;\n font-size: 14px;\n}\n\np {\n margin: 3%;\n font-size: 16px;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js\"></script>\n<div class=\"container\">\n <div class=\"sim\" id=\"sim\"> </div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-13T04:20:18.123",
"Id": "230627",
"ParentId": "229981",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "230627",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T14:38:11.423",
"Id": "229981",
"Score": "2",
"Tags": [
"javascript",
"canvas",
"physics",
"d3.js",
"svg"
],
"Title": "d3.js canvas performance"
} | 229981 |
<h3>Heap Sort</h3>
<p>A Binary Heap is a Complete Binary Tree where the items are stored in a special order such that the value in a parent node is greater or smaller than the two values in the children nodes. </p>
<p>Heap Sort is a comparison-based sorting algorithm — somewhat similar to selection sort — which divides a list into sorted and unsorted parts, then it iteratively shrinks the unsorted part by extracting the largest value and moving that to the sorted part. The improvement consists of the usage of a heap data structure rather than a linear-time search to find the maximum.</p>
<hr>
<h3>Binary Tree Sort</h3>
<p>A Binary Tree Sort is an algorithm that builds a binary search tree from the elements to be sorted, and then traverses the tree (in-order) so that the elements come out in sorted order. </p>
<p>Average Case Time Complexity : <span class="math-container">\$O(N\: log N)\$</span> adding one element to a Binary Search Tree on average takes <span class="math-container">\$O(log N)\$</span> time (height of a tree). Therefore, adding <span class="math-container">\$n\$</span> elements will take <span class="math-container">\$O(N\: log N)\$</span> time. </p>
<p>Worst Case Time Complexity : <span class="math-container">\$O(N^2)\$</span>. The worst case can be improved by using a self-balancing binary search tree, which will take <span class="math-container">\$O(N\: log N)\$</span> time to sort the array in worst case.</p>
<hr>
<p>Just for practicing OOP, I've implemented the above algorithms, and if you'd like to review the code and provide any change/improvement recommendations (especially I'm not still sure how to design exception handler for each class), please do so, and I appreciate that.</p>
<h2><a href="https://ideone.com/avkKvC0" rel="nofollow noreferrer">ideone.com Demo (Python)</a></h2>
<hr>
<h3>Code</h3>
<pre><code>'''
This module combines Tree Sorting Algorithms, just for practicing OOP in Python.
It is an imaginary problem to solve assuming that we should use OOP to write these algorithms, even if that'd be unnecessary.
Currently it has a __super__ class TreeSortingAlgorithms
with two internal HeapSort and BinarySort classes, each with their own internal classes.
I'm not sure how to design an OOP exception handling for each class or for the entire module.
'''
# imports random for testing the algorithms
import random
# imports TypeVar and List typings for type hinting
from typing import List, TypeVar
# Instantiates the TypeVar
T = TypeVar('T')
class TreeSortingAlgorithms:
'''This super class has two subclasses of HeapSort and BinarySort.'''
class HeapSort:
'''HeapSort gets an input list, uses iterative or recursive bottom-up approaches
and sorts the input list.
'''
class ExceptionHandling(Exception):
'''This class is supposed to handle the exceptions for Heap Sort, not yet though'''
pass
def heap_sort(input_list: List[T], input_size: int) -> None:
'''
Sorts a numerical list in an ascending order
e.g., [None, 5, 3.1, 2, 9] to [None, 2, 3.1, 5, 9]
Input list is a list which has a None first element at index 0
The zero index is just set to None for simplicity.
'''
TreeSortingAlgorithms.HeapSort.buttom_up_heap_sort(
input_list, input_size)
while input_size > 1:
# Assigns the max value of the heap
max_value = input_list[1]
# Swaps the max value with the last element value
input_list[1], input_list[input_size] = input_list[input_size], max_value
# Increments
input_size -= 1
# Restores down the first element
TreeSortingAlgorithms.HeapSort.restore_down(
1, input_list, input_size)
def buttom_up_heap_sort(input_list: List[T], input_size: int) -> None:
'''
Builds the heap sort using bottom up approach
'''
heap_index = input_size // 2
while heap_index >= 1:
# Restores down the element
TreeSortingAlgorithms.HeapSort.restore_down(
heap_index, input_list, input_size)
# Increments
heap_index -= 1
def restore_down(heap_index: int, input_list: List[T], input_size: int) -> None:
'''
Restores down the element
'''
# Assigns the item value
heap_value = input_list[heap_index]
# Assigns the left and right child indices
left_child_index, right_child_index = 2 * heap_index, 2 * heap_index + 1
while right_child_index <= input_size:
if heap_value >= input_list[right_child_index] and heap_value >= input_list[left_child_index]:
input_list[heap_index] = heap_value
return
elif input_list[left_child_index] > input_list[right_child_index]:
input_list[heap_index], heap_index = input_list[left_child_index], left_child_index
else:
input_list[heap_index], heap_index = input_list[right_child_index], right_child_index
# Assigns the left and right child indices
left_child_index, right_child_index = 2 * heap_index, 2 * heap_index + 1
if left_child_index == input_size and heap_value < input_list[left_child_index]:
input_list[heap_index], heap_index = input_list[left_child_index], left_child_index
input_list[heap_index] = heap_value
class BinarySort:
'''Binary Sort class has a class of Node, an ExceptionHandling class (to be written),
and the following methods:
is_empty: returns boolean if the tree is empty
recursive_insert: recursively insert the new values in the tree
iterative_insert: iteratively insert the new values in the tree'''
def __init__(self) -> None:
'''
Initializes the Root Node of the Binary Tree to None;
'''
self.root: BinarySort = None
class ExceptionHandling(Exception):
'''This class is supposed to handle the exceptions for Binary Sort, not yet though'''
pass
class Node:
'''This class instantiate the Node'''
def __init__(self, node_value: float) -> None:
'''
Initializes a node with three attributes;
`node_value` (Node Value): Must be an float;
`right_child` (Right Child): Initializes to `None`; Its value must be larger than the Root Node;
`left_child` (Left Child): Initializes to `None`; Its value must be smaller than the Root Node;
'''
self.node_value: Node = node_value
self.right_child: Node = None
self.left_child: Node = None
def is_empty(self) -> bool:
'''
Returns True if the tree doesn't have a node;
'''
return self.root is None
def recursive_insert(self, new_value: float) -> None:
'''
Recursively inserts an float-value Node in the Tree;
'''
self.root = self._recursive_insert(self.root, new_value)
def _recursive_insert(self, parent_node: Node, new_value: float) -> Node:
'''
Inserts an float value in the left or right Node;
Returns the parent Node;
'''
# If the parent node is none
if parent_node is None:
parent_node = TreeSortingAlgorithms.BinarySort.Node(new_value)
# If the new Node value is smaller than its parent Node value
elif new_value < parent_node.node_value:
parent_node.left_child = self._recursive_insert(
parent_node.left_child, new_value)
# If the new Node value is bigger than its parent Node value
else:
parent_node.right_child = self._recursive_insert(
parent_node.right_child, new_value)
return parent_node
def iterative_insert(self, new_value: float) -> None:
'''Iteratively inserts a new value as a Node in the Binary Search Tree'''
new_node = TreeSortingAlgorithms.BinarySort.Node(new_value)
# If tree is not empty
if TreeSortingAlgorithms.BinarySort().is_empty():
# Assigns the parent node to the Root
parent_node = self.root
while True:
# If the new value is smaller than the parent node value
if new_value < parent_node.node_value:
# If parent node has a left child
if parent_node.left_child:
parent_node = parent_node.left_child
# If parent node doesn't have a left child
else:
parent_node.left_child = new_node
break
# If the new value is not smaller than the parent node value
else:
# If parent node has a right child
if parent_node.right_child:
parent_node = parent_node.right_child
else:
# If parent node doesn't have a right child
parent_node.right_child = new_node
break
return
self.root = new_node
def __iter__(self) -> None:
'''
Calls the _inorder traversing method recursively;
'''
self._inorder(self.root)
def _inorder(self, parent_node: Node) -> None:
'''
Traverses the tree inorder (Left Node, Root Node, Right Node)
'''
if parent_node is None:
return
# Recurse the left node
self._inorder(parent_node.left_child)
# Prints the parent node
print(parent_node.node_value)
# Recurse the right node
self._inorder(parent_node.right_child)
if __name__ == '__main__':
# -------------------------------------------------------------------------
# ---------------------------- Binary Sort Tests ---------------------------
# -------------------------------------------------------------------------
tree = TreeSortingAlgorithms.BinarySort()
delimiter = '-' * 50
# -------------------------- Recursive Test --------------------------
print('Recursive Binary Search Tree outputs: ')
for i in range(random.randint(20, 30)):
tree.recursive_insert(random.uniform(-10, 10))
tree.__iter__()
# -------------------------- Iterative Test --------------------------
print('Iterative Binary Search Tree outputs: ')
for i in range(random.randint(20, 30)):
tree.iterative_insert(random.uniform(-10, 10))
tree.__iter__()
# -------------------------------------------------------------------------
# ---------------------------- Heap Sort Tests ---------------------------
# -------------------------------------------------------------------------
# Tests the heap sort with some randomly generated lists
for test_heap_index in range(10):
# Generates random input list size for testing
input_size = random.randint(20, 50)
# Assigns the first element of the input list to None
input_list = [None]
# Randomly generates the other elements of the input list
# Also, assigns that to a second test list for comparison
test_list = input_list[1:] = [random.randint(100, 1000)
for _ in range(1, input_size + 1)]
# Sorts the input list
TreeSortingAlgorithms.HeapSort.heap_sort(input_list, input_size)
# If heap sort list output is equal to Python built-in sort output
if (sorted(test_list) == input_list[1:]):
print(f' Heap Sort Test {test_heap_index + 1} was successful!')
# Otherwise if the input list is not sorted
else:
print(f' Heap Sort Test {test_heap_index + 1} was not successful!')
</code></pre>
<h3>Sources</h3>
<p>The Binary Tree Sort section of this question has been also previously reviewed in the first following link:</p>
<ul>
<li><p><a href="https://codereview.stackexchange.com/questions/229921/binary-tree-sort-algorithm-python">Binary Tree Sort Algorithm (Python) - Code Review</a></p></li>
<li><p><a href="https://www.geeksforgeeks.org/heap-sort/" rel="nofollow noreferrer">Heap Sort - Geeks for Geeks</a></p></li>
<li><p><a href="https://en.wikipedia.org/wiki/Heapsort" rel="nofollow noreferrer">Heap Sort - Wiki</a></p></li>
<li><p><a href="https://en.wikipedia.org/wiki/Tree_sort" rel="nofollow noreferrer">Tree Sort - Wiki</a></p></li>
<li><p><a href="https://www.geeksforgeeks.org/tree-sort/" rel="nofollow noreferrer">Tree Sort - Geeks for Geeks</a></p></li>
</ul>
| [] | [
{
"body": "<h2>Modules instead of \"namespace\" classes</h2>\n\n<p><code>TreeSortingAlgorithms</code> has no right to exist. It's good to want to put stuff in namespaces, but your nested classes are confusing and difficult-to-read. Instead, just put your algorithmic classes into a different file and use it as a module. That will get you a namespace but also be more legible, easier to deal with in source control, etc.</p>\n\n<p>Also, be careful:</p>\n\n<blockquote>\n <p>This super class has two subclasses of HeapSort and BinarySort.</p>\n</blockquote>\n\n<p>Most people would interpret that as <code>HeapSort</code> being a child or derivation of <code>TreeSortingAlgorithms</code>, which is not the case. This is not a superclass/subclass relationship, but rather a nested class relationship.</p>\n\n<h2>Terminology</h2>\n\n<pre><code> # Increments\n heap_index -= 1\n</code></pre>\n\n<p>That's not an increment, it's a decrement.</p>\n\n<h2>Loop like a native</h2>\n\n<pre><code> while heap_index >= 1:\n # Restores down the element\n TreeSortingAlgorithms.HeapSort.restore_down(\n heap_index, input_list, input_size)\n # Increments\n heap_index -= 1\n</code></pre>\n\n<p>should be something like</p>\n\n<pre><code>starting_index = heap_index\nfor heap_index in range(starting_index, 0, -1):\n # ...\n</code></pre>\n\n<h2>Useful comments</h2>\n\n<pre><code># Assigns the left and right child indices\n</code></pre>\n\n<p>This is worse than not having a comment at all. If you're near-verbatim rewriting Python into English, it's time to delete the comment or write something useful, e.g.</p>\n\n<pre><code># The left index starts at double the heap index because (algorithmic explanation)\n</code></pre>\n\n<h2>English is not C</h2>\n\n<p>This isn't my first review of your code, and you need to change this (again). Stop writing semicolons at the end of your comments.</p>\n\n<h2>Real tests</h2>\n\n<p>It's great that you've written some test code. To make it useful, you should add some <code>assert</code>s that test the output of your code against known expected outputs.</p>\n\n<h2>Unicode symbols</h2>\n\n<p>Your apples are hilarious. Keep them, but I think that they may present problems if ever you have team-shared code across a wide variety of platforms and editors. Consider something like this instead:</p>\n\n<pre><code>GREEN_APPLE = '\\U0001F34F'\n\n# ...\n\nprint(f'{GREEN_APPLE} Heap Sort Test {test_heap_index + 1} was successful!')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T01:08:41.007",
"Id": "230008",
"ParentId": "229982",
"Score": "3"
}
},
{
"body": "<h2>Iterators</h2>\n\n<p>This is wrong:</p>\n\n<pre><code>class BinarySort:\n\n def __iter__(self) -> None:\n '''\n Calls the _inorder traversing method recursively;\n '''\n self._inorder(self.root)\n\n def _inorder(self, parent_node: Node) -> None:\n ...\n</code></pre>\n\n<p>In <a href=\"https://codereview.stackexchange.com/a/229934/100620\">this answer</a>, I suggested instead of creating a function for printing the tree in order, you create an iterator that could return the values in the tree in order, which the caller could print. I mentioned <code>__iter__(self)</code> and <code>__next__(self)</code> methods, with the hope/intention that you would do some research yourself into how to create iterators.</p>\n\n<p>I suppose I could have provided an example:</p>\n\n<pre><code>class Container:\n\n def __init__(self, *data):\n self._items = data\n\n def __iter__(self):\n return Container.Iterator(self)\n\n class Iterator:\n def __init__(self, container):\n self._container = container\n self._i = 0\n\n def __next__(self):\n if self._i < len(self._container._items):\n item = self._container._items[self._i]\n self._i += 1\n return item\n raise StopIteration\n</code></pre>\n\n<p>Here, I have a <code>Container</code>. It stores a sequence of items.</p>\n\n<pre><code>>>> stuff = Container(1, 2, 3, 5, 8, 13)\n</code></pre>\n\n<p>While it defines an <code>__iter__</code> method, you should never call that method yourself. Instead, you should use the <code>iter()</code> function:</p>\n\n<pre><code>>>> it = iter(stuff)\n>>> type(it)\n<class '__main__.Container.Iterator'>\n</code></pre>\n\n<p>Note that the <code>__iter__</code> method does return something. It must return an iterator, which is something that implements the <code>__next__</code> method. Our <code>Container.Iterator</code> object does do that. Again, you never call the <code>__next__</code> method yourself; you call the <code>next()</code> function instead:</p>\n\n<pre><code>>>> next(it)\n1\n>>> next(it)\n2\n>>> next(it)\n3\n>>> next(it), next(it), next(it)\n(5, 8, 13)\n>>> next(it)\nTraceback (most recent call last):\n File \"<pyshell#40>\", line 1, in <module>\n next(it)\n File \"C:\\Users\\aneufeld\\Desktop\\Playground\\Python\\StackOverflow\\iter.py\", line 19, in __next__\n raise StopIteration\nStopIteration\n</code></pre>\n\n<p>Notice how that <code>iter(stuff)</code> returned an iterator, and calling <code>next(iterator)</code> returned each item from our container in sequence.</p>\n\n<p>Normally, you would use the iterator in a loop, breaking out when <code>StopIteration</code> is raised:</p>\n\n<pre><code>>>> it = iter(stuff)\n>>> while True:\n try:\n val = next(it)\n print(val)\n except StopIteration:\n break\n\n1\n2\n3\n5\n8\n13\n>>> \n</code></pre>\n\n<p>But Python will call <code>it = iter()</code> and <code>val = next(it)</code>, and catch the <code>StopIteration</code> exception for you, if you write it like this:</p>\n\n<pre><code>>>> for val in stuff:\n print(val)\n\n\n1\n2\n3\n5\n8\n13\n>>> \n</code></pre>\n\n<h2>Tree Iterator</h2>\n\n<p>A Tree iterator would be slightly more complicated. The iterator itself would need a stack (<code>list</code>) to keep track of which node it is at. While a node has a left child, you'd travel down to those children, pushing the current node onto your stack. When no left child exist, you'd return the node's value. When a right child exists, you'd travel down to those children, but not pushing the current node onto the stack. When no children exists, you'd pop the last node you pushed off of your stack, return its value, and visit its right child node. Effectively, you are traversing the tree inorder, but instead of using recursive calls, you have to keep track of where you are, and which direction you are going.</p>\n\n<p>Left to student.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T22:27:20.617",
"Id": "230194",
"ParentId": "229982",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "230008",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T14:56:12.643",
"Id": "229982",
"Score": "4",
"Tags": [
"python",
"beginner",
"algorithm",
"sorting",
"tree"
],
"Title": "Heap Sort and Binary Tree Sort Algorithms (Python)"
} | 229982 |
<p>I have a Python function w/ specified functionality, and two proposed approaches - which do you prefer, and why? (performance, simplicity, clarity, etc) (both use <code>import random</code>)</p>
<hr>
<p><strong>PROBLEM</strong>: Need a plain Python function that accepts an arbitrary number of iterables (tuples, lists, dictionaries), and returns them shuffled in the same order:</p>
<pre class="lang-py prettyprint-override"><code>a = (1, 2, {3: 4}, 5)
b = [(5,6), [7,8], [9,0], [1,2]]
c = {'arrow': 5, 'knee': 'guard', 0: ('x',2)}
x, y, z = magic(a, b, c)
print(x, y, z, sep='\n')
# ({3: 4}, 1, 2)
# [[9, 0], (5, 6), [7, 8]]
# {0: ('x', 2), 'arrow': 5, 'knee': 'guard'}
</code></pre>
<p>The function must:</p>
<ol>
<li>Return iterables shuffled in the same order (see above)</li>
<li>Accept any number of iterables</li>
<li>Preserve iterables <em>types</em></li>
<li>Support nested iterables of any <em>depth</em> and <em>type</em></li>
<li><em>Not</em> shuffle nested elements themselves (eg. <code>[7,8]</code> above doesn't become <code>[8,7]</code>)</li>
<li>Return iterables with length of shortest iterable's length w/o raising error (see above)</li>
<li>Return shuffled iterables in the same order they're passed in (see above)</li>
</ol>
<p><strong>NOTE</strong>: requires Python 3.7. Can work with Python 3.6- if excluding dicts, as dicts aren't ordered.
<hr>
<strong>SOLUTION 1</strong>:</p>
<pre class="lang-py prettyprint-override"><code>def ordered_shuffle(*args):
args_types = [type(arg) for arg in args] # [1]
_args = [arg if type(arg)!=dict else arg.items() for arg in args] # [2]
args_split = [arg for arg in zip(*_args)] # [3]
args_shuffled = random.sample(args_split, len(args_split)) # [4]
args_shuffled = map(tuple, zip(*args_shuffled)) # [5]
return [args_types[i](arg) for i, arg in enumerate(args_shuffled)] # [6]
</code></pre>
<p>Explanation: <a href="https://puu.sh/EnEsK/784ae4ae75.png" rel="nofollow noreferrer">img</a><br></p>
<hr>
<p><strong>SOLUTION 2</strong>:</p>
<pre class="lang-py prettyprint-override"><code>def shuffle_containers(*args):
min_length = min(map(len, args))
idx = list(range(min_length))
random.shuffle(idx)
results = []
for arg in args:
if isinstance(arg, list):
results.append([arg[i] for i in idx])
elif isinstance(arg, tuple):
results.append(tuple(arg[i] for i in idx))
elif isinstance(arg, dict):
items = list(arg.items())
results.append(dict(items[i] for i in idx))
else:
raise ValueError(
"Encountered", type(arg),
"expecting only list, dict, or tuple"
)
return results
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T15:57:02.023",
"Id": "447815",
"Score": "0",
"body": "Heads up: the edit you reverted has been made by a diamond moderator here to clarify the extent of the code up for review in your question. I strongly advise you to not roll it back. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T16:10:13.810",
"Id": "447816",
"Score": "0",
"body": "@Vogel612 It is up for review - it resulted from someone improving Sol 1, so someone could also improve GZ0 mod or comment on its performance/readability"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T16:12:34.147",
"Id": "447818",
"Score": "0",
"body": "if you want to put it up for review, please understand that it's not allowed on this site to update the question in a way that invalidates existing answers. See also *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*"
}
] | [
{
"body": "<p>I think your solution 2 is heading the right direction here. What I consider it's advantages over solution 1:</p>\n\n<ol>\n<li>It is much more readable</li>\n<li>It clearly shows that every member of *args is treated the same.</li>\n</ol>\n\n<p>You might want to generic-ify it a bit more to handle more types. For example, the following has a good chance of also handling custom container types:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import collections\n# -- Other code ---\n if isinstance(arg, collections.abc.Mapping):\n items = list(arg.items())\n results.append(type(arg)(items[i] for i in idx))\n else:\n results.append(type(arg)(arg[i] for i in idx))\n</code></pre>\n\n<p>Which will inspect the type of the iterable and feed it an iterator in an attempt to create a new one. This version here will handle lists and tuples the same as your does. If any custom container type supports a <code>__init__(self, *args)</code> constructor to fill itself, it'll also work.</p>\n\n<p>To be honest, those will probably be very rare. I've never seen one. But this is a very easy generic to support, and it's already worth it because you have the same code handling tuples and lists, in my opinion.</p>\n\n<p>Keep in mind you need at least python 3.6 for dictionaries to have a stable insertion ordering. </p>\n\n<h3>Readability > Shortness.</h3>\n\n<p>Unless you're planning on visiting <a href=\"https://codegolf.stackexchange.com/\">Codegolf</a>, don't do this. But if you do, you can shorten your functions a lot more, like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>f = lambda *a:[type(y[i])(b) for i,bin enumerate(map(list, zip(*random.sample([y for y in \n zip(*[x if type(x)!=dict else x.items() for x in a])], min(len(z) for z in a)))))]\n</code></pre>\n\n<p>I hope this example makes it abundantly clear why readability is important. If not, try and figure out if there's a bug in here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T18:55:53.820",
"Id": "447685",
"Score": "0",
"body": "Thanks for the response; _readability_ is the one aspect I wouldn't expect (1) to lose to (2); I suppose (1) is 'fancier', but it's nearly 3x as short, and each line serves a clear purpose as shown in the explanation. Do you find [(3) or (4)](https://puu.sh/EnFem/9fe49aad9a.png) here any more readable?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T19:07:16.877",
"Id": "447691",
"Score": "2",
"body": "Readability doesn't have much to do with \"short\" once you're above amateur programmer. The readability means that in solution 2, I can see what happens easily, and just as easily understand what happens. It requires no backtracking, no re-reads. I've read solution 1 ten times, and without looking up documentation on `random.sample`, I wouldn't be sure what it does. I've read it three times just for this comment to make sure I really got what happened."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T19:33:58.300",
"Id": "447698",
"Score": "0",
"body": "Fair; [(5)](https://puu.sh/EnFSm/c9509c5ea2.png) possibly wins the \"shortest\" / \"fanciest\" contest, but good luck figuring it out in one read. Agreeably it comes down to preference; each uses Pythonic methods (`hasattr, zip, map, enumerate`) and Pythonic type-casting, but (2)'s perhaps more pseudocode-friendly (i.e. requires less background)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T19:37:16.783",
"Id": "447700",
"Score": "1",
"body": "Yes, preference matters a lot in cases of readability. List comprehensions and related things are totally awesome tools in python (and I use them a lot), but they can kill readability just as fast as code golf does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T20:03:37.483",
"Id": "447717",
"Score": "0",
"body": "I've added your solution with a credit in the [original](https://stackoverflow.com/questions/58177254/how-to-shuffle-multiple-iterables-in-same-order). If you found this question interesting, an (↑) on it would be appreciated, as it's been rather [controversial](https://meta.stackoverflow.com/questions/389975/how-to-restore-a-derailed-question). Will keep this question open for a while more for discussion, then accept an answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T20:05:12.647",
"Id": "447718",
"Score": "1",
"body": "Done for the question, but I have the same readability concerns about that answer that I raised here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T03:47:59.070",
"Id": "447745",
"Score": "0",
"body": "Updated answer w/ performance benchmark you may find of interest; also, change `y[i]` to `args[i]` in Gloweye's lambda"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T09:39:10.070",
"Id": "447771",
"Score": "1",
"body": "Checking for `isinstance(arg, collections.abc.Mapping)` might be more appropriate, so that the code will work for any [mapping](https://docs.python.org/3/glossary.html#term-mapping) even if it's not a subclass of `dict`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T09:45:01.103",
"Id": "447772",
"Score": "1",
"body": "Good one. Added in."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T18:32:21.687",
"Id": "229990",
"ParentId": "229988",
"Score": "7"
}
},
{
"body": "<h3>functools.singledispatch</h3>\n\n<p><a href=\"https://docs.python.org/3.6/library/functools.html\" rel=\"noreferrer\">functools</a> library includes the <code>singledispatch()</code> decorator. It lets you provide a generic function, but provide special cases based on the <em>type</em> of the first argument.</p>\n\n<pre><code>import functools\nimport random\n\n@functools.singledispatch\ndef shuffle(arg, order):\n \"\"\"this is the generic shuffle function\"\"\"\n\n lst = list(arg)\n return type(arg)(lst[i] for i in order)\n\n\n@shuffle.register(dict)\ndef _(arg, order):\n \"\"\"this is shuffle() specialized to handle dicts\"\"\"\n\n item = list(arg.items())\n return dict(item[i] for i in order)\n\n\ndef ordered_shuffle(*args):\n min_length = min(map(len, args))\n\n indices = random.sample(range(min_length), min_length)\n\n return [shuffle(arg, indices) for arg in args]\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>a = (1, 2, {3: 4}, 5)\nb = [(5,6), [7,8], [9,0], [1,2]]\nc = {'arrow': 5, 'knee': 'guard', 0: ('x',2)}\n\nordered_shuffle(a, b, c)\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>[({3: 4}, 1, 2),\n [[9, 0], (5, 6), [7, 8]],\n {0: ('x', 2), 'arrow': 5, 'knee': 'guard'}]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T03:49:43.487",
"Id": "447746",
"Score": "0",
"body": "Interesting alternative - wonder how much fancy Python's hoarding that I've never seen. It is, however, slowest compared w/ others according to my benchmark (see updated answer) - but to be fair, for most uses, it's entirely negligible"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T20:25:19.600",
"Id": "447856",
"Score": "0",
"body": "@Vogel612 Read the rules, fair enough - I'm willing to post removed edits in an answer"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T23:08:09.790",
"Id": "230005",
"ParentId": "229988",
"Score": "12"
}
},
{
"body": "<p>While I do agree with others that Solution 2 is more readable with some improvements, there are also a few improvements that can be done on Solution 1.</p>\n\n<ul>\n<li><p>It is unnecessary to construct lists from iterables (e.g., generator expressions) when all that is needed is an iterable. For example, </p>\n\n<pre><code>_args = [arg if type(arg)!=dict else arg.items() for arg in args]\nargs_split = [arg for arg in zip(*_args)]\n</code></pre>\n\n<p>Here, the unpacking operator <code>*</code> works on arbitrary iterables. So one can just do</p>\n\n<pre><code>_args = (arg if type(arg)!=dict else arg.items() for arg in args)\nargs_split = [arg for arg in zip(*_args)]\n</code></pre>\n\n<p>The parantheses keep the generator expressions without actually materializing them into lists.</p></li>\n<li><p>It is better to use <code>isinstance(arg, cls)</code> rather than <code>type(arg) == cls</code></p></li>\n<li>Unpacking an iterable into a list can be done using <code>list(iterable)</code>, which is more efficient than a list comprehension <code>[arg for arg in iterable]</code> that uses an explicit <code>for</code>-loop.</li>\n<li><p>This expression</p>\n\n<pre><code>[args_types[i](arg) for i, arg in enumerate(args_shuffled)]\n</code></pre>\n\n<p>can be rewritten using <code>zip</code> to avoid the need of indices:</p>\n\n<pre><code>[cls(arg) for cls, arg in zip(args_types, args_shuffled)]\n</code></pre></li>\n</ul>\n\n<p>Following is an improved version of Solution 1</p>\n\n<pre><code>def ordered_shuffle(*args):\n arg_types = map(type, args)\n arg_elements = (arg.items() if isinstance(arg, dict) else arg for arg in args)\n zipped_args = list(zip(*arg_elements))\n random.shuffle(zipped_args)\n return [cls(elements) for cls, elements in zip(arg_types, zip(*zipped_args))]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T04:48:50.600",
"Id": "447754",
"Score": "0",
"body": "A [shorter version](https://pastebin.com/YpyG2MRA), maybe shortest, for anyone interested; 42 chars shorter than Gloweye's lambda"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T05:01:52.873",
"Id": "447755",
"Score": "1",
"body": "@OverLordGoldDragon For pure golfing there are more tricks that can be applied. [Here](https://tio.run/##LYzdboMwDEbveQrfxUbW1NKxHyqehHGRQrJGKyEyQStUfXYWpN34WJ@Pv7DE6@hP22ZlHEC07xPcEEaJedYbCxZzoSpfuV5dwBz1i4tmmJCchd51sa7jEgxqMrfJgAY7SprOgxCdp@ts7c3gSmcxcRbfdGhoVzrOzW7tpYMOuJewEOcrtZuGGvDIUDA8ThW8PhlKyi4pbbDkN2Jo3vmjTfjkw44jF22bdUl4KC0y/qoKSgb1441Jq/qetfSK4VABqrvigp5ZdmdYGNb0ZFEzXBg6yoI4H/H/xDCZUKsvr2j7Aw) is an example of what regular golfed code would look like."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T19:19:49.857",
"Id": "447995",
"Score": "0",
"body": "Selected as the answer, but other answers are valuable also - selection rationale in my answer. Thanks for your solution"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T04:43:52.413",
"Id": "230012",
"ParentId": "229988",
"Score": "7"
}
},
{
"body": "<p>Below is an answer highlight and performance comparison of various solutions. <em>Note</em>: the differences should be negligible in practice - if otherwise, timing variance is substantial, and all are ~on par (per benchmark)</p>\n\n<hr>\n\n<p><strong>SOLUTION 1 GZ0-Mod+</strong>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def ordered_shuffle(*args):\n zipped_args = list(zip(*(a.items() if isinstance(a, dict) else a for a in args)))\n random.shuffle(zipped_args)\n return [cls(elems) for cls, elems in zip(map(type, args), zip(*zipped_args))] \n</code></pre>\n\n<hr>\n\n<p><strong>SOLUTION 1 GZ0-Mod++</strong>: <em>(latest)</em></p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def ordered_shuffle(*args):\n zipped_args = list(zip(*(a.items() if isinstance(a, dict) else a for a in args)))\n np.random.shuffle(zipped_args)\n return [(_type(data) if _type != np.ndarray else np.asarray(data)) \n for _type, data in zip(map(type, args), zip(*zipped_args))]\n</code></pre>\n\n<p>This solution is simply the first but accounting for <code>numpy</code> arrays (also <code>_type</code> should be more intuitive, and spares <code>random</code> import since <code>numpy</code> is already imported).</p>\n\n<hr>\n\n<p><strong>UPDATE</strong>: Ran a <a href=\"https://pastebin.com/PnqtvEbz\" rel=\"nofollow noreferrer\">performance benchmark</a> - results for <code>iterations = 1e7</code>, and <code>a, b, c = tuple, list, dict</code> of length 10, nested, respectively:</p>\n\n<ul>\n<li><strong>#1</strong>: Solution 1 GZ0-Mod+   <code>114.2 sec, 71.2% faster than slowest</code></li>\n<li><strong>#2</strong>: Solution 2 <code>---------- 131.9 sec, 48.0% faster than slowest</code></li>\n<li><strong>#3</strong>: Solution 1 <code>---------- 155.7 sec, 25.4% faster than slowest</code></li>\n<li><strong>#4</strong>: Gloweye's lambda <code>--- 160.5 sec, 21.7% faster than slowest</code></li>\n<li><strong>#5</strong>: RootTwo's functools <code>-- 195.3 sec</code></li>\n</ul>\n\n<hr>\n\n<p><strong>Selected answer rationale</strong>:</p>\n\n<ul>\n<li>Best minimalism, acceptable readability</li>\n<li>Uses plain Python - no high-level libraries; easier to debug & understand</li>\n<li>Well-explained answer, describing pitfalls of original approach & how it's remedied</li>\n<li>Best performance (a bonus, not major factor)</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T19:07:48.560",
"Id": "230112",
"ParentId": "229988",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "230012",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T17:10:15.630",
"Id": "229988",
"Score": "10",
"Tags": [
"python",
"python-3.x",
"comparative-review",
"random",
"iteration"
],
"Title": "Shuffling multiple iterators in order"
} | 229988 |
<p>I recently attempted a coding problem, but my solution was not well received during the interview (modified slightly to reduce Google-ability).</p>
<blockquote>
<p>Suppose a child has several Lego blocks, and wants to build a toy from them. Every piece has a size, and when two pieces are combined a new piece is created whose size is the sum of the attached blocks. The time it takes to combine two blocks is equal to the size of the individual blocks</p>
<p>Find the sequence of combinations that takes the least amount of time to combine all of the Legos</p>
</blockquote>
<p>Here is an example: </p>
<blockquote>
<p>Given the following blocks: <code>5, 2, 8</code> the child could combine them in the following methods:</p>
<pre><code>5 + 8 = 13 --> Kid spent 13 units of time
13 + 2 = 15 --> Kid spent 15 units of time
Total time spent: 13 + 15 = 28
</code></pre>
<p>Another combination would be:</p>
<pre><code>2 + 5 = 7
7 + 8 = 15
Total time spent: 22
</code></pre>
</blockquote>
<p>I came up with the following algorithm to find the shortest time required to combine all of the blocks:</p>
<pre class="lang-java prettyprint-override"><code>import java.util.Arrays;
import java.util.Collections;
import java.util.List;
class AssemblyTime {
int shortestAssemblyTime(List<Integer> lego) {
Collections.sort(lego);
int counter = lego.size() - 1;
int sum = lego.get(0) * (lego.size() - 1);
for (int i = 1; i < lego.size(); i++) {
sum += lego.get(i) * counter;
counter--;
}
return sum;
}
public static void main(String[] args) {
int i = new AssemblyTime().shortestAssemblyTime(Arrays.asList(5, 2, 8, 4));
assert i == 36;
}
}
</code></pre>
<p>The test cases are not available to me, however my solution timed out on 6 of the 10 (it passed the other 4).</p>
<p>The idea of my algorithm is as follows. Given my test case in code, the process is something like this:</p>
<pre class="lang-none prettyprint-override"><code>2 + 4
2 + 4 + 5
2 + 4 + 5 + 8
</code></pre>
<p>So the last element is added once, the <code>last-1</code> is added twice until elements at index 0 and 1, which are both added <code>list.length - 1</code> times.</p>
<p>How can I improve the performance for this algorithm? Is there any other data structure I can use?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T13:12:11.110",
"Id": "447784",
"Score": "0",
"body": "Where do the test cases come from?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T14:56:48.340",
"Id": "447801",
"Score": "0",
"body": "@dustytrash God knows, it was one of those online platforms. I will try the suggestions in the answers when I have time and will try testing against some large data, and comment under each of them. I also have another idea now after thinking about this question a few days, I might add my own answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T16:10:56.267",
"Id": "447817",
"Score": "0",
"body": "Are you sure your answer is correct? The way I interpret the rules, your solution is wrong for input [10, 11, 12, 13]. Your answer is 100. If you first add 10 + 11 = 21; then put 12 + 13 = 25 and after that add those 2 new blocks together 21 + 25 = 46; you get a total time of 21 + 25 + 46 = 92."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T16:15:34.010",
"Id": "447819",
"Score": "0",
"body": "@Imus I think you are right and this is very embarrassing. I do not know what to do now, delete this answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T18:10:19.770",
"Id": "447831",
"Score": "0",
"body": "Since there are a couple of answers it's now no longer possible to update your question. So it might be best to delete it indeed. Feel free to post a new one once you fixed the mistake and want to know if that new solution looks good or could use improvements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T04:29:11.977",
"Id": "448460",
"Score": "3",
"body": "I wouldn't delete the question at this stag anymore. What you can do is provide a self-answer where you review your own question and let others know the bug that was found."
}
] | [
{
"body": "<p>Your inner loop contains an addition, multiplication, subtraction and two assignments. The multiplication is unnecessary as you can do with two additions and two assignments:</p>\n\n<pre><code>int totalTimeSpent = 0;\nint sumOfPair = lego.get(0);\nfor (int i = 1; i < lego.size(); i++) {\n sumOfPair += lego.get(i);\n totalTimeSpent += sumOfPair;\n}\n</code></pre>\n\n<p>Regarding the data structures: were you forced to use a List? An int array with <code>Arrays.sort(int[])</code> would have been more efficient.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T06:58:22.567",
"Id": "230018",
"ParentId": "229992",
"Score": "4"
}
},
{
"body": "<p>You could use reverse order and multiply by array index +1 (except last element):</p>\n\n<pre><code>2 + 4\n2 + 4 + 5\n2 + 4 + 5 + 8\n</code></pre>\n\n<p>Could be transformed to:</p>\n\n<pre><code>element index result\n 8 * 1 8\n 5 * 2 10 \n 4 * 3 12\n 2 * 3 6 \n 36\n</code></pre>\n\n<p>It allows you to remove reverse counter.\nAlso you can use Array it consume less memory.</p>\n\n<p>Here is my implementation:</p>\n\n<pre><code>class AssemblyTime {\n\n int shortestAssemblyTime(Integer... lego) {\n Arrays.sort(lego, Collections.reverseOrder());\n int sumOfLastElement = lego[lego.length - 1] * (lego.length - 1);\n return IntStream.range(1, lego.length)\n .map(i -> lego[i] * (i + 1))\n .sum() + sumOfLastElement;\n }\n\n public static void main(String[] args) {\n int i = new AssemblyTime().shortestAssemblyTime(5, 2, 8, 4);\n assert i == 36;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T07:35:19.523",
"Id": "230019",
"ParentId": "229992",
"Score": "4"
}
},
{
"body": "<p>As TorbenPutkonen already said, the good way to improve the performance of your solution is relying on primitive types using <code>Arrays.sort(int[]</code> and rewriting of loop as he suggested. I add my thoughts and code, consider that for your interviewer can be edge cases like o or 1 toy blocks , in this case the shortest time is equal to <code>0</code>. Now you can use a method having as parameter an <code>int[]</code> array to avoid use of <code>Integer</code> class and operations of boxing and unboxing:</p>\n\n<pre><code>public static int shortestAssemblyTime(int[] arr) {\n int n = arr.length;\n if (n < 2) { return 0; } //<-- edge cases 0, 1\n int[] copy = Arrays.copyOf(arr, n);\n Arrays.sort(copy);\n}\n</code></pre>\n\n<p>I created a copy of the original array, because for me the method is supposed to not modify the original array passed as parameter and I added the <code>static</code> modifier. Once you have the copy ordered inside the method, you can calculate the shortest time like the code below:</p>\n\n<pre><code>int shortestTime = 0;\nint toylength = copy[0];\nfor (int i = 1; i < n; ++i) {\n toylength += copy[i];\n shortestTime += toylength;\n}\nreturn shortestTime;\n</code></pre>\n\n<p>Below the code of the class Assembly.java with main method including one test:</p>\n\n<pre><code>import java.util.Arrays;\n\npublic class AssemblyTime {\n\n public static int shortestAssemblyTime(int[] arr) {\n int n = arr.length;\n if (n < 2) { return 0; }\n int[] copy = Arrays.copyOf(arr, n);\n Arrays.sort(copy);\n int shortestTime = 0;\n int toylength = copy[0];\n for (int i = 1; i < n; ++i) {\n toylength += copy[i];\n shortestTime += toylength;\n }\n return shortestTime;\n }\n\n public static void main(String[] args) {\n int[] arr = new int[]{5, 2, 8, 4};\n System.out.println(AssemblyTime.shortestAssemblyTime(arr)); // print 36\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T09:42:29.340",
"Id": "230023",
"ParentId": "229992",
"Score": "4"
}
},
{
"body": "<p>You have a more fundamental problem here than performance: your solution isn't actually correct. Consider 4 lego pieces all of size 1. Your solution combines them as </p>\n\n<ol>\n<li><span class=\"math-container\">\\$1+1=2\\$</span></li>\n<li><span class=\"math-container\">\\$2+1=3\\$</span></li>\n<li><span class=\"math-container\">\\$3+1=4\\$</span></li>\n</ol>\n\n<p>for a total cost of <span class=\"math-container\">\\$2+3+4 = 9\\$</span>. However, we can combine more efficiently in the following way</p>\n\n<ol>\n<li><span class=\"math-container\">\\$1+1=2\\$</span></li>\n<li><span class=\"math-container\">\\$1+1=2\\$</span></li>\n<li><span class=\"math-container\">\\$2+2=4\\$</span></li>\n</ol>\n\n<p>for a total cost of <span class=\"math-container\">\\$8\\$</span>. In general this problem is asking you to rediscover the famous <a href=\"https://en.wikipedia.org/wiki/Huffman_coding\" rel=\"nofollow noreferrer\">Huffman coding</a>. If you consider your size <span class=\"math-container\">\\$w\\$</span> blocks to be code words with frequency <span class=\"math-container\">\\$w\\$</span>, then the solution is asking you to find the cost of the optimal prefix code for those code words. </p>\n\n<p>The optimal combination is obtained by at each step picking the two smallest size blocks and combining them. We need a data structure where we can efficiently find and remove the smallest element, and also insert new elements (we need to reinsert combined blocks at each step). This can be done efficiently with a min priority queue.</p>\n\n<p>Strictly speaking, in an actual interview, you might be asked to justify why the above algorithm gives the most efficient combination. For this, see a resource on the Huffman code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T21:22:09.277",
"Id": "230341",
"ParentId": "229992",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "230341",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T19:22:05.243",
"Id": "229992",
"Score": "6",
"Tags": [
"java",
"time-limit-exceeded",
"interview-questions"
],
"Title": "Building a toy from Lego toys"
} | 229992 |
<p>I'm working on writing a Chess Logic Library in JavaScript for learning purposes and was wondering how good these two slightly different implementations of a BitBoard are.</p>
<p>The first stores the board as a 64 length string of zeros and ones and the second uses an Array containing 8 numbers each representing a byte. The body of each is mainly methods to allow for binary operations between two BitBoards or a BitBoard and a number representing an index where the operation is performed against 1.</p>
<p>Is this the best way to represent an unsigned 64 bit number in JavaScript?</p>
<p>Any feedback would be greatly appreciated since I'm fairly new to programming.</p>
<p><strong>String BitBoard</strong></p>
<pre><code>/**
*
* @class BitBoard
* @param bitRows: [optional] Array<number>
* Each number must be an INTEGER in the range of 0-255; i.e. each number is a byte
* DEFAULT: bitRows = [0,0,0,0,0,0,0,0].length = 8; i.e. 8 bytes)
* Each value: n is converted to an integer and then set to 0 if n > 255
*/
class BitBoard {
public board: string;
public length: number;
/**
* @param bitRows: Array<number>
*/
constructor(bitRows: number[] = [0, 0, 0, 0, 0, 0, 0, 0]) {
if (!Array.isArray(bitRows) || bitRows.some(x => typeof x !== 'number')) {
throw new TypeError('Invalid Input. Must be "Array" of "numbers"')
}
for (let i: number = 0, length: number = bitRows.length; i < length; i++) {
if (Math.floor(bitRows[i]) !== bitRows[i] || bitRows[i] < 0 || bitRows[i] > 255) {
throw new RangeError('inputs to bitRows array must be integers greater than or equal to zero and less than 256')
}
}
this.board = bitRows.map(byte => padString(byte.toString(2), 8, '0', true)).join('');
this.length = this.board.length;
}
/**
* @param bit: Object
* @returns boolean
*/
determineIfBitBoard(bit: BitBoard): boolean {
const names = Object.getOwnPropertyNames(bit);
if (typeof bit === 'object' && names.indexOf('board') !== -1 && names.indexOf('length') !== -1) {
const isLengthByteMultiple: boolean = bit.length % 8 === 0;
const isBoardString: boolean = typeof bit.board === 'string';
const isBoardLengthCorrect: boolean = bit.board.length === bit.length;
const doPrototypesMatch: boolean = Object.getPrototypeOf(bit) === BitBoard.prototype;
return isLengthByteMultiple && isBoardString && isBoardLengthCorrect && doPrototypesMatch;
}
return false;
}
/**
*
* @param index: number
* @returns number
*/
getIndex(index: number): number {
if (Math.floor(index) === index && index > -1 && index < this.length) {
return parseInt(this.board[this.length - 1 - index]);
}
throw new RangeError('index must be integer greater than or equal to 0 and less than BitBoard.length');
}
/**
* @returns BitBoard
*/
copy(): BitBoard {
let newBoard = new BitBoard();
newBoard.board = this.board;
return newBoard;
}
/**
*
* @param bitBoardOrIndex: BitBoard | number
* @returns BitBoard
*/
and(bitBoardOrIndex: BitBoard | number): BitBoard {
let newBoard: BitBoard = this.copy();
if (typeof bitBoardOrIndex === 'number') {
if (bitBoardOrIndex >= 0 && bitBoardOrIndex < this.length) {
return newBoard;
}
throw new RangeError('index must be integer greater than or equal to 0 and less than BitBoard.length')
} else if (this.determineIfBitBoard(bitBoardOrIndex)) {
if (this.length === bitBoardOrIndex.length) {
let str: string = '';
for (let i: number = 0; i < this.length; i++) {
str += String(parseInt(newBoard.board[i]) & parseInt(bitBoardOrIndex.board[i]));
}
newBoard.board = str;
return newBoard;
}
throw new RangeError('BitBoard lengths do not match');
}
throw new TypeError('Invalid input. Must be of type "BitBoard" or "number"');
}
/**
*
* @param bitBoardOrIndex: BitBoard | number
* @returns BitBoard
*/
or(bitBoardOrIndex: BitBoard | number): BitBoard {
let newBoard: BitBoard = this.copy();
if (typeof bitBoardOrIndex === 'number') {
if (bitBoardOrIndex >= 0 && bitBoardOrIndex < this.length) {
const start: string = newBoard.board.slice(0, this.length - bitBoardOrIndex - 1);
const altered: string = String(parseInt(this.board[this.length - 1 - bitBoardOrIndex]) | 1);
const end: string = newBoard.board.slice(this.length - bitBoardOrIndex);
newBoard.board = start + altered + end;
return newBoard;
}
throw new RangeError('index must be integer greater than or equal to 0 and less than BitBoard.length');
} else if (this.determineIfBitBoard(bitBoardOrIndex)) {
if (this.length === bitBoardOrIndex.length) {
let str: string = '';
for (let i: number = 0; i < this.length; i++) {
str += String(parseInt(newBoard.board[i]) | parseInt(bitBoardOrIndex.board[i]));
}
newBoard.board = str;
return newBoard;
}
throw new RangeError('BitBoard lengths do not match');
}
throw new TypeError('Invalid input. Must be of type "BitBoard" or "number"');
}
/**
*
* @param bitBoardOrIndex: BitBoard | number
* @returns BitBoard
*/
xOr(bitBoardOrIndex: BitBoard | number): BitBoard {
let newBoard: BitBoard = this.copy();
if (typeof bitBoardOrIndex === 'number') {
if (bitBoardOrIndex >= 0 && bitBoardOrIndex < this.length) {
const start: string = newBoard.board.slice(0, this.length - bitBoardOrIndex - 1);
const altered: string = String(parseInt(this.board[this.length - 1 - bitBoardOrIndex]) ^ 1);
const end: string = newBoard.board.slice(this.length - bitBoardOrIndex);
newBoard.board = start + altered + end;
return newBoard;
}
throw new RangeError('index must be integer greater than or equal to 0 and less than BitBoard.length');
} else if (this.determineIfBitBoard(bitBoardOrIndex)) {
if (this.length === bitBoardOrIndex.length) {
let str: string = '';
for (let i: number = 0; i < this.length; i++) {
str += String(parseInt(newBoard.board[i]) ^ parseInt(bitBoardOrIndex.board[i]));
}
newBoard.board = str;
return newBoard;
}
throw new RangeError('BitBoard lengths do not match');
}
throw new TypeError('Invalid input. Must be of type "BitBoard" or "number"')
}
/**
* @returns BitBoard
*/
not(): BitBoard {
let newBoard: BitBoard = this.copy();
let str: string = '';
for (let i: number = 0; i < this.length; i++) {
str += newBoard.board[i] === '1' ? '0' : '1';
}
newBoard.board = str;
return newBoard;
}
/**
*
* @param shiftAmount: number
* @returns BitBoard
*/
shiftLeft(shiftAmount: number): BitBoard {
if (typeof shiftAmount === 'number') {
if (shiftAmount >= 0 && shiftAmount <= this.length) {
let newBoard: BitBoard = this.copy();
newBoard.board = padString(newBoard.board, this.length + shiftAmount, '0', false).slice(shiftAmount);
return newBoard;
}
throw new RangeError('Invalid input. Must be greater than or equal to zero and less than or equal to BitBoard.length');
}
throw new TypeError('Invalid input. Must be "number"');
}
/**
*
* @param shiftAmount: number
* @returns BitBoard
*/
shiftRight(shiftAmount: number): BitBoard {
if (typeof shiftAmount === 'number') {
if (shiftAmount >= 0 && shiftAmount <= this.length) {
let newBoard: BitBoard = this.copy();
newBoard.board = padString(newBoard.board, this.length + shiftAmount, '0', true).slice(0, this.length);
return newBoard;
}
throw new RangeError('Invalid input. Must be greater than or equal to zero and less than or equal to BitBoard.length');
}
throw new TypeError('Invalid input. Must be "number"');
}
}
/**
* @param str: string
* @param length: number
* @param padValue: string
* @param start: boolean
* @returns string
*/
function padString(str: string, length: number, padValue: string, start: boolean): string {
if (start) {
for (let i: number = str.length; i < length; i++) {
str = padValue + str;
}
} else {
for (let i: number = str.length; i < length; i++) {
str += padValue;
}
}
return str;
}
export = BitBoard;
</code></pre>
<p><strong>Number Array BitBoard</strong></p>
<pre><code>/**
*
* @class BitBoard
* @param bitRows: [optional] Array<number>
* Each number must be an INTEGER in the range of 0-255; i.e. each number is a byte
* DEFAULT: bitRows = [0,0,0,0,0,0,0,0].length = 8; i.e. 8 bytes)
* Each value: n is converted to an integer and then set to 0 if n > 255
*/
class BitBoard {
public board: Array<number>;
public length: number;
private bitsPerByte: number;
/**
* @param bitRows: Array<number>
*/
constructor(bitRows: number[] = [0, 0, 0, 0, 0, 0, 0, 0]) {
if (!Array.isArray(bitRows) || bitRows.some(x => typeof x !== 'number')) {
throw new TypeError('Invalid Input. Must be "Array" of "numbers"')
}
for (let i: number = 0, length: number = bitRows.length; i < length; i++) {
if (Math.floor(bitRows[i]) !== bitRows[i] || bitRows[i] < 0 || bitRows[i] > 255) {
throw new RangeError('inputs to bitRows array must be integers greater than or equal to zero and less than 256')
}
}
this.board = bitRows;
this.length = this.board.length * 8;
this.bitsPerByte = 8;
}
/**
* @param bit: Object
* @returns boolean
*/
determineIfBitBoard(bit: BitBoard): boolean {
const names = Object.getOwnPropertyNames(bit);
if (typeof bit === 'object' && names.indexOf('board') !== -1 && names.indexOf('length') !== -1 && names.indexOf('bitsPerByte') !== -1) {
const isLengthByteMultiple: boolean = bit.length % 8 === 0;
const isBoardArray: boolean = Array.isArray(bit.board);
const isBoardValidNumber: boolean = bit.board.every(b => typeof b === 'number' && b >= 0 && b <= 255 && Math.floor(b) === b);
const isBoardLengthCorrect: boolean = bit.board.length * 8 === bit.length;
const doPrototypesMatch: boolean = Object.getPrototypeOf(bit) === BitBoard.prototype;
return isLengthByteMultiple && isBoardArray && isBoardValidNumber && isBoardLengthCorrect && doPrototypesMatch;
}
return false;
}
/**
* @returns string
*/
boardToString() {
let str = '';
for (let i = 0; i < this.board.length; i++) {
str += padString(this.board[i].toString(2), this.bitsPerByte, '0', true);
}
return str;
}
/**
*
* @param index: number
* @returns number
*/
getIndex(index: number): number {
if (Math.floor(index) === index && index > -1 && index < this.length) {
const powOfTwo = 2 ** (index % this.bitsPerByte);
const numberOfBuckets = this.length / this.bitsPerByte;
return (this.board[numberOfBuckets - 1 - Math.floor(index / this.bitsPerByte)] & (powOfTwo)) / powOfTwo;
}
throw new RangeError('index must be integer greater than or equal to 0 and less than BitBoard.length');
}
/**
* @returns BitBoard
*/
copy = (): BitBoard => new BitBoard(this.board.slice());
/**
*
* @param bitBoardOrIndex: BitBoard | number
* @returns BitBoard
*/
and(bitBoardOrIndex: BitBoard | number): BitBoard {
let newBoard: BitBoard = this.copy();
if (typeof bitBoardOrIndex === 'number') {
if (bitBoardOrIndex >= 0 && bitBoardOrIndex < this.length) {
return newBoard;
}
throw new RangeError('index must be integer greater than or equal to 0 and less than BitBoard.length')
} else if (this.determineIfBitBoard(bitBoardOrIndex)) {
if (this.length === bitBoardOrIndex.length) {
for (let i = 0; i < this.board.length; i++) {
newBoard.board[i] &= bitBoardOrIndex.board[i];
}
return newBoard;
}
throw new RangeError('BitBoard lengths do not match');
}
throw new TypeError('Invalid input. Must be of type "BitBoard" or "number"');
}
/**
*
* @param bitBoardOrIndex: BitBoard | number
* @returns BitBoard
*/
or(bitBoardOrIndex: BitBoard | number): BitBoard {
let newBoard: BitBoard = this.copy();
if (typeof bitBoardOrIndex === 'number') {
if (bitBoardOrIndex >= 0 && bitBoardOrIndex < this.length) {
const numberOfBuckets = this.length / this.bitsPerByte;
newBoard.board[numberOfBuckets - 1 - Math.floor(bitBoardOrIndex / this.bitsPerByte)] |= 2 ** (bitBoardOrIndex % this.bitsPerByte);
return newBoard;
}
throw new RangeError('index must be integer greater than or equal to 0 and less than BitBoard.length')
} else if (this.determineIfBitBoard(bitBoardOrIndex)) {
if (this.length === bitBoardOrIndex.length) {
for (let i = 0; i < this.board.length; i++) {
newBoard.board[i] |= bitBoardOrIndex.board[i];
}
return newBoard;
}
throw new RangeError('BitBoard lengths do not match');
}
throw new TypeError('Invalid input. Must be of type "BitBoard" or "number"');
}
/**
*
* @param bitBoardOrIndex: BitBoard | number
* @returns BitBoard
*/
xOr(bitBoardOrIndex: BitBoard | number): BitBoard {
let newBoard: BitBoard = this.copy();
if (typeof bitBoardOrIndex === 'number') {
if (bitBoardOrIndex >= 0 && bitBoardOrIndex < this.length) {
const numberOfBuckets = this.length / this.bitsPerByte;
newBoard.board[numberOfBuckets - 1 - Math.floor(bitBoardOrIndex / this.bitsPerByte)] ^= 2 ** (bitBoardOrIndex % this.bitsPerByte);
return newBoard;
}
throw new RangeError('index must be integer greater than or equal to 0 and less than BitBoard.length')
} else if (this.determineIfBitBoard(bitBoardOrIndex)) {
if (this.length === bitBoardOrIndex.length) {
for (let i = 0; i < this.board.length; i++) {
newBoard.board[i] ^= bitBoardOrIndex.board[i];
}
return newBoard;
}
throw new RangeError('BitBoard lengths do not match');
}
throw new TypeError('Invalid input. Must be of type "BitBoard" or "number"');
}
/**
* @returns BitBoard
*/
not(): BitBoard {
let strBoard: string = this.boardToString();
let newStr: string;
let notBoard: Array<number> = [];
let i: number = 0
while (i < this.length) {
newStr = '';
while(i % this.bitsPerByte !== 0) {
newStr += strBoard[i] === '1' ? '0' : '1';
i++;
}
notBoard.push(parseInt(newStr, 2))
}
const newBoard = this.copy();
newBoard.board = notBoard;
return newBoard;
}
/**
*
* @param shiftAmount: number
* @returns BitBoard
*/
shiftLeft(shiftAmount: number): BitBoard {
if (typeof shiftAmount === 'number') {
if (shiftAmount >= 0 && shiftAmount <= this.length) {
let str: string = this.boardToString();
str += '0'.repeat(shiftAmount);
str = str.slice(shiftAmount);
let newBoard = this.copy();
for (let i: number = 0, b = 0; i < this.board.length; i++ , b += this.bitsPerByte) {
newBoard.board[i] = parseInt(str.slice(b, b + this.bitsPerByte), 2);
}
return newBoard;
}
throw new RangeError('Invalid input. Must be greater than or equal to zero and less than or equal to BitBoard.length');
}
throw new TypeError('Invalid input. Must be "number"');
}
/**
*
* @param shiftAmount: number
* @returns BitBoard
*/
shiftRight(shiftAmount: number): BitBoard {
if (typeof shiftAmount === 'number') {
if (shiftAmount >= 0 && shiftAmount <= this.length) {
let str = this.boardToString();
str = '0'.repeat(shiftAmount) + str;
str = str.slice(0, this.length);
let newBoard = this.copy();
for (let i = 0, b = 0; i < this.board.length; i++ , b += this.bitsPerByte) {
newBoard.board[i] = parseInt(str.slice(b, b + this.bitsPerByte), 2);
}
return newBoard;
}
throw new RangeError('Invalid input. Must be greater than or equal to zero and less than or equal to BitBoard.length');
}
throw new TypeError('Invalid input. Must be "number"');
}
}
/**
* @function padString: function
* @param str: string
* @param length: number
* @param padValue: string
* @param start: boolean
* @returns string
*/
function padString(str: string, length: number, padValue: string, start: boolean): string {
if (start) {
for (let i: number = str.length; i < length; i++) {
str = padValue + str;
}
} else {
for (let i: number = str.length; i < length; i++) {
str += padValue;
}
}
return str;
}
export = BitBoard;
</code></pre>
| [] | [
{
"body": "<p>The main attractions of a bitboard are, to put it shortly:</p>\n\n<ol>\n<li>Use the bit-parallel nature of bitwise operations to replace some simple loops.</li>\n<li>Use the power of arithmetic operations to replace non-trivial algorithms (eg <a href=\"https://www.chessprogramming.org/Subtracting_a_Rook_from_a_Blocking_Piece\" rel=\"nofollow noreferrer\">o^(o-2r)</a>).</li>\n</ol>\n\n<p>If a bitboard is emulated with a binary string, neither of those is realized. Effectively what you're dealing with then is a boolean array, but stored in a string. I think it misses the point. Bitboards aren't nice just because they encode the data in ones and zeroes, they're nice because they can be operated on in a computer-friendly way, and that property is lost.</p>\n\n<p>The array of numbers based board does a bit better, it can get at least <em>some</em> use out of its encoding. It can do some operations on 8 cells at the time. The code is still very \"stringy\" in some places (shifts, <code>not</code>) but that could be improved. This isn't the full power of bitboards, but it isn't <em>none</em> of it either, sort of in between. </p>\n\n<blockquote>\n <p>Is this the best way to represent an unsigned 64 bit number in JavaScript?</p>\n</blockquote>\n\n<p>Unfortunately this is a difficult problem. But there are alternatives.</p>\n\n<p>A <code>BigInt</code> has no problem storing a 64bit integer. There have been some performance issues with manipulating lots of tiny instances <code>BigInt</code>, I just did some quick tests to see if it had changed, but they were not encouraging. Also, browser support for it is not universal. Perhaps this will be a good approach someday.</p>\n\n<p>For now a better alternative is: use a pair of numbers, each storing 32 bits. That way you get the maximum use out of the 32bit bitwise operations that JavaScript can perform. Even emulating 64bit addition/subtraction (for the more advanced bitboard techniques) seems reasonable. For example <a href=\"https://github.com/scala-js/scala-js/blob/10d67c9e479b40714a9e134522a181829b8f64bc/library/src/main/scala/scala/scalajs/runtime/RuntimeLong.scala\" rel=\"nofollow noreferrer\">Scala.js</a> uses such an approach for its 64bit integers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T14:01:50.703",
"Id": "447788",
"Score": "0",
"body": "Whats the best approach for performing operations when numbers overflow into negatives for any number >= 2^31=2147483648 or for small numbers you NOT? E.g. ~n = negative number; AND, OR, and XOR return negative numbers for n >= 2^31. Also how would you approach the carrying of bits shifted off from one bucket into another? I chose 255 to be the max per bucket so you would never get negative numbers from any operation. I see the negative numbers posing a problem if you want to convert the board to a string since (1+n).toString(2) === (~n).toString(2).slice(1)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T14:12:58.393",
"Id": "447790",
"Score": "1",
"body": "@casual234 you could use the `>>> 0` trick before calling `toString`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T18:02:00.693",
"Id": "447829",
"Score": "0",
"body": "I updated the bitboard based on your advice; should I post it here for an updated review?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T18:03:10.213",
"Id": "447830",
"Score": "0",
"body": "@casual234 not in the same post, but in a new one sure go ahead"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T19:05:24.900",
"Id": "447848",
"Score": "0",
"body": "Here's the [new version](https://codereview.stackexchange.com/questions/230052/bitboard-class-in-typescript-for-chess-logic-follow-up)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T23:25:37.253",
"Id": "230006",
"ParentId": "229993",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "230006",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T19:24:32.567",
"Id": "229993",
"Score": "5",
"Tags": [
"beginner",
"comparative-review",
"typescript",
"chess",
"bitset"
],
"Title": "BitBoard class In TypeScript for chess logic"
} | 229993 |
<p>Given a tuple of elements, in <code>elementTupleParam</code> and the number in each combination <code>r</code>, we compute all the possible combinations of <code>r</code> elements, in a list of tuples. This is a recursive implementation. </p>
<p>One "challenge" is the inputs <code>r</code>, <code>n</code>, <code>elementTuple</code>, and the list holding the results, <code>combinationList</code>, are shared for all invocations of the recursive function. One method is to use global variables and bind them like below; which I think is rather ugly/bloated. Another method is to pass these are parameters to the recursive function, which may result in long parameter lists. Yet another is to make <code>partialCombinations</code> an inner function of <code>getCombinations</code>. </p>
<p>Another issue is the choice of data structure to hold the partial combinations and the result. I chose <code>tuple</code> because it's immutable: <code>prevTuple</code> is shared across many subsequent invocations, and is less prone to errors caused by accidental modifications.</p>
<p>What do you think? Any thoughts on these or other aspects would be appreciated.</p>
<pre><code>r = 0
n = 0
elementTuple = ()
combinationList = []
# get the vanilla combinations, nCr in number
def getCombinations(elementTupleParam, rParam):
global r
global n
global elementTuple
global combinationList
r = rParam
elementTuple = tuple(elementTupleParam)
n = len(elementTuple)
combinationList = []
if r == 0 or n == 0 or r > n:
return combinationList
partialCombinations((), -1)
return combinationList
def partialCombinations(prevTuple, prevVisitedIndex):
for thisIndex in range(prevVisitedIndex + 1, n):
thisTuple = prevTuple + (elementTuple[thisIndex],)
# If we exhausted all indices and have not formed a long enough tuple, then this is a dead-end, and don't do anything
if thisIndex == n - 1 and not len(thisTuple) == r:
continue
if len(thisTuple) == r: # Found combination
combinationList.append(thisTuple)
continue
partialCombinations(thisTuple, thisIndex)
#sanity check, should be moved to a unit test in another file
if __name__ == '__main__':
result = getCombinations((2,3,4), 2)
print(result)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T08:17:50.197",
"Id": "447766",
"Score": "0",
"body": "In those combinations, is order important?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T08:30:21.417",
"Id": "447767",
"Score": "0",
"body": "@Gloweye No, it's not."
}
] | [
{
"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 while writing your code and the following goes accordingly:</p>\n\n<ul>\n<li><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. I suggest you include docstrings to your functions indicating what they do and what they return instead of writing a comment above each function.</li>\n<li><p><strong>Python naming conventions:</strong> </p>\n\n<p><code>def getCombinations(elementTupleParam, rParam):</code></p>\n\n<p><code>def partialCombinations(prevTuple, prevVisitedIndex):</code></p>\n\n<p>Function names should be lowercase, with words separated\nby underscores as necessary to improve readability same goes for\nparameter names.</p></li>\n<li><strong>Descriptive variable names:</strong> <code>thisIndex</code> <code>thisTuple</code> <code>prevTuple</code> are examples of bad non-descriptive names. Names should reflect the significance of the variable/function/parameter they represent and the less ambiguous they are, the more readable is your code.</li>\n</ul>\n\n<h1>Code</h1>\n\n<ul>\n<li><strong>Global variables:</strong> are bad in Python and programming languages in general and are advised against. I suggest enclosing variables inside functions. The reason they are bad that they may allow functions to have hidden/hard to detect side effects leading to an increased complexity potentially leading to Spaghetti code. Examples of good use of global variables include: algorithm optimization - caching and memoization. </li>\n<li><p>There is a built-in Python library <code>itertools</code> that does the same functionality using <code>itertools.combinations()</code> which saves you the effort of implementing the thing yourself.</p>\n\n<p><strong>Code can be shortened into the following:</strong>\nAnd according to GZO's comment, there is no need for the warpper function <code>get_combinations()</code>, use <code>combinations()</code> directly. I included it just for the sake of the example.</p>\n\n<pre><code>from itertools import combinations\n\n\ndef get_combinations(n: list, r: int):\n \"\"\"Return combinations iterator.\"\"\"\n return combinations(n, r)\n\n\nif __name__ == '__main__':\n print(list(get_combinations([2, 3, 4], 2)))\n</code></pre></li>\n</ul>\n\n<p><strong>Check these references(regarding global variables):</strong></p>\n\n<ul>\n<li><p><a href=\"https://softwareengineering.stackexchange.com/questions/148108/why-is-global-state-so-evil\">https://softwareengineering.stackexchange.com/questions/148108/why-is-global-state-so-evil</a></p></li>\n<li><p><a href=\"https://stackoverflow.com/questions/19158339/why-are-global-variables-evil\">https://stackoverflow.com/questions/19158339/why-are-global-variables-evil</a></p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T21:12:59.320",
"Id": "447726",
"Score": "0",
"body": "Good call on using type hints for function parameters (even though they're just comments in Python)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T21:16:01.753",
"Id": "447727",
"Score": "0",
"body": "Thanks man, I hope i was of some help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T22:22:48.100",
"Id": "447734",
"Score": "0",
"body": "There is no need for the wrapper function `get_combinations` function when `combinations` is used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T22:36:02.487",
"Id": "447736",
"Score": "0",
"body": "@GZO I know, it's just for the sake of the example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T00:44:37.077",
"Id": "447740",
"Score": "0",
"body": "*main guard: shouldn't be moved to another file* - This is not true. It's beneficial in a module for functions to be separated into separate files as logic and organization dictate. Often, a module's `__main__.py` will have little code other than an entry point."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T00:48:58.697",
"Id": "447741",
"Score": "0",
"body": "@Reinderien Thanks for letting me know, I'll remove that part"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T20:28:15.507",
"Id": "229996",
"ParentId": "229994",
"Score": "5"
}
},
{
"body": "<p>As pointed out by @bullseye, the <code>itertools</code> library provides <code>combinations()</code>.</p>\n\n<p>If you are trying to learn how to implement your own version, here is a simple recursive version:</p>\n\n<pre><code>def combinations(seq, r):\n \"\"\"returns a list of all r-length combinations of the elements of seq.\"\"\"\n\n if len(seq) == r:\n # only one combination\n return [seq]\n\n elif r == 0:\n # yield an empty seq of the same type as seq\n return [seq[:0]]\n\n else:\n # combinations that _include_ seq[0] + those that exclude seq[0]\n return [seq[:1] + tail for tail in combinations(seq[1:], r-1)] + combinations(seq[1:], r)\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>combinations((1,2,3,4), 3), combinations('abcde', 3)\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>([(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)],\n ['abc', 'abd', 'abe', 'acd', 'ace', 'ade', 'bcd', 'bce', 'bde', 'cde'])\n</code></pre>\n\n<p>Here is an alternative version that generates the combinations lazily:</p>\n\n<pre><code>def combinations(seq, r):\n if len(seq) == r:\n # only one combination\n yield seq\n\n elif r == 0:\n # yield an empty seq of the same type as seq\n yield seq[:0]\n\n else:\n # yield all combinations that _include_ seq[0]\n yield from (seq[:1] + tail for tail in combinations(seq[1:], r-1))\n\n # yield all combinations that _exclude_ seq[0]\n yield from combinations(seq[1:], r)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T02:15:26.200",
"Id": "230010",
"ParentId": "229994",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "229996",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T19:59:27.233",
"Id": "229994",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"recursion",
"reinventing-the-wheel"
],
"Title": "Get list of all combinations from a set"
} | 229994 |
<p><a href="https://leetcode.com/problems/spiral-matrix-ii/" rel="nofollow noreferrer">https://leetcode.com/problems/spiral-matrix-ii/</a>
Please review for performance, how can this code run faster</p>
<blockquote>
<p>Given a positive integer n, generate a square matrix filled with
elements from 1 to n^2 in spiral order.</p>
<p>Example:</p>
<pre><code>Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
</code></pre>
</blockquote>
<pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ArrayQuestions
{
/// <summary>
/// https://leetcode.com/problems/spiral-matrix-ii/
/// </summary>
[TestClass]
public class SpiralMatrix2Test
{
[TestMethod]
public void Example3x3Test()
{
int size = 3;
int[][] expected =
{
new[]{1,2,3},
new [] {8,9,4},
new []{7,6,5}
};
int[][] res= SpiralMatrix2.GenerateMatrix(size);
for (int i = 0; i < size; i++)
{
CollectionAssert.AreEqual(expected[i],res[i]);
}
}
}
public class SpiralMatrix2
{
public static int[][] GenerateMatrix(int n)
{
int startCol = 0;
int endCol = n - 1;
int startRow = 0;
int endRow = n - 1;
int num = 1;
int[][] res = new int[n][];
for (int i = 0; i < n; i++)
{
res[i] = new int[n];
}
if (n == 0)
{
return res;
}
while (startCol <= endCol && startRow <= endRow)
{
for (int i = startCol; i <= endCol; i++)
{
res[startRow][i] = num++;
}
startRow++;// already did this row skip to the next one
for (int i = startRow; i <= endRow; i++)
{
res[i][endCol] = num++;
}
endCol--;// already did the last col move back one col
for (int i = endCol; i >= startCol; i--)
{
//keep in mind this is a spiral we can be in a line we are not suppose to touch the values
//only in the upper half of the matrix we need
if (startRow <= endRow)
{
res[endRow][i] = num++;
}
}
endRow--;
for (int i = endRow; i >= startRow; i--)
{
//we need to print the numbers only in the left half of the matrix
if (startCol <= endCol)
{
res[i][startCol] = num++;
}
}
startCol++;
}
return res;
}
}
}
</code></pre>
| [] | [
{
"body": "<p>If <code>n</code> is zero then the loop</p>\n\n<pre><code>while (startCol <= endCol && startRow <= endRow)\n</code></pre>\n\n<p>does nothing, which means that the test</p>\n\n<pre><code>if (n == 0)\n</code></pre>\n\n<p>is not necessary.</p>\n\n<p>Here</p>\n\n<pre><code>for (int i = endCol; i >= startCol; i--)\n{\n //keep in mind this is a spiral we can be in a line we are not suppose to touch the values\n //only in the upper half of the matrix we need\n if (startRow <= endRow)\n {\n res[endRow][i] = num++;\n }\n}\n</code></pre>\n\n<p>the condition of the if-statement is a loop invariant, so that it can be done outside of the loop:</p>\n\n<pre><code>if (startRow <= endRow)\n{\n for (int i = endCol; i >= startCol; i--)\n {\n res[endRow][i] = num++;\n }\n}\n</code></pre>\n\n<p>Even if the C# compiler is smart enough to recognize the loop invariant and reorders the statements, the latter variant would be clearer to the reader of your code. The same applies to the next loop in your function.</p>\n\n<p>Then note that <code>startRow</code>/<code>startCol</code> and <code>endRow</code>/<code>endCol</code> have the same value at the start of the loop body, and the tests </p>\n\n<pre><code>if (startRow <= endRow) ...\nif (startCol <= endCol) ...\n</code></pre>\n\n<p>can fail only in the <em>last</em> iteration. Therefore one can move that case out of the main loop, use only two variables for the first and last row/column, and write the inner loops in a symmetric fashion:</p>\n\n<pre><code>int start = 0;\nint end = n - 1;\n\nwhile (start < end)\n{\n for (int i = start; i < end; i++)\n {\n res[start][i] = num++;\n }\n for (int i = start; i < end; i++)\n {\n res[i][end] = num++;\n }\n for (int i = end; i > start; i--)\n {\n res[end][i] = num++;\n }\n for (int i = end; i > start; i--)\n {\n res[i][start] = num++;\n }\n\n start++;\n end--;\n}\n\nif (start <= end)\n{\n res[start][start] = num;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T09:03:59.220",
"Id": "230084",
"ParentId": "229997",
"Score": "1"
}
},
{
"body": "<p>Ignoring everything else, you're iterating the array in a very cache-inefficient manner, and that will ultimately limit the performance. You need to iterate in column-major order, i.e. iterate down a column, and only then advance to next column - assuming that the indices mean <code>[row][column]</code>.</p>\n\n<p>Technically all you need to provide is a way to quickly generate these numbers on the fly, and provide a double-indexable property on the \"matrix\" object, and you're done. But whether LeetCode's implementation can deal with a double-indexable object other than <code>int[][]</code> is unknown to me.</p>\n\n<p>That might be the fastest, since there's no memory overhead, and a conversion between the index and the value is quick (I urge you to look the formula up or figure it out yourself). Note that integer multiplications are fast, so doing a couple of them will be still faster than a cache miss.</p>\n\n<p>But once you got that done, filling the array in any order - whether row-major or column-major is trivial, and it can be parallelized, too. And perhaps you can figure a formula that leverages such order and does even less work than a general item-value formula :)</p>\n\n<p>Let's also note that <code>int</code> is a 32-bit signed type, so the largest integer square that will fit into it must be less than 2^31. Thus, the largest input is 0xB504, and the resulting square matrix has 0x7FFEA810 elements. You'd want to check the argument to make sure it's not too large, and throw an <code>ArgumentOutOfRangeException</code> otherwise.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T12:02:11.157",
"Id": "230092",
"ParentId": "229997",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "230084",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T20:34:01.167",
"Id": "229997",
"Score": "1",
"Tags": [
"c#",
"programming-challenge",
"array"
],
"Title": "LeetCode: Spiral Matrix II C#"
} | 229997 |
<p>I am trying to draw 2d patterns onto grids of different geometric units. I have a small example for a halfmoon pattern on the grid below. In the future, I will add different kinds of movement (eg. fullmoon or circular motion). Eventually there will be different base geometric units as well.</p>
<p>I wonder if there's a way to clean out the direction code, as it's kind of big and randomly splashed around. I also wonder if there's a better way to write the initialization of the grid itself (which is currently a i j for loop).</p>
<p>Any other tips would also be appreciated.</p>
<pre class="lang-py prettyprint-override"><code>import tkinter as tk
import time
import numpy
# set hex colors
cream = '#fafaeb'
umber = '#21201f'
root = tk.Tk()
canvas = tk.Canvas(root, width=650, height=450, bg=umber)
canvas.pack(fill="both", expand=True)
# TODO: freezes when trying to click again sometimes
direction='DOWN'
# note that tkinter canvas starts with an origin in the corner, moving down therefore is *adding* y value,
# so some of the math may look inverted
motion='HALFMOON'
# change direction or motion
def apply_directives(event):
global direction
global motion
if event.char == 'u':
direction = 'UP'
if event.char == 'd':
direction = 'DOWN'
if event.char == 'r':
direction = 'RIGHT'
if event.char == 'l':
direction = 'LEFT'
if event.char == 'c': # stands for 'click'
motion = 'CLICK'
root.bind("<Key>", apply_directives)
WIDTH = 6
# apply bold to line
def bold(event):
# initial boldness
# find arc user meant
id = event.widget.find_closest(event.x,event.y)[0]
# retrieve arc tag
tag = canvas.gettags(id)[1]
# bold arc
canvas.itemconfigure(id,width=WIDTH)
# redraw canvas
canvas.update()
# give time to make each drawing piecemeal
time.sleep(.5)
if motion == 'HALFMOON':
# find within the next enclosed box in the right, the arc with a tag that fits the motion type so long as
# there are no more arcs to the right
set_a = 0
set_b = 0
# sets inverse depending on vertical or horizontal direction
if direction == 'RIGHT' or direction == 'LEFT':
set_a = ['1','2'] # tags are in type string, so we match the type
set_b = ['3','4']
if direction == 'UP' or direction == 'DOWN':
set_a = ['1','4'] # tags are in type string, so we match the type
set_b = ['2','3']
current_set = []
# check to see what kind of curve this is
if tag in set_a:
current_set = set_a
else:
current_set = set_b
# TODO: Sometimes takes an arc that shouldn't be within the bounding box, but can't consistently
# replicate this. find out way and fix
# possibly when you double click?
# direction logic
directional_additive = 0
if direction == 'RIGHT':
directional_additive = numpy.array([arc_width,0])
if direction == 'LEFT':
directional_additive = numpy.array([-arc_width,0])
if direction == 'UP':
directional_additive = numpy.array([0,-arc_width])
if direction == 'DOWN':
directional_additive = numpy.array([0,arc_width])
prev_id = 0
# TODO: buggy while. figure out previous id while loop?
# when there are no more arcs to the desired direction
while (id != prev_id):
print('in while')
print('x is ' + str(event.x))
print('x bound is ' + str(canvas.winfo_width() - arc_width))
print('y is ' + str(event.y))
print('y bound is ' + str(canvas.winfo_height() - arc_width))
# set up variables to find next coordinates
current_box_coords = numpy.array(canvas.coords(id))
# box is too big, we just want the arc box
normalizer = 0
if tag == '1': # take upper right of box
normalizer = numpy.array([arc_width,0,0,-arc_width])
if tag == '2': # take upper left of box
normalizer = numpy.array([0,0,-arc_width,-arc_width])
if tag == '3': # take lower left of box
normalizer = numpy.array([0,arc_width,-arc_width,0])
if tag == '4': # take lower right of box
normalizer = numpy.array([arc_width,arc_width,0,0])
current_arc_coords = current_box_coords + normalizer
next_coords_additive = 0
# directional logic
if direction == 'RIGHT':
next_coords_additive = numpy.array([arc_width,0,arc_width,0])
if direction == 'LEFT':
next_coords_additive = numpy.array([-arc_width,0,-arc_width,0])
if direction == 'UP':
next_coords_additive = numpy.array([0,-arc_width,0,-arc_width])
if direction == 'DOWN':
next_coords_additive = numpy.array([0,arc_width,0,arc_width])
# tkinter's find_enclosed method will exclude any objects it finds right at the perimeter, so make the perimeter slightly larger
boundaries_additive = numpy.array([-1,-1,1,1])
# obtain the next coordinates
next_coords = current_arc_coords + next_coords_additive + boundaries_additive
# obtain list of the next IDs
next_ids = event.widget.find_enclosed(*next_coords)
# obtain list of the next tags
next_tags = [canvas.gettags(next_id)[1] for next_id in next_ids]
last_event_x = event.x
prev_id = id
for next_id,next_tag in zip(next_ids,next_tags):
if ((id != next_id) & (next_tag in current_set)):
# move cursor to the desired direction
if direction == 'RIGHT':
event.x += arc_width
if direction == 'LEFT':
event.x -= arc_width
if direction == 'UP':
event.y -= arc_width
if direction == 'DOWN':
event.y += arc_width
# bold the new arc
canvas.itemconfigure(next_id, width=WIDTH)
canvas.update()
time.sleep(.5)
# update current arc
id = event.widget.find_closest(event.x, event.y)[0]
# update current tag
tag = canvas.gettags(id)[1]
# each bounding box is 100 x 100
class Box():
def __init__(self, coords):
# give the class a tag for tkinter to find later
self.tag = 'box{}'.format(id(self))
# make each arc
self.arcs = [
# arc 1
canvas.create_arc(coords, start=0, extent=90, outline=cream, style="arc", tag=(self.tag, 1)),
# arc 2
canvas.create_arc(coords, start=90, extent=90, outline=cream, style="arc", tag=(self.tag, 2)),
# arc 3
canvas.create_arc(coords, start=180, extent=90, outline=cream, style="arc", tag=(self.tag, 3)),
# arc 4
canvas.create_arc(coords, start=270, extent=90, outline=cream, style="arc", tag=(self.tag, 4))
]
# allow each arc to be bolded
self.bind()
def bind(self):
# apply binding to every arc in box
for arc in self.arcs:
canvas.tag_bind(arc, "<Button-1>", bold)
# coordinates are (x,y) of upper left corner, and then (x,y) of lower left corner
# use numpy array for vector addition
coords = numpy.array([0, 0, 100, 100])
# use box width to calculate grid indice
box_width = coords[2] - coords[0]
# grid indice to move around
grid_indice = box_width/2
# use arc width for width of 1 component
# 4 components in 1 box
arc_width = box_width/2
# make desired size of grid (width, height)
size=[6*2,4*2]
for i in range(size[1]):
for j in range(size[0]):
# keep adding 1 grid indice to the x as you move to the right
box_coords = coords + numpy.array([0 + grid_indice*j, 0, 0 + grid_indice*j, 0])
# create variables to check parity
even_row = i%2 == 0
odd_row = not even_row
even_column = j%2 == 0
odd_column = not even_column
# only draw a box on the same parity of i and j
# that is: on an odd row (i), only draw on odd column (j) values
if even_row & even_column:
Box(tuple(box_coords))
elif odd_row & odd_column:
Box(tuple(box_coords))
# keep adding 1 grid indice to the y as you move down
coords = coords + numpy.array([0, 0 + grid_indice, 0, 0 + grid_indice])
root.mainloop()
</code></pre>
| [] | [
{
"body": "<h2>Const capitalization</h2>\n\n<pre><code>cream = '#fafaeb'\number = '#21201f'\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>CREAM = '#fafaeb'\nUMBER = '#21201f'\n</code></pre>\n\n<h2>Dict lookups</h2>\n\n<pre><code> if event.char == 'u':\n direction = 'UP'\n if event.char == 'd':\n direction = 'DOWN'\n if event.char == 'r':\n direction = 'RIGHT'\n if event.char == 'l':\n direction = 'LEFT'\n</code></pre>\n\n<p>Make a dictionary where the keys are your individual letters and the values are the output direction. This will reduce the actual lookup code to one line.</p>\n\n<p>Do similarly for this block:</p>\n\n<pre><code> # direction logic\n directional_additive = 0\n if direction == 'RIGHT':\n directional_additive = numpy.array([arc_width,0])\n if direction == 'LEFT':\n directional_additive = numpy.array([-arc_width,0])\n if direction == 'UP':\n directional_additive = numpy.array([0,-arc_width])\n if direction == 'DOWN':\n directional_additive = numpy.array([0,arc_width])\n</code></pre>\n\n<p>as well as your <code>normalizer</code> assignment, and so on. In fact, this pattern of four lookups happens so very often that you're probably better off making a <code>Direction</code> class with four instances. Each instance would hold all data specific to its direction.</p>\n\n<h2>Functions</h2>\n\n<p>Try to move your globally-scoped code into logical functions or classes (as appropriate).</p>\n\n<h2>Grammar</h2>\n\n<p><code>indice</code> should actually be <code>index</code>, plural <code>indices</code>.</p>\n\n<h2>Logical, not bit-wise, operations</h2>\n\n<pre><code> if even_row & even_column:\n</code></pre>\n\n<p>Those variables are boolean, so use <code>and</code> instead of <code>&</code>.</p>\n\n<h2>In-place addition</h2>\n\n<pre><code>coords = coords + numpy.array([0, 0 + grid_indice, 0, 0 + grid_indice])\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>coords += numpy.array([0, 0 + grid_indice, 0, 0 + grid_indice])\n</code></pre>\n\n<h2>Exclusive or</h2>\n\n<p>First, </p>\n\n<pre><code> if even_row & even_column:\n Box(tuple(box_coords))\n elif odd_row & odd_column:\n Box(tuple(box_coords))\n</code></pre>\n\n<p>shouldn't have an <code>elif</code> at all. Your second branch does the exact same thing as your first. Instead, use</p>\n\n<pre><code>if (\n even_row and even_column or\n odd_row and odd_column\n):\n</code></pre>\n\n<p>If you want to get fancier, recognize that this is an <em>exclusive nor</em>:</p>\n\n<pre><code>if not (even_row ^ even_column):\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T00:36:32.907",
"Id": "230007",
"ParentId": "229998",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T20:42:02.410",
"Id": "229998",
"Score": "3",
"Tags": [
"python",
"tkinter"
],
"Title": "Create a geometry automata"
} | 229998 |
<p>I wrote some code that iterates over some queries and counts the number of times each query appears in a vector of words. My first iteration iterated through all the words in the vector for each query which is wasteful. I improved it and come up with this. </p>
<pre><code>unordered_map<string, int> matchingStrings(vector<string>& strings, vector<string>& queries) {
sort(strings.begin(), strings.end());
sort(queries.begin(), queries.end());
unordered_map<string,int> counts;
auto s = strings.begin();
bool notfound;
int count = 0;
for (auto& q : queries) {
count = 0;
auto temp = s;
notfound = false;
while (q.compare(*s)) {
if (s != strings.end()-1) {
s++;
}
else {
counts[q] = count;
notfound = true;
s = temp;
break;
}
}
if (notfound) continue;
while (!q.compare(*s)) {
count++;
if (s != strings.end()-1) {
s++;
}
else {
break;
}
}
counts[q] = count;
}
return counts;
}
</code></pre>
<p>It works on my test cases, so I think it has some place here on code review. I would like to know how I can tidy this up? also! In the case where the query is not found we go back to the string the non-present query started at. Is there a way to get around this?</p>
<p>By "tidy this up" I mean, avoiding code repetition and maybe some alternative ideas? Possibly some modern c++ tools even?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T08:01:47.577",
"Id": "447763",
"Score": "0",
"body": "Could you include your tests? That will show what results you expect, and perhaps identify cases you've not tested."
}
] | [
{
"body": "<ul>\n<li><p>You start by sorting both the queries and the strings to search, but you don't seem to make a whole lot of use of the fact that afterwards they're sorted. Fortunately, parts of the standard library make it fairly easy to take better advantage of that as well.</p></li>\n<li><p>It looks like you've preceded your code by something like <code>using namespace std;</code>. This is generally considered a poor idea, and should usually be avoided.</p></li>\n<li><p>When you just want to know if one string equals another, it's often simpler and more readable to use something like <code>if (a == b)</code> than <code>if (!a.compare(b))</code>.</p></li>\n<li><p>The single biggest thing I see here is that the standard library already provides most of the functionality you want, so using it can make the code quite a bit simpler.</p></li>\n</ul>\n\n<p>I'd probably write the code something on this general order:</p>\n\n<p>[edit: modified code to optimize for unique queries, as OP stated in comment.]</p>\n\n<pre><code>std::unordered_map<std::string, int> matchingStrings(std::vector<std::string> &strings, \n std::vector<std::string> &queries) \n{\n std::sort(strings.begin(), strings.end());\n std::sort(queries.begin(), queries.end());\n\n std::unordered_map<std::string, int> counts;\n\n auto start = strings.begin();\n\n for (auto const &q : queries) {\n auto p = std::equal_range(start, strings.end(), q);\n counts[q] = p.second - p.first;\n start = p.second;\n }\n return counts;\n}\n</code></pre>\n\n<p><code>std::equal_range</code> looks for a range (in a sorted sequence) of objects that are equal to one that's specified. It can use a binary search to find the beginning and end of the range, so if the number of strings being searched is large, it can potentially save quite a bit of time. It returns an <code>std::pair</code>--the first item is an iterator to the beginning of the range, and the second an iterator to the beginning of the range. So, we use that to find all the strings that match a given query, and count them by subtracting the two.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T08:08:35.383",
"Id": "447764",
"Score": "0",
"body": "Given that both vectors are sorted, we don't need to start `equal_range()` at `strings.begin()` every time - we should be able to re-use the last `p.second` as the next start point."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T12:07:46.067",
"Id": "447782",
"Score": "0",
"body": "This is what I was attempting to get at when sorting both vectors. If all elements in the query vector appear in my strings vector then I think the complexity is linear in the number of strings as each only gets touched about once irrespective of how many queries (they are both swept through simultaneously). Maybe I have misunderstood. If so then some comments on complexity would be nice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T14:26:10.380",
"Id": "447791",
"Score": "0",
"body": "@TobySpeight: We can only start where the previous search ended if we're guaranteed that queries are unique (and I see nothing in the question to guarantee that). Of course, we could work around that as well, but it's not immediately clear whether we'd gain enough to justify the work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T14:31:59.897",
"Id": "447792",
"Score": "1",
"body": "@HMPARTICLE: `std::equal_range` uses a binary search, so the search part of this (i.e., ignoring the sorting for the moment) is O(N log M), where N is the number of queries, and M is the number of strings. If we guarantee unique queries, we gain a little, but not nearly as much as you might initially think. Assuming random strings, starting from the end of the previous range means searching half as many strings on average. For a binary search, that means one fewer comparisons per search, so it's still O(N log M)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T14:41:13.187",
"Id": "447795",
"Score": "1",
"body": "@JerryCoffin, if queries are non-unique, then `p.first` (instead of `p.second`) still beats `strings.begin()`. As you say, the benefit is small."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T18:13:54.107",
"Id": "447832",
"Score": "0",
"body": "The queries can be considered unique I this case"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T06:25:44.867",
"Id": "230016",
"ParentId": "229999",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "230016",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T21:14:08.100",
"Id": "229999",
"Score": "1",
"Tags": [
"c++"
],
"Title": "Finding the number of times a query string appears in a vector of strings c++"
} | 229999 |
<p><a href="https://leetcode.com/problems/rotting-oranges/" rel="nofollow noreferrer">https://leetcode.com/problems/rotting-oranges/</a><br>
Please review for coding style in 40 minutes job interview.<br></p>
<blockquote>
<p>In a given grid, each cell can have one of three values:</p>
<p>the value 0 representing an empty cell; the value 1 representing a
fresh orange; the value 2 representing a rotten orange. Every minute,
any fresh orange that is adjacent (4-directionally) to a rotten orange
becomes rotten.</p>
<p>Return the minimum number of minutes that must elapse until no cell
has a fresh orange. If this is impossible, return -1 instead.</p>
<pre><code>Example 1:
Input: [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Example 2:
Input: [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
Example 3:
Input: [[0,2]]
Output: 0
Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.
</code></pre>
<p>Note:</p>
<ol>
<li>1 <= grid.length <= 10 </li>
<li>1 <= grid[0].length <= 10 </li>
<li>grid[i][j] is only 0, 1, or 2.</li>
</ol>
</blockquote>
<pre><code>using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace GraphsQuestions
{
/// <summary>
/// https://leetcode.com/problems/rotting-oranges/
/// </summary>
[TestClass]
public class RottingOrangesTest
{
[TestMethod]
public void ExampleTest()
{
int[][] grid =
{
new []{2, 1, 1 },
new []{1, 1, 0},
new []{0, 1, 1}
};
Assert.AreEqual(4, RottingOrangesClass.OrangesRotting(grid));
}
[TestMethod]
public void BadExampleTest()
{
int[][] grid =
{
new []{2, 1, 1 },
new []{0, 1, 1},
new []{1, 0, 1}
};
Assert.AreEqual(-1, RottingOrangesClass.OrangesRotting(grid));
}
}
public class RottingOrangesClass
{
/// <summary>
/// we will use BFS and not DFS because we can move in one step to all of the directions.
/// not one by one and in this way we will get the best result
/// </summary>
/// <param name="grid"></param>
/// <returns></returns>
public static int OrangesRotting(int[][] grid)
{
if (grid == null || grid.Length == 0)
{
return 0;
}
int countFreshOranges = 0;
Queue<int[]> Q = new Queue<int[]>();
for (int row = 0; row < grid.Length; row++)
{
for (int col = 0; col < grid[0].Length; col++)
{
if (grid[row][col] == 2)
{
Q.Enqueue(new int[] { row, col }); // we save the rotten oranges
}
else if (grid[row][col] == 1)
{
countFreshOranges++; // we count the fresh oranges
}
}
}
if (countFreshOranges == 0)
{
return 0;
}
int count = 0;
while (Q.Count > 0)
{
count++;
int size = Q.Count;
for (int i = 0; i < size; i++)
{
int[] point = Q.Dequeue();
//try all directions
int x = point[0];
int y = point[1];
countFreshOranges = TryDirection(grid, x + 1, y, Q, countFreshOranges);
countFreshOranges = TryDirection(grid, x - 1, y, Q, countFreshOranges);
countFreshOranges = TryDirection(grid, x, y + 1, Q, countFreshOranges);
countFreshOranges = TryDirection(grid, x, y - 1, Q, countFreshOranges);
}
}
if (countFreshOranges == 0)
{
return count - 1;
}
return -1;
}
private static int TryDirection(int[][] grid, int x, int y, Queue<int[]> Q, int countFreshOranges)
{
//check out of bounds
//also check for no orange or already rotten
if (x < 0 || y < 0 || x >= grid.Length || y >= grid[0].Length || grid[x][y] == 2 || grid[x][y] == 0)
{
return countFreshOranges;
}
grid[x][y] = 2;
Q.Enqueue(new int[] { x, y });
countFreshOranges--;
return countFreshOranges;
}
}
}
</code></pre>
| [] | [
{
"body": "<p>In your </p>\n\n<pre><code>private static int TryDirection(int[][] grid, int x, int y, Queue<int[]> Q, int countFreshOranges)\n</code></pre>\n\n<p>method I would invert the logic: If the given coordinate is valid and the field contains a fresh orange, then do something:</p>\n\n<pre><code>private static int TryDirection(int[][] grid, int x, int y, Queue<int[]> Q, int countFreshOranges)\n{\n if (x >= 0 && y >= 0 && x < grid.Length && y < grid[0].Length && grid[x][y] == 1)\n {\n grid[x][y] = 2;\n Q.Enqueue(new int[] { x, y });\n countFreshOranges--;\n }\n return countFreshOranges;\n}\n</code></pre>\n\n<p>That is shorter and easier to understand.</p>\n\n<p>The while loop in</p>\n\n<pre><code>public static int OrangesRotting(int[][] grid)\n</code></pre>\n\n<p>does one iteration more than is necessary: When all fresh oranges have rotten, another loop iteration is needed to empty the queue. That is also the reason why <code>count - 1</code> is returned in the success case. It becomes clearer if both <code>countFreshOranges</code> and the queue are checked in the while condition:</p>\n\n<pre><code>int count = 0;\nwhile (countFreshOranges > 0 && Q.Count > 0)\n{\n count++;\n // ...\n}\nreturn countFreshOranges == 0 ? count : -1;\n</code></pre>\n\n<p>That makes also the preceding check</p>\n\n<pre><code>if (countFreshOranges == 0)\n{\n return 0;\n}\n</code></pre>\n\n<p>obsolete.</p>\n\n<p>Some more thoughts:</p>\n\n<ul>\n<li>Use an <code>enum</code> type (with values <code>Free</code>, <code>Fresh</code> and <code>Rotten</code>) instead of the integer constants <code>0</code>, <code>1</code>, <code>2</code>, so that the code becomes more self-explaining.</li>\n<li>Instead of pushing <code>int[]</code> onto the queue, a tuple with two elements, or a <code>struct</code> with two members <code>x</code> and <code>y</code> would be sufficient.</li>\n<li><code>Q</code> is too short as a variable name, it does not tell what the variable is used for.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T15:43:00.573",
"Id": "230110",
"ParentId": "230000",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "230110",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T21:24:40.433",
"Id": "230000",
"Score": "4",
"Tags": [
"c#",
"programming-challenge",
"interview-questions",
"breadth-first-search"
],
"Title": "LeetCode: Rotting Oranges in C#"
} | 230000 |
<p>I have a dictionary that looks like this</p>
<pre><code>masterdict = {'a':['b','c','d','e'],
'b':['c','d','e'],
'c':['d','e'],
'd':['e']
'e':[]}
</code></pre>
<p>where the list has all the values that are 'compatible' with the key and vice-versa. Since the dictionary is non-redundant, repeated compatiblities are not reported in the dictionary. For eg. 'e' is compatible with 'a','b','c' and 'd' but masterdict['e'] is empty since it is reported in the other lists. I would like to identify all groups of elements, such that all the elements are mutually compatible. Hence for the masterdict given above, the solution would be <code>[['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'e'], ['a', 'b', 'd', 'e'], ['a', 'c', 'd', 'e'], ['b', 'c', 'd', 'e']]</code>. Not showing lists of smaller size.</p>
<pre><code>masterdict = {'a':['b','d','e'],
'b':['c','d'],
'c':['e'],
'd':['e'],
'e':[] }
</code></pre>
<p>then the solution would be <code>[['a', 'b', 'd'], ['a', 'd', 'e']]</code>. I did write a recursive function to do this, but it is slow for larger dictionaries (len(list) > 1000). The code is given below. I would like some suggestions on how to write a faster version, maybe using itertools or some other module. Thanks alot</p>
<pre><code>import sys
import os
def recursive_finder(p1,list1,masterdict,d,ans):
# if lenght of d is more than 2, store that list in ans
if len(d) >2 :
ans.append(d)
nextlist = []
# if lenght of list is 0, do not do anythin
if len(list1) == 0:
pass
else:
other = []
for i in list1:
if i in masterdict[p1]:
new = []
new.extend(d)
new.append(i)
other.append(new)
nextlist.append(i)
for i in range(len(nextlist)):
p1 = nextlist[i]
dnew = other[i]
recursive_finder(p1,nextlist[i+1:],masterdict,dnew,ans)
masterdict = {'a':['b','d','e'],
'b':['c','d'],
'c':['e'],
'd':['e'],
'e':[] }
final = []
ans = []
for mainkey in masterdict:
if len(masterdict[mainkey]) > 1:
for i in range(len(masterdict[mainkey])):
p1 = masterdict[mainkey][i]
recursive_finder(p1,masterdict[mainkey][i+1:],masterdict,[mainkey,p1],ans)
print(ans)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T01:47:10.633",
"Id": "447742",
"Score": "5",
"body": "The problem can be formulated as [finding cliques in graphs](https://en.wikipedia.org/wiki/Clique_problem). Finding maximal cliques is an NP-Complete problem. You could consider using third-party libraries such as [networkx](https://networkx.github.io/documentation/stable/reference/algorithms/clique.html) for the task."
}
] | [
{
"body": "<h1>Indentation</h1>\n\n<p>You should use four (4) spaces for indentation, not eight (8).</p>\n\n<h1>Logic</h1>\n\n<p>This</p>\n\n<pre><code>if len(list1) == 0:\n pass\nelse:\n</code></pre>\n\n<p>should be changed to</p>\n\n<pre><code>if list:\n ... code here ...\n</code></pre>\n\n<p>This removes the need for the <code>else</code>, as you instead check if the list contains anything. Check out the <a href=\"https://docs.python.org/3/library/stdtypes.html#truth-value-testing\" rel=\"nofollow noreferrer\">Python Docs on Truth Testing</a>.</p>\n\n<h1>Enumerate</h1>\n\n<p>This</p>\n\n<pre><code>for mainkey in masterdict:\n if len(masterdict[mainkey]) > 1:\n for i in range(len(masterdict[mainkey])):\n p1 = masterdict[mainkey][i]\n recursive_finder(p1,masterdict[mainkey][i+1:],masterdict,[mainkey,p1],ans)\n</code></pre>\n\n<p>can be changed to this</p>\n\n<pre><code>for mainkey in masterdict:\n if len(masterdict[mainkey]) > 1:\n for i, value in enumerate(masterdict[mainkey]):\n p1 = value\n recursive_finder(p1,masterdict[mainkey][i+1:],masterdict,[mainkey,p1],ans)\n</code></pre>\n\n<p>Use enumerate since you are using both the index and the value.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T22:59:36.130",
"Id": "447881",
"Score": "1",
"body": "The `for`-loop can be changed to `for mainkey, mainvalue in masterdict.items()` to avoid multiple references to `masterdict[mainkey]`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T22:29:44.690",
"Id": "230063",
"ParentId": "230009",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T01:30:51.350",
"Id": "230009",
"Score": "3",
"Tags": [
"python",
"hash-map"
],
"Title": "identifying pairwise groups from dictionary"
} | 230009 |
<p>Here's my type:</p>
<pre><code>data Tree a = Empty | Node a (Tree a) (Tree a)
</code></pre>
<p>Here's the instance declaration for Monoid:</p>
<pre><code>instance (Monoid a) => Monoid (Tree a) where
mempty = Empty
mappend Empty Empty = Empty
mappend Empty t = t
mappend t Empty = t
mappend (Node val ta tb) (Node val' ta' tb') = (Node (mappend val val') (mappend ta ta') (mappend tb tb'))
</code></pre>
<p>This compiles, but it was tedious to write and very repetitive. Is there a better way of doing this?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-30T19:30:46.997",
"Id": "451702",
"Score": "0",
"body": "In addition to @Garrison's answer it might be nicer to use the infix `<>` operator in the last line in the place of `mappend`."
}
] | [
{
"body": "<p>You can remove <code>mappend Empty Empty = Empty</code> because that case will be caught by <code>mappend Empty t = t</code>.</p>\n\n<pre><code>instance (Monoid a) => Monoid (Tree a) where\n mempty = Empty\n mappend Empty t = t\n mappend t Empty = t\n mappend (Node val ta tb) (Node val' ta' tb') = (Node (mappend val val') (mappend ta ta') (mappend tb tb'))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T05:52:55.437",
"Id": "230015",
"ParentId": "230013",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T05:13:53.077",
"Id": "230013",
"Score": "3",
"Tags": [
"haskell"
],
"Title": "This is a Monoid instance I wrote for a Tree data type. Is this the most terse way to express mappend?"
} | 230013 |
<p><em>Brevity is for kings as it requires context and context is for kings. Me.</em></p>
<p><a href="https://github.com/dmitrynogin/drycancellation" rel="noreferrer">GitHub</a> and <a href="https://www.nuget.org/packages/Dry.Cancellations" rel="noreferrer">NuGet</a></p>
<p>How many times you have been writing something like this passing those tedious logger/token parameters?</p>
<pre><code>interface IMyService
{
void Method1(…, ILogger logger, CancellationToken token);
void Method2(…, ILogger logger, CancellationToken token);
…
}
</code></pre>
<p>Enough is enough. Please see <a href="https://codereview.stackexchange.com/questions/229222/operation-logger">here</a> about ambient logging. Below is about ambient cancellation.</p>
<p>What we are about to do is to use a special <code>Cancellation</code> helper class like this:</p>
<pre><code> static void Main(string[] args)
{
using (new Cancellation())
{
Task.Run(PingAsync);
ReadLine();
Cancellation.Request();
ReadLine();
}
}
static async Task PingAsync()
{
try
{
while (!Cancellation.Requested)
{
await Task.Delay(100, Cancellation.Token);
WriteLine("Ping");
}
Cancellation.ThrowIfRequested();
}
catch(OperationCanceledException)
{
WriteLine("Ping cancelled");
}
}
</code></pre>
<p>Where <code>Cancellation</code> is defined as:</p>
<pre><code>public class Cancellation : IDisposable
{
static AsyncLocal<CancellationTokenSource> Context { get; } =
new AsyncLocal<CancellationTokenSource>();
public Cancellation()
: this(CancellationToken.None)
{
}
public Cancellation(CancellationToken cancellationToken)
: this(cancellationToken, Timeout.InfiniteTimeSpan)
{
}
public Cancellation(int timeout)
: this(TimeSpan.FromMilliseconds(timeout))
{
}
public Cancellation(TimeSpan timeout)
: this(CancellationToken.None, timeout)
{
}
public Cancellation(CancellationToken cancellationToken, int timeout)
: this(cancellationToken, TimeSpan.FromMilliseconds(timeout))
{
}
public Cancellation(CancellationToken cancellationToken, TimeSpan timeout)
{
Parent = Context.Value;
Context.Value = CancellationTokenSource
.CreateLinkedTokenSource(cancellationToken);
Context.Value.CancelAfter(timeout);
}
public void Dispose()
{
var cts = Context.Value;
Context.Value = Parent;
cts.Dispose();
}
CancellationTokenSource Parent { get; }
public static CancellationToken Token =>
Context.Value?.Token ?? CancellationToken.None;
public static void Request() => Context.Value?.Cancel();
public static bool Requested => Token.IsCancellationRequested;
public static void ThrowIfRequested() => Token.ThrowIfCancellationRequested();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T06:38:53.987",
"Id": "447899",
"Score": "0",
"body": "This `CancellationTokenSource Parent { get; }` won't work in certain context switching situations that's why the `T` of `AsyncLocal` _must_ be the class itself and link to itself too. I experimented with something similar to your solution and wanted to make it a [generic AsycLocal helper](https://github.com/he-dev/reusable/blob/dev/Reusable.OmniLog/src/LoggerScope.cs#L98) but I had to use the `Action<AsyncLocalValueChangedArgs<T>>` ctor overload to make it work when the thread context changed. As this was too tricky I reverted it to use the simpler code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T06:45:33.527",
"Id": "447900",
"Score": "0",
"body": "This is the issue I experienced: [Restore AsyncLocal.Value on ThreadContextChanged](https://stackoverflow.com/questions/57346693/restore-asynclocal-value-on-threadcontextchanged) - the code was running fine with the debugger but it was failing when run under xunit where it was _loosing_ its `Value` property of `AsyncLocal`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T20:16:27.893",
"Id": "449132",
"Score": "0",
"body": "Am I wrong to assume you couldn't use `Cancellation` twice at the same time?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T22:10:30.323",
"Id": "449146",
"Score": "0",
"body": "@IEatBagels There is only one `Cancellation` in the context at a given moment, but you could create a nested one with `using(new Cancellation(...) { ... })`. You would need to pass old plain `CancellationToken` explicitly where two or more are required the same time at the same place though - rarely thing to happen."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T22:12:28.603",
"Id": "449147",
"Score": "0",
"body": "@IEatBagels Here you could find a ready to be tried [demo](https://github.com/dmitrynogin/ambientcontext)."
}
] | [
{
"body": "<p>Not sure if it counts as an answer, but the most important missing part was the following ASP.NET Core attribute:</p>\n\n<pre><code>public class AmbientContextAttribute : Attribute, IAsyncActionFilter\n{\n public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)\n {\n using (new Op(context.HttpContext.Request.GetDisplayUrl()))\n using (new Cancellation(context.HttpContext.RequestAborted))\n await next();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T19:51:58.637",
"Id": "449291",
"Score": "0",
"body": "By lack of more answers, I grant you the bounty for the combined question/answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T06:18:16.060",
"Id": "230075",
"ParentId": "230014",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T05:26:07.603",
"Id": "230014",
"Score": "9",
"Tags": [
"c#",
"asynchronous"
],
"Title": "Operation cancellation"
} | 230014 |
<p>Recently I created a small project: 'media library' (which allow to search, sort and filter items) and I will be glad if some give me constructive feedback about my code. The starting point is <strong>Angular-CLI</strong>, and the full code with starting page is <a href="https://github.com/kamil-kielczewski/media-library/tree/c13ca5cbf7151f02245c16d9ab602375ff99a298/src/app/pages/media-library/media-library-presenter.component.ts" rel="nofollow noreferrer">HERE</a>. And below is 'main' model used in app</p>
<p><a href="https://i.stack.imgur.com/k2dcj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/k2dcj.png" alt="enter image description here"></a></p>
<p>Here are all files which I add/change</p>
<p>file: <strong>media-library//src/index.html</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>MediaLibrary</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<!-- KK: usually we copy fonts to angular project, but here it is not
important so we donwload them on front side -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.css" integrity="sha256-46qynGAkLSFpVbEBog43gvNhfrOj+BmwXdxFgVK/Kvc=" crossorigin="anonymous" />
</head>
<body>
<app-root></app-root>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>file: <strong>media-library//src/app/directives/click-outside.directive.ts</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import {
Directive,
ElementRef,
Output,
EventEmitter,
HostListener
} from '@angular/core';
@Directive({
selector: '[clickOutside]'
})
export class ClickOutsideDirective {
constructor(private _elementRef: ElementRef) {}
@Output()
public clickOutside = new EventEmitter < MouseEvent > ();
@HostListener('document:click', ['$event', '$event.target'])
public onClick(event: MouseEvent, targetElement: HTMLElement): void {
if (!targetElement) {
return;
}
const clickedInside = this._elementRef.nativeElement.contains(targetElement);
if (!clickedInside) {
this.clickOutside.emit(event);
}
}
}</code></pre>
</div>
</div>
</p>
<p>file: <strong>media-library//src/app/app.component.html</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code><!--
KK: Here we usually create layout which contains e.g. menu, top bar... which
comunicate with pages by global events - but for simplicity we ommit global
events setup (like BehaviorSubject or @ngxs/store etc...)
-->
<router-outlet></router-outlet></code></pre>
</div>
</div>
</p>
<p>file: <strong>media-library//src/app/app-routing.module.ts</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import {
NgModule
} from '@angular/core';
import {
Routes,
RouterModule
} from '@angular/router';
import {
MediaLibraryPresenterComponent
} from './pages/media-library/media-library-presenter.component';
const routes: Routes = [{
path: '',
component: MediaLibraryPresenterComponent
}, ];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}</code></pre>
</div>
</div>
</p>
<p>file: <strong>media-library//src/app/models/media-item.ts</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>export class MediaItem {
public id: number;
public title: string;
public type: MediaItemTypeEnum;
public fileType: string;
public keyword: string;
public uploadedAt: string;
public constructor(mediaItem: any) {
if (mediaItem) {
Object.assign(this, mediaItem)
}
}
}
export enum MediaItemTypeEnum {
image = 'image',
document = 'document',
video = 'video',
interactiveVideo = 'interactiveVideo',
audio = 'audio',
}</code></pre>
</div>
</div>
</p>
<p>file: <strong>media-library//src/app/app.module.ts</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import {
BrowserModule
} from '@angular/platform-browser';
import {
NgModule
} from '@angular/core';
import {
AppRoutingModule
} from './app-routing.module';
import {
AppComponent
} from './app.component';
import {
MediaLibraryPresenterComponent
} from './pages/media-library/media-library-presenter.component';
import {
SearchBoxComponent
} from './components/search-box/search-box.component';
import {
MediaItemsListComponent
} from './components/media-items-list/media-items-list.component';
import {
DropdownComponent
} from './components/dropdown/dropdown.component';
import {
TopBarComponent
} from './pages/media-library/top-bar/top-bar.component';
import {
ClickOutsideDirective
} from './directives/click-outside.directive';
import {
FormsModule
} from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
ClickOutsideDirective,
DropdownComponent,
MediaItemsListComponent,
MediaLibraryPresenterComponent,
SearchBoxComponent,
TopBarComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}</code></pre>
</div>
</div>
</p>
<p>file: <strong>media-library//src/app/components/dropdown/dropdown.component.html</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="selected" (click)="showListToggleHandler($event)">
<div class="selected__text">
<div class="selected__label">{{ title }}</div>
<div class="selected__title">{{ selectedItem ? selectedItem.title: 'None' }}</div>
</div>
<div class="selected__button" [class.fa-rotate-90]="!showList">
<i class="fas fa-chevron-down"></i>
</div>
</div>
<div class="list" [class.list__show]="showList" (clickOutside)="hideListHandler()">
<div *ngFor="let item of list; index as i" (click)="selectionHandler(i)" [class.list__item--show]="showList" class="list__item">
<div class="title">{{ item.title }}</div>
<div class="list__selected"><i *ngIf="selectedItemIndex==i" class="fas fa-check"></i></div>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>file: <strong>media-library//src/app/components/dropdown/dropdown.component.scss</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.selected {
border: 1px solid #eee;
border-bottom: none;
border-top: none;
width: 150px;
display: flex;
padding: 10px;
align-items: center;
justify-content: space-between;
cursor: pointer;
}
.selected__label {
color: gray;
font-size: 12px;
}
.selected__title {
color: red;
}
.selected__button {
color: red;
width: 20px;
height: 20px;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.5s;
}
.list {
transition: all 0.5s;
opacity: 0px;
border: 1px solid #eee;
width: 170px;
position: absolute;
background: white;
border-bottom: none;
}
.list__show {
border-bottom: 1px solid #eee;
}
.list__item {
height: 0px;
transition: all 0.5s;
overflow: hidden;
padding-left: 10px;
padding-right: 10px;
opacity: 0;
display: flex;
justify-content: space-between;
align-items: center;
cursor: pointer;
}
.list__item--show {
opacity: 1;
height: 40px;
padding: 10px;
border-bottom: 1px solid #eee;
}
.list__item--show:hover {
background: #eee;
}</code></pre>
</div>
</div>
</p>
<p>file: <strong>media-library//src/app/components/dropdown/dropdownItem.ts</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// KK: We save this 'model' not in `models` directory because this is
// very componnent-inner-view modeel - we don't mix common (api) models with component models
export class DropdownItem {
public title: string;
public value: string;
public constructor(mediaItem: any) {
if (mediaItem) {
this.title = mediaItem.title;
this.value = mediaItem.value;
}
}
}</code></pre>
</div>
</div>
</p>
<p>file: <strong>media-library//src/app/components/dropdown/dropdown.component.ts</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import {
Component,
OnInit,
Output,
EventEmitter,
Input
} from '@angular/core';
import {
MediaItem
} from '../../models/media-item';
import {
DropdownItem
} from './dropdownItem';
@Component({
selector: 'dropdown',
templateUrl: './dropdown.component.html',
styleUrls: ['./dropdown.component.scss']
})
export class DropdownComponent implements OnInit {
@Input() list: DropdownItem[] = [];
@Input() title: string = '';
@Output() select = new EventEmitter < any > ();
public selectedItemIndex = 0;
public selectedItem: DropdownItem = null;
public showList = false;
constructor() {}
ngOnInit() {}
// KK: inner handler
public selectionHandler(index) {
this.selectItem(index);
this.select.emit({
item: this.selectedItem,
index
});
this.showList = false;
}
// KK: part of component 'interface'
public selectItem(index) {
this.selectedItemIndex = index;
this.selectedItem = this.list[index];
}
public getSelected() {
return {
item: this.selectedItem,
index: this.selectedItemIndex
};
}
public showListToggleHandler(event) {
this.showList = !this.showList;
event.stopPropagation();
}
public hideListHandler() {
this.showList = false;
}
}</code></pre>
</div>
</div>
</p>
<p>file: <strong>media-library//src/app/components/media-items-list/media-items-list.component.scss</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.list {
display: flex;
flex - direction: column;
background: white;
padding - bottom: 5 px;
padding - top: 5 px;
}
.row {
display: flex;
flex - direction: column;
background: #ddd;
border - radius: 10 px;
padding: 10 px;
margin: 10 px;
margin - top: 5 px;
margin - bottom: 5 px;
}
.title {
font - size: 20 px;
}
.info {
display: flex;
font - size: 14 px;
}
.keywords {
color: gray;
}
.date {
margin - right: 10 px;
}
.file - type {
margin - left: 10 px;
text - decoration: underline;
}</code></pre>
</div>
</div>
</p>
<p>file: <strong>media-library//src/app/components/media-items-list/media-items-list.component.html</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="list">
<div *ngFor="let item of list" class="row">
<div class="title">{{ item.title }}</div>
<div class="info">
<div class="date">{{ item.uploadedAt | date}}</div>
<div class="keywords">{{ item.keywords }}</div>
<div class="file-type">{{ item.fileType }}</div>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>file: <strong>media-library//src/app/components/media-items-list/media-items-list.component.ts</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import {
Component,
OnInit,
Output,
EventEmitter,
Input
} from '@angular/core';
import {
MediaItem
} from '../../models/media-item';
@Component({
selector: 'media-items-list',
templateUrl: './media-items-list.component.html',
styleUrls: ['./media-items-list.component.scss']
})
export class MediaItemsListComponent implements OnInit {
constructor() {}
@Output() change = new EventEmitter < any > ();
@Input() list: MediaItem[] = [];
ngOnInit() {}
}</code></pre>
</div>
</div>
</p>
<p>file: <strong>media-library//src/app/components/search-box/search-box.component.ts</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import {
Component,
OnInit,
Output,
EventEmitter
} from '@angular/core';
@Component({
selector: 'search-box',
templateUrl: './search-box.component.html',
styleUrls: ['./search-box.component.scss']
})
export class SearchBoxComponent implements OnInit {
@Output() changeSearch = new EventEmitter < any > ();
public searchBoxValue = ''
constructor() {}
ngOnInit() {}
// KK: Normally better would be trigger this handler using some deboucne
// but task demand to fire event every each keystroke
public changeHandler() {
this.changeSearch.emit(this.searchBoxValue);
}
public clean() {
this.searchBoxValue = '';
}
}</code></pre>
</div>
</div>
</p>
<p>file: <strong>media-library//src/app/components/search-box/search-box.component.html</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="search">
<input (keyup)="changeHandler()" [(ngModel)]="searchBoxValue" type='text' class="search-box" autofocus placeholder="Search by Title, Keyword or File Type...">
<div class="icon"><i class="fas fa-search"></i></div>
</div></code></pre>
</div>
</div>
</p>
<p>file: <strong>media-library//src/app/components/search-box/search-box.component.scss</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.search {
display: flex;
background: #444;
}
.search-box {
width: 50%;
margin: 20px;
margin-right: 0;
height: 30px;
border: 1px solid gray;
padding-left: 20px;
font-size: 14px;
outline: none;
border-right: none;
}
.icon {
display: flex;
justify-content: center;
border: 1px solid gray;
align-items: center;
margin: 20px;
margin-left: 0px;
padding: 8px;
border-left: none;
background: #eee;
color: #ccc;
}
input::placeholder {
color: #ccc;
}</code></pre>
</div>
</div>
</p>
<p>file: <strong>media-library//src/app/pages/media-library/media-library-presenter.component.scss</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.main-container {
padding: 20px;
}</code></pre>
</div>
</div>
</p>
<p>file: <strong>media-library//src/app/pages/media-library/media-library-presenter.component.ts</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import {
Component,
OnInit,
ViewChild
} from '@angular/core';
import {
MediaItem
} from '../../models/media-item';
import {
ApiMediaLibraryService
} from '../../services/api-media-library.service';
import {
SearchBoxComponent
} from '../../components/search-box/search-box.component';
import {
TopBarComponent
} from './top-bar/top-bar.component';
@Component({
selector: 'media-library-presenter',
templateUrl: './media-library-presenter.component.html',
styleUrls: ['./media-library-presenter.component.scss']
})
export class MediaLibraryPresenterComponent implements OnInit {
@ViewChild('searchBox', {
static: false
}) public searchBox: SearchBoxComponent;
@ViewChild('topBar', {
static: false
}) public topBar: TopBarComponent;
constructor(public apiMediaLibraryService: ApiMediaLibraryService) {}
itemsAll = [] as MediaItem[];
itemsViewed = [] as MediaItem[];
sortField = '';
sortAsc = true;
filterType = '';
searchString = '';
ngOnInit() {
this.apiMediaLibraryService.getMediaItemsList().subscribe(items => {
this.itemsAll = items;
this.itemsViewed = [...items];
this.topBarCleanHandler();
});
}
public prepareData() {
let itemsFound = this.apiMediaLibraryService.search(this.itemsAll, this.searchString);
let itemsFiltered = this.apiMediaLibraryService.filterBy(itemsFound, this.filterType);
this.itemsViewed = this.apiMediaLibraryService.sort(itemsFiltered, this.sortField, this.sortAsc);
}
public topBarCleanHandler() {
this.searchString = '';
this.sortField = 'uploadedAt';
this.filterType = 'all';
this.searchBox.clean();
this.topBar.resetChildren();
this.sortAsc = true;
this.prepareData();
}
public topBarUpdateSortHandler(event: {
field: string,
sortAsc: boolean
}) {
this.sortField = event.field;
this.sortAsc = event.sortAsc;
this.prepareData();
}
public searchBoxChangeHandler(searchString: string) {
this.searchString = searchString;
this.prepareData();
}
public topBarUpdateFilterHandler(type) {
this.filterType = type;
this.prepareData()
}
}</code></pre>
</div>
</div>
</p>
<p>file: <strong>media-library//src/app/pages/media-library/media-library-presenter.component.html</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main-container">
<search-box #searchBox (changeSearch)="searchBoxChangeHandler($event)">
</search-box>
<top-bar (clean)="topBarCleanHandler()" (updateSort)="topBarUpdateSortHandler($event)" (updateFilter)="topBarUpdateFilterHandler($event)" #topBar>
</top-bar>
<media-items-list [list]="itemsViewed"></media-items-list>
</div></code></pre>
</div>
</div>
</p>
<p>file: <strong>media-library//src/app/pages/media-library/top-bar/top-bar.component.html</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="bar">
<div class="drop-downs-section">
<dropdown #dropdownFilterBy [list]="filterByList" [title]="'Filter By:'" (select)="filterBySelectionHandler($event)">
</dropdown>
<dropdown #dropdownSortBy [list]="sortByList" [title]="'Sort By:'" (select)="sortBySelectionHandler($event)" class="dropdown">
</dropdown>
</div>
<div class="right-buttons">
<div class="clean__btn" (click)="cleanHandler()">
<i class="far fa-times-circle"></i>
<div class="clean__label">Clear</div>
</div>
<div class="sort__btn " (click)="toggleSortDirectionHandler()">
<i *ngIf="!sortAsc" class="fas fa-sort-amount-up-alt"></i>
<i *ngIf="sortAsc" class="fas fa-sort-amount-down-alt"></i>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>file: <strong>media-library//src/app/pages/media-library/top-bar/top-bar.component.ts</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import {
Component,
OnInit,
Output,
EventEmitter,
Input,
ViewChild
} from '@angular/core';
import {
DropdownComponent
} from '../../../components/dropdown/dropdown.component';
import {
DropdownItem
} from '../../../components/dropdown/dropdownItem';
import {
MediaItemTypeEnum
} from '../../../models/media-item';
@Component({
selector: 'top-bar',
templateUrl: './top-bar.component.html',
styleUrls: ['./top-bar.component.scss']
})
export class TopBarComponent implements OnInit {
@ViewChild('dropdownFilterBy', {
static: false
}) public dropdownFilterBy: DropdownComponent;
@ViewChild('dropdownSortBy', {
static: false
}) public dropdownSortBy: DropdownComponent;
//@Input() selectedItem: MediaItem[] = [];
@Output() updateSort = new EventEmitter < any > ();
@Output() updateFilter = new EventEmitter < any > ();
@Output() clean = new EventEmitter < any > ();
public filterByList = [] as DropdownItem[];
public sortByList = [] as DropdownItem[];
public sortAsc = true;
constructor() {}
ngOnInit() {
this.filterByList = [{
title: 'All',
value: 'all'
},
{
title: 'Videos',
value: < string > MediaItemTypeEnum.video
},
{
title: 'Interactive Videos',
value: < string > MediaItemTypeEnum.interactiveVideo
},
{
title: 'Audio',
value: < string > MediaItemTypeEnum.audio
},
{
title: 'Images',
value: < string > MediaItemTypeEnum.image
},
{
title: 'Documents',
value: < string > MediaItemTypeEnum.document
},
].map(item => new DropdownItem(item));
this.sortByList = [{
title: 'Date upload',
value: 'uploadedAt'
},
{
title: 'Alphabetical',
value: 'title'
},
].map(item => new DropdownItem(item));
setTimeout(() => {
this.resetChildren();
});
}
public filterBySelectionHandler(event: {
item: DropdownItem,
index: number
}) {
this.updateFilter.emit(event.item.value);
}
public sortBySelectionHandler(event: {
item: DropdownItem,
index: number
}) {
let e = {
field: event.item.value,
sortAsc: this.sortAsc
}
this.updateSort.emit(e);
}
public cleanHandler() {
this.clean.emit();
}
public toggleSortDirectionHandler() {
this.sortAsc = !this.sortAsc;
this.updateSort.emit({
field: this.dropdownSortBy.getSelected().item.value,
sortAsc: this.sortAsc
});
}
public resetChildren() {
this.dropdownFilterBy.selectItem(0)
this.dropdownSortBy.selectItem(0)
this.sortAsc = true;
}
}</code></pre>
</div>
</div>
</p>
<p>file: <strong>media-library//src/app/pages/media-library/top-bar/top-bar.component.scss</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.drop-downs-section {
display: flex;
}
.dropdown {
margin-left: -1px;
}
.bar {
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 2px solid #eee;
border-top: 2px solid #eee;
background: #fff;
}
.right-buttons {
display: flex;
color: #ddd;
cursor: pointer;
}
.clean__btn {
display: flex;
border-right: 2px solid #eee;
height: 52px;
align-items: center;
padding-right: 10px;
}
.clean__btn:hover {
color: black
}
.clean__label {
margin-left: 5px;
}
.sort__btn {
display: flex;
align-items: center;
justify-content: center;
padding: 15px;
}
.sort__btn:hover {
color: black
}</code></pre>
</div>
</div>
</p>
<p>file: <strong>media-library//src/app/services/api-media-library.service.ts</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import {
Injectable
} from '@angular/core';
import {
HttpClient
} from '@angular/common/http';
import { of ,
Observable
} from 'rxjs';
import {
delay,
map
} from 'rxjs/operators';
import {
MediaItem
} from '../models/media-item';
@Injectable({
providedIn: 'root'
})
export class ApiMediaLibraryService {
constructor() {}
getMediaItemsList(): Observable < MediaItem[] > {
// return this.httpClient
// .get(this.apiUrl + `/api/media-library/items`)
// .pipe(map((res: any) => res.map(item => new MediaItem(item))));
// mockup
return of([{
id: 1,
title: 'Mona Lisa',
type: 'image',
fileType: 'png',
keywords: 'woman',
uploadedAt: "2019-07-01 14:20"
},
{
id: 2,
title: 'The Last Supper',
type: 'image',
fileType: 'jpg',
keywords: 'jesus people',
uploadedAt: "2019-07-02 14:20"
},
{
id: 3,
title: 'Scream',
type: 'image',
fileType: 'gif',
keywords: 'colors face',
uploadedAt: "2019-07-03 14:20"
},
{
id: 4,
title: 'Letting Go: The Pathway of Surrender ',
type: 'document',
fileType: 'pdf',
keywords: 'emotions autotherapy',
uploadedAt: "2019-07-09 14:08"
},
{
id: 5,
title: 'Three Pillars of Zen',
type: 'document',
fileType: 'docx',
keywords: 'japan mind',
uploadedAt: "2019-07-08 14:20"
},
{
id: 6,
title: 'Dhammapada',
type: 'document',
fileType: 'html',
keywords: 'buddha quotes',
uploadedAt: "2019-07-07 14:20"
},
{
id: 7,
title: 'Forest Gump',
type: 'video',
fileType: 'avi',
keywords: 'tom hanks war',
uploadedAt: "2019-07-06 14:20"
},
{
id: 8,
title: 'The Matrix',
type: 'interactiveVideo',
fileType: 'mov',
keywords: 'neo trinity phone',
uploadedAt: "2019-07-05 14:20"
},
{
id: 9,
title: 'Nic śmiesznego',
type: 'video',
fileType: 'mpeg',
keywords: 'pazura komedia',
uploadedAt: "2019-07-04 14:20"
},
].map(item => new MediaItem(item))).pipe(delay(500));
}
public sort(mediaItems: MediaItem[], field, asc) {
return [...mediaItems].sort((a: MediaItem, b: MediaItem) =>
(asc ? 1 : -1) * a[field].localeCompare(b[field])
);
}
public search(mediaItems: MediaItem[], search: string) {
return mediaItems.filter(item => ['title', 'keywords', 'fileType'].some(field =>
item[field].toLocaleLowerCase().includes(search.toLocaleLowerCase())
));
}
public filterBy(mediaItems: MediaItem[], type: string) {
if (type == 'all') return [...mediaItems];
return mediaItems.filter(item => item.type == type);
}
}</code></pre>
</div>
</div>
</p>
<p>file: <strong>media-library//src/styles.scss</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* You can add global styles to this file, and also import other style files */
body,
html {
margin: 0;
padding: 0;
background: gray;
height: 100%;
}</code></pre>
</div>
</div>
</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T08:22:08.547",
"Id": "230020",
"Score": "1",
"Tags": [
"typescript",
"angular-2+"
],
"Title": "Media library project using Angular"
} | 230020 |
<p>Its a conference service code from controller to DAO for conference application.
it contains controller, conference service, dao and entity class, I am seeking for any improvement or code review comments for this. </p>
<pre><code>/**
* This class is responsible for representing as a conference features, this will be the entry point for the conference management system
*
*/
public class ConferenceFacadeController {
private ConferenceService conferenceService;
private VotingService votingService;
private DashBoardService dashBoardService;
private UserService userService;
public ConferenceFacadeController(ConferenceService conferenceService, VotingService votingService,
DashBoardService dashBoardService, UserService userService) {
super();
this.conferenceService = conferenceService;
this.votingService = votingService;
this.dashBoardService = dashBoardService;
this.userService = userService;
}
/**
* This method is responsible for calling conference creation.
* @param meetingName
* @param meetingDescription
* @param organizedBy
* @param conferenceSlides
* @param scheduledTime
* @param attendees
*/
public void createConference(String meetingName, String meetingDescription, String organizedBy,
List<ConferenceSlide> conferenceSlides, LocalDateTime scheduledTime, List<Attendee> attendees) {
ConferenceDetail conferenceDetail = new ConferenceDetail(UUID.randomUUID().timestamp(), meetingName,
meetingDescription, organizedBy, attendees, conferenceSlides, "New", scheduledTime);
conferenceService.createConference(conferenceDetail);
}
/**
* This method is responsible for calling update conference.
* @param updatConferenceDetail
*/
public void updateConferenceDetails(ConferenceDetail updatConferenceDetail) {
conferenceService.updateConferenceDetails(updatConferenceDetail);
}
/**
* This method is responsible for calling cancel conference
* @param cancelledConferenceDetail
*/
public void cancelConference(ConferenceDetail cancelledConferenceDetail) {
conferenceService.cancleConference(cancelledConferenceDetail);
}
/**
* This method is responsible for calling voting service.
* @param voteUpOrDown
*/
public void voteForConference(VoteUpOrDown voteUpOrDown) {
votingService.addVoting(voteUpOrDown);
}
/**
* This method is responsible for providing dash board object.
* @param user
* @return
* @throws UserNotFoundException
*/
public DashBoard getDashBoardData(User user) throws UserNotFoundException{
if(! userService.isUserExists(user)) {
throw new UserNotFoundException();
}
return dashBoardService.getDashBoardData(user);
}
}
////////////////////////////////
/**
* This is a service class which is responsible for performing all the operation for conference.
*
*
*/
public class ConferenceService {
private ConferenceDao conferenceDao;
private ConferenceSlideService conferenceSlideService;
private AttendeeService attendeeService;
private NotificationService notificationService;
public ConferenceService(ConferenceDao conferenceDao, ConferenceSlideService conferenceSlideService,
AttendeeService attendeeService,NotificationService notificationService) {
this.conferenceDao = conferenceDao;
this.conferenceSlideService = conferenceSlideService;
this.attendeeService = attendeeService;
this.notificationService=notificationService;
}
/**
* This method is to create conference.
* @param conferenceDetail
*/
public void createConference(ConferenceDetail conferenceDetail) {
attendeeService.addAttendee(conferenceDetail.getAttendeeList());
conferenceSlideService.addConferenceSlide(conferenceDetail.getConferenceSlide());
conferenceDao.createConference(conferenceDetail);
Notification notification=new Notification(conferenceDetail.getStatus(),conferenceDetail,NotifyStatus.NEW_MEETING);
notificationService.notifyAttendees(notification);
}
/**
* This method is to cancel conference.
* @param cancelledConferenceDetail
*/
public void cancleConference(ConferenceDetail cancelledConferenceDetail) {
cancelledConferenceDetail.setStatus("Cancelled");
conferenceDao.cancelConference(cancelledConferenceDetail);
Notification notification=new Notification(cancelledConferenceDetail.getStatus(),cancelledConferenceDetail,NotifyStatus.CANCEL_MEETING);
notificationService.notifyAttendees(notification);
}
/**
* This method is to update conference
* @param updatConferenceDetail
*/
public void updateConferenceDetails(ConferenceDetail updatConferenceDetail) {
conferenceDao.updateConference(updatConferenceDetail);
Notification notification=new Notification(updatConferenceDetail.getStatus(),updatConferenceDetail,NotifyStatus.UPDATED_MEETING);
notificationService.notifyAttendees(notification);
}
/**
* Get all the organized conference of a user.
* @param user
* @return
*/
public List<ConferenceDetail> getAllConferenceOrganizedBy(User user) {
return conferenceDao.getAllConferenceOrganizedBy(user);
}
/**
* This method is responsible for getting conference by date
* @param date
* @return
*/
public List<ConferenceDetail> getConferencesByDate(LocalDateTime date) {
return conferenceDao.getConferenceByDate(date);
}
}
/**
* This is a DAO class for ConferenceDao.
*
*
*/
public class ConferenceDao {
/**
* This method is responsible for creation of conference.
* @param conferenceDetail
* @return
*/
public ConferenceDetail createConference(ConferenceDetail conferenceDetail) {
throw new UnsupportedOperationException();
}
/**
* This method is responsible for updation of conference.
* @param updateConferenceDetail
* @return
*/
public ConferenceDetail updateConference(ConferenceDetail updateConferenceDetail) {
throw new UnsupportedOperationException();
}
/**
* This method is responsible for cancelation of conference.
* @param cancelledConferenceDetail
* @return
*/
public boolean cancelConference(ConferenceDetail cancelledConferenceDetail) {
throw new UnsupportedOperationException();
}
/**
* This method is responsible for getting all the organized conference of a user
* @param user
* @return
*/
public List<ConferenceDetail> getAllConferenceOrganizedBy(User user) {
throw new UnsupportedOperationException();
}
/**
* This method is responsible for getting conference by date.
* @param date
* @return
*/
public List<ConferenceDetail> getConferenceByDate(LocalDateTime date) {
throw new UnsupportedOperationException();
}
}
/**
* This class is representing DTO object for conference.
*
*
*/
public class ConferenceDetail implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private long id;
private long meetingId;
private String meetingName;
private String meetingDescription;
private String organizedBy;
private List<Attendee> attendeeList;
private List<ConferenceSlide> conferenceSlide;
private LocalDateTime scheduledTime;
private String status;
public ConferenceDetail(long meetingId, String meetingName, String meetingDescription, String organizedBy,
List<Attendee> attendeeList, List<ConferenceSlide> conferenceSlide, String status,LocalDateTime scheduledTime) {
super();
this.meetingId = meetingId;
this.meetingName = meetingName;
this.meetingDescription = meetingDescription;
this.organizedBy = organizedBy;
this.attendeeList = attendeeList;
this.conferenceSlide = conferenceSlide;
this.status = status;
this.scheduledTime=scheduledTime;
}
public LocalDateTime getScheduledTime() {
return scheduledTime;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public long getId() {
return id;
}
public long getMeetingId() {
return meetingId;
}
public String getMeetingName() {
return meetingName;
}
public String getMeetingDescription() {
return meetingDescription;
}
public String getOrganizedBy() {
return organizedBy;
}
public List<Attendee> getAttendeeList() {
return attendeeList;
}
public List<ConferenceSlide> getConferenceSlide() {
return conferenceSlide;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((attendeeList == null) ? 0 : attendeeList.hashCode());
result = prime * result + ((conferenceSlide == null) ? 0 : conferenceSlide.hashCode());
result = prime * result + (int) (id ^ (id >>> 32));
result = prime * result + ((meetingDescription == null) ? 0 : meetingDescription.hashCode());
result = prime * result + (int) (meetingId ^ (meetingId >>> 32));
result = prime * result + ((meetingName == null) ? 0 : meetingName.hashCode());
result = prime * result + ((organizedBy == null) ? 0 : organizedBy.hashCode());
result = prime * result + ((scheduledTime == null) ? 0 : scheduledTime.hashCode());
result = prime * result + ((status == null) ? 0 : status.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ConferenceDetail other = (ConferenceDetail) obj;
if (attendeeList == null) {
if (other.attendeeList != null)
return false;
} else if (!attendeeList.equals(other.attendeeList))
return false;
if (conferenceSlide == null) {
if (other.conferenceSlide != null)
return false;
} else if (!conferenceSlide.equals(other.conferenceSlide))
return false;
if (id != other.id)
return false;
if (meetingDescription == null) {
if (other.meetingDescription != null)
return false;
} else if (!meetingDescription.equals(other.meetingDescription))
return false;
if (meetingId != other.meetingId)
return false;
if (meetingName == null) {
if (other.meetingName != null)
return false;
} else if (!meetingName.equals(other.meetingName))
return false;
if (organizedBy == null) {
if (other.organizedBy != null)
return false;
} else if (!organizedBy.equals(other.organizedBy))
return false;
if (scheduledTime == null) {
if (other.scheduledTime != null)
return false;
} else if (!scheduledTime.equals(other.scheduledTime))
return false;
if (status == null) {
if (other.status != null)
return false;
} else if (!status.equals(other.status))
return false;
return true;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T09:54:31.360",
"Id": "447773",
"Score": "0",
"body": "Welcome to Code Review. I noticed you have defined `equals` and `hashcode' methods of `ConferenceDetail` class using all its fields, are you sure they are all necessary?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T10:35:48.777",
"Id": "447778",
"Score": "2",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] | [
{
"body": "<p>I would suggest folowing:</p>\n\n<p>1) Controller's methods are responsible not only for service call but for request parameter validations. Im <code>getDashBoardData</code> you make validation but what about the other methods.</p>\n\n<p>2) Calling service from service (sample: <code>attendeeService.addAttendee(...)</code> in <code>ConferenceService</code>) is dangerous approach because you can end up in cyclic dependencies. In other words <code>conferenceService</code> depends on <code>attendeeService</code> and <code>attendeeService</code> depends on <code>servicex</code> and <code>servicex</code> depends on <code>conferenceService</code>. Usually it can be solved by extraction common code common logic into dedicated class. So by my ippinion we should not call service from service.</p>\n\n<p>3) Use <a href=\"https://projectlombok.org/features/all\" rel=\"nofollow noreferrer\">lombock</a> library if you can (@Getter, @Setter, @EqualsAndHashCode, @RequiredArgsConstructor). It will make your code clean and highly readable. </p>\n\n<p>4) When you create conference it is good to return at least ID (or created object).</p>\n\n<p>5) Consider to use DTO with mappers (for example <a href=\"https://mapstruct.org/\" rel=\"nofollow noreferrer\">mapstract</a> ). It allows you to separate and control external API and internal implementation.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T09:56:26.977",
"Id": "230025",
"ParentId": "230021",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T09:07:18.350",
"Id": "230021",
"Score": "-3",
"Tags": [
"java"
],
"Title": "Please point out any improvement in it"
} | 230021 |
<p>I did this test for a job and the feedback was:</p>
<p>"while many were added to test private methods, they did not do anything to ensure the public interface worked correctly, edge cases were missed"</p>
<p>But I thought I covered the public interface and edge cases. </p>
<p>Any other improvements I could have made would be appreciated too. </p>
<p>Thanks </p>
<pre><code># Given a words.txt file containing a newline-delimited list of dictionary
# words, please implement the Anagrams class so that the get_anagrams() method
# returns all anagrams from words.txt for a given word.
#
# Requirements:
# - Optimise the code for fast retrieval
# - Thread Safe implementation
# - Write more tests
import unittest
from unittest.mock import patch, MagicMock
import itertools
class Anagrams:
def __init__(self, filename):
self.filename = filename
self.map = {}
def _create_word_list(self):
return open(self.filename).read().splitlines()
def initialise(self):
# This method is to make testing easier (as opposed to creating the map in __init__).
# (we shouldn't need words.txt to exist to be able to test the methods
# unrelated to reading the file
self.words = self._create_word_list()
self.map = self._create_map()
def _create_word_key(self, word):
abbr = sorted(word)
return ''.join(abbr)
def _create_map(self):
word_map = {}
for word in self.words:
key = self._create_word_key(word)
word_map.setdefault(key, []).append(word)
return word_map
def get_anagrams(self, word):
key = self._create_word_key(word)
try:
return self.map[key]
except KeyError:
print('Word is not in dictionary')
# Integration tests
class TestAnagrams(unittest.TestCase):
def test_anagrams(self):
anagrams = Anagrams('words.txt')
anagrams.initialise()
self.assertEqual(anagrams.get_anagrams('plates'), ['palest', 'pastel', 'petals', 'plates', 'staple'])
self.assertEqual(anagrams.get_anagrams('eat'), ['ate', 'eat', 'tea'])
@patch('builtins.print')
def test_anagrams_not_exist(self, mock_print):
anagrams = Anagrams('words.txt')
anagrams.initialise()
anagrams.get_anagrams('abcdef')
mock_print.assert_called_once_with('Word is not in dictionary')
# Unit tests
class TestAnagramsMethods(unittest.TestCase):
def test_create_word_key(self):
words = ['palest', 'pastel', 'petals', 'plates', 'staple']
anagrams = Anagrams('fakefilename')
results = []
for word in words:
key = anagrams._create_word_key(word)
results.append(key)
expected = 'aelpst'
for result in results:
self.assertEqual(result, expected)
def test_create_map(self):
anagrams = Anagrams('fakefilename')
anagrams._get_word_key = MagicMock(side_effect=['key1', 'key1', 'key1', 'key2', 'key2', 'key2'])
anagrams.words = ['palest', 'pastel', 'plates', 'ate', 'eat', 'tea']
result = anagrams._create_map()
expected = {'aelpst': ['palest', 'pastel', 'plates'],
'aet': ['ate', 'eat', 'tea']}
self.assertEqual(result, expected)
@patch('builtins.open')
def test_create_word_list(self, mock_open):
mock_open.return_value.read.return_value = 'one\ntwo\nthree\n'
anagrams = Anagrams('fakefilename')
result = anagrams._create_word_list()
self.assertEqual(result, ['one', 'two', 'three'])
def test_initialise(self):
anagrams = Anagrams('fakefilename')
anagrams._create_word_list = MagicMock(return_value='word_list')
anagrams._create_map = MagicMock(return_value='map')
anagrams.initialise()
anagrams._create_map.assert_called_once()
anagrams._create_word_list.assert_called_once()
self.assertEqual(anagrams.words, 'word_list')
self.assertEqual(anagrams.map, 'map')
class TestGetAnagrams(unittest.TestCase):
def test_existing_word(self):
anagrams = Anagrams('fakefilename')
anagrams._create_word_key = MagicMock(return_value='key')
anagrams.map = {'key': ['anagram1', 'anagram2']}
result = anagrams.get_anagrams('word')
self.assertEqual(result, ['anagram1', 'anagram2'])
@patch('builtins.print')
def test_incorrect_word(self, mock_print):
anagrams = Anagrams('fakefilename')
anagrams._get_word_key = MagicMock(return_value='key')
anagrams.map = {'notkey': ['anagram1', 'anagram2']}
result = anagrams.get_anagrams('word')
mock_print.assert_called_once_with('Word is not in dictionary')
if __name__ == '__main__':
unittest.main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T09:56:47.880",
"Id": "447774",
"Score": "1",
"body": "Did the feedback not inform you about any missed edge-cases? That sounds like rather terrible feedback to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T10:02:15.240",
"Id": "447775",
"Score": "1",
"body": "Because of your description I added the [tag:interview-questions] tag. Feel free to remove it if you don't deem it appropriate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T11:08:54.837",
"Id": "447781",
"Score": "0",
"body": "I guess I should have also done the following (?):\n1) returned a helpful error message if a non-string argument was given to get_anagrams() and created a unit test for this\n2) Created unit test for get_anagrams() with empty string argument (although I think this is the same as the unit test test_incorrect_word())\n3) Created a unit test for when initialise() is not called first (so self.map doesn't exist). However I think this is also the same as test_incorrect_word()"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T19:04:14.167",
"Id": "447846",
"Score": "0",
"body": "@Gloweye Absolutely. Unfortunately, that appears to be somewhat common nowadays."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T13:46:31.723",
"Id": "447951",
"Score": "0",
"body": "Can you add more context about what the code is supposed to do? If this is a programming challenge/interview question, can you include the prompt and your own explanation of how you solved it?"
}
] | [
{
"body": "<p>For an interview, I would test everything very thoroughly. </p>\n\n<p>The public interface consists of <code>Anagrams()</code>, <code>Anagrams.initialise()</code>, and <code>Anagrams.get_anagram()</code>. The public interface also includes the fact that <code>initialise()</code> needs to be called before <code>get_anagram()</code> and the format of text file.</p>\n\n<p>So test everything:</p>\n\n<p>For <code>Anagram(filename)</code>: (some of these errors don't occur until <code>initialise()</code> is called)</p>\n\n<ul>\n<li>no filename</li>\n<li>empty filename</li>\n<li>bad filename (bad characters in the filename)</li>\n<li>bad file permissions</li>\n</ul>\n\n<p>For <code>initialise()</code></p>\n\n<ul>\n<li>call <code>get_anagrams() without calling</code>initialize()` first</li>\n<li>was the file opened?</li>\n<li>did the whole file get read?</li>\n<li>was the file closed? (No)</li>\n<li>bad format of the file (multiple words per line; blank lines; with/without \\n at the end; words with hyphens, apostrophes, or other unusual characters, ...)</li>\n</ul>\n\n<p>For <code>get_anagrams(word)</code>:</p>\n\n<ul>\n<li>called with no word</li>\n<li>called with empty word</li>\n<li>called with really long word</li>\n<li>called with word that has spaces, control characters, digits, uppercase, lowercase, apostrophes, hyphens, and/or strange unicode characters</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T18:23:29.557",
"Id": "230048",
"ParentId": "230024",
"Score": "1"
}
},
{
"body": "<p>This mostly a response to your comment, but I feel it really shouldn't be another comment.</p>\n\n<blockquote>\n <p>I guess I should have also done the following (?): 1) returned a helpful error message if a non-string argument was given to get_anagrams() and created a unit test for this 2) Created unit test for get_anagrams() with empty string argument (although I think this is the same as the unit test test_incorrect_word()) 3) Created a unit test for when initialise() is not called first (so self.map doesn't exist). However I think this is also the same as test_incorrect_word()</p>\n</blockquote>\n\n<p>I disagree on all those cases.</p>\n\n<ol>\n<li>I would expect to get raised a TypeError in this case. A wrong argument is an exceptional case, and exceptions are the best way to handle it. Arguably, getting a non-string here is a programming error, though in rare cases it might be a user error. </li>\n<li>This should be able to be handled perfectly fine with an ordinary response. The response to any string is a list of anagrams. Since there are no anagrams to an empty string, a list with just an empty string is the correct response, just like the response to any other word without anagram is just a list containing that word.</li>\n<li>You should still do that work in <code>__init__</code>. However, you might want to supply a special testing file upon instantiation for tests, containing just the anagrams you test on. For tests that don't care about reading the file, you can give it an empty file. You can import from the <a href=\"https://docs.python.org/3/library/tempfile.html\" rel=\"nofollow noreferrer\">tempfile</a> module for this. You can also hardcode the contents of your testing file, dump it into a tempfile, and use that for testing the tests that DO need a file.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T06:47:50.593",
"Id": "230077",
"ParentId": "230024",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T09:44:26.203",
"Id": "230024",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"unit-testing",
"interview-questions"
],
"Title": "Unit tests for anagram finder"
} | 230024 |
<p>I'm creating a download manager in C# (in combination with Unity 2019.1.8, running the .NET 4.x equivalent (MONO) scripting back end). To accomplish this I decided to start using interfaces and class inheritance through an (abstract) base class. As those are things I have never used before, To get to know how they work and learn to use them properly.</p>
<p>The below code works for my implementation and does what I expect it to do, but I am wondering if i'm using the interface and inheritance correctly (and if it is needed at all), or if I should adjust things to adhere to the rules around using these correctly. So my questions are mostly about the structure of the code, but other feedback is also appreciated!</p>
<p><code>IDownloadEntry</code>: The interface I use to lay down the minimum requirements a DownloadEntry needs to have</p>
<pre><code>using System.Collections.Generic;
using System.Net;
interface IDownloadEntry
{
int CommandSequenceNumber { get; }
string FileName { get; }
HttpListenerResponse DownloadResponse { get; }
List<byte> DownloadDataBuffer { get; set; }
List<ResponseHeaderData> ResponseHeaders { get; set; }
void AddToDataBuffer(byte[] data);
void AddResponseHeader(ResponseHeaderData responseHeader);
void ClearDataBuffer();
string LogDownloadDataBuffer();
string LogClassBuffer();
}
</code></pre>
<p>From this interface I create the abstract base class <code>DownloadEntry</code> which contains the implementations of the interface for the Properties and Methods I think every derived class <em>needs</em> to have implemented in order for it to function as a download type.
<code>DownloadEntry:</code></p>
<pre><code>using System.Collections.Generic;
using System.Net;
using System.Text;
/// <summary>
/// Base class for the different DownloadEntry types
/// </summary>
public abstract class DownloadEntry : IDownloadEntry
{
//CommandSequenceNumber is used to track a specific download
public int CommandSequenceNumber { get; private set; }
public string FileName { get; private set; }
public HttpListenerResponse DownloadResponse { get; private set; }
//The data downloaded
private List<byte> downloadDataBuffer;
public List<byte> DownloadDataBuffer
{
get
{
if (downloadDataBuffer == null) downloadDataBuffer = new List<byte>();
return downloadDataBuffer;
}
set
{
downloadDataBuffer = value;
}
}
//The responses send by the server containing information about the send packets
private List<ResponseHeaderData> responseHeaders;
public List<ResponseHeaderData> ResponseHeaders
{
get
{
if (responseHeaders == null) responseHeaders = new List<ResponseHeaderData>();
return responseHeaders;
}
set
{
responseHeaders = value;
}
}
/// <summary>
/// Create a new base DownloadEntry
/// </summary>
/// <param name="CommandSequenceNumber">The csn associated with this download</param>
/// <param name="FileName">The file name of the file downloaded</param>
/// <param name="DownloadResponse">The response over which the data can be send</param>
public DownloadEntry(int CommandSequenceNumber, string FileName, HttpListenerResponse DownloadResponse)
{
this.CommandSequenceNumber = CommandSequenceNumber;
this.FileName = FileName;
this.DownloadResponse = DownloadResponse;
UnityEngine.Debug.LogFormat("<color=#00aa00>Base Constructor:</color> Created type: {0}: {1}", GetType().Name, ToString());
}
public void AddResponseHeader(ResponseHeaderData responseHeader) => responseHeaders.Add(responseHeader);
public void ClearResponseHeader() => responseHeaders.Clear();
public void AddToDataBuffer(byte[] data) => downloadDataBuffer.AddRange(data);
public void ClearDataBuffer() => downloadDataBuffer.Clear();
/// <summary>
/// Get the ASCII representation of the data found in the data buffer
/// </summary>
/// <returns>ASCII string of the DownloadDataBuffer</returns>
public string LogDownloadDataBuffer() => Encoding.ASCII.GetString(DownloadDataBuffer.ToArray());
public abstract string LogClassBuffer();
public override string ToString() => string.Format("CommandSequenceNumber: {0}, FileName: {1}, Data.length: {2}", CommandSequenceNumber, FileName, DownloadDataBuffer.Count);
}
</code></pre>
<p>I inherit from this base class when creating the download classes themselves, which I have divided into four categories: </p>
<ul>
<li><code>RunningDownloadEntry</code> for downloads that are active.</li>
<li><code>CompletedDownloadEntry</code> for downloads that have successfully completed.</li>
<li><code>FailedDownloadEntry</code> for downloads that encoutered an error and could not finish</li>
<li><code>CanceledDownloadEntry</code> for downloads that have been canceled by the user.</li>
</ul>
<p>being implemented like this:</p>
<pre><code>using System.Collections.Generic;
using System.Net;
using System.Text;
/// <summary>
/// Class used for downloads that have been completed without Error or cancelation
/// </summary>
public sealed class CompletedDownloadEntry : DownloadEntry
{
internal CompletedDownloadEntry(int CommandSequenceNumber, string FileName, HttpListenerResponse DownloadResponse)
: base(CommandSequenceNumber, FileName, DownloadResponse) { }
internal byte[] CompletionBuffer { get; private set; }
internal void SetCompletionBuffer(byte[] data) => CompletionBuffer = data;
internal void ClearCompletionBuffer() => CompletionBuffer = new byte[0];
public override string LogClassBuffer() => string.Format("CompletionBuffer: {0}", Encoding.ASCII.GetString(CompletionBuffer));
}
/// <summary>
/// Class used to store downloads that have failed with an error, and won't have any usable data.
/// </summary>
public sealed class FailedDownloadEntry : DownloadEntry
{
internal FailedDownloadEntry(int CommandSequenceNumber, string FileName, HttpListenerResponse DownloadResponse)
: base(CommandSequenceNumber, FileName, DownloadResponse)
{
UnityEngine.Debug.LogErrorFormat("Download {0} failed: {1}", ToString(), LogClassBuffer());
}
internal byte[] ErrorBuffer { get; private set; }
internal void SetErrorBuffer(byte[] data) => ErrorBuffer = data;
internal void ClearErrorBuffer() => ErrorBuffer = new byte[0];
public override string LogClassBuffer() => string.Format("ErrorBuffer: {0}", Encoding.ASCII.GetString(ErrorBuffer));
}
/// <summary>
/// Class used for downloads that have been canceled but still contain usuable data
/// </summary>
public sealed class CanceledDownloadEntry : DownloadEntry
{
internal CanceledDownloadEntry(int CommandSequenceNumber, string FileName, HttpListenerResponse DownloadResponse)
: base(CommandSequenceNumber, FileName, DownloadResponse) { }
internal byte[] CanceledBuffer { get; private set; }
internal void SetCanceledBuffer(byte[] data) => CanceledBuffer = data;
internal void ClearCanceledBuffer() => CanceledBuffer = new byte[0];
public override string LogClassBuffer() => string.Format("CanceledBuffer: {0}", Encoding.ASCII.GetString(CanceledBuffer));
}
</code></pre>
<p>This is the implementation:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
public class ServerConnect : MonoBehaviour
{
internal static bool applicationRunning = true;
internal static TcpClient client;
internal static HttpListener listener;
internal static HttpListenerContext listenerContext;
private static string uri = "0.0.0.0";
internal static DownloadManager dlManager;
internal static string LocalIP { get; private set; }
static string GetLocalIPAddress()
{
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("No available IPv4 network was found");
}
internal static int LocalPort { get; private set; }
private static int GetLocalOpenPort()
{
TcpListener l = new TcpListener(IPAddress.Loopback, 0);
l.Start();
int port = ((IPEndPoint)l.LocalEndpoint).Port;
l.Stop();
return port;
}
private void Start()
{
dlManager = new DownloadManager();
LocalIP = GetLocalIPAddress();
LocalPort = GetLocalOpenPort();
Thread openConnectionThread = new Thread(() => OpenConnection());
openConnectionThread.Start();
Thread setupListenerThread = new Thread(() => SetupHttpListener());
setupListenerThread.Start();
}
private void OnApplicationQuit()
{
client.Close();
applicationRunning = false;
}
private static void OpenConnection()
{
IPAddress hostAddress = Dns.GetHostAddresses(uri)[0];
IPEndPoint hostEndPoint = new IPEndPoint(hostAddress, 8080);
client = new TcpClient(AddressFamily.InterNetwork);
}
static void SetupHttpListener()
{
listener = new HttpListener();
listener.Prefixes.Add(string.Format("http://{0}:{1}/", LocalIP, LocalPort));
listener.Start();
Thread listenerThread = new Thread(ListenOnHttp);
listenerThread.Start();
}
static void ListenOnHttp()
{
Debug.Log("Starting HttpListener on threadID: " + Thread.CurrentThread.ManagedThreadId);
//We want the listener to be listening at all times
while (applicationRunning)
{
if (!listener.IsListening)
{
Debug.LogErrorFormat("Listener has stopped listening");
}
else
{
IAsyncResult result = listener.BeginGetContext(new AsyncCallback(HttpListenerCallback), listener);
//Wait until a new request has been send over http...
result.AsyncWaitHandle.WaitOne(-1, false);
}
}
}
private static void HttpListenerCallback(IAsyncResult ar)
{
HttpListener listener = (HttpListener)ar.AsyncState;
var downloadContext = listener.EndGetContext(ar);
string requestedFileName = downloadContext.Request.Url.AbsolutePath.Substring(1);
HttpListenerResponse response = downloadContext.Response;
dlManager.CreateVideoFileRequest(requestedFileName, response);
}
}
public class DownloadManager
{
internal List<RunningDownloadEntry> runningDownloads = new List<RunningDownloadEntry>();
internal List<CompletedDownloadEntry> completedDownloads = new List<CompletedDownloadEntry>();
internal List<FailedDownloadEntry> failedDownloads = new List<FailedDownloadEntry>();
internal List<CanceledDownloadEntry> canceledDownloads = new List<CanceledDownloadEntry>();
private static int commandSequenceNumber = 10000;
internal int GetNewCommandSequenceNumber() => ++commandSequenceNumber;
internal DownloadManager()
{
//Start a thread on which the responses from the server can be downloaded
Thread downloadResponseThread = new Thread(DownloadResponseListener);
downloadResponseThread.Start();
}
private void DownloadResponseListener()
{
while (ServerConnect.applicationRunning)
{
if (ServerConnect.client?.Available > 0)
{
ReadDownloadResponse();
}
}
}
private void SendServerRequest(byte[] data)
{
//Send the request to the server
NetworkStream stream = ServerConnect.client.GetStream();
stream.Write(data, 0, data.Length);
}
internal void CreateVideoFileRequest(string fileName, HttpListenerResponse response)
{
//Create the request string
string requestString = string.Format("GET_FILE {0}", fileName);
byte[] message = Encoding.ASCII.GetBytes(requestString);
int requestCommandSequenceNumber = GetNewCommandSequenceNumber();
//Wrap the request in a header that the server can validate
GeneralHeaderData requestWithHeader = new GeneralHeaderData(message.Length, GeneralHeaderData.PacketType.Download_Control, requestCommandSequenceNumber, message);
byte[] serializedRequest = requestWithHeader.SerializeHeader();
//Create a new download entry for the requested file
RunningDownloadEntry downloadEntry = new RunningDownloadEntry(requestCommandSequenceNumber, fileName, response);
runningDownloads.Add(downloadEntry);
SendServerRequest(serializedRequest);
}
private void ReadDownloadResponse()
{
//Create an empty response header
var packetSize = -1;
GeneralHeaderData.PacketType module = GeneralHeaderData.PacketType.Undefined;
var sequenceNumber = -1;
//Get the header from the first 12 bytes
GetNewDataPacketHeader(ref packetSize, ref module, ref sequenceNumber);
//Wait for the client to have enough data available to downlaod the entire package in one go. This *shouldn't* be necessary, but it is...
while (ServerConnect.client.Available < packetSize - 12)
{
Thread.Sleep(0);
}
//Get the matching DownloadEntry from the runningDownloads based on the commandSequenceNumber found in the header
RunningDownloadEntry currentDownload = null;
try
{
currentDownload = runningDownloads.Where(o => o.CommandSequenceNumber == sequenceNumber).FirstOrDefault();
}
catch (Exception e)
{
//throw new NullReferenceException();
Debug.LogErrorFormat("e:{0}", e);
return;
}
//Determine how much data needs to be read
var bytesLeftToRead = packetSize - 12;
var totalBytesRead = 0;
var bytesReadThisPacket = 0;
var dataReadBuffer = new byte[bytesLeftToRead];
//Read all the data off the NetworkStream
NetworkStream stream = ServerConnect.client.GetStream();
while (totalBytesRead < bytesLeftToRead)
{
bytesReadThisPacket = stream.Read(dataReadBuffer, totalBytesRead, bytesLeftToRead);
totalBytesRead += bytesReadThisPacket;
bytesLeftToRead -= bytesReadThisPacket;
}
ReadResponseMessage(dataReadBuffer, module, currentDownload);
}
static void GetNewDataPacketHeader(ref int packetSize, ref GeneralHeaderData.PacketType module, ref int sequenceNumber)
{
byte[] headerBuffer = new byte[12];
int numberOfHeaderBytesRead = 0;
//Wait for the server to atleast have 12 bytes available so it can download an entire header
while (ServerConnect.client.Available < 12)
{
Thread.Sleep(0);
}
//Download the header
while (numberOfHeaderBytesRead < 12)
{
NetworkStream stream = ServerConnect.client.GetStream();
numberOfHeaderBytesRead = stream.Read(headerBuffer, numberOfHeaderBytesRead, headerBuffer.Length - numberOfHeaderBytesRead);
}
//Extract the data from the header
packetSize = BitConverter.ToInt32(headerBuffer, 0);
module = (GeneralHeaderData.PacketType)BitConverter.ToInt32(headerBuffer, 4);
sequenceNumber = BitConverter.ToInt32(headerBuffer, 8);
}
private void ReadResponseMessage(byte[] data, GeneralHeaderData.PacketType module, RunningDownloadEntry currentDownload)
{
switch (module)
{
//Packet types marked as Download_Control only contain data about the oncoming, or peviousy downloaded file data, but no actual file data.
case GeneralHeaderData.PacketType.Download_Control:
var responseMessage = Encoding.ASCII.GetString(data);
//If we encounter an error we remove the current download from the running list and add it to the error list. Closes the outputstream
if (responseMessage.Contains("error"))
{
Debug.LogErrorFormat("Moving {0} to failedDownloads from ERROR case", currentDownload.ToString());
currentDownload.SetErrorBuffer(data);
Debug.LogErrorFormat("Error: {0}", currentDownload.LogErrorBuffer());
currentDownload.DownloadResponse.OutputStream.Close();
failedDownloads.Add((FailedDownloadEntry)currentDownload);
runningDownloads.Remove(currentDownload);
}
//DELETED signifies that the entire file has been transfered, moves the currentDownload to the completed list
//Writes all the data to the response.outputstream and closes the stream.
else if (responseMessage.Contains("deleted"))
{
currentDownload.SetCompletionBuffer(data);
string s = Encoding.ASCII.GetString(currentDownload.AcknowledgeBuffer.ToArray());
if (s.Contains("cancel"))
{
currentDownload.DownloadResponse.OutputStream.Close();
canceledDownloads.Add((CanceledDownloadEntry)currentDownload);
runningDownloads.Remove(currentDownload);
return;
}
currentDownload.SetCompletionBuffer(data);
try
{
if (runningDownloads.Contains(currentDownload))
{
currentDownload.DownloadResponse.OutputStream.Write(currentDownload.DownloadDataBuffer.ToArray(), 0, currentDownload.DownloadDataBuffer.Count);
}
else
{
Debug.LogErrorFormat("CurrentDownload was not in runningDownloads, not writing data");
}
}
catch (IOException e)
{
Debug.LogErrorFormat("OutputStream.Write:: {0}", e);
Debug.LogErrorFormat("current download: {0}", currentDownload.ToString());
currentDownload.DownloadResponse.OutputStream.Close();
}
currentDownload.DownloadResponse.OutputStream.Close();
completedDownloads.Add((CompletedDownloadEntry)currentDownload);
runningDownloads.Remove(currentDownload);
}
else if (responseMessage.Contains("ok"))
{
currentDownload.AddToAcknowledgeBuffer(data);
}
else if (responseMessage.Contains(("prop")))
{
currentDownload.SetPropertiesBuffer(data);
}
break;
//Packets marked Download_Data only contain a 12 byte header and data. Add the downloaded data to the currentDownload's DataBuffer
case GeneralHeaderData.PacketType.Download_Data:
//Extract the 12 byte header containing the package number and max package number
try
{
if (runningDownloads.Contains(currentDownload))
{
currentDownload.AddToDataBuffer(data.Skip(12).ToArray());
}
}
catch (Exception e)
{
Debug.LogErrorFormat("DownloadData:: {0}", e);
}
break;
default:
break;
}
}
}
public class GeneralHeaderData
{
private readonly int packetSize;
public enum PacketType { Undefined = 0, General = 1, Config = 2, Database = 3, Download_Control = 4, Download_Data = 5, Upload_Control = 6, Upload_Data = 7 };
private readonly PacketType packetType;
private readonly int packetCommandSequenceNumber;
private readonly List<byte> packetData = new List<byte>();
public GeneralHeaderData(int size, PacketType type, int sequenceNumber, byte[] data)
{
//we add +12 to the size because that is the total amount of bytes used for the header itself (3x int32 which is 4bytes * 3)
packetSize = size + 12;
packetType = type;
packetCommandSequenceNumber = sequenceNumber;
packetData = data.ToList();
}
public byte[] SerializeHeader()
{
List<byte> packetAsBytes = new List<byte>();
packetAsBytes.AddRange(BitConverter.GetBytes(packetSize));
packetAsBytes.AddRange(BitConverter.GetBytes((int)packetType));
packetAsBytes.AddRange(BitConverter.GetBytes(packetCommandSequenceNumber));
packetAsBytes.AddRange(packetData);
byte[] result = packetAsBytes.ToArray();
return result;
}
}
[System.Serializable]
public class ResponseHeaderData
{
public enum Mp4DataPart { WholeFile = 0, Ftyp_Moov = 1, Ftyp = 2, Moov = 3, Mfra = 4, AllFragments = 5, Fragment = 6 };
public Mp4DataPart mp4DataPart { get; private set; }
public int BlockSequenceNumber { get; private set; }
public int TotalNumberOfBlocks { get; private set; }
public ResponseHeaderData(byte[] responseHeader)
{
mp4DataPart = (Mp4DataPart)BitConverter.ToInt32(responseHeader, 0);
BlockSequenceNumber = BitConverter.ToInt32(responseHeader, 4);
TotalNumberOfBlocks = BitConverter.ToInt32(responseHeader, 8);
}
}
</code></pre>
<p>I have not further implemented the handling of Entries after they have been sorted, but that would be out of scope for this question.</p>
<p>My question(s):</p>
<ul>
<li>Am I using interface correctly/does it make sense to use in this case?</li>
<li>Am I using inheritance from an abstract base class correctly? I went with abstract to force inheritors to implement their own <code>LogClassBuffer</code> method.</li>
<li>To be able to cast a <code>RunningDownloadEntry</code> to any of the other three I implemented my own User-defined conversion operators. Is this a proper way to do this?</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T16:49:39.533",
"Id": "447981",
"Score": "0",
"body": "Could you show us how you are using these classes and how you switch e.g. from `RunningDownloadEntry` to let's say `FailedDownloadEntry`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T06:55:46.210",
"Id": "448050",
"Score": "0",
"body": "Can you post the real code? This one is heavily edited; many parts are missing and the ones that are there use invalid syntax and contain many typos."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T08:07:19.263",
"Id": "448060",
"Score": "1",
"body": "@t3chb0t I've added the actual implementation, I had to remove any sensitive data like ip addresses and validation though. I hope this is enough information to work with, as i'm not able to provide any further information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T08:57:01.927",
"Id": "448073",
"Score": "1",
"body": "I'd say this is enough and it looks good now ;-]"
}
] | [
{
"body": "<ol>\n<li>There's clearly no value in the interface.</li>\n<li>Although I'm a proponent of using inheritance only in cases when you need to exercise <a href=\"https://www.geeksforgeeks.org/dynamic-method-dispatch-runtime-polymorphism-java/\" rel=\"nofollow noreferrer\">dynamic polymorphism</a> and this is not a case, your abstract class looks kinda ok as implementations are pretty similar and there's a lot of them. Still, you might consider using composition which is <a href=\"https://en.wikipedia.org/wiki/Composition_over_inheritance\" rel=\"nofollow noreferrer\">preferrable</a>. Making <code>LogClassBuffer</code> abstract is a neat trick and widely used for abstract classes. The only real downfall I see is that your classes do not conform <a href=\"https://en.wikipedia.org/wiki/Liskov_substitution_principle\" rel=\"nofollow noreferrer\">Liskov substitution principle</a>. I would suggest you to rename your methods to <code>SetBuffer</code>, <code>ClearBuffer</code> and move them up to abstract class.</li>\n<li>I guess there's not much wrong with casts. I'm not sure whether smth like this could work too for your case</li>\n</ol>\n\n<pre><code>internal CanceledDownloadEntry(DownloadEntry entry) \n{\n //your cast\n}\n</code></pre>\n\n<p>You might want to investigate it at some point\n4. This not relates to a question but you can replace this</p>\n\n<pre><code>currentDownload = runningDownloads.Where(o => o.CommandSequenceNumber == sequenceNumber).FirstOrDefault();\n</code></pre>\n\n<p>with this</p>\n\n<pre><code>currentDownload = runningDownloads.FirstOrDefault(o => o.CommandSequenceNumber == sequenceNumber);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T14:07:44.400",
"Id": "448112",
"Score": "0",
"body": "I will definitely look through these resources you've provided.\nA question about `There's clearly no value in the interface.`. Would it have made sense to use the interface if I hadn't also used the base class? So that i'd make my classes using `RunningDownloadEntry : IDownloadEntry` `FailedDownloadEntry : IDownloadEntry` etc? Meaning using *both* a base class and interface makes the interface redundant?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T14:23:27.973",
"Id": "448115",
"Score": "0",
"body": "Both class and interface are definitely redundant. Surely, this was my main motivation. But that's not the only my point. Interfaces are generally useful when you employ dynamic dispatch mentioned in my above answer or in order to facilitate unit testing. Both are not the case for the code you've presented."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T14:25:02.127",
"Id": "448116",
"Score": "0",
"body": "Thank you for the information and answer!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T15:02:47.247",
"Id": "448121",
"Score": "0",
"body": "You're welcome!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T11:03:04.313",
"Id": "230151",
"ParentId": "230028",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "230151",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T11:01:41.710",
"Id": "230028",
"Score": "2",
"Tags": [
"c#",
"object-oriented",
"inheritance",
"interface"
],
"Title": "Interface and inheritance; creating download types for a download manager"
} | 230028 |
<p>I have made an Android app called RunTracker - <a href="https://github.com/michaelnares/runtracker/tree/master/app" rel="nofollow noreferrer">https://github.com/michaelnares/runtracker/tree/master/app</a>. The intended functionality is that the app saves runs to the local filesystem, shows your current location and current run, and has a clickable list of runs. I feel that the existing code can be improved, but I'm not sure how. For example, the code for the MainActivity is quite verbose:</p>
<pre><code>package com.michaelnares.runtracker.activities;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import com.michaelnares.runtracker.R;
import com.michaelnares.runtracker.data.RunPoint;
import com.michaelnares.runtracker.utils.PermissionsHandler;
import com.michaelnares.runtracker.utils.RunsViewModel;
import com.michaelnares.runtracker.utils.Utils;
import org.json.JSONException;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ArrayList<RunPoint> runPointsList = new ArrayList<>();
private RunsViewModel runsViewModel;
private AppCompatActivity activity = this;
private PermissionsHandler permissionsHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
permissionsHandler = new PermissionsHandler(this, MainActivity.this);
setContentView(R.layout.activity_main);
permissionsHandler.checkForPermissions();
runsViewModel = ViewModelProviders.of(this).get(RunsViewModel.class);
runsViewModel.setActivity(this);
runsViewModel.setContext(getApplicationContext());
final Button goToListButton = findViewById(R.id.goToList);
goToListButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Intent intent = new Intent(MainActivity.this, RunsListActivity.class);
startActivity(intent);
}
}); // The setOnClickListener() block ends here.
final Switch locationSwitch = findViewById(R.id.locationSwitch);
locationSwitch.setChecked(runsViewModel.canTrackLocation());
locationSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
runsViewModel.setCanTrackLocation(isChecked);
if (isChecked && permissionsHandler.allConditionsMet()) {
permissionsHandler.startTrackingRuns();
} else { // So save the current run, if the user switches the toggle off.
saveCurrentRun();
}
}
});
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // Keeps the screen on always, when the app is running.
} // The onCreate() method ends here
private void saveCurrentRun() {
if (runsViewModel == null) {
runsViewModel = ViewModelProviders.of(this).get(RunsViewModel.class);
}
try {
runsViewModel.saveCurrentRun(); // Saving them to external storage.
} catch (JSONException e) {
Log.e(Utils.getPackageName(MainActivity.this), "There was a JSONException whilst trying to save the journey points.");
e.printStackTrace();
} catch (IOException e) {
Log.e(Utils.getPackageName(MainActivity.this), "There was an IOException whilst trying to save the journey points.");
e.printStackTrace();
}
}
} // The main class ends here.
</code></pre>
<p>Can I rewrite the code to achieve better separation of concerns, i.e. less code in the MainActivity. How can the code be improved elsewhere?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T14:06:27.897",
"Id": "447789",
"Score": "0",
"body": "How are `this` and `MainActivity.this` distinct in this context? There's no class nesting at your `permissionsHandler` assignment."
}
] | [
{
"body": "<p>I don't know anything about Android programming, so bear with me.</p>\n\n<h2>Unused variable</h2>\n\n<pre><code>private AppCompatActivity activity = this;\n</code></pre>\n\n<p>This is unused - and even if it were used, you could just replace all references of it with <code>this</code>.</p>\n\n<p><code>runPointsList</code> is similarly unused.</p>\n\n<h2>Outer class <code>this</code> references</h2>\n\n<p>This code:</p>\n\n<pre><code> @Override\n public void onClick(View v) {\n final Intent intent = new Intent(MainActivity.this, RunsListActivity.class);\n startActivity(intent);\n }\n</code></pre>\n\n<p>is justified in referencing <code>MainActivity.this</code> because it's an inner class. This code:</p>\n\n<pre><code> permissionsHandler = new PermissionsHandler(this, MainActivity.this);\n</code></pre>\n\n<p>is not. You should be able to drop <code>MainActivity.</code> .</p>\n\n<h2>Multiple exceptions</h2>\n\n<p>This:</p>\n\n<pre><code> } catch (JSONException e) {\n Log.e(Utils.getPackageName(MainActivity.this), \"There was a JSONException whilst trying to save the journey points.\");\n e.printStackTrace();\n } catch (IOException e) {\n Log.e(Utils.getPackageName(MainActivity.this), \"There was an IOException whilst trying to save the journey points.\");\n e.printStackTrace();\n }\n</code></pre>\n\n<p>should be able to have its two handlers collapsed to one with <code>catch (JSONException|IOException e)</code> syntax, since they do almost the same thing.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T14:15:56.083",
"Id": "230033",
"ParentId": "230029",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "230033",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T11:02:54.963",
"Id": "230029",
"Score": "3",
"Tags": [
"java",
"android"
],
"Title": "Code feedback on running app"
} | 230029 |
<p>Here is an async task queue implementation. The idea is to reuse node.js standard library as much as possible.</p>
<pre><code>const { Readable, Writable } = require('stream');
const delay = (ms) =>
new Promise((resolve) => {
setTimeout(resolve, ms)
})
const task = (message) => {
console.log(`${message} started`)
return delay(500).then(() => message + ' solved')
}
class AsyncTaskQueue {
constructor(limit = 7) {
this.queue = new Readable({
objectMode: true,
read(size) {}
})
this.processor = new Writable({
objectMode: true,
highWaterMark: limit + 1,
write(task, encoding, callback) {
task().finally(() => callback())
},
writev(tasks, callback) {
Promise.all(tasks.map(({chunk}) => chunk().catch(err => err)))
.finally(() => callback())
}
});
this.queue.pipe(this.processor)
}
addTask(execute) {
const closure = { resolve: null, reject: null }
const task = () => execute().then(closure.resolve).catch(closure.reject)
const promise = new Promise((resolve, reject) => {
closure.resolve = resolve;
closure.reject = reject;
})
this.queue.push(task)
return promise
}
}
const q = new AsyncTaskQueue();
for (let i = 0; i< 100; i++) {
q.addTask(
task.bind(null, i)
).then(console.log)
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T13:24:50.217",
"Id": "230032",
"Score": "2",
"Tags": [
"javascript",
"node.js",
"asynchronous"
],
"Title": "Node.js async task queue implementation"
} | 230032 |
<p>lastbudget and lastactual are both Lists</p>
<p>These lists populate 2 columns in an infragistics ultragrid</p>
<ul>
<li>PrevFY</li>
<li>Actual_c</li>
</ul>
<p><em>So the grid has defined datasource already. These 2 columns I added programmaticly onto the grid which has a datasource.</em></p>
<p><strong>(dgvBudget is the name of the ultragrid)</strong></p>
<pre><code>int rowIndex = dgvBudget.Rows.Count;
if (half == "Second Half Budget")
{
for (int i = 6; i < rowIndex; i++)
{
var row = dgvBudget.Rows[i];
row.Cells["PrevFY"].Value = lastbudget[i];
row.Cells["Actual_c"].Value = lastactual[i];
}
for (int i = 0; i < 6; i++)
{
var row = dgvBudget.Rows[i];
row.Cells["PrevFY"].Value = lastactual[i];
row.Cells["Actual_c"].Value = 0;
}
}
else
{
for (int i = 0; i < rowIndex; i++)
{
var row = dgvBudget.Rows[i];
row.Cells["PrevFY"].Value = lastbudget[i];
row.Cells["Actual_c"].Value = lastactual[i];
}
}
</code></pre>
<p>My goal is to create a new datasource and import the binded data to the the datagridview with the 3 new columns I have created to cut down on MS when executing.</p>
<p>At the moment it is taking 8-10 seconds to execute</p>
<pre><code>private void bringPreviousData()
{
Stopwatch stopwatch = Stopwatch.StartNew();
List<string> lastactual = new List<string>();
List<string> lastbudget = new List<string>();
Control cmbBudgetCode = csm.GetNativeControlReference("17dd127e-7b02-48e9-a7bb-e98164aea713");
EpiDataView bhView = (EpiDataView)(oTrans.EpiDataViews["GLBudgetHd"]);
if (!dgvBudget.DisplayLayout.Bands[0].Columns.Exists("PrevFY"))
{
dgvBudget.DisplayLayout.Bands[0].Columns.Add("PrevFY", "Previous FY Budgeted");
dgvBudget.DisplayLayout.Bands[0].Columns["PrevFY"].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.Currency;
}
if (!dgvBudget.DisplayLayout.Bands[0].Columns.Exists("FiscalMonth"))
{
dgvBudget.DisplayLayout.Bands[0].Columns.Add("FiscalMonth", "Month");
SetColumnReadOnly("FiscalMonth", true);
}
else
{
string[] monthNames = { "April", "May", "June", "July", "August", "September", "October", "November", "December", "January", "February", "March" };
for (int i = 0; i < monthNames.Length; i++)
{
dgvBudget.Rows[i].Cells["FiscalMonth"].Value = monthNames[i];
}
}
string half = cmbBudgetCode.Text;
lastactual = GetLastActual(half);
lastbudget = GetLastBudget(half);
int rowIndex = dgvBudget.Rows.Count;
if (half == "Second Half Budget")
{
for (int i = 6; i < rowIndex; i++)
{
var row = dgvBudget.Rows[i];
row.Cells["PrevFY"].Value = lastbudget[i];
row.Cells["Actual_c"].Value = lastactual[i];
}
for (int i = 0; i < 6; i++)
{
var row = dgvBudget.Rows[i];
row.Cells["PrevFY"].Value = lastactual[i];
row.Cells["Actual_c"].Value = 0;
}
}
else
{
for (int i = 0; i < rowIndex; i++)
{
var row = dgvBudget.Rows[i];
row.Cells["PrevFY"].Value = lastbudget[i];
row.Cells["Actual_c"].Value = lastactual[i];
}
}
decimal total = 0m;
foreach (UltraGridRow row in dgvBudget.Rows)
{
total += Convert.ToDecimal(row.Cells["PrevFY"].Value);
}
if (Config.typeofAccount != "Overtime")
{
if (GetAcctType(bhView.CurrentDataRow["SegValue1"].ToString()))
{
nbrPrevStatTotal.Value = total;
}
else
{
nbrPrevTotal.Value = total;
}
}
else
{
nbrPrevTotal.Value = total;
}
stopwatch.Stop();
MessageBox.Show(stopwatch.ElapsedMilliseconds.ToString());
}
</code></pre>
<p>So at the moment what this code is doing is</p>
<ol>
<li>Grabs 2 lists of data</li>
<li>Then adds 2 columns if they do not exist (prevFy, and FiscalMonth)</li>
<li>Then populates the ultragridview with current datasource plus my added data and columns</li>
<li>Then Sums the values in the cells to show in a text box</li>
</ol>
<p>Could I please have some help on how I can speed this up because right now it works it does, it's just so sloooooooooooow thank you!</p>
<p>EDIT**</p>
<p>The class is 1000+ lines so I can include the methods that get the lists. I've also added the begin update and ending update aswell as synchronization.</p>
<pre><code>private List<string> GetLastBudget(string half)
{
// string list is returned
List<string> lastbudget = new List<string>();
// BAQ gets the Budgeted ammount for last year
DynamicQueryAdapter dqa = new DynamicQueryAdapter(oTrans);
dqa.BOConnect();
string baq = "ko_test";
QueryExecutionDataSet qeds = dqa.GetQueryExecutionParametersByID(baq);
EpiDataView bhView = (EpiDataView)(oTrans.EpiDataViews["GLBudgetHd"]);
string fy = bhView.CurrentDataRow["FiscalYear"].ToString();
string balacct = bhView.CurrentDataRow["BalanceAcct"].ToString();
string acct = bhView.CurrentDataRow["SegValue1"].ToString();
string budgetcode = "Main";
// If it's first half, get data for last year.
// Second half still needs this year's "Main" Budget data
if (half == "Main")
{
int fyint = (Convert.ToInt32(fy) - 1);
fy = fyint.ToString();
}
qeds.ExecutionParameter.Clear();
qeds.ExecutionParameter.AddExecutionParameterRow("FiscalYear", fy, "int", false, Guid.NewGuid(), "A");
qeds.ExecutionParameter.AddExecutionParameterRow("BalanceAcct", balacct, "nvarchar", false, Guid.NewGuid(), "A");
qeds.ExecutionParameter.AddExecutionParameterRow("BudgetCode", budgetcode, "nvarchar", false, Guid.NewGuid(), "A");
dqa.ExecuteByID(baq, qeds);
LastBudgetData = dqa.QueryResults.Tables["Results"].AsEnumerable();
if (dqa.QueryResults.Tables["Results"].Rows.Count > 0)
{
Config.stat = GetAcctType(acct);
// Expense
if (Config.stat == false)
{
foreach (var item in LastBudgetData)
{
lastbudget.Add(item["GLBudgetDtl_BudgetAmt"].ToString());
}
}
// Statistical
else
{
foreach (var item in LastBudgetData)
{
lastbudget.Add(item["GLBudgetDtl_BudgetStatAmt"].ToString());
}
}
}
// If there are no results from the query set to 0s
else
{
for (int i = 0; i < 12; i++)
{
lastbudget.Add("0");
}
}
return lastbudget;
}
</code></pre>
<p>And here is the list to get the actual</p>
<pre><code>private List<string> GetLastActual(string half)
{
// string list is returned
List<string> lastactual = new List<string>();
EpiDataView bhView = (EpiDataView)(oTrans.EpiDataViews["GLBudgetHd"]);
string fy = bhView.CurrentDataRow["FiscalYear"].ToString();
string balacct = bhView.CurrentDataRow["BalanceAcct"].ToString();
string acct = bhView.CurrentDataRow["SegValue1"].ToString();
string budgetcode = "Main";
// If it's first half, get data for last year.
// Second half still needs this year's "Main" Budget data
if (half == "Main")
{
int fyint = (Convert.ToInt32(fy) - 1);
fy = fyint.ToString();
}
// GLTracker gets the actual spent for the year
GLTrackerAdapter gladapter = new GLTrackerAdapter(oTrans);
gladapter.BOConnect();
int year = Convert.ToInt32(fy);
int startIndex = 0;
decimal balance;
DataSet glds = gladapter.GetRows("MainBook", "D", false, balacct, year, "", budgetcode, out balance);
if (glds.Tables["GLTracker"].Rows.Count > 0)
{
bool stat = GetAcctType(acct);
// Expense
if (stat == false)
{
SetColumnReadOnly("PrevFY", true);
for (int i = 0; i < 12; i++)
{
DataRow row = glds.Tables["GLTracker"].Rows[i];
decimal cDebit = decimal.Parse(row["DebitAmt"].ToString());
decimal cCredit = decimal.Parse(row["CreditAmt"].ToString());
decimal cUsed = cDebit - cCredit;
lastactual.Add(cUsed.ToString());
}
}
// Statistical
else
{
for (int i = 0; i < 12; i++)
{
DataRow row = glds.Tables["GLTracker"].Rows[i];
decimal cDebit = decimal.Parse(row["DebitStatAmt"].ToString());
lastactual.Add(cDebit.ToString());
}
}
}
// If there are no results from the query set to 0s
else
{
for (int i = 0; i < 12; i++)
{
lastactual.Add("0");
}
}
return lastactual;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T15:52:30.583",
"Id": "447814",
"Score": "0",
"body": "Look into ways to bind a grid to for instance a `Dataset` or a `BindingList<T>`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T17:33:00.267",
"Id": "447827",
"Score": "0",
"body": "I edited it, The grid already has a datasource, these 2 other columns are added in code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T18:14:21.530",
"Id": "447833",
"Score": "0",
"body": "Then why not add these columns to the datasource?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T19:50:40.297",
"Id": "447851",
"Score": "0",
"body": "The months I can, but the previous I can't. It needs to be fetched per user and against their search request. So I am calling in Epicor a BAQ to fetch me the data from the appropriate table"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T14:56:20.810",
"Id": "448267",
"Score": "1",
"body": "It might be better if you provide the entire class(es) so that we could provide a better review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T11:59:54.860",
"Id": "448505",
"Score": "0",
"body": "@pacmaninbw I added the list returns but the whole entire class is 1000+ lines which I can add if you'd prefer, but this is what I have and like I said it is working but it is taking way to long then it should since when you run the BAQ you only get 12 results."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T17:52:21.057",
"Id": "448564",
"Score": "0",
"body": "Just FYI, it is possible to post more than 3000 lines of code (a lot more)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T18:16:14.957",
"Id": "448571",
"Score": "0",
"body": "@pacmaninbw I can do that if you would like, but I thought it was referred to as a \"code dump\" I appreciate you taking the time on helping me make this faster! I'll add it at the bottom if you'd like me to."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T13:57:19.693",
"Id": "448688",
"Score": "0",
"body": "I'd suggest building a unit test that doesn't include the ERP system and profile that. Because of the ERP system it would be good to have a standalone unit test for the class anyway."
}
] | [
{
"body": "<p>As is typical of \"bulk controls\", this grid has the methods:</p>\n\n<ul>\n<li><code>BeginUpdate</code>, stops the control from refreshing on modifications.</li>\n<li><code>EndUpdate</code>, re-enables refreshing on modification.</li>\n</ul>\n\n<p>Surrounding a batch of modifications with those methods makes it faster and prevents flickering of the control while the modifications are being performed. It is commonly recommended to use <code>try</code>/<code>finally</code> to prevent the control staying frozen in case of a mishap:</p>\n\n<pre><code>try\n{\n dgvBudget.BeginUpdate();\n\n // do updates\n}\nfinally\n{\n dgvBudget.EndUpdate();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T12:11:33.340",
"Id": "448507",
"Score": "0",
"body": "I have tried adding these but it doesn't make it much faster still in between 7-8 seconds"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T12:13:41.603",
"Id": "448508",
"Score": "0",
"body": "@Knowledge pity, it would have been so easy.. can you profile the code then? I can't run it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T12:18:42.727",
"Id": "448510",
"Score": "0",
"body": "I wouldn't know how to profile this because it is built within Epicor which is a ERP."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T12:26:09.507",
"Id": "448511",
"Score": "0",
"body": "I have added the list methods I used however."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T20:06:36.600",
"Id": "230183",
"ParentId": "230037",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T14:34:17.373",
"Id": "230037",
"Score": "1",
"Tags": [
"c#",
"performance"
],
"Title": "Shorten the time it is taking to fill data in an ultragrid"
} | 230037 |
<p>I have multiple repositories that contain <code>userId</code>, <code>paidDate</code> and amount attributes like <code>Bills(userId, paidDate, amount)</code> <code>Shoppings(userId, paidDate, amount)</code> etc. I want to get sum of amounts and group them by userId and get something like this <code>{user1: {amount1, amount2, amount3 ..}, user2: {amount4, ..}}</code></p>
<p>I created a <code>expenseDetails</code> model that contains all of repositories above.</p>
<pre><code>public class ExpenseDetails
{
public IEnumerable<ApplicationUser> ApplicationUsers { get; set; }
public IEnumerable<Bill> Bills { get; set; }
public IEnumerable<Shopping> Shoppings { get; set; }
public IEnumerable<Rent> Rents { get; set; }
}
</code></pre>
<p>And I created a helper method for calculate the sum of amounts with looping every model in <code>expenseDetails</code>.</p>
<pre><code>public static Dictionary<string, List<double>> UsersExpense(ExpenseDetails expenseDetails)
{
Dictionary<string, List<double>> TotalCosts = new Dictionary<string, List<double>>();
List<double> Total = new List<double>();
double sum = 0;
foreach (var user in expenseDetails.ApplicationUsers)
{
foreach (var item in expenseDetails.Shoppings)
{
if (item.ApplicationUserId == user.Id)
{
if (Convert.ToInt32(item.PaidDate.Split("/")[1]) == DateTime.Now.Month)
{
sum = item.Amount + sum;
}
}
}
Total.Add(sum);
sum = 0;
foreach (var item in expenseDetails.Bills)
{
if (item.ApplicationUserId == user.Id)
{
if (Convert.ToInt32(item.PaidDate.Split("/")[1]) == DateTime.Now.Month)
{
sum = item.Amount + sum;
}
}
}
Total.Add(sum);
sum = 0;
foreach (var item in expenseDetails.Rents)
{
if (item.ApplicationUserId == user.Id)
{
if (Convert.ToInt32(item.PaidDate.Split("/")[1]) == DateTime.Now.Month)
{
sum = item.Amount + sum;
}
}
}
Total.Add(sum);
sum = 0;
TotalCosts.Add(user.Id, Total.ToList());
Total.Clear();
}
return TotalCosts;
}
</code></pre>
<p>But this is not a good one for programming. How can I achive this with best practice? I am using repository pattern by the way.</p>
| [] | [
{
"body": "<p>Some quick remarks:</p>\n\n<ul>\n<li>Why isn't <code>PaidDate</code> a <code>DateTime</code>?</li>\n<li>What is a \"Shopping\"? (I realize that often naming things is hard, but be careful when inventing new English words that do not adequately describe their contents, because the next person to maintain this code will find it harder to do so when they have to first decipher various terms.)</li>\n<li>Use descriptive names: <code>item</code> is way too vague.</li>\n<li><code>TotalCosts</code> and <code>Total</code> should be camelCased.</li>\n<li><code>sum = item.Amount + sum;</code> can be shortened to <code>sum += item.Amount;</code>.</li>\n<li>Don't do <code>if (item.ApplicationUserId == user.Id)</code>, instead use LINQ to extract the relevant records, e.g. <code>expenseDetails.Shoppings.Where(x => x.ApplicationUserId == user.Id)</code>. And if <code>PaidDate</code> was a <code>DateTime</code>, you could easily also include that in the LINQ query and immediately calculate the sum.</li>\n<li>Why do you do <code>Total.ToList()</code>? How can it be anything else?</li>\n</ul>\n\n<hr>\n\n<p>But all of that is IMHO just plugging some small holes, while ignoring the massive dam breach elsewhere: surely this logic could be done easily in one SQL query? </p>\n\n<p>On a related note: is there even a point to have a <code>List<double> Total</code>? I wouldn't be surprised if all you did with those is add them up. </p>\n\n<p>And if you're not adding them up and always assume that the first item is the sum of <code>Shoppings</code> etc. and use this to display them elsewhere: please don't. In such cases always use the key-value pair structure, so you'd know that value X is definitely the sum of the <code>Shoppings</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T09:10:25.980",
"Id": "448210",
"Score": "0",
"body": "Thank you for your advices BCdotWEB"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T15:49:46.300",
"Id": "230041",
"ParentId": "230038",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T14:46:53.700",
"Id": "230038",
"Score": "1",
"Tags": [
"c#",
"entity-framework",
"asp.net-core"
],
"Title": "Calculate sum of an attribute across multiple repositories"
} | 230038 |
<p>I am solving a problem of increasing the ROI of a retinal image using the below algorithm-</p>
<blockquote>
<p>First, the set of pixels of the exterior border of the ROI is determined, i.e., pixels that are outside the ROI and are neighbors (using four-neighbourhood) to pixels inside it. Then, each pixel value of this set is replaced with the mean value of its neighbors (this time using eight-neighbourhood) inside the ROI. Finally, the ROI is expanded by the inclusion of this altered set of pixels. This process is repeated and can be seen as artificially increasing the ROI.</p>
</blockquote>
<p>My image is of following type-
<a href="https://i.stack.imgur.com/cKXol.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cKXol.png" alt="enter image description here"></a></p>
<p>and the mask on which I am applying the algorithm is below-
<a href="https://i.stack.imgur.com/n3haM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/n3haM.png" alt="enter image description here"></a></p>
<p>Pseudocode for the above approach which I got from <a href="https://stackoverflow.com/q/58186472/6642287">here</a> is below-</p>
<blockquote>
<pre><code>while there are pixels not in the ROI:
border_pixels = []
# find the border pixels
for each pixel p=(i, j) in image
if p is not in ROI and ((i+1, j) in ROI or (i-1, j) in ROI or (i, j+1) in ROI or (i, j-1) in ROI)):
add p to border_pixels
# calculate the averages
for each pixel p in border_pixels:
color_sum = (0, 0, 0)
count = 0
for each pixel n in 8-neighborhood of p:
if n in ROI:
color_sum += color(n)
count += 1
color(p) = color_sum / count
# update the ROI
for each pixel p=(i, j) in border_pixels:
set p to be in ROI
</code></pre>
</blockquote>
<p>and my implementation for the above pseudocode is below-</p>
<pre><code>img = Image.open(path_dir)
pixelMap = img.load()
@jit
def roifun(img,pixelMap):
roi = []
for i in range(img.size[0]):
for j in range(img.size[1]):
if pixelMap[i,j] == 255:
roi.append([i,j])
return roi
roi= roifun(img,pixelMap)
notroi = img.size[0]*img.size[1] - len(roi)
@jit
def border_enhance(img,pixelMap,roi,notroi):
while(notroi):
border_pixels = []
for i in range(img.size[0]):
for j in range(img.size[1]):
if [i,j] not in roi and ([i+1, j] in roi or [i-1, j] in roi or [i, j+1] in roi or [i, j-1] in roi):
border_pixels.append([i,j])
for (each_i,each_j) in border_pixels:
color_sum = 0
count = 1
eight_neighbourhood = [[each_i-1,each_j],[each_i+1,each_j],[each_i,each_j-1],[each_i,each_j+1],[each_i-1,each_j-1],[each_i-1,each_j+1],[each_i+1,each_j-1],[each_i+1,each_j+1]]
for pix_i,pix_j in eight_neighbourhood:
if (pix_i,pix_j) in roi:
color_sum+=pixelMap[pix_i,pix_j]
count+=1
pixelMap[each_i,each_j]=(color_sum//count)
for (each_i,each_j) in border_pixels:
roi.append([each_i,each_j])
border_pixels.remove([each_i,each_j])
notroi = notroi-1
print(notroi)
border_enhance(img,pixelMap,roi,notroi)
</code></pre>
<p>I run this code for image of dimension 50×50 and it is running correctly but for an image of larger size like 512×512, it is taking too long a time.
I also tried modifying it using numba but it gave me plenty of warnings and then taking the same time as before.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T02:18:06.807",
"Id": "448022",
"Score": "0",
"body": "Looping over pixels in Python will make your code very slow. Try Numba to compile it, or vectorize your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T18:20:50.603",
"Id": "449266",
"Score": "0",
"body": "@CrisLuengo I tried running it using Numba but it is taking the same time after giving warnings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T22:29:04.483",
"Id": "449319",
"Score": "0",
"body": "I'm not sure I understand the code— you defined a `border_enhance` function, but it never gets called."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T22:34:47.950",
"Id": "449320",
"Score": "0",
"body": "I just tried to post a minimal example, I edited it with by calling it now"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-21T00:42:33.557",
"Id": "450356",
"Score": "0",
"body": "Okay posted it in the right place now! Let me know if you have any questions with the code."
}
] | [
{
"body": "<p>The secret to performance is to choose the appropriate data structures which lay out the memory as raw arrays of bytes (or <code>uint8_t</code> values). This is done by creating cython <code>typed memoryviews</code> from numpy arrays or images loaded through <code>PIL</code>. This applies to the <code>border</code> list as well; that is, I create an array of (x, y) coordinates rather than a list of python tuples (which is slow, not contiguous in memory, and requires conversions to access the data from python to C or vice versa. Below is the preliminary code that I have so far, hope this helps.</p>\n\n<pre><code>from libc.stdint cimport *\nfrom libc.string cimport *\ncimport libc.math as c_math\nimport numpy as np\nfrom PIL import Image\n\ncpdef uint8_t[:, :, :] load_image(str image_path):\n cdef uint8_t[:, :, :] image_data\n image = Image.open(image_path).convert(\"RGBA\")\n image_np = np.array(image)\n image_np.setflags(write=1)\n image_data = image_np\n return image_data\n\ncpdef save_image(uint8_t[:, :, :] image_data, str image_path):\n image = Image.fromarray(np.array(image_data)).convert(\"RGBA\")\n image.save(image_path)\n\ncpdef border_enhance(uint8_t[:, :, :] image, uint8_t[:, :, :] mask):\n cdef:\n uint8_t[:, :, :] out\n uint8_t[:] color\n uint8_t[:, :] roi\n uint32_t[:, :] border\n size_t i, j, k\n size_t w = image.shape[0]\n size_t h = image.shape[1]\n size_t num_border\n size_t num_not_roi = 0\n float avg[4]\n size_t avg_count\n size_t x, y\n size_t sx, sy\n int a, b\n\n roi = np.zeros((w, h), dtype=np.uint8)\n border = np.zeros((w * h, 2), dtype=np.uint32)#assumes no product overflow\n out = image[:, :, :]\n\n #define ROI from mask; only white pixels are part of the mask?\n for i in range(w):\n for j in range(h):\n color = mask[i, j]\n if color[0] == 255 and color[1] == 255 and color[2] == 255 and color[3] == 255:\n roi[i, j] = True\n else:\n roi[i, j] = False\n num_not_roi += 1\n\n while num_not_roi:\n\n #Create border\n k = 0\n for i in range(w):\n for j in range(h):\n if not roi[i, j]:\n #assumes edges wrap over\n if roi[i-1, j] or roi[i+1, j] or roi[i, j-1] or roi[i, j+1]:\n border[k, 0] = i\n border[k, 1] = j\n k += 1\n\n for i in range(k):\n x = border[i, 0]\n y = border[i, 1]\n avg_count = 0\n avg = [0, 0, 0, 0]\n for a in range(-1, 2):\n for b in range(-1, 2):\n sx = x+a\n sy = y+b\n if roi[sx, sy]:\n #print(np.array(image[sx, sy]))\n avg[0] += image[sx, sy, 0]\n avg[1] += image[sx, sy, 1]\n avg[2] += image[sx, sy, 2]\n avg[3] += image[sx, sy, 3]\n avg_count += 1\n for a in range(4):\n avg[a] /= avg_count\n out[x, y, a] = <uint8_t>c_math.round(avg[a])\n\n for i in range(k):\n x = border[i, 0]\n y = border[i, 1]\n roi[x, y] = True\n num_not_roi -= 1\n #dprint(num_not_roi)\n\n save_image(out, \"./images/out.png\")\n\ncdef:\n uint8_t[:, :, :] image\n uint8_t[:, :, :] mask\n size_t count\n\nimage = load_image(\"./images/image.png\")\nmask = load_image(\"./images/mask.png\")\nborder_enhance(image, mask)\n</code></pre>\n\n<p>That being said, the results do not seem particularly correct. The intermediate border step generates the correct pixel results, but the final result is wrong. Here is my output for the <code>out.png</code> after the call to the <code>border_enhance</code> function:</p>\n\n<p><a href=\"https://i.stack.imgur.com/5ncKJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/5ncKJ.png\" alt=\"enter image description here\"></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-21T01:14:20.873",
"Id": "450359",
"Score": "1",
"body": "damn, you wrote it in Cython. You are one badass programmer.I'll check it where the problem lies and will get back at you, though writing in cython is super dope."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-21T01:34:57.610",
"Id": "450360",
"Score": "1",
"body": "@Mark It is not too hard once you are familiar with how things are laid out in memory. I would take a look at [the cython docs](https://cython.readthedocs.io/en/latest/src/userguide/memoryviews.html) for how to use memoryviews. I would also look at [this](https://jakevdp.github.io/blog/2014/05/09/why-python-is-slow/) to get an idea as to what makes python so slow and what to avoid. Writing fast cython code is basically like writing C code with a nicer syntactic sugar, so taking some time to learn some C basics (e.g. for memory management and data structures) will pay off in the long run."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-21T15:08:54.287",
"Id": "450473",
"Score": "0",
"body": "Thanks a lot for the links. I was finding it hard to wrap my head around cython, hope they will help me out. Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-07T01:41:31.057",
"Id": "452755",
"Score": "1",
"body": "@Mark Out of curiosity, were you able to figure out what was wrong with the code or get your issue solved?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-07T14:49:26.270",
"Id": "452821",
"Score": "0",
"body": "There are some unusual edges which are present in the boundary which are responsible for the above unexpected increase in images, I got it from here-https://stackoverflow.com/questions/58512248/unable-to-increase-the-region-of-interest-of-an-image/58527837#58527837 but the thing is it is still slow, taking 149 sec for a single image so I am trying to convert the above solution into cython using your approach"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-21T00:42:08.923",
"Id": "231073",
"ParentId": "230044",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "231073",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T16:18:41.283",
"Id": "230044",
"Score": "4",
"Tags": [
"python",
"algorithm",
"time-limit-exceeded",
"image",
"signal-processing"
],
"Title": "Expanding the region of interest of an image"
} | 230044 |
<p>How can my solution be improved / optimized?</p>
<p><strong><em>explaination of db models :</em></strong><br>
<em>thinkpad</em> is a <code>equipment</code> of <em>laptop</em> <code>subcategory</code>.and <em>laptop subcategory</em> has a <code>category</code> called <em>electronics</em>.<br>
now <em>laptop</em> can have many <code>attributes</code> like <code>processor,ram,color,screen_size</code>. </p>
<p><strong><em>Question :</em></strong><br>
Find out all the <code>equipments</code> with their<code>equipment detail ,subcategory_name and attribute names,value</code> which have <em>category_id =1</em> . </p>
<p><strong><em>Desired Output:</em></strong> </p>
<pre><code>[
{
'equipment_id':1,
'subcategory__name':'laptop',
'attribute_detail':[
{
'attribute_name':'color',
'attribute_value':'red'
},
{
'attribute_name':'ram',
'attribute_value':'6gb'
}
]
},
{ 'equipment_id':2,
'subcategory__name':'Mouse',
'attribute_detail':[
{
'attribute_name':'color',
'attribute_value':'red'
},
{
'attribute_name':'dpi',
'attribute_value':'800'
}
]
}
]
</code></pre>
<p><strong><em>Solution:</em></strong> </p>
<pre><code>equipments = Equipment.objects.filter(subcategory__category__category_id=1)
all_equipments_data = []
# iterate over each equipment
for equipment in equipments:
single_equipment_data = {}
single_equipment_data['equipment_id'] = equipment.equipment_id
single_equipment_data['subcategory__name'] = equipment.subcategory.subcategory_name
attributes_detail_of_equipment = []
# iterate over each equipmentdetail of single equipment
for eqdetail in equipment.equipment_eqdetail.all():
single_attribute_detail_of_equipment = {}
single_attribute_detail_of_equipment['attribute_name'] = eqdetail.attribute.attribute_name
single_attribute_detail_of_equipment['attribute_value'] = eqdetail.value
attributes_detail_of_equipment.append(single_attribute_detail_of_equipment)
single_equipment_data['attribute_detail'] = attributes_detail_of_equipment
all_equipments_data.append(single_equipment_data)
</code></pre>
<p><strong><em>Models :</em></strong> </p>
<pre><code>class Category(models.Model):
category_id = models.AutoField(primary_key=True, default=None)
category_name = models.CharField(max_length=15, unique=True)
created_at = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.category_id)+","+self.category_name
class Meta:
db_table = "category"
class Subcategory(models.Model):
subcategory_id = models.AutoField(primary_key=True, default=None)
category = models.ForeignKey(
Category, on_delete=models.CASCADE, related_name="category_subc", verbose_name="category_id")
subcategory_name = models.CharField(max_length=15, unique=True)
created_at = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.subcategory_id)+","+self.subcategory_name
class Meta:
db_table = "subcategory"
class Equipment(models.Model):
equipment_id = models.AutoField(primary_key=True, default=None)
subcategory = models.ForeignKey(
Subcategory, on_delete=models.CASCADE, related_name="subcategory_eq", verbose_name="subcategory_id")
created_at = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.equipment_id)
class Meta:
db_table = "equipment"
class Attribute(models.Model):
attribute_id = models.AutoField(primary_key=True, default=None)
attribute_name = models.CharField(max_length=15, unique=True)
subcategory = models.ManyToManyField(
Subcategory, through="SubcategoryAttributeMap")
created_at = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.attribute_id)+","+self.attribute_name
class Meta:
db_table = "attribute"
class SubcategoryAttributeMap(models.Model):
id = models.AutoField(primary_key=True, default=None)
subcategory = models.ForeignKey(
Subcategory, on_delete=models.CASCADE, related_name="subcategory_sub_attr_map", verbose_name="subcategory_id")
attribute = models.ForeignKey(
Attribute, on_delete=models.CASCADE, related_name="attribute_sub_attr_map", verbose_name="attribute_id")
created_at = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.id)
class Meta:
db_table = "subcategory_attribute_map"
class EquipmentDetail(models.Model):
equipment_detail_id = models.AutoField(primary_key=True, default=None)
equipment = models.ForeignKey(
Equipment, on_delete=models.CASCADE, related_name="equipment_eqdetail", verbose_name="equipment_id")
attribute = models.ForeignKey(
Attribute, on_delete=models.CASCADE, related_name="attribute_eqdetail", verbose_name="attribute_id")
value = models.CharField(max_length=15)
created_at = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.equipment_detail_id)+","+self.value
class Meta:
db_table = "equipment_detail"
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T18:32:21.057",
"Id": "447835",
"Score": "1",
"body": "Hey Naveen, please edit your title to state what your code does. Asking questions in the title makes it difficult for users to be interested in the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T21:59:58.983",
"Id": "447878",
"Score": "0",
"body": "@IEatBagels i have updated the title , but i dont understand why downvote when everything seems proper"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T12:44:13.777",
"Id": "447932",
"Score": "2",
"body": "Don't worry about a single downvote. Your post is good, it'll attract the votes and the answers :)"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T17:39:56.193",
"Id": "230046",
"Score": "1",
"Tags": [
"python",
"performance",
"mysql",
"django"
],
"Title": "Listing all related details of a model object through Django ORM"
} | 230046 |
<p>I'n written this small file encryption module to work on my skills with the <code>os</code> module. It's my very first time using it to navigate files and file structures, so I'm sure some things can be improved. I used the following file structure to ensure it works with multiple directories:</p>
<h1>File Structure</h1>
<pre><code>.
├── files
│ ├── files
│ │ ├── test.txt
│ │ ├── test2.txt
│ │ └── test3.txt
│ ├── files2
│ │ ├── files
│ │ │ ├── test.txt
│ │ │ ├── test2.txt
│ │ │ └── test3.txt
│ │ ├── test.txt
│ │ ├── test2.txt
│ │ └── test3.txt
│ ├── test.txt
│ ├── test2.txt
│ └── test3.txt
├── key.py
└── virus.py
</code></pre>
<p>It works flawlessly. I'm looking for feedback on a couple topics:</p>
<ol>
<li><strong><code>os</code> module</strong>: Are there other functions in the <code>os</code> module that could be used to accomplish the same thing, but easier or faster?</li>
<li><strong>file management</strong>: Is there a faster way to work with files than I did? The time it takes is noticeable ( 0s < time < 1s for a file of ~2500 characters) but I'm sure it gets longer with bigger files.</li>
</ol>
<pre><code>"""
File Encryption & Decryption
"""
import os
from cryptography.fernet import Fernet
from key import KEY
DIRECTORY = "files"
FERNET = Fernet(KEY)
def crypt(encrypt=True) -> None:
"""
Encrypts/Decrypts the files in DIRECTORY
"""
for root, _, files in os.walk(DIRECTORY, topdown=True):
for name in files:
file = os.path.join(root, name)
with open(file, "rb") as in_file:
data = in_file.read()
data = FERNET.encrypt(data) if encrypt else FERNET.decrypt(data)
with open(file, "wb") as out_file:
out_file.write(data)
if __name__ == '__main__':
# Encrypt #
crypt()
# Decrypt #
crypt(encrypt=False)
</code></pre>
| [] | [
{
"body": "<p>Some suggestions:</p>\n\n<ol>\n<li>Boolean arguments are a code smell. Especially in a case like this you'd want to have separate <code>encrypt</code> and <code>decrypt</code> functions, which both reuse a third function which does all the bookkeeping. In this case the third function could just take the <code>FERNET.encrypt</code> or <code>FERNET.decrypt</code> method as an argument, and apply it to the data.</li>\n<li>For this to be generally usable you'll want to add some argument parsing, possibly with <code>argparse</code>, to be able to pass an arbitrary path to work with.</li>\n<li>The key should not be in code - it's just data, and should be stored in the original key format. If it's just a /dev/urandom dump with no structure to it that would be a .bin format, but I'm not familiar with Fernet. The code would normally be told about the key by passing a path argument or by passing the contents on standard input.</li>\n</ol>\n\n<p>Generally I wouldn't worry about encryption and decryption taking a long time. If your key is too long (algorithm-specific) it could slow down the algorithm considerably, but many algorithms can be considered quite slow with common inputs. I don't know why you chose Fernet specifically, but there are many algorithms available, and you might want to evaluate them for strength and speed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T20:35:26.257",
"Id": "230058",
"ParentId": "230047",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "230058",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T18:04:16.483",
"Id": "230047",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"file"
],
"Title": "File Encryption"
} | 230047 |
<p>Update from <a href="https://codereview.stackexchange.com/q/229264/209774">Digitizing paper label system with Python</a></p>
<p>I have implemented a username and password log in and main application to be used after successful log in.</p>
<p>I am ready for some more feedback.</p>
<p>My main troubles is error handling. For example log in screen, I'll need to implement statement to show if user does not exist etc.. Nothing too fancy. Also, maybe add a scroll bar and center the screen for both classes when opened up.</p>
<p>Also, if there is nothing inside a folder, the drop down menu dissapears and shows nothing, I'll need to work on that too. Maybe pop another screen saying 'No files in folder, come back later'.</p>
<p>Here is my full code:</p>
<pre><code>from tkinter import *
from tkinter import DISABLED, messagebox
import tkinter.ttk as ttk
import os
import glob
from PIL import Image, ImageTk, ImageGrab
from pathlib import Path
import pyautogui
import time
def main():
root = Tk()
app = Window1(root)
root.mainloop()
class Window1:
def __init__(self,master):
self.master = master
self.master.title("User Log In")
self.master.geometry('400x150')
self.frame = Frame(self.master)
self.frame.pack(fill="both", expand=True)
self.label_username = Label(self.frame, text="Username: ",font=("bold",16))
self.entry_username = Entry(self.frame, font = ("bold", 14))
self.label_password = Label(self.frame, text="Password: ",font=("bold",16))
self.entry_password = Entry(self.frame, show="*", font = ("bold", 14))
self.label_username.pack()
self.entry_username.pack()
self.label_password.pack()
self.entry_password.pack()
self.logbtn = Button(self.frame, text="Login", font = ("bold", 10), command=self._login_btn_clicked)
self.logbtn.pack()
#close and stop tkinter running in backround, also see line #64
def on_closing(self):
self.master.destroy()
def _login_btn_clicked(self):
# print("Clicked")
username = self.entry_username.get()
password = self.entry_password.get()
# print(username, password)
account_list = [line.split(":", maxsplit=1) for line in open("passwords.txt")]
# list of 2-tuples. Usersnames with colons inside not supported.
accounts = {key: value.rstrip() for key, value in account_list}
# Convert to dict[username] = password, and slices off the line ending.
# Does not support passwords ending in whitespace.
if accounts[username] == password:
self.master.withdraw()
self.newWindow = Toplevel(self.master)
self.newWindow.protocol("WM_DELETE_WINDOW", self.on_closing)
self.app = Window2(self.newWindow, window1 = self)
else:
messagebox.showinfo("User message", "Invalid username or password specified please try again")
class Window2:
def __init__(self,master, window1):
notebook = ttk.Notebook(master)
notebook.pack(expand = 1, fill = "both")
#Frames
main = ttk.Frame(notebook)
manual = ttk.Frame(notebook)
notebook.add(main, text='Main-Screen')
notebook.add(manual, text='Manual')
self.window1 = window1
def clock():
t=time.strftime('%d/%m/%Y, %H:%M:%S, ',time.localtime())
if t!='':
self.display_time.config(text=t,font='times 15')
main.after(100,clock)
self.display_time=Label(main)
self.display_time.grid(column = 3, row = 0)
clock()
username = self.window1.entry_username.get()
self.User = Label(main, text = 'User: '+ username, font = ('15'))
self.User.grid(column = 4, row = 0)
var1 = IntVar()
var2 = IntVar()
var3 = IntVar()
var4 = IntVar()
var5 = IntVar()
var6 = IntVar()
var7 = IntVar()
var8 = IntVar()
var9 = IntVar()
var10 = IntVar()
var11 = IntVar()
var12 = IntVar()
#Displaying checkboxes and assigning to variables
self.Checkbox1 = Checkbutton(main, text="Ingredients present in full (any allergens in bold with allergen warning if necessary)", variable=var1)
self.Checkbox1.grid(column = 2, row = 1, sticky = W)
self.Checkbox2 = Checkbutton(main, text="May Contain Statement.", variable=var2)
self.Checkbox2.grid(column = 2, row = 2, sticky = W)
self.Checkbox3 = Checkbutton(main, text="Cocoa Content (%).", variable=var3)
self.Checkbox3.grid(column = 2, row = 3, sticky = W)
self.Checkbox4 = Checkbutton(main, text="Vegetable fat in addition to Cocoa butter", variable=var4)
self.Checkbox4.grid(column = 2, row = 4, sticky = W)
self.Checkbox5 = Checkbutton(main, text="Instructions for Use.", variable=var5)
self.Checkbox5.grid(column = 2, row = 5, sticky = W)
self.Checkbox6 = Checkbutton(main, text="Additional warning statements (pitt/stone, hyperactivity etc)", variable=var6)
self.Checkbox6.grid(column = 2, row = 6, sticky = W)
self.Checkbox7 = Checkbutton(main, text="Nutritional Information Visible", variable=var7)
self.Checkbox7.grid(column = 2, row = 7, sticky = W)
self.Checkbox8 = Checkbutton(main, text="Storage Conditions", variable=var8)
self.Checkbox8.grid(column = 2, row = 8, sticky = W)
self.Checkbox9 = Checkbutton(main, text="Best Before & Batch Information", variable=var9)
self.Checkbox9.grid(column = 2, row = 9, sticky = W)
self.Checkbox10 = Checkbutton(main, text="Net Weight & Correct Font Size.", variable=var10)
self.Checkbox10.grid(column = 2, row = 10, sticky = W)
self.Checkbox11 = Checkbutton(main, text="Barcode - Inner", variable=var11)
self.Checkbox11.grid(column = 2, row = 11, sticky = W)
self.Checkbox12 = Checkbutton(main, text="Address & contact details correct", variable=var12)
self.Checkbox12.grid(column = 2, row = 12, sticky = W)
#PrintScreen
def PrintScreen():
pyautogui.keyDown('alt')
pyautogui.keyDown('printscreen')
pyautogui.keyUp('printscreen')
pyautogui.keyUp('alt')
self.dataSend['state'] = 'normal'
def var_states():
text_file = open("logfile.txt", "a")
text_file.write("Username: [%s], option 1: [%d], option 2: [%d], option 3: [%d], option 4: [%d], option 5: [%d], option 6: [%d], option 7: [%d], option 8: [%d], option 9: [%d], option 10: [%d], option 11: [%d], option 12: [%d], Original Sign Off: [%s]\n" % (username,var1.get(), var2.get(), var3.get(), var4.get(), var5.get(), var6.get(), var7.get(), var8.get(), var9.get(), var10.get(), var11.get(), var12.get(), self.p))
text_file.close()
self.img = ImageGrab.grabclipboard()
self.img.save("%s" % ('//SERVER/shared_data/Technical/Label Sign Off Sheets/sign off project/Signed/'+ os.path.basename(self.p).strip('- to sign.jpg') + ' ' + username+ '.jpg'), 'JPEG')
ed = ('//SERVER/shared_data/Technical/Label Sign Off Sheets/sign off project/Signed/'+ os.path.basename(self.p).strip('- to sign.jpg') +' ed'+ '.jpg')
Nb = ('//SERVER/shared_data/Technical/Label Sign Off Sheets/sign off project/Signed/'+ os.path.basename(self.p).strip('- to sign.jpg') +' Nb'+ '.jpg')
jj = ('//SERVER/shared_data/Technical/Label Sign Off Sheets/sign off project/Signed/'+ os.path.basename(self.p).strip('- to sign.jpg') +' jj'+ '.jpg')
kl = ('//SERVER/shared_data/Technical/Label Sign Off Sheets/sign off project/Signed/'+ os.path.basename(self.p).strip('- to sign.jpg') +' kl'+ '.jpg')
if os.path.exists(ed) and os.path.exists(Nb) or os.path.exists(jj) or os.path.exists(kl):
os.remove('//SERVER/shared_data/Technical/Label Sign Off Sheets/sign off project/To sign/' + os.path.basename(self.p))
else:
print("False")
self.dataSend = Button(main, text = "Send", command = var_states, state = DISABLED)
self.dataSend.grid(column = 1, row = 13, sticky = W)
self.CaptureScreen = Button(main, text = "PrintScreen", command = PrintScreen, state = DISABLED)
self.CaptureScreen.grid(column = 1, row = 14, sticky = W)
###################################################################################################################################
##Load Image##
###################################################################################################################################
# Create a Tkinter variable
self.tkvar = StringVar()
# Directory
self.nonedisplayed = "N/A"
self.directory = "//SERVER/shared_data/Technical/Label Sign Off Sheets/sign off project/To Sign"
self.choices = glob.glob(os.path.join(self.directory, "*- to sign.jpg"))
self.tkvar.set('...To Sign Off...') # set the default option
# Images
def change_dropdown():
imgpath = self.tkvar.get()
img = Image.open(imgpath)
photo = ImageTk.PhotoImage(img)
label2.image = photo
label2.configure(image=photo)
self.CaptureScreen['state'] = 'normal'
#return path value
self.p = None
def func(value):
global p
self.p = Path(value)
print(self.p)
#widgets
self.msg1 = Label(main, text = "Choose here")
self.msg1.grid(column = 0, row = 0)
self.popupMenu = OptionMenu(main, self.tkvar, *self.choices, command = func)
self.popupMenu.grid(row=1, column=0)
self.display_label = label2 = Label(main, image=None)
self.display_label.grid(row=2, column=0, rowspan = 500)
self.open_button = Button(main, text="Open", command=change_dropdown)
self.open_button.grid(row=502, column=0)
###################################################################################################################################
##TAB 2 - MANUAL##
###################################################################################################################################
def manualopen():
os.startfile('//SERVER/shared_data/Technical/Food Safety & Quality Manual/Section 21 - Process Control/21.LABL.02 - Labelling notes.docx')
self.manualBtn = Button(manual, text= "open doc", command = manualopen)
self.manualBtn.pack()
if __name__ == '__main__':
main()
</code></pre>
<p>Also, my passwords.txt file looks like this:</p>
<pre><code>ed:password1
Nb:rother
jj:4spaces
kl:timepass
</code></pre>
| [] | [
{
"body": "<h1>Storing passwords in plaintext</h1>\n\n<p>I already mentioned this in a comment to your question: Don't store passwords in plaintext! It's usually not even a good idea for testing (when are you going to test the password storage then?). Plus, it's quite easy to do in Python e.g. using the <a href=\"https://passlib.readthedocs.io/\" rel=\"noreferrer\">passlib</a> library. Inspired from their <a href=\"https://passlib.readthedocs.io/en/1.7.1/narr/hash-tutorial.html\" rel=\"noreferrer\">example section</a>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from passlib.hash import pbkdf2_sha256\n\nhash_ = pbkdf2_sha256.hash(\"password\")\nprint(hash_)\n$pbkdf2-sha256$29000$2RtjbM0ZY8y5l/IeQyhFCA$wxMKXJPS6gtJRKHWki1.z0UQHQlR292ZvFvWEm0wSYc\n# verify provides a constant time key comparison function in order to avoid timing attacks\nassert pbkdf2_sha256.verify(\"password\", hash_)\nassert not pbkdf2_sha256.verify(\"password2\", hash_)\n</code></pre>\n\n<p>The example above uses <a href=\"https://en.wikipedia.org/wiki/PBKDF2\" rel=\"noreferrer\">PBKDF2</a> algorithm to store the password, but passlib also supports <a href=\"https://passlib.readthedocs.io/en/stable/lib/passlib.hash.bcrypt.html#passlib.hash.bcrypt\" rel=\"noreferrer\">bcrypt</a>, <a href=\"https://passlib.readthedocs.io/en/stable/lib/passlib.hash.scrypt.html#passlib.hash.scrypt\" rel=\"noreferrer\">scrypt</a>, and the current \"state of the art\" <a href=\"https://passlib.readthedocs.io/en/stable/lib/passlib.hash.argon2.html\" rel=\"noreferrer\">argon2</a>. All of them are hash functions specifically designed to be used for password storage.</p>\n\n<p>If you don't want to work with an external library, the Python standard library module <code>hashlib</code> has <code>hashlib.scrypt</code> from Python 3.6 onwards (if your platform supports OpenSSL). The usage of this function might not be as smooth as with the library above, and will require a little bit more care from your side.</p>\n\n<h1>Hard-coded paths</h1>\n\n<p>Your application has a few hard-coded paths where your labels should be stored (probably?). You'd usually want to avoid that, so that your code does not have to be changed whenever the location of those files should change. <a href=\"https://docs.python.org/3/library/os.html#file-names-command-line-arguments-and-environment-variables\" rel=\"noreferrer\">Environment variables</a> or a <a href=\"https://docs.python.org/3/library/configparser.html\" rel=\"noreferrer\">config file</a>, maybe also written in <a href=\"https://docs.python.org/3/library/json.html\" rel=\"noreferrer\">JSON</a>, are things to look at. If that's all to fancy for what you have in mind, at least store them into a <code>MODULE_LEVEL_CONSTANT</code> in order to avoid copy-and-pasting the same long string over and over again.</p>\n\n<h1>Reading and writing files</h1>\n\n<p>When using <code>open(...)</code> it's a common <a href=\"https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files\" rel=\"noreferrer\">best practice</a> to use it in conjunction with a context manager, aka <code>with</code> statement. Using <code>with open(...) as file_:</code> takes care to properly close the file no matter what, i.e. also in the event of an exception, which would usually require using something like <code>try: ... finally: ...</code>.</p>\n\n<h1>String formatting</h1>\n\n<p>The current code uses the \"old style\" <code>%</code> string formatting, which was superseded by <code>.format(...)</code> in Python 2.7 and f-strings in Python 3.6.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>foo = 1\n# old style\n\"%d\" % foo\n# Python 2.7+\n\"{}\".format(foo)\n# Python 3.6+\nf\"{foo}\"\n</code></pre>\n\n<p>Especially f-string are very powerful and convenient. Maybe have a look at <a href=\"https://realpython.com/python-f-strings/\" rel=\"noreferrer\">this blog post</a> if you are interested to learn more about each of the three variants and their features.</p>\n\n<h1>Style and formatting</h1>\n\n<p>The overall appearance of the code seems a bit rough. Especially blank lines are not used very to structure the code into logical blocks. Since your code has grown quite a bit, I'd highly recommend looking for an IDE with autoformatting capabilities or at least a style-checker integration (<a href=\"http://flake8.pycqa.org/en/latest/\" rel=\"noreferrer\">Flake8</a>, <a href=\"https://www.pylint.org/\" rel=\"noreferrer\">Pylint</a>, ...). <a href=\"https://codereview.meta.stackexchange.com/a/5252/92478\">This meta post</a> here on Code Review lists a good first overview of tools and editors to choose from. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T20:26:35.137",
"Id": "447857",
"Score": "0",
"body": "Hey @AlexV appreciate for your time in reviewing my Python script. I will take everything on account and improve my script and keep it updated on Code Review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T20:29:32.230",
"Id": "447859",
"Score": "3",
"body": "I really appreciate that you like the answer enough to accept it right away. Here on Code Review it's usually a good idea to wait a bit (at least a few hours to half a day) before accepting one, since answers here can take quite some time and you never know what there is to come from other members of the community :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T20:31:36.023",
"Id": "447860",
"Score": "0",
"body": "I am sorry, I will remove it for now.. and accept it in few days."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T20:32:44.753",
"Id": "447862",
"Score": "2",
"body": "That is nothing to be sorry about. Just give the community some time to work with your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T09:05:11.190",
"Id": "447918",
"Score": "2",
"body": "F\"{foo}\" method is really short, love it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T08:13:26.533",
"Id": "448061",
"Score": "0",
"body": "Do you have any suggestions on how to center all widgets, or maybe separating frames? Because when I load an image every content moves about."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T08:20:43.273",
"Id": "448063",
"Score": "1",
"body": "I don't really work with `tkinter` so I'm not in the position to give you suggestions on that (it's also something comments are not meant for). If you cannot find the answer using Google or the search at [so], maybe consider asking a new question there on [so] (also check the [How to Ask](https://stackoverflow.com/help/how-to-ask) page there)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T18:36:22.243",
"Id": "448894",
"Score": "0",
"body": "@98Ed There are many ways to manage widget movement in tkinter. I suspect you will want to look into `grid()` with `rowconfigure()` and `columnconfigure()` as well as `sticky()` and `anchor()`. With those tools you can normally get the behavior you need."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T05:55:26.543",
"Id": "448973",
"Score": "0",
"body": "@Mike-SMT thanks for the suggestion Mike!"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T20:20:19.073",
"Id": "230057",
"ParentId": "230049",
"Score": "5"
}
},
{
"body": "<p>First lets fix your imports.</p>\n\n<p>You are importing * and you should do <code>import tkinter as tk</code> so you don't overwrite anything.\nYou are also importing <code>DISABLED</code> and that is already imported from * so on the very next line you are already overwriting imports.</p>\n\n<p>Next did major PEP8 clean up. This includes proper spacing between qualifiers, classes, functions, comments and so on as well as working on the <a href=\"http://docs.bigchaindb.com/projects/contributing/en/latest/cross-project-policies/python-style-guide.html#maximum-line-length\" rel=\"nofollow noreferrer\">max line length</a> for coding.</p>\n\n<p>Next we got rid of a lot of unneeded <code>self</code> prefixes. You only need self when you have a class attribute or method you will need to use again in the code down the line.</p>\n\n<p>Then we need to replace all you concatenation with <code>format()</code> as format is the current correct method of concatenation.</p>\n\n<p>One big save on rows is to build your Check Buttons into a list and then reference that list when writing your data.</p>\n\n<p>One last change was to convert your Window1 class to be the root window through inheritance as well as convert Window2 to a Toplevel class. This allows us to use <code>self.master</code> to work with the parent window.</p>\n\n<p>I got your code down to 147 lines of code and I could probably get it down lower if I could do some testing. Take a look at the below and let me know if you have any questions.</p>\n\n<p>I do have a concern on this line:</p>\n\n<pre><code>account_list = [line.split(\":\", maxsplit=1) for line in open(\"passwords.txt\")]\n</code></pre>\n\n<p>I am a fan of one liners however I think (I may be wrong) this remains open as you never tell it to close. I would instead load the file using a <code>with open()</code> statement instead and then take the data and throw that into your one liner. The benefit to using <code>with open()</code> is that once the work is complete it will auto close the connection/file.</p>\n\n<p>I will be adding more detail to this answer when I get home but for now this should be a good start.</p>\n\n<p>Edit: Some more error fixing.</p>\n\n<pre><code>import tkinter as tk\nimport tkinter.ttk as ttk\nfrom tkinter import messagebox\nfrom PIL import Image, ImageTk, ImageGrab\nfrom pathlib import Path\nimport pyautogui\nimport glob\nimport time\nimport os\n\n\ndef main():\n Window1().mainloop()\n\n\ndef manual_open():\n os.startfile('//SERVER/shared_data/Technical/Food Safety & Quality Manual/Section 21 -'\n ' Process Control/21.LABL.02 - Labelling notes.docx')\n\n\nclass Window1(tk.Tk):\n def __init__(self):\n super().__init__()\n self.title(\"User Log In\")\n self.geometry('400x150')\n frame = tk.Frame(self)\n frame.pack(fill=\"both\", expand=True)\n\n tk.Label(frame, text=\"Username: \", font=(\"bold\", 16)).pack()\n self.entry_username = tk.Entry(frame, font=(\"bold\", 14))\n self.entry_username.pack()\n tk.Label(frame, text=\"Password: \", font=(\"bold\", 16)).pack()\n self.entry_password = tk.Entry(frame, show=\"*\", font=(\"bold\", 14))\n self.entry_password.pack()\n tk.Button(frame, text=\"Login\", font=(\"bold\", 10), command=self._login_btn_clicked).pack()\n\n def on_closing(self):\n self.destroy()\n\n def _login_btn_clicked(self):\n username = self.entry_username.get()\n password = self.entry_password.get()\n account_list = [line.split(\":\", maxsplit=1) for line in open(\"passwords.txt\")]\n accounts = {key: value.rstrip() for key, value in account_list}\n if accounts[username] == password:\n self.withdraw()\n self.app = Window2()\n self.app.protocol(\"WM_DELETE_WINDOW\", self.on_closing)\n else:\n messagebox.showinfo(\"User message\", \"Invalid username or password specified please try again\")\n\n\nclass Window2(tk.Toplevel):\n def __init__(self):\n super().__init__()\n notebook = ttk.Notebook(self)\n notebook.pack(expand=1, fill=\"both\")\n main = ttk.Frame(notebook)\n manual = ttk.Frame(notebook)\n notebook.add(main, text='Main-Screen')\n notebook.add(manual, text='Manual')\n self.display_time = tk.Label(main)\n self.display_time.grid(column=3, row=0)\n self.clock()\n self.username = self.master.entry_username.get()\n tk.Label(main, text='User: {}'.format(self.username), font='15').grid(column=4, row=0)\n\n self.checkbutton_list = []\n checkbutton_verb = [\"Ingredients present in full (any allergens in bold with allergen warning if necessary)\",\n \"May Contain Statement.\", \"Cocoa Content (%).\", \"Vegetable fat in addition to Cocoa butter\",\n \"Instructions for Use.\", \"Additional warning statements (pitt/stone, hyperactivity etc)\",\n \"Nutritional Information Visible\", \"Storage Conditions\", \"Best Before & Batch Information\",\n \"Net Weight & Correct Font Size.\", \"Barcode - Inner\", \"Address & contact details correct\"]\n\n for ndex, i in enumerate(checkbutton_verb):\n x = tk.IntVar()\n self.checkbutton_list.append([tk.Checkbutton(main, text=i, variable=x), x])\n self.checkbutton_list[-1][0].grid(column=2, row=ndex+1, sticky='w')\n\n directory = \"//SERVER/shared_data/Technical/Label Sign Off Sheets/sign off project/To Sign\"\n choices = glob.glob(os.path.join(directory, \"*- to sign.jpg\"))\n tk.Label(main, text=\"Choose here\").grid(column=0, row=0)\n self.tkvar = tk.StringVar()\n self.tkvar.set('...To Sign Off...')\n tk.OptionMenu(main, self.tkvar, *choices, command=self.func).grid(row=1, column=0)\n self.label2 = tk.Label(main, image=None)\n self.label2.grid(row=2, column=0, rowspan=500)\n tk.Button(main, text=\"Open\", command=self.change_dropdown).grid(row=502, column=0)\n self.dataSend = tk.Button(main, text=\"Send\", command=self.var_states, state='disabled')\n self.dataSend.grid(column=1, row=13, sticky='w')\n self.CaptureScreen = tk.Button(main, text=\"PrintScreen\", command=self.print_screen, state='disabled')\n self.CaptureScreen.grid(column=1, row=14, sticky='w')\n self.manualBtn = tk.Button(manual, text=\"open doc\", command=manual_open)\n self.manualBtn.pack()\n\n def clock(self):\n t = time.strftime('%d/%m/%Y, %H:%M:%S, ', time.localtime())\n if t != '':\n self.display_time.config(text=t, font='times 15')\n self.after(1000, self.clock)\n\n def print_screen(self):\n pyautogui.keyDown('alt')\n pyautogui.keyDown('printscreen')\n pyautogui.keyUp('printscreen')\n pyautogui.keyUp('alt')\n self.dataSend['state'] = 'normal'\n\n def var_states(self):\n text_file = open(\"logfile.txt\", \"a\")\n formatted_string = 'Username: {}'.format(self.username)\n for ndex, sub_list in enumerate(self.checkbutton_list):\n formatted_string = '{}, Option {}: '.format(formatted_string, ndex+1, sub_list[1].get())\n text_file.write(formatted_string)\n text_file.close()\n self.img = ImageGrab.grabclipboard()\n self.img.save('//SERVER/shared_data/Technical/Label Sign Off Sheets/sign off project/Signed/{} {} .jpg'\n .format(os.path.basename(self.p).strip('- to sign.jpg'), self.username), 'JPEG')\n ed = '//SERVER/shared_data/Technical/Label Sign Off Sheets/sign off project/Signed/{} ed.jpg'\\\n .format(os.path.basename(self.p).strip('- to sign.jpg'))\n nb = '//SERVER/shared_data/Technical/Label Sign Off Sheets/sign off project/Signed/{} Nb.jpg'\\\n .format(os.path.basename(self.p).strip('- to sign.jpg'))\n jj = '//SERVER/shared_data/Technical/Label Sign Off Sheets/sign off project/Signed/{} jj.jpg'\\\n .format(os.path.basename(self.p).strip('- to sign.jpg'))\n kl = '//SERVER/shared_data/Technical/Label Sign Off Sheets/sign off project/Signed/{} kl.jpg'\\\n .format(os.path.basename(self.p).strip('- to sign.jpg'))\n\n if os.path.exists(ed) and os.path.exists(nb) or os.path.exists(jj) or os.path.exists(kl):\n os.remove('//SERVER/shared_data/Technical/Label Sign Off Sheets/sign off project/To sign/{}'\n .format(os.path.basename(self.p)))\n else:\n print(\"False\")\n\n def change_dropdown(self):\n img = Image.open(self.tkvar.get())\n photo = ImageTk.PhotoImage(img)\n self.label2.image = photo\n self.label2.configure(image=photo)\n self.CaptureScreen['state'] = 'normal'\n self.p = None\n\n def func(self, value):\n self.p = Path(value)\n print(self.p)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>For your error in the comments I am not getting this same issue.\nPlease provide full trace back. As you can see below I can print the value of <code>accounts</code> resulting from this line <code>accounts = {key: value.rstrip() for key, value in account_list}</code> and that is the same line you get an error on.</p>\n\n<p><a href=\"https://i.stack.imgur.com/M3Cow.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/M3Cow.png\" alt=\"enter image description here\"></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T07:26:46.553",
"Id": "448797",
"Score": "0",
"body": "Hi Mike, thanks for your feedback! For your code, this error shows up `self.tk = master.tk\nAttributeError: 'function' object has no attribute 'tk'`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T11:54:44.140",
"Id": "448840",
"Score": "0",
"body": "@98Ed Ah I think that is because I forgot super in your top level class. I added that in. IF you can give me a line number for the error that would help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T18:44:24.227",
"Id": "448898",
"Score": "0",
"body": "@98Ed I found the error sorry. I had `self.frame` instead of `frame` in one of the buttons. It should run now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-09T19:02:01.340",
"Id": "448901",
"Score": "0",
"body": "@98Ed Ok I did some testing by removing some code (related to your paths) and it should all work now. Let me know if you have any more problems."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T05:54:42.327",
"Id": "448972",
"Score": "0",
"body": "Hi Mike, sorry for late reply. Here is the `ValueError` for the script above: ``` accounts = {key: value.rstrip() for key, value in account_list}\nValueError: not enough values to unpack (expected 2, got 1)```"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T12:17:41.533",
"Id": "449033",
"Score": "0",
"body": "@98Ed I cannot reproduce your error. See my updated answer."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T20:40:16.343",
"Id": "230386",
"ParentId": "230049",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T18:27:14.687",
"Id": "230049",
"Score": "5",
"Tags": [
"python",
"tkinter"
],
"Title": "Paper label system in Python"
} | 230049 |
<p>Simplified the actual problem to focus on comparing/removing performance.</p>
<p>Given a set S with n elements , find the most optimal way to compare each element to all others until a condition is met that decides if and which item to remove. I experience long runtimes when n is high (e.g. n=3000 has a runtime of 2500ms on an intel i5-6500 cpu)</p>
<p>An element is a Tuple object (itv, t) where itv holds an integer interval value (between 0 and 4, inclusive) and t holds an integer total benefit value.</p>
<p>The condition: Given Tuple s and another Tuple s', if itv == itv', then if t <= t' remove s, else remove s'.</p>
<p>A naïve example. S={(1,20),(0,40),(1,35)}</p>
<ol>
<li><p>Compare (1,20) with (0,40): itv != itv', continue.</p></li>
<li><p>Compare (1,20) with (1,35): itv == itv', t < t', remove (1,20) from S.</p></li>
<li><p>Compare (0,40) with (1,34): itv != itv', return S.</p></li>
</ol>
<p>Due to Java's constraints on removing elements while iterating, for-loops are wildly inefficient and I currently use a nested foreach-loop inside an Iterator loop. However, I still feel like it underperforms. This thought is mostly because the code looks terrible, in my opinion.</p>
<p>Below is my implementation. It tries to reduce the amount of unnecessary comparisons as much as possible. My code uses an outer Iterator for comparing the main Tuple to the others. In the case that the interval matches and the main Tuple's total benefit is worse, the inner loop is stopped, the main Tuple is removed and we continue with the next Iterator item. If the inner Tuple is worse, however, then the inner Tuple is marked for deletion and will be deleted at the end of the outer loop iteration.</p>
<p>Does anyone see any glaring mistakes, have any comments about performance (expensive calls) or refactoring for code clarity?</p>
<pre><code>public static HashSet<Tuple> compareAndRemove(HashSet<Tuple> set) {
HashSet<Tuple> bestTuples = new HashSet<>(set.size()); //Return set
Collection<Tuple> tupleRemovals = new HashSet<>(); //Tuples to remove this iteration
Iterator<Tuple> s_iter;
do {
set.removeAll(tupleRemovals);
removedElements += tupleRemovals.size();
tupleRemovals = new HashSet<>();
s_iter = set.iterator();
if (s_iter.hasNext()) {
Tuple s = s_iter.next();
if (!s_iter.hasNext()) { //Last element; nothing to compare anymore
bestTuples.add(s);
s_iter.remove();
break;
}
//Compare with other
boolean removeMainTuple = false;
for (Tuple s_prime : set) {
boolean equalIntervals = true;
if (s.equals(s_prime)) continue; //Skip same element
//Check interval
if (s.itv == s_prime.itv) {
//Decide which Tuple to discard
if (s.t <= s_prime.t) {
removeMainTuple = true; //Remove Iterator element
break;
} else {
tupleRemovals.add(s_prime); //Remove foreach element
}
}
}
//Move current item to return set if it was the best
if (!removeMainTuple) {
bestTuples.add(s);
}
s_iter.remove();
}
} while (s_iter.hasNext());
bestTuples.addAll(set);
return bestTuples;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T18:38:45.100",
"Id": "447839",
"Score": "0",
"body": "This looks like a great first post, good job!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T18:45:17.503",
"Id": "447840",
"Score": "0",
"body": "Thank you! I'm curious if I designed my algorithm wrong, or if I just made a few simple mistakes like using the wrong data structure..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T21:55:08.693",
"Id": "447876",
"Score": "0",
"body": "Are you just trying to find the best tuples, or are you trying to mutate the Set in the parameter to remove the ones that aren't the best, or both? (If both, shouldn't the result of the mutation and the Set returned be the same Set?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T13:40:48.750",
"Id": "447947",
"Score": "0",
"body": "Runtime has precedence over space complexity for this, although I do appreciate a solution that does not have an unnecessarily large space complexity."
}
] | [
{
"body": "<p>In the case where you just want to find the best tuples, the code can be much simpler:</p>\n\n<ul>\n<li>find the <code>Tuple</code> with the best <code>t</code> for each value of <code>itv</code> (sounds like a job for <code>Map</code>)</li>\n<li>put the best bunch of <code>Tuple</code> into a Set, and return it</li>\n</ul>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static Set<Tuple> bestTuples(Set<Tuple> set) {\n\n Map<Integer, Tuple> bestTuplesByItv = new HashMap<Integer, Tuple>();\n Tuple bestTupleSoFar;\n for (Tuple t: set) {\n if ((bestTupleSoFar = bestTuplesByItv.get(t.itv)) == null || t.t > bestTupleSoFar.t) {\n bestTuplesByItv.put(t.itv, t);\n }\n }\n\n Set<Tuple> bestTuples = new HashSet<Tuple>();\n bestTuples.addAll(bestTuplesByItv.values());\n\n return bestTuples;\n\n}\n</code></pre>\n\n<p>This should also be faster - your solution has some nested loops, O(n^2), but the suggestion above just iterates through the entire <code>set</code> once. My gut tells me that removing things from a Set is slower than just making a new set with the things we want, but I'm not sure about HashSet.</p>\n\n<p>Since the values for the <code>Map</code> are coming from a <code>HashSet</code>, all the values are guaranteed to have unique hash value. Since that's the case, we don't need a <code>LinkedHashMap</code> - a plain <code>HashMap</code> will work just fine (<code>LinkedHashMap</code> creates linked lists to deal with hash collisions - but that's unnecessary as we won't have any).</p>\n\n<p>Your code seems to be mutating the <code>Set</code> that is passed in as a parameter though - if that's desired behaviour, it's a trivial modification from the code above - just clear the values in <code>set</code> and add the values we want before returning:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static Set<Tuple> compareAndRemove(Set<Tuple> set) {\n\n Map<Integer, Tuple> bestTuplesByItv = new HashMap<Integer, Tuple>();\n Tuple bestTupleSoFar;\n for (Tuple t: set) {\n if ((bestTupleSoFar = bestTuplesByItv.get(t.itv)) == null || t.t > bestTupleSoFar.t) {\n bestTuplesByItv.put(t.itv, t);\n }\n }\n\n set.clear();\n set.addAll(bestTuplesByItv.values());\n\n return set;\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T13:37:39.530",
"Id": "447945",
"Score": "0",
"body": "Very good answer! I'll accept it, but I do still promote discussion for other's opinions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T23:18:43.427",
"Id": "230066",
"ParentId": "230050",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "230066",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T18:31:20.297",
"Id": "230050",
"Score": "6",
"Tags": [
"java",
"performance",
"algorithm",
"set"
],
"Title": "Remove elements compared with other elements in a Set based on a condition"
} | 230050 |
<p>I am using <a href="https://github.com/tjanczuk/edge" rel="nofollow noreferrer">EdgeJS</a> in my application. The application is used to run a user-provided javascript program from C#. Because we allow execution of user scripts some sandboxing is required. I am using <a href="https://github.com/patriksimek/vm2" rel="nofollow noreferrer">vm2</a> for sandboxing. Is it correct to add custom logic by overriding a function exposed by NodeJS library?</p>
<p>Here is the C# program:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using EdgeJs;
using Newtonsoft.Json;
namespace EdgeJSApplication
{
class Program
{
private const string SWSANDBOXEDSCRIPTIPLISTING = "EdgeJSApplication.NodeScripts.SandboxedScriptIPListing.js";
private const string SANDBOXEDSCRIPT = "EdgeJSApplication.NodeScripts.SandboxedScript.js";
private const string SAMPLE_SCRIPT = "EdgeJSApplication.NodeScripts.SampleScript.js";
static void Main(string[] args)
{
try
{
//chrome://inspect/#devices
//Environment.SetEnvironmentVariable("EDGE_NODE_PARAMS", $"--max_old_space_size=2048 --inspect-brk");
Environment.SetEnvironmentVariable("EDGE_NODE_PARAMS", $"--max_old_space_size=2048");
var sanboxedScript = GetScript(SWSANDBOXEDSCRIPTIPLISTING);
var script = GetScript(SAMPLE_SCRIPT);
var func = Edge.Func(sanboxedScript);
var executorSettings = new Dictionary<string, object>();
executorSettings.Add("Tokens", null);
var funcTask = func(new
{
Script = script,
ScriptExecutionContext = new
{
Tokens = new
{
OutputFileName = "",
IsOutgoingIpWhitelistEnabled = "true",
}
},
AssemblyDirectory = GetAssemblyDirectory()
});
dynamic scriptResult = funcTask.Result;
var json = JsonConvert.SerializeObject(scriptResult.output);
Console.WriteLine(json);
Console.Read();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private static string GetScript(string script)
{
var assembly = Assembly.GetExecutingAssembly();
string sanboxedScript;
using (var stream = assembly.GetManifestResourceStream(script))
{
if (stream != null)
{
using (var reader = new StreamReader(stream))
{
sanboxedScript = reader.ReadToEnd();
}
}
else
{
throw new ArgumentNullException("Script not found!");
}
}
return sanboxedScript;
}
private static string GetAssemblyDirectory()
{
string codeBase = typeof(Program).Assembly.CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
var assemblyDirectory = Path.GetDirectoryName(path);
return assemblyDirectory;
}
}
}
</code></pre>
<p>This program calls a Sandbox script and provides it with an input of user-provided script. Below is the sandbox script and user-provided script</p>
<p>Sandbox script:</p>
<pre><code> var func = function (context, postresult) {
const { NodeVM, VM, VMScript } = require('vm2');
var scriptExecutionContext = context.ScriptExecutionContext;
const vm = new NodeVM({
console: 'inherit',
setTimeout: setTimeout,
require: {
external: {
modules:['request', 'xpath', 'xmldom', 'xml2js']
},
builtin: false,
context: 'host'
},
root: './ ',
sandbox: {
context: scriptExecutionContext,
callback: callback,
eval: undefined
}
});
var script = context.Script;
vm.run(script, context.AssemblyDirectory + '\\edge\\SampleScript.js');
process.on('uncaughtException',
(err) => {
postresult(null,
{
output: null,
previousRunContext: null,
scriptLogs: [],
success: false,
errormessage: "SCRIPTUNCAUGHTEXCEPTION: " + err.message
});
});
function callback(scope, result) {
result.success = true;
postresult(scope, result);
}
};
return func;
</code></pre>
<p>User-Provided script:</p>
<pre><code>debugger;
var httpRequest = require('request');
var xPath = require('xpath');
var xmlDOM = require('xmldom');
var parser = require('xml2js');
//var express = require('express'); //external
//var fs = require('fs'); //builtin
var someURI = "https://api.github.com/users";
var someMethod = "GET";
var someHeaders = {
'User-Agent': 'Node.js'
}
makeRequest(someURI, someMethod, someHeaders);
function makeRequest(httpEndpoint, httpMethod, httpHeaders) {
httpRequest(
{
method: httpMethod,
uri: httpEndpoint,
headers: httpHeaders
},
function handleResponse(error, response, body) {
debugger;
if (response.statusCode == 200) {
callback(null, {
output: JSON.parse(body),
previousRunContext: "myContextVariable"
});
}
else {
throw new Error("The request did not return a 200 (OK) status.\r\nThe returned error was:\r\n" + error);
}
}
);
}
</code></pre>
<p>The users are allowed to use only whitelisted external modules in their script. This is controlled from the following code block in Sandbox script.</p>
<pre><code>require: {
external: {
modules:['request', 'xpath', 'xmldom', 'xml2js']
},
builtin: false,
context: 'host'
}
</code></pre>
<p>So if in the sample program following lines are uncommented it will return error</p>
<pre><code>//var express = require('express'); //external
//var fs = require('fs'); //builtin
</code></pre>
<p>Recently I was asked to add a validation to check if the IPs used in the user-provided script are whitelisted. This is how I implemented it:</p>
<pre><code> var func = function (context, postresult) {
debugger;
const { NodeVM, VM, VMScript } = require('vm2');
const extend = require('extend');
const dns = require('dns');
const url = require('url');
var whitelistedIps = ['140.82.118.5'];
var scriptExecutionContext = context.ScriptExecutionContext;
var prepareRequire = function (){}
var modifiedRequire = function (module) {
console.log(module);
var preparedRequire = prepareRequire(module);
if (module === 'request') {
return function request(uri, options, callback) {
var mergedInput = mergeInput(uri, options, callback);
var uri = url.parse(mergedInput.uri);
if (isValidIpAddress(uri.host)) {
if (!isAllowedIP(uri.host)) {
let message = `Data Request IP (${uri.host}) does not fall within the outgoing IP whitelist range.`;
throw new Error(message);
}
else {
return preparedRequire(mergedInput, mergedInput.callback);
}
}
else {
dns.lookup(uri.host, function (err, result) {
if (result) {
if (!isAllowedIP(result)) {
let message = `Data Request URI (${uri.host}) whose IP is (${result}) does not fall within the outgoing IP whitelist range.`;
throw new Error(message);
}
else {
return preparedRequire(mergedInput, mergedInput.callback);
}
}
else {
throw err;
}
});
}
}
}
return preparedRequire;
}
const vm = new NodeVM({
console: 'inherit',
setTimeout: setTimeout,
require: {
external: {
modules:['request', 'xpath', 'xmldom', 'xml2js']
},
builtin: false,
context: 'host'
},
root: './ ',
sandbox: {
context: scriptExecutionContext,
callback: callback,
eval: undefined,
modifiedRequire: modifiedRequire
}
});
prepareRequire = vm._prepareRequire(context.AssemblyDirectory+ '\\edge');
var script = `require = modifiedRequire;\n` + context.Script;
vm.run(script, context.AssemblyDirectory + '\\edge\\SampleScript.js');
process.on('uncaughtException',
(err) => {
postresult(null,
{
output: null,
previousRunContext: null,
scriptLogs: [],
success: false,
errormessage: "SCRIPTUNCAUGHTEXCEPTION: " + err.message
});
});
function callback(scope, result) {
result.success = true;
postresult(scope, result);
}
function isAllowedIP(ipAddress) {
let ipAddressInt = toInt(ipAddress);
for (let index = 0; index < whitelistedIps.length; index++) {
var val = whitelistedIps[index];
if (val.indexOf('-') !== -1) {
let ipRange = val.split('-');
let minIp = toInt(ipRange[0]);
let maxIp = toInt(ipRange[1]);
if (ipAddressInt >= minIp && ipAddressInt <= maxIp) {
return true;
}
}
else {
let ip = toInt(val);
if (ip === ipAddressInt) {
return true;
}
}
}
return false;
}
function mergeInput(uri, options, callback) {
if (typeof options === 'function') {
callback = options
}
var mergedInput = {}
if (options !== null && typeof options === 'object') {
extend(mergedInput, options, { uri: uri })
}
else if (typeof uri === 'string') {
extend(mergedInput, { uri: uri })
}
else {
extend(mergedInput, uri)
}
mergedInput.callback = callback || mergedInput.callback
return mergedInput
}
function toInt(ip) {
return ip.split('.').map((octet, index, array) => {
return parseInt(octet) * Math.pow(256, (array.length - index - 1));
}).reduce((prev, curr) => {
return prev + curr;
});
}
function isValidIpAddress(value) {
const regexIP = /\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/;
return regexIP.test(value);
}
};
return func;
</code></pre>
<p>Basically I am overriding the <code>_prepareRequire</code> function and added logic to check IP validity if the module is of type <code>request</code>. If the module is any other module, then I execute the _prepareRequire function provided by <code>vm2</code> library as is. This is working as expected. I would like to know if there is any issue with this approach?</p>
<p>The complete program can be found <a href="https://github.com/AashishUpadhyay/EdgeJSApplication/tree/233869cc68d8faf029face3da312f5bcceeec87d" rel="nofollow noreferrer">here</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T19:08:12.610",
"Id": "447849",
"Score": "0",
"body": "Why was this question downvoted? What's wrong?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T19:55:35.023",
"Id": "447852",
"Score": "1",
"body": "I'll take a guess since i'm not the one who downvoted : You tagged your question with `c#`, I don't think this is accurate. And you title is probably too vague. You should try to edit it to make it clearer. Apart from those two points, I'm not sure I see why your question would've been downvoted. Is the code supplied sufficient to understand the scope of the problem?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T20:00:20.730",
"Id": "447854",
"Score": "0",
"body": "Thanks, I will make the necessary edits. The code above will explain the scope. However, that in itself is not enough to run the application, I have provided a link to github repo where entire working code is present."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T20:07:33.913",
"Id": "447855",
"Score": "3",
"body": "Maybe this is the reason, then. The thing with CodeReview is that you must have all the code necessary to understand the context (so, is every variable/function you use in the code above defined in the said code or would someone need to follow the GitHub link?). It's hard to make it right, but it's worth it. Try to make sure someone can understand the whole code without having to follow external links."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T18:52:16.650",
"Id": "230051",
"Score": "4",
"Tags": [
"c#",
"javascript",
"node.js",
"sandbox"
],
"Title": "Running a JavaScript program from C# with sandboxing"
} | 230051 |
<p>I'm learning C so I thought to apply it to <a href="https://www.reddit.com/r/dailyprogrammer/comments/cmd1hb/20190805_challenge_380_easy_smooshed_morse_code_1/" rel="noreferrer">miniproject on reddit</a>. The smorse function takes in a string and spits out some morse code. It works if you supply the function with only lowercase letters. I feel awkward making a first for loop in my smorse function to calculate the size of buffer I need to malloc and then making a second for loop to add the characters.</p>
<pre><code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char **master = NULL;
char* smorse(char *str) {
int i;
char *ele;
int end = strlen(str);
char *output = "";
int totalSize = 0;
for (i = 0; i < end; i++) {
ele = master[(*str) - 97];
totalSize += sizeof(ele) * sizeof(char);
str++;
}
output = malloc(totalSize);
str -= end;
for (i = 0; i < end; i++) {
ele = master[(*str) - 97];
strcat(output, ele);
str++;
}
return output;
}
int main(int argc, char *argv[]) {
int i;
char key[] = ".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --..";
master = (char **)malloc(26 * sizeof(char *));
char *ele = strtok(key, " ");
for (i = 0; i < 26; i++) {
if (i != 0)
ele = strtok(NULL, " ");
master[i] = (char *)malloc(sizeof(ele) * sizeof(char));
master[i] = ele;
}
printf("%s\n", smorse("sos"));
printf("%s\n", smorse("daily"));
printf("%s\n", smorse("programmer"));
printf("%s\n", smorse("bits"));
printf("%s\n", smorse("three"));
free(master);
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T07:42:19.540",
"Id": "447904",
"Score": "4",
"body": "Links can rot. [Please include a description of the challenge here in your question.](//codereview.meta.stackexchange.com/q/1993)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T14:08:34.897",
"Id": "447955",
"Score": "2",
"body": "Since it's in your example, I should mention that pro-words such as SOS are transmitted without spaces, unlike ordinary words that have a dash-length pause between each letter, and three dashes pause between words."
}
] | [
{
"body": "<p>regarding: </p>\n\n<pre><code>int main(int argc, char *argv[]) { \n</code></pre>\n\n<p>Since the parameters are not used, the compiler will output two messages about unused parameters. Strongly suggest using the signature: </p>\n\n<pre><code>int main( void ) \n</code></pre>\n\n<p>regarding: </p>\n\n<pre><code>master[i] = (char *)malloc(sizeof(ele) * sizeof(char));\n</code></pre>\n\n<p>1) the returned type is void* which can be assigned to any pointer. Casting just clutters the code, making it more difficult to understand, debug. etc. Suggest removing that cast. </p>\n\n<p>2) The expression: <code>sizeof( char )</code> is defined in the C standard as 1. Multiplying by 1 has no effect. </p>\n\n<p>Suggest removing that expression. </p>\n\n<p>3) always check (!=NULL) the returned value to assure the operation was successful. If not successful, call </p>\n\n<pre><code>perror( \"malloc failed\" ); \n</code></pre>\n\n<p>to output both your error message 'malloc failed' and the text reason the system thinks the error occurred to <code>stderr</code>. </p>\n\n<p>regarding: </p>\n\n<pre><code>int end = strlen(str); \n</code></pre>\n\n<p>The function: <code>strlen()</code> returns a <code>size_t</code> which is an <code>unsigned long int</code>. This will result in the compiler outputting a message about this (error prone) implicit conversion. Suggest:</p>\n\n<pre><code>size_t end = strlen( str );\n</code></pre>\n\n<p>regarding: </p>\n\n<pre><code>totalSize += sizeof(ele) * sizeof(char); \n</code></pre>\n\n<p>the variable <code>ele</code> is a pointer, so <code>sizeof( ele )</code> results in the size of a pointer. Depending on the underlying hardware architecture the resulting value will be 4 or 8</p>\n\n<p>The array <code>master[]</code> can be easily directly coded, so no need to waste time, code, CPU cycles developing that array. Suggest:</p>\n\n<pre><code>char **master[] =\n{\n \".-\",\n \"-...\",\n etc.\n};\n</code></pre>\n\n<p>Then in <code>smorse()</code> a loop similar to:</p>\n\n<pre><code>for( size_t i = 0; str[i]; i++ )\n{ \n printf( \"%s \", master[ tolower( str[i] ) ] );\n}\n\nputs( \"\" );\n</code></pre>\n\n<p>where the <code>tolower()</code> is from the header file: <code>ctype.h</code></p>\n\n<p>in <code>main()</code>, these statements:</p>\n\n<pre><code>printf(\"%s\\n\", smorse(\"sos\"));\nprintf(\"%s\\n\", smorse(\"daily\"));\nprintf(\"%s\\n\", smorse(\"programmer\"));\nprintf(\"%s\\n\", smorse(\"bits\"));\nprintf(\"%s\\n\", smorse(\"three\"));\n</code></pre>\n\n<p>can be replaced with: </p>\n\n<pre><code>smorse( \"sos\" );\nsmorse( \"daily\" );\netc.\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T03:33:49.713",
"Id": "230072",
"ParentId": "230056",
"Score": "4"
}
},
{
"body": "<h2>main()</h2>\n\n<p>It looks like this line it trying to allocate some memory to store one of the morse code strings (e.g., \"-...\").</p>\n\n<pre><code>master[i] = (char *)malloc(sizeof(ele) * sizeof(char));\n</code></pre>\n\n<p>However, <code>ele</code> is a char* and <code>sizeof(char)</code> is 1. So, this allocates memory for one char*, not enough to store a string of up to 4 char plus a terminating NULL. To get the length of the string pointed to by <code>ele</code> use <code>strlen()</code>. </p>\n\n<p>A pointer to the allocated memory is then stored in <code>master[i]</code>. But, the very next line:</p>\n\n<pre><code>master[i] = ele;\n</code></pre>\n\n<p>overwrites that pointer with the pointer returned by <code>strtok()</code>. The malloced memory is goes unused and un-freed. And is in fact not needed.</p>\n\n<p>This loop could be written like:</p>\n\n<pre><code>int i = 0;\nfor (char *ele = strtok(key, \" \"); ele; ele = strtok(NULL, \" \")) {\n master[i++] = ele;\n}\n</code></pre>\n\n<p>Or better yet, just hard code <code>master</code>, like user3629249 said.</p>\n\n<p><code>smorse()</code> returns a pointer to malloc'd memory that is never freed.</p>\n\n<h2>smorse()</h2>\n\n<p>For proper morse code, you need a short space, or break, between letters and a slightly longer one between words. The inter-letter space can be a space at the end of each master code.</p>\n\n<p>The longest morse code string is 5 characters (including a space at the end of each code), so you could just do:</p>\n\n<pre><code>output = (char *)malloc(5 * strlen(str))\n</code></pre>\n\n<p>In this loop, <code>i</code> is never used:</p>\n\n<pre><code>for (i = 0; i < end; i++) {\n ele = master[(*str) - 97];\n strcat(output, ele);\n str++;\n}\n</code></pre>\n\n<p>It could be coded like:</p>\n\n<pre><code>for (char *c = str; *c; c++) {\n ele = master[(*c) - 97];\n strcat(output, ele);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T07:53:24.863",
"Id": "230081",
"ParentId": "230056",
"Score": "2"
}
},
{
"body": "<h1>Memory leak</h1>\n<p>Consider this (I removed the pointless cast and identity multiplication):</p>\n<blockquote>\n<pre><code> master[i] = malloc(sizeof ele);\n master[i] = ele;\n</code></pre>\n</blockquote>\n<p>Here, we allocate memory (if <code>malloc()</code> succeeds), but then immediately overwrite our one and only pointer to it, so we're unable to ever free it. The first assignment should just be removed, leaving only <code>master[i] = ele</code>.</p>\n<h1>Another memory leak:</h1>\n<blockquote>\n<pre><code>printf("%s\\n", smorse("sos"));\n</code></pre>\n</blockquote>\n<p>The <code>smorse()</code> function returns a pointer to allocated memory, which we need to release when we've finished using it:</p>\n<pre><code>const char *m = smorse("sos");\nputs(m);\nfree(m);\n</code></pre>\n<p>(The <code>puts()</code> call is exactly equivalent to using <code>printf("%s\\n", m)</code>, but more readable and possible more efficient.)</p>\n<h1>Character coding assumptions</h1>\n<p>The magic value <code>97</code> in a couple of places suggests that we're assuming that characters are encoded as ASCII values. That's not a portable assumption: C permits a wide range of encodings. Notably, EBCDIC systems do not have letters in the same positions as ASCII (or even as a contiguous block, so replacing with <code>'a'</code> doesn't solve the problem).</p>\n<p>Also, there's no checking that the input to the function contains only characters that we can handle. If we pass anything outside of the expected range, then we index <code>master</code> outside its bounds, which is Undefined Behaviour in C. That means that the program may do anything - if we're lucky, it will simply crash, helping us to identify the problem, but there's no guarantee of that.</p>\n<p>We ought to be converting more than just letters - digits have a standard Morse representation, as do certain other useful symbols.</p>\n<h1>Value conversions</h1>\n<p>It seems that this has been compiled with a very low level of warnings enabled. Building with my usual compiler flags results in over a dozen warnings, most about suspect conversions.</p>\n<p>To pick a couple of examples:</p>\n<blockquote>\n<pre><code>int end = strlen(str);\n</code></pre>\n</blockquote>\n<p><code>strlen()</code> returns a <code>size_t</code>, which is of different signedness to <code>int</code>, and very likely to be bigger, so there's a risk of undefined behaviour here.</p>\n<blockquote>\n<pre><code>char *output = "";\n</code></pre>\n</blockquote>\n<p>It's dangerous to point a modifiable pointer at constant data (a string literal is of type <code>char const*</code>).</p>\n<blockquote>\n<pre><code>printf("%s\\n", smorse("sos"));\n</code></pre>\n</blockquote>\n<p>Passing a string literal loses constness here - <code>smorse()</code> ought to accept pointer to <code>const</code> instead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T14:11:21.620",
"Id": "447956",
"Score": "0",
"body": "Excellent point about character encoding assumptions. I made the same error in my own rewrite, but I've now fixed it with a C11 `_Static_assert`. How would you handle, say, EBCDIC or UTF8 in a portable way?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T14:23:32.963",
"Id": "447958",
"Score": "0",
"body": "@Edward - for single-byte encodings, I'd probably go for an array of size `UCHAR_MAX+1` and index it directly; for UTF-8 and other multi-byte encodings, read into a `wchar_t` and probably look up in a binary-searchable map (I don't think we could create that at compile-time, but we could define it with the correct elements and sort it before use). I'm imagining an array of `struct { char index; char const* morse; }`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T09:37:27.827",
"Id": "230085",
"ParentId": "230056",
"Score": "5"
}
},
{
"body": "<p>I see some things that may help you improve your program.</p>\n\n<h2>Omit unused variables</h2>\n\n<p>Because <code>argc</code> and <code>argv</code> are unused, you could use the alternative form of <code>main</code>:</p>\n\n<pre><code>int main()\n</code></pre>\n\n<h2>Eliminate global variables where practical</h2>\n\n<p>Having routines dependent on global variables makes it that much more difficult to understand the logic and introduces many opportunities for error. In this case <code>master</code> can easily be eliminated and I'll show below.</p>\n\n<h2>Minimize the scope of variables</h2>\n\n<p>Somewhat related to eliminating global variables is the idea that variables should be defined in the minimum practical scope. In this case, for instance, <code>key</code> doesn't really belong in <code>main</code> but should instead be in <code>smorse</code> as I'll describe in the next suggestion.</p>\n\n<h2>Use a better data structure</h2>\n\n<p>Right now, <code>key[]</code> is a poorly named data structure which is then post-processed at runtime to create the data structure that's actually used. Better would be to simply use a better data structure in the first place. Here's how I'd do it:</p>\n\n<pre><code>static const char* morse[] = {\".-\", \"-...\", \"-.-.\", \"-..\", \".\", \"..-.\", \"--.\", \"....\", \"..\", \".---\", \"-.-\", \".-..\", \"--\", \"-.\", \"---\", \".--.\", \"--.-\", \".-.\", \"...\", \"-\", \"..-\", \"...-\", \".--\", \"-..-\", \"-.--\", \"--..\"};\n</code></pre>\n\n<h2>Fix the bug</h2>\n\n<p>Right now, <code>output</code> is uninitialized when the call to <code>strcat</code> is made, making this <em>undefined behavior</em>. You don't want that! Instead, initialize <code>output</code> like this:</p>\n\n<pre><code>output[0] = '\\0';\n</code></pre>\n\n<h2>Check for <code>NULL</code> pointers</h2>\n\n<p>If the call to <code>malloc</code> fails, the program will dereference a <code>NULL</code> pointer which is undefined behavior. Instead, explicitly check for a <code>NULL</code> pointer. You may also want to check to make sure that <code>smorse</code> has not been passed a <code>NULL</code> pointer.</p>\n\n<h2>Don't leak memory</h2>\n\n<p>Right now, because the pointer that <code>smorse</code> returns is only passed to <code>printf</code>, it can't be freed, which means that the program leaks memory. I'd change <code>main</code> to look like this:</p>\n\n<pre><code>int main() {\n const char *words[] = { \"sos\", \"daily\", \"programmmer\", \"bits\", \"three\", NULL };\n for (const char **word = words; *word; ++word) {\n char *morse = smorse(*word);\n puts(morse);\n free(morse);\n }\n}\n</code></pre>\n\n<h2>Eliminate \"magic numbers\"</h2>\n\n<p>There are a few numbers in the code, such as <code>26</code> and <code>97</code> that have a specific meaning in their particular context. By using named constants such as <code>LetterCount</code> or the character constant <code>'a'</code>, the program becomes easier to read and maintain. </p>\n\n<h2>Use <code>const</code> where practical</h2>\n\n<p>The <code>keys</code> variable should never be changed, and so it should be declared <code>const</code>. Further, it would be better to have the argument to <code>smorse</code> also be a <code>const char *</code> to indicate to the caller that the passed word is not changed.</p>\n\n<h2>Perform input sanitation</h2>\n\n<p>The <code>smorse</code> function is not particularly robust for general user input. For instance, if the user passes the string <code>\"Z93!\"</code>, this code doesn't catch the fact that these letters are out of range and attempts to address an array with a negative index value. On my machine, this causes a segfault and a program crash.</p>\n\n<h2>Create a test function</h2>\n\n<p>Since you have some known inputs and expected outputs, it would make sense to use those to create some test vectors that could be used by a test function. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T13:28:23.447",
"Id": "230097",
"ParentId": "230056",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "230072",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T20:07:18.203",
"Id": "230056",
"Score": "6",
"Tags": [
"beginner",
"c"
],
"Title": "Morse Code Converter in C"
} | 230056 |
<p>2 years ago I did this:</p>
<p><a href="https://codereview.stackexchange.com/questions/144584/smallvector-stdvector-like-container-on-the-stack">SmallVector - std::vector like container on the stack</a></p>
<p>now, 2 years later, I am reinventing the wheel again, this time with fully constexpr SmallVector.</p>
<p>This time, because I decided it will have only constexpr functions, I decided to remove all non POD types.</p>
<pre><code>#ifndef MY_SMALL_VECTOR_H_
#define MY_SMALL_VECTOR_H_
#include <stdexcept> // std::bad_alloc while push_back
#include <type_traits> // std::is_trivial, std::is_standard_layout
#include <initializer_list>
//
// Based on
// http://codereview.stackexchange.com/questions/123402/c-vector-the-basics
// http://lokiastari.com/blog/2016/03/19/vector-simple-optimizations/
//
template<typename T, std::size_t SIZE>
class SmallVector{
static_assert(std::is_trivial<T>::value, "T must be POD...");
static_assert(std::is_standard_layout<T>::value, "T must be POD...");
private:
static constexpr std::size_t SIZEOF = sizeof(T);
static constexpr bool DEBUG_ = true;
public:
// TYPES
using value_type = T;
using size_type = std::size_t;
using iterator = T*;
using const_iterator = const T*;
private:
size_type length = 0;
T buffer[SIZE] = {};
public:
// STANDARD C-TORS
constexpr SmallVector() = default;
template<class IT>
constexpr SmallVector(IT begin, IT end){
appendCopy(begin, end);
}
constexpr SmallVector(const std::initializer_list<T> & list) :
SmallVector(list.begin(), list.end()){}
// MISC
constexpr
void reserve(size_type const) const noexcept{
// left for compatibility
}
constexpr
void clear() noexcept{
length = 0;
}
// COMPARISSON
constexpr bool operator==(const SmallVector &other) const noexcept{
if (length != other.length)
return false;
auto first = other.begin();
auto last = other.end();
auto me = begin();
for(; first != last; ++first, ++me){
if ( ! (*first == *me) )
return false;
}
return true;
}
template<typename CONTAINER>
constexpr bool operator!=(const CONTAINER &other) const noexcept{
return ! operator==(other);
}
// ITERATORS
constexpr
iterator begin() noexcept{
return buffer;
}
constexpr
iterator end() noexcept{
return buffer + length;
}
// CONST ITERATORS
constexpr const_iterator begin() const noexcept{
return buffer;
}
constexpr const_iterator end() const noexcept{
return buffer + length;
}
// C++11 CONST ITERATORS
constexpr const_iterator cbegin() const noexcept{
return begin();
}
constexpr const_iterator cend() const noexcept{
return end();
}
// SIZE
constexpr size_type size() const noexcept{
return length;
}
constexpr bool empty() const noexcept{
return size() == 0;
}
// MORE SIZE
constexpr size_type capacity() const noexcept{
return SIZE;
}
constexpr size_type max_size() const noexcept{
return SIZE;
}
// DATA
constexpr
value_type *data() noexcept{
return buffer;
}
constexpr const value_type *data() const noexcept{
return buffer;
}
// ACCESS WITH RANGE CHECK
constexpr
value_type &at(size_type const index){
validateIndex_(index);
return buffer[index];
}
constexpr const value_type &at(size_type const index) const{
validateIndex_(index);
return buffer[index];
}
// ACCESS DIRECTLY
constexpr
value_type &operator[](size_type const index) noexcept{
// see [1] behavior is undefined
return buffer[index];
}
constexpr const value_type &operator[](size_type const index) const noexcept{
// see [1] behavior is undefined
return buffer[index];
}
// FRONT
constexpr
value_type &front() noexcept{
// see [1] behavior is undefined
return buffer[0];
}
constexpr const value_type &front() const noexcept{
// see [1] behavior is undefined
return buffer[0];
}
// BACK
constexpr
value_type &back() noexcept{
// see [1] behavior is undefined
return buffer[length - 1];
}
constexpr const value_type &back() const noexcept{
// see [1] behavior is undefined
return buffer[length - 1];
}
// MUTATIONS
constexpr
void push_back(const value_type &value){
emplace_back(value);
}
constexpr
void push_back(value_type &&value){
emplace_back(std::move(value));
}
template<typename... Args>
constexpr
void emplace_back(Args&&... args){
if (length == SIZE){
throw std::bad_alloc{};
}
buffer[length++] = value_type(std::forward<Args>(args)...);
}
constexpr
void pop_back() noexcept{
// see [1]
--length;
}
public:
// NON STANDARD APPEND
template<class IT>
constexpr
void appendCopy(IT begin, IT end) {
for(auto it = begin; it != end; ++it)
push_back(*it);
}
private:
constexpr
void validateIndex_(size_type const index) const{
if (index >= length){
throw std::out_of_range("Out of Range");
}
}
// Remark [1]
//
// If the container is not empty,
// the function never throws exceptions (no-throw guarantee).
// Otherwise, it causes undefined behavior.
};
#endif
</code></pre>
<p>Here is small demo / test:</p>
<pre><code>#include "smallvector.h"
using vectorPod = SmallVector<int, 5>;
namespace{
constexpr auto test_constexpr2(){
vectorPod v{};
v.push_back(4);
v.clear();
v.emplace_back(5);
v.push_back(54);
int a = 9;
v.push_back(a);
vectorPod w{ 5, 54, 9 };
if (v == w)
v.at(0) = 7;
auto x = v.begin();
++x;
*x = 4;
return v;
}
} // namespace
int main(){
constexpr auto v = test_constexpr2();
return v[0];
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T06:54:01.987",
"Id": "447901",
"Score": "0",
"body": "You can use something along the lines of `union Buffer { T elem; char dummy; }; Buffer elems[N]; std::size_t count;` to support constexpr non-POD types."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T07:50:18.573",
"Id": "447905",
"Score": "0",
"body": "I thought about support trivially destructible but those are still unclear to me. what i mean, suppose you have a class that extends another class probably with virtual methods, but without any destructor. it will be OK to be inserted into the vector as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T07:51:24.890",
"Id": "447906",
"Score": "0",
"body": "by without any destructor I mean no d-tor at all, not even ~ = default;"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T23:54:53.440",
"Id": "448175",
"Score": "0",
"body": "How are destructors relevant? I suggested union because that’s the only way you can control lifetime at compile time. (Good news: since C++20 std::construct_* and std::destroy_* are allowed in constexpr contexts, so we can do it the normal way. )"
}
] | [
{
"body": "<p>Here's my suggestions:</p>\n\n<h1>Design</h1>\n\n<ul>\n<li><p>Calling the constructors and destructors at the correct time with <code>constexpr</code> is indeed nontrivial, but disrespect object lifetime != POD. Your implementation is conceptually fine with some non-POD types. Maybe \"trivial\" is what you are looking for.</p></li>\n<li><p>You are missing a lot of functionality. Users may want to use them, so you shouldn't be omitting them. In particular:</p>\n\n<ul>\n<li><p>Missing types: <code>(const_)?(reference|pointer|reverse_iterator)</code> and <code>difference_type</code>.</p></li>\n<li><p>Missing constructors: <code>(count)</code>, <code>(count, value)</code>.</p></li>\n<li><p>Missing functions: <code>assign</code>, <code>c?r(begin|end)</code>, <code>resize</code>, <code>emplace</code>, <code>insert</code>, <code>erase</code>, <code>swap</code>.</p></li>\n<li><p>Missing operators: <code><</code>, <code><=</code>, <code>></code>, <code>>=</code>.</p></li>\n</ul></li>\n<li><p>Don't provide a feature for the sake of providing it. For example, <code>capacity</code> or <code>reserve</code> isn't applicable, so drop them.</p></li>\n<li><p>Many things can be <code>noexcept</code>.</p></li>\n<li><p><code>std::bad_alloc</code> is for dynamic allocation failures. Don't abuse it for stack overflow.</p></li>\n<li><p><code>appendCopy</code> should check the total size first instead of failing halfway done.</p></li>\n</ul>\n\n<h1>Code</h1>\n\n<ul>\n<li><p>Sort the include directives in alphabetical order.</p></li>\n<li><p>Don't use ALL CAPS names for template parameters. Reserve them for macros.</p></li>\n<li><p>The <code>SIZEOF</code> and <code>DEBUG_</code> variables are never used. Remove them.</p></li>\n<li><p>Don't use multiple <code>public:</code> and <code>private:</code> labels.</p></li>\n<li><p>In <code>T buffer[SIZE] = {};</code>, is there a special reason for copy-initialization from <code>{}</code>? If yes, state it in a comment. Otherwise, just remove the <code>=</code>.</p></li>\n<li><p><code>std::initializer_list</code> should be taken by value, not const reference.</p></li>\n<li><p>The <code>(first, last)</code> constructor should be constrained.</p></li>\n<li><p>The comparison operators should be non-members.</p></li>\n<li><p>Don't make function parameters <code>const</code>.</p></li>\n<li><p><code>operator[]</code>, <code>front</code>, <code>back</code> shouldn't be <code>noexcept</code> even though it does not actually throw an exception in a well-defined way. <code>noexcept</code> should be used for functions that <em>never fail</em>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T08:38:36.963",
"Id": "448200",
"Score": "1",
"body": "Is there any reason why you would advise against making function parameters `const`. That is anithetical to `const`-correcteness and consequently a bad advise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T09:59:56.917",
"Id": "448215",
"Score": "1",
"body": "@miscco It doesn't matter to the caller for value types (it's a copy so the caller doesn't need to know). It makes the important `const`s harder to notice (reference types / pointer types). It can also be misleading, since C++ matches declarations with a `const` parameter with function definitions where the parameter isn't specified as `const`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T18:37:30.183",
"Id": "448433",
"Score": "0",
"body": "@user673679 That it doesnt matter for the caller is a non argument. He does not care so there is no value here. The same with C++ ignoring `const` from function definitions. Its sad but why do something bad because the language does something else badly? Also there are no important parts of beeing correct. You either are or not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T19:29:34.113",
"Id": "448444",
"Score": "1",
"body": "Extra `const`s may make your code slightly safer, but you pass the burden on to the user, who has to read the function declaration. `InputIt find(InputIt begin, const InputIt end, const T& value);` - `begin` isn't `const` because we use it as a loop variable (an implementation detail), whereas `end` doesn't change. `end` being `const` is meaningless noise to the user of the function. Only the last `const` actually conveys useful information. Pointers are especially messy: `std::size_t do_a_thing(char* const data, const std::size_t data_size)` - it's easy to misread that first parameter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T19:32:10.153",
"Id": "448445",
"Score": "0",
"body": "It's certainly debatable though: https://stackoverflow.com/questions/117293/use-of-const-for-function-parameters"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T00:23:59.067",
"Id": "448452",
"Score": "0",
"body": "@miscco I agree with user673679. Personally, I am against top-level `const` parameters because they are just confusing, both to the implementer and user. You own this object, so it doesn't matter too much whether it is `const` or not, taking into consideration that it is just a local variable used in a function of several lines. Removing the `const` allows you to direct modify the copied object when needed, and does no harm otherwise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T04:35:49.887",
"Id": "448461",
"Score": "0",
"body": "@L.F. Removing `const` always allows you to modify and by itself never does any harm... There is nothing confusing about const arguments. I am given a value and I will never change it. That is a clear statement of intent. Take `operator[](size_t index)` It bothers me mightily that `index` could be changed. The other case where you might want to change it is the rare case and please note that I am not _against_ non const arguments. But I want them to stand out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T04:40:49.283",
"Id": "448463",
"Score": "0",
"body": "@miscco Yes, `index` can be changed, inside the function. Common example: `while (size--) it++;` But as a user, I don't care what the function does with its own copy of the index; that's part of the implementation detail. I just know that `vec[i]` won't change my `i` and that's enough :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T04:42:16.293",
"Id": "448464",
"Score": "1",
"body": "@miscco I also find user673679's `mycopy(T* first, T* const last, const T* src)` very explanatory"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T08:06:20.780",
"Id": "230211",
"ParentId": "230061",
"Score": "1"
}
},
{
"body": "<p>Here is my unpopular opinion: This class has no reason to exist and you should use <a href=\"https://en.cppreference.com/w/cpp/container/array\" rel=\"nofollow noreferrer\"><code>std::array</code></a> instead which does what you need.</p>\n\n<p>If you need it to be compatible with <code>std:: vector</code> for template meta programming, you can just add a thin wrapper on top or use SFINAE to call <code>reserve</code> only if it exists.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T09:52:55.653",
"Id": "448214",
"Score": "0",
"body": "This container has dynamic size. `std::array` has static size. The fact that this container uses the stack and imposes an upper limit on the size does not matter. Keeping track of the actual number of elements is definitely useful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T20:52:32.210",
"Id": "448305",
"Score": "0",
"body": "perfectly OK except is not constexpr until c++17"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T08:55:50.837",
"Id": "230215",
"ParentId": "230061",
"Score": "1"
}
},
{
"body": "<p>We can use the standard library for equality comparison:</p>\n\n<pre><code>#include <algorithm>\n\nconstexpr bool operator==(const SmallVector &other) const noexcept {\n return std::equal(begin(), end(), other.begin(), other.end());\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T10:39:08.110",
"Id": "448220",
"Score": "1",
"body": "`std::equal` is not `constexpr` until C++20"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T10:08:19.293",
"Id": "230216",
"ParentId": "230061",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "230211",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T22:01:13.887",
"Id": "230061",
"Score": "6",
"Tags": [
"c++",
"reinventing-the-wheel",
"c++14",
"vectors"
],
"Title": "constexpr SmallVector - std::vector like container on the stack"
} | 230061 |
<p>I have created my own wrapping framework for the COM interfaces exposed via <code>Microsoft.Office.Interop</code>.</p>
<hr />
<h1>MIRRORING WRAPPERS</h1>
<p>The first purpose is to be able to unit test the rest of my applications, and also to be able to intuitively log some of the calls.</p>
<p>The wrapping is achieved through 2 layers of interfaces: the first layer exposes office-wide members, whilst the second layer exposes application-specific members.</p>
<p><em>Note that for the sake of readability I provide here a simplified sample. Only the variety of objects, types, and member names change from the original.</em></p>
<pre><code>#Region "Office Wrappers"
Interface IApplication(Of Out T As IFile(Of IVariable))
ReadOnly Property Documents As IEnumerable(Of T)
End Interface
Interface IFile(Of Out T As IVariable)
ReadOnly Property Variables As IEnumerable(Of T)
ReadOnly Property Name As String
End Interface
Interface IVariable
Property SomeProperty As String
End Interface
#End Region
#Region "Word Wrappers"
Interface IWordApplication(Of Out T As IWordDocument(Of IWordVariable))
Inherits IApplication(Of T)
End Interface
Interface IWordDocument(Of Out T As IWordVariable)
Inherits IFile(Of T)
ReadOnly Property Paragraphs As IEnumerable(Of IWordParagraph)
End Interface
Interface IWordVariable
Inherits IVariable
End Interface
Interface IWordParagraph
Property SomeProperty As String
End Interface
#End Region
</code></pre>
<p>These interfaces are instantiated via a Factory which is injected and creates the relevant object for a given object which implements an <code>Office.Interop</code> interface.</p>
<pre><code>#Region "Word objects"
Interface IWordFactory
Function Create(Application As Microsoft.Office.Interop.Word.Application) As IWordApplication(Of IWordDocument(Of IWordVariable))
Function Create(Document As IEnumerable(Of Microsoft.Office.Interop.Word.Document)) As IEnumerable(Of IWordDocument(Of IWordVariable))
Function Create(Paragraph As IEnumerable(Of Microsoft.Office.Interop.Word.Paragraph)) As IEnumerable(Of IWordParagraph)
Function Create(Variable As IEnumerable(Of Microsoft.Office.Interop.Word.Variable)) As IEnumerable(Of IWordVariable)
End Interface
Class WordApplication
Implements IWordApplication(Of IWordDocument(Of IWordVariable))
Protected ThisApplication As Microsoft.Office.Interop.Word.Application
Protected ThisFactory As IWordFactory
Sub New(Application As Microsoft.Office.Interop.Word.Application, Factory As IWordFactory)
Me.ThisApplication = Application
Me.ThisFactory = Factory
End Sub
Public ReadOnly Property Documents As IEnumerable(Of IWordDocument(Of IWordVariable)) Implements IApplication(Of IWordDocument(Of IWordVariable)).Documents
Get
Return Me.ThisFactory.Create(Me.ThisApplication.Documents.Cast(Of Microsoft.Office.Interop.Word.Document))
End Get
End Property
End Class
Class WordDocument
Implements IWordDocument(Of IWordVariable)
Protected ThisDocument As Microsoft.Office.Interop.Word.Document
Protected ThisFactory As IWordFactory
Sub New(Document As Microsoft.Office.Interop.Word.Document, Factory As IWordFactory)
Me.ThisDocument = Document
Me.ThisFactory = Factory
End Sub
Public ReadOnly Property Name As String Implements IFile(Of IWordVariable).Name
Get
Return Me.ThisDocument.Name
End Get
End Property
Public ReadOnly Property Paragraphs As IEnumerable(Of IWordParagraph) Implements IWordDocument(Of IWordVariable).Paragraphs
Get
Return Me.ThisFactory.Create(Me.ThisDocument.Paragraphs.Cast(Of Microsoft.Office.Interop.Word.Paragraph))
End Get
End Property
Public ReadOnly Property Variables As IEnumerable(Of IWordVariable) Implements IFile(Of IWordVariable).Variables
Get
Return Me.ThisFactory.Create(Me.ThisDocument.Variables.Cast(Of Microsoft.Office.Interop.Word.Variable))
End Get
End Property
End Class
Class WordParagraph
Implements IWordParagraph
Protected ThisParagraph As Microsoft.Office.Interop.Word.Paragraph
Protected ThisFactory As IWordFactory
Sub New(Paragraph As Microsoft.Office.Interop.Word.Document, Factory As IWordFactory)
Me.ThisParagraph = Paragraph
Me.ThisFactory = Factory
Me.SomeProperty = "Something"
End Sub
Public Property SomeProperty As String Implements IWordParagraph.SomeProperty
End Class
Class WordVariable
Implements IWordVariable
Protected ThisVariable As Microsoft.Office.Interop.Word.Variable
Protected ThisFactory As IWordFactory
Sub New(Variable As Microsoft.Office.Interop.Word.Document, Factory As IWordFactory)
Me.ThisVariable = Variable
Me.ThisFactory = Factory
Me.SomeProperty = "Something"
End Sub
Public Property SomeProperty As String Implements IVariable.SomeProperty
End Class
#End Region
</code></pre>
<hr />
<h1>EXTENDING THE WRAPPERS</h1>
<p>On top of these basic mirroring wrappers, I have a set of custom functionalities which extend the possibilities offered by each wrapper. These functionalities are not directly included in the above wrappers so that they can be unit tested.
Again, two layers, following the same pattern:</p>
<pre><code>#Region "Extension of Office Wrappers"
Interface IExtApplication(Of Out T As IExtFile(Of IVariable))
Inherits IApplication(Of T)
End Interface
Interface IExtFile(Of Out T As IVariable)
Inherits IFile(Of T)
Sub SomeCustomMethod()
End Interface
#End Region
#Region "Extension of Word Wrappers"
Interface IExtWordApplication
Inherits IWordApplication(Of IExtWordDocument), IExtApplication(Of IExtWordDocument)
End Interface
Interface IExtWordDocument
Inherits IWordDocument(Of IExtWordVariable), IExtFile(Of IExtWordVariable)
Function SomeCustomFunction(Parameter As Boolean) As Integer
End Interface
Interface IExtWordVariable
Inherits IWordVariable
End Interface
Interface IExtWordParagraph
Inherits IWordParagraph
Sub SomeCustomAction()
End Interface
#End Region
</code></pre>
<p>They are implemented following the same principle as before:</p>
<pre><code>#Region "Extended Word objects"
Interface IExtWordFactory
Inherits IWordFactory
Function Extend(Application As IWordApplication(Of IWordDocument(Of IWordVariable))) As IExtWordApplication
Function Extend(Document As IEnumerable(Of IWordDocument(Of IWordVariable))) As IEnumerable(Of IExtWordDocument)
Function Extend(Paragraph As IEnumerable(Of IWordParagraph)) As IEnumerable(Of IExtWordParagraph)
Function Extend(Variable As IEnumerable(Of IWordVariable)) As IEnumerable(Of IExtWordVariable)
End Interface
Class ExtWordApplication
Inherits WordApplication
Implements IExtWordApplication
Protected Shadows ThisFactory As IExtWordFactory
Sub New(Application As Microsoft.Office.Interop.Word.Application, ExtFactory As IExtWordFactory)
MyBase.New(Application, ExtFactory)
End Sub
Public Overloads ReadOnly Property Documents As IEnumerable(Of IExtWordDocument) Implements IApplication(Of IExtWordDocument).Documents
Get
Return Me.ThisFactory.Extend(MyBase.Documents)
End Get
End Property
End Class
Class ExtWordDocument
Inherits WordDocument
Implements IExtWordDocument
Protected Shadows ThisFactory As IExtWordFactory
Sub New(Document As Microsoft.Office.Interop.Word.Document, ExtFactory As IExtWordFactory)
MyBase.New(Document, ExtFactory)
End Sub
Public Overloads ReadOnly Property Name As String Implements IExtFile(Of IExtWordVariable).Name
Get
Return MyBase.Name
End Get
End Property
Public Overloads ReadOnly Property Variables As IEnumerable(Of IExtWordVariable) Implements IFile(Of IExtWordVariable).Variables
Get
Return Me.ThisFactory.Extend(MyBase.Variables)
End Get
End Property
Public Overloads ReadOnly Property Paragraphs As IEnumerable(Of IWordParagraph) Implements IWordDocument(Of IExtWordVariable).Paragraphs
Get
Return Me.ThisFactory.Extend(MyBase.Paragraphs)
End Get
End Property
Public Sub SomeCustomMethod() Implements IExtFile(Of IExtWordVariable).SomeCustomMethod
'DoSomething
End Sub
Public Function SomeCustomFunction(Parameter As Boolean) As Integer Implements IExtWordDocument.SomeCustomFunction
Return 123456
End Function
End Class
Class ExtWordParagraph
Inherits WordParagraph
Implements IExtWordParagraph
Protected Shadows ThisFactory As IExtWordFactory
Sub New(Paragraph As Microsoft.Office.Interop.Word.Paragraph, ExtFactory As IExtWordFactory)
MyBase.New(Paragraph, ExtFactory)
End Sub
Public Sub SomeCustomAction() Implements IExtWordParagraph.SomeCustomAction
'DoSomething
End Sub
End Class
Class ExtWordVariable
Inherits WordVariable
Implements IExtWordVariable
Protected Shadows ThisFactory As IExtWordFactory
Sub New(Variable As Microsoft.Office.Interop.Word.Variable, ExtFactory As IExtWordFactory)
MyBase.New(Variable, ExtFactory)
End Sub
End Class
#End Region
</code></pre>
<hr />
<h1>USAGE</h1>
<p>An extended factory is injected and used to instantiate the extended wrapper of the <code>Office.Interop</code> application. The reference to the Extended Application is then injected in all subsequent objects required for my models.
Some models are application-spcific, some are designed to proceed without worrying whether we are dealing with a Word Document or an Excel Workbook:</p>
<pre><code>Module Main
Sub Startup(InjectedFactory As IExtWordFactory)
Dim MyFactory As IExtWordFactory = InjectedFactory
Dim InteropApp As Microsoft.Office.Interop.Word.Application = Globals.ThisAddIn.Application
Dim MyApp As IExtWordApplication = MyFactory.Extend(MyFactory.Create(InteropApp))
FromOfficeWideOperationsLibrary(MyApp)
FromWordSpecificOperationsLibrary(MyApp)
End Sub
Sub FromOfficeWideOperationsLibrary(MyApp As IExtApplication(Of IExtFile(Of IVariable)))
For Each MyOpenFile As IExtFile(Of IVariable) In MyApp.Documents
MsgBox($"File name is {MyOpenFile.Name}")
MyOpenFile.SomeCustomMethod()
Next
End Sub
Sub FromWordSpecificOperationsLibrary(MyApp As IExtWordApplication)
For Each MyOpenDoc As IExtWordDocument In MyApp.Documents
MsgBox($"Document has {MyOpenDoc.Paragraphs.Count} paragraphs")
Next
End Sub
End Module
</code></pre>
<hr />
<h1>DISCUSSION</h1>
<p>I am far from being satisfied by this architecture:</p>
<ol>
<li>The first frustration is that when dealing with office-wide models, I am forced to repeatedly type <code>MyApp As IExtApplication(Of IExtFile(Of IVariable))</code>, where a simple <code>MyApp As IextApplication</code> would be much cleaner.</li>
<li>If I add a member to <code>IApplication</code>, I subsequently need to add an <code>Overloads</code> member in <code>ExtWordApplication</code> even if it is already implemented in <code>WordApplication</code> (look in the code above how the implementation of <code>Overlaods ReadOnly Property Name as String</code> is needlessly required for <code>ExtWordDocument</code>)</li>
<li>Although some extending objects are equal to their non extended version, it is still required to implement them (empty). For example, if <code>IExtFile</code> did not include any additional member when compared to <code>IFile</code>, I would still require to define the interface and its implementations so that starting from <code>ExtWordApplication</code>, it would be possible to travel the tree all the way down to <code>ExtWordParagraph</code>.</li>
</ol>
<p>Any thoughts?</p>
| [] | [
{
"body": "<p>I believe I have managed to substantially improve code by:</p>\n\n<ol>\n<li>Relying on aliases: <code>Imports IObject = IFoo(Of IBar(Of Something))</code></li>\n<li>Injecting the Office-wide objects inside Application-specific objects, rather than incorporating the base functionalities via Class inheritance. This allows for better unit testing.</li>\n</ol>\n\n<p>Any suggestions are still very welcome :)</p>\n\n<pre><code>Imports IApplication = MyNamespace.IApplication(Of MyNamespace.IFile(Of MyNamespace.IVariable))\nImports IFile = MyNamespace.IFile(Of MyNamespace.IVariable)\nImports IVariable = MyNamespace.IVariable\n\nImports IWordApplication = MyNamespace.IWordApplication(Of MyNamespace.IWordDocument(Of MyNamespace.IWordVariable))\nImports IWordDocument = MyNamespace.IWordDocument(Of MyNamespace.IWordVariable)\n\nImports IExtApplication = MyNamespace.IExtApplication(Of MyNamespace.IExtFile(Of MyNamespace.IVariable))\nImports IExtFile = MyNamespace.IExtFile(Of MyNamespace.IVariable)\n\n\n#Region \"Office Wrappers\"\n\n\nInterface IApplication(Of Out T As IFile)\n\n ReadOnly Property Documents As IEnumerable(Of T)\n\nEnd Interface\n\nInterface IFile(Of Out T As IVariable)\n\n ReadOnly Property Variables As IEnumerable(Of T)\n\n ReadOnly Property Name As String\n\nEnd Interface\n\nInterface IVariable\n\n Property SomeProperty As String\n\nEnd Interface\n\n\n#End Region\n\n\n#Region \"Extension of Office Wrappers\"\n\n\nInterface IExtApplication(Of Out T As IExtFile)\n Inherits IApplication(Of T)\n\nEnd Interface\n\nInterface IExtFile(Of Out T As IVariable)\n Inherits IFile(Of T)\n\n Sub SomeCustomMethod()\n\nEnd Interface\n\n\n#End Region\n\n\n#Region \"Word Wrappers\"\n\n\nInterface IWordApplication(Of Out T As IWordDocument)\n Inherits IApplication(Of T)\n\n\nEnd Interface\n\nInterface IWordDocument(Of Out T As IWordVariable)\n Inherits IFile(Of T)\n\n ReadOnly Property Paragraphs As IEnumerable(Of IWordParagraph)\n\nEnd Interface\n\nInterface IWordVariable\n Inherits IVariable\n\nEnd Interface\n\nInterface IWordParagraph\n\n Property SomeProperty As String\n\nEnd Interface\n\n\n#End Region\n\n\n#Region \"Extension of Word Wrappers\"\n\n\nInterface IExtWordApplication\n Inherits IWordApplication(Of IExtWordDocument), IExtApplication(Of IExtWordDocument)\n\nEnd Interface\n\nInterface IExtWordDocument\n Inherits IWordDocument(Of IExtWordVariable), IExtFile(Of IExtWordVariable)\n\n Function SomeCustomFunction(Parameter As Boolean) As Integer\n\nEnd Interface\n\nInterface IExtWordVariable\n Inherits IWordVariable\n\nEnd Interface\n\nInterface IExtWordParagraph\n Inherits IWordParagraph\n\n Sub SomeCustomAction()\n\nEnd Interface\n\n\n#End Region\n\n\n#Region \"Word objects\"\n\n\nInterface IWordFactory\n\n Function Create(Application As Microsoft.Office.Interop.Word.Application) As IWordApplication\n\n Function Create(Document As IEnumerable(Of Microsoft.Office.Interop.Word.Document)) As IEnumerable(Of IWordDocument)\n\n Function Create(Paragraph As IEnumerable(Of Microsoft.Office.Interop.Word.Paragraph)) As IEnumerable(Of IWordParagraph)\n\n Function Create(Variable As IEnumerable(Of Microsoft.Office.Interop.Word.Variable)) As IEnumerable(Of IWordVariable)\n\nEnd Interface\n\n\nClass WordApplication\n Implements IWordApplication\n\n Protected ThisApplication As Microsoft.Office.Interop.Word.Application\n Protected ThisFactory As IWordFactory\n\n Sub New(Application As Microsoft.Office.Interop.Word.Application, Factory As IWordFactory)\n Me.ThisApplication = Application\n Me.ThisFactory = Factory\n End Sub\n\n Public ReadOnly Property Documents As IEnumerable(Of IWordDocument) Implements IApplication(Of IWordDocument).Documents\n Get\n Return Me.ThisFactory.Create(Me.ThisApplication.Documents.Cast(Of Microsoft.Office.Interop.Word.Document))\n End Get\n End Property\n\nEnd Class\n\n\nClass WordDocument\n Implements IWordDocument\n\n Protected ThisDocument As Microsoft.Office.Interop.Word.Document\n Protected ThisFactory As IWordFactory\n\n Sub New(Document As Microsoft.Office.Interop.Word.Document, Factory As IWordFactory)\n Me.ThisDocument = Document\n Me.ThisFactory = Factory\n End Sub\n\n Public ReadOnly Property Name As String Implements IFile(Of IWordVariable).Name\n Get\n Return Me.ThisDocument.Name\n End Get\n End Property\n\n Public ReadOnly Property Paragraphs As IEnumerable(Of IWordParagraph) Implements IWordDocument.Paragraphs\n Get\n Return Me.ThisFactory.Create(Me.ThisDocument.Paragraphs.Cast(Of Microsoft.Office.Interop.Word.Paragraph))\n End Get\n End Property\n\n Public ReadOnly Property Variables As IEnumerable(Of IWordVariable) Implements IFile(Of IWordVariable).Variables\n Get\n Return Me.ThisFactory.Create(Me.ThisDocument.Variables.Cast(Of Microsoft.Office.Interop.Word.Variable))\n End Get\n End Property\n\nEnd Class\n\nClass WordParagraph\n Implements IWordParagraph\n\n Protected ThisParagraph As Microsoft.Office.Interop.Word.Paragraph\n Protected ThisFactory As IWordFactory\n\n Sub New(Paragraph As Microsoft.Office.Interop.Word.Document, Factory As IWordFactory)\n Me.ThisParagraph = Paragraph\n Me.ThisFactory = Factory\n Me.SomeProperty = \"Something\"\n End Sub\n\n Public Property SomeProperty As String Implements IWordParagraph.SomeProperty\n\nEnd Class\n\nClass WordVariable\n Implements IWordVariable\n\n Protected ThisVariable As Microsoft.Office.Interop.Word.Variable\n Protected ThisFactory As IWordFactory\n\n Sub New(Variable As Microsoft.Office.Interop.Word.Document, Factory As IWordFactory)\n Me.ThisVariable = Variable\n Me.ThisFactory = Factory\n Me.SomeProperty = \"Something\"\n End Sub\n\n Public Property SomeProperty As String Implements IVariable.SomeProperty\n\nEnd Class\n\n\n#End Region\n\n\n#Region \"Extended Word objects\"\n\n\nInterface IExtWordFactory\n Inherits IWordFactory\n\n Function Extend(Application As IWordApplication(Of IWordDocument(Of IWordVariable))) As IExtWordApplication\n\n Function Extend(Document As IEnumerable(Of IWordDocument(Of IWordVariable))) As IEnumerable(Of IExtWordDocument)\n\n Function Extend(Paragraph As IEnumerable(Of IWordParagraph)) As IEnumerable(Of IExtWordParagraph)\n\n Function Extend(Variable As IEnumerable(Of IWordVariable)) As IEnumerable(Of IExtWordVariable)\n\nEnd Interface\n\n\nClass ExtWordApplication\n Implements IExtWordApplication\n\n Private ThisWordApplication As IWordApplication\n Protected Shadows ThisFactory As IExtWordFactory\n\n Sub New(WordApplication As IWordApplication, ExtFactory As IExtWordFactory)\n Me.ThisWordApplication = WordApplication\n End Sub\n\n Public Overloads ReadOnly Property Documents As IEnumerable(Of IExtWordDocument) Implements IApplication(Of IExtWordDocument).Documents\n Get\n Return Me.ThisFactory.Extend(Me.ThisWordApplication.Documents)\n End Get\n End Property\n\nEnd Class\n\n\nClass ExtWordDocument\n Implements IExtWordDocument\n\n Private ThisWordDocument As IWordDocument\n Protected Shadows ThisFactory As IExtWordFactory\n\n Sub New(WordDocument As IWordDocument, ExtFactory As IExtWordFactory)\n Me.ThisWordDocument = WordDocument\n End Sub\n\n Public Overloads ReadOnly Property Name As String Implements IExtFile(Of IExtWordVariable).Name\n Get\n Return Me.ThisWordDocument.Name\n End Get\n End Property\n\n Public Overloads ReadOnly Property Variables As IEnumerable(Of IExtWordVariable) Implements IFile(Of IExtWordVariable).Variables\n Get\n Return Me.ThisFactory.Extend(Me.ThisWordDocument.Variables)\n End Get\n End Property\n\n Public Overloads ReadOnly Property Paragraphs As IEnumerable(Of IWordParagraph) Implements IWordDocument(Of IExtWordVariable).Paragraphs\n Get\n Return Me.ThisFactory.Extend(Me.ThisWordDocument.Paragraphs)\n End Get\n End Property\n\n Public Sub SomeCustomMethod() Implements IExtFile(Of IExtWordVariable).SomeCustomMethod\n 'DoSomething\n End Sub\n\n Public Function SomeCustomFunction(Parameter As Boolean) As Integer Implements IExtWordDocument.SomeCustomFunction\n Return 123456\n End Function\n\nEnd Class\n\n\nClass ExtWordParagraph\n Implements IExtWordParagraph\n\n Private ThisWordParagraph As IWordParagraph\n Protected Shadows ThisFactory As IExtWordFactory\n\n Sub New(WordParagraph As IWordParagraph, ExtFactory As IExtWordFactory)\n Me.ThisWordParagraph = WordParagraph\n End Sub\n\n Public Property SomeProperty As String Implements IWordParagraph.SomeProperty\n Get\n Return Me.ThisWordParagraph.SomeProperty\n End Get\n Set(value As String)\n Me.ThisWordParagraph.SomeProperty = value\n End Set\n End Property\n\n Public Sub SomeCustomAction() Implements IExtWordParagraph.SomeCustomAction\n 'DoSomething\n End Sub\n\nEnd Class\n\n\nClass ExtWordVariable\n Implements IExtWordVariable\n\n Private ThisWordVariable As IWordVariable\n Protected Shadows ThisFactory As IExtWordFactory\n\n Sub New(WordVariable As IWordVariable, ExtFactory As IExtWordFactory)\n Me.ThisWordVariable = WordVariable\n End Sub\n\n Public Property SomeProperty As String Implements IVariable.SomeProperty\n Get\n Return Me.ThisWordVariable.SomeProperty\n End Get\n Set(value As String)\n Me.ThisWordVariable.SomeProperty = value\n End Set\n End Property\n\nEnd Class\n\n\n#End Region\n\n\nClass Main\n\n Sub Startup(InjectedFactory As IExtWordFactory)\n\n Dim MyFactory As IExtWordFactory = InjectedFactory\n Dim InteropApp As Microsoft.Office.Interop.Word.Application = Nothing 'Globals.ThisAddIn.Application\n Dim MyApp As IExtWordApplication = MyFactory.Extend(MyFactory.Create(InteropApp))\n\n FromOfficeWideOperationsLibrary(MyApp)\n FromWordSpecificOperationsLibrary(MyApp)\n\n End Sub\n\n Sub FromOfficeWideOperationsLibrary(MyApp As IExtApplication)\n\n For Each MyOpenFile As IExtFile In MyApp.Documents\n MsgBox($\"File name is {MyOpenFile.Name}\")\n MyOpenFile.SomeCustomMethod()\n Next\n\n End Sub\n\n Sub FromWordSpecificOperationsLibrary(MyApp As IExtWordApplication)\n\n For Each MyOpenDoc As IExtWordDocument In MyApp.Documents\n MsgBox($\"Document has {MyOpenDoc.Paragraphs.Count} paragraphs\")\n Next\n\n End Sub\n\nEnd Class\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T15:17:35.370",
"Id": "230106",
"ParentId": "230062",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T22:08:14.100",
"Id": "230062",
"Score": "1",
"Tags": [
"vb.net"
],
"Title": "Cascading interfaces for wrapping VSTO Microsoft.Office.Interop"
} | 230062 |
<p>This is my attempt to write a numpy-optimized version of a nearest centroid classifier to classify some images from the <code>MNIST</code> data set of handwritten digits. I am somewhat new to numpy and was surprised by how succinctly this code could be written with the help of broadcasting and vectorized operations, but was wondering if I was still missing some possibly important improvements.</p>
<hr>
<p>So first, the starting data are a set of 10000 training images and 1000 test images, each of which are represented as a vector of 784 pixels (corresponding to a 28x28 grayscale image). Normally these would be actual MNIST images of handwritten digits, but for simplicity, here are some "dummy" data:</p>
<pre><code>import numpy as np
train_data = np.random.randint(256, size=(784, 10000), dtype="uint8")
test_data = np.random.randint(256, size=(784, 1000), dtype="uint8")
</code></pre>
<p>Note that the way the data is (would be, if it was the real data) arranged is such that the first tenth of each data set is a 0, the next tenth is a 1, and so on through 9 (this is important for how the data gets processed below).</p>
<p>Now, to process the data, I compute the mean for each digit in the training set, classify each image in both the training and test sets, and then compute and output both the training and test accuracies:</p>
<pre><code>train_means = np.mean(train_data.reshape(784, 10, 1000), axis=2)
train_classes, test_classes = (np.argmin(np.sum(np.square(data[:,:,np.newaxis] - train_means[:,np.newaxis,:]), axis=0), axis=1) for data in (train_data, test_data))
train_acc, test_acc = (np.mean(np.equal(classes, np.repeat(np.arange(10), classes.size // 10))) for classes in (train_classes, test_classes))
print("training accuracy: {}\n testing accuracy: {}".format(train_acc, test_acc))
</code></pre>
<hr>
<p>How can the above code be improved in terms of (1) efficiency, (2) memory, and (3) style / simplicity?</p>
<p>For instance, one concern I have is that the subtraction <code>data[:,:,np.newaxis] - train_means[:,np.newaxis,:]</code> creates a <code>(784, 10000, 10)</code> array, which is more memory than I need to use. Could I avoid allocating this much memory while not sacrificing any efficiency (and ideally any simplicity of code)?</p>
<p>Another concern is the comprehension I use to apply the procedures to both the training data and testing data. Would that be encouraged or considered convoluted (or maybe this is just irrelevant personal preference)?</p>
<p>Also: in general, is the code too condensed?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T05:39:05.170",
"Id": "447896",
"Score": "0",
"body": "Please comment on question deficiencies after downvoting :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T06:11:36.197",
"Id": "447897",
"Score": "5",
"body": "Maybe the downvoter didn't see how to run this piece of code, and where the input comes from. A more detailed project setup description would be nice, in order to reproduce your results, and to demonstrate that this code is a complete program."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T12:52:31.467",
"Id": "447934",
"Score": "0",
"body": "I didn't downvote, but there's one sure thing that'd make your code better and it would be to split it on more than 3 lines. Right now, I'd guess people downvote your post because there's so little code and it's usually a sign of a bad question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T18:49:42.243",
"Id": "450801",
"Score": "0",
"body": "@RolandIllig Thanks for the feedback! I updated the question to give a more detailed setup such that someone can just copy and paste the code and run it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-23T18:53:12.610",
"Id": "450802",
"Score": "1",
"body": "@IEatBagels The program is not meant to be too complicated, but definitely if you think that it is too condensed and would be better split into more lines, that could be a helpful part of an answer. Hopefully the code being bad as in the question does not itself make the question bad... otherwise there would not seem to be much purpose in asking a good question!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-24T12:53:29.033",
"Id": "450928",
"Score": "1",
"body": "@Grayscale No, don't worry. The code being bad (not necessarily yours) doesn't mean the question is bad :) I was supposing, in this particular case, but bad code shouldn't mean bad question, it's a code review after all!"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T23:10:56.277",
"Id": "230065",
"Score": "1",
"Tags": [
"python",
"numpy",
"machine-learning",
"vectorization"
],
"Title": "condensed nearest centroid classifier in numpy"
} | 230065 |
<p>I'm building an example REST API in PHP in my local environment to learn how they work. The starting point was an online tutorial. The example is working fine; however, I have a hunch that there is room for improvement in the logic that handles the endpoints which is stored in a script called <code>RestController.php</code>.</p>
<p>Currently, I have the example working both via a UI and, separately, using Postman. The pertinent lines in <code>.htaccess</code> file are:</p>
<pre><code>RewriteRule ^mobile/?$ controllers/RestController.php [nc,L]
RewriteRule ^mobile/([0-9]+)/?$ controllers/RestController.php?id=$1 [nc,qsa,L]
</code></pre>
<p>Here is an example of a Postman test for the GET one mobile API endpoint:
<a href="https://i.stack.imgur.com/j6fxX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j6fxX.png" alt="enter image description here"></a></p>
<p>The code that follows is RestController.php. I'm wondering if there is a way to refactor this into a class but still have the ability to use Postman for testing the endpoints. If so, how would one go about doing that?</p>
<pre><code><?php
require_once("../classes/MobileRestHandler.php");
# read raw data from request body and stuff it into $_POST
$_POST = json_decode(file_get_contents('php://input'), true);
# get parameter values according to the method
$method = $_SERVER['REQUEST_METHOD'];
# initialize and populate $parameters_* variables
if (in_array($method, ['GET', 'PUT', 'DELETE'])) {
$id = isset($_GET["id"]) ? $_GET["id"] : "";
$parameters_id_only = ['id' => $id];
}
if (in_array($method, ['POST', 'PUT'])) {
$name = isset($_POST["name"]) ? $_POST["name"] : "";
$model = isset($_POST["model"]) ? $_POST["model"] : "";
$color = isset($_POST["color"]) ? $_POST["color"] : "";
$parameters_no_id = ['name' => $name, 'model' => $model, 'color' => $color];
}
if ($method == 'PUT') {
$parameters_all = array_merge($parameters_id_only, $parameters_no_id);
}
# this logic controls the RESTful services URL mapping
$mobileRestHandler = new MobileRestHandler();
if (!in_array($method, ['GET', 'POST', 'PUT', 'DELETE'])) {
$statusCode = 404;
$statusMessage = $mobileRestHandler->getHttpStatusMessage($statusCode);
exit($statusCode . ' - ' . $statusMessage);
} else {
if ($method == 'GET' && strlen($id) == 0) {
$result = $mobileRestHandler->getAllMobiles(); // handles method GET + REST URL /mobile/
} else if ($method == 'GET') {
$result = $mobileRestHandler->getMobile($parameters_id_only); // handles method GET + REST URL /mobile/<id>/
} else if ($method == 'POST') {
$result = $mobileRestHandler->addMobile($parameters_no_id); // handles method POST + REST URL /mobile/
} else if ($method == 'PUT') {
$result = $mobileRestHandler->editMobile($parameters_all); // handles method PUT + REST URL /mobile/<id>/
} else if ($method == 'DELETE') {
$result = $mobileRestHandler->deleteMobile($parameters_id_only); // handles method DELETE + REST URL /mobile/<id>/
}
echo $result;
}
?>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T14:45:27.177",
"Id": "447961",
"Score": "0",
"body": "Why not learn and use [GraphQL](https://graphql.org/) instead, as REST is simply not that great design.."
}
] | [
{
"body": "<p>Unless I am missing something in your requirements, I don't think there is a terrific need for the overhead of a class. (I could be wrong)</p>\n\n<p>I do spy some opportunities to ratchet up your code though. Consider these points and if you decide to further develop your script into a class, then this should move you in that direction with some single responsibility thinking.</p>\n\n<ol>\n<li><p>Don't extract data until you are sure that you will use it.</p></li>\n<li><p>Don't Repeat Yourself (DRY). Don't make the server repeat any operations that provide results that its already provided.</p></li>\n<li><p><code>switch()</code> blocks are verbose, but they are appropriately used when you are performing multiple evaluations on the same variable.</p></li>\n</ol>\n\n<hr>\n\n<pre><code>require_once(\"../classes/MobileRestHandler.php\");\n\nfunction getId() {\n return ['id' => $_GET[\"id\"] ?? ''];\n}\n\nfunction getPost() {\n $defaults = array_fill_keys(['name', 'model', 'color'], '');\n $posted = json_decode(file_get_contents('php://input'), true);\n return array_replace($defaults, array_intersect_key($posted, $defaults));\n}\n\nfunction getIdAndPost() {\n return array_merge(getId(), getPost());\n}\n\nswitch ($_SERVER['REQUEST_METHOD']) {\n case 'GET':\n $result = empty($_GET['id'])\n ? $mobileRestHandler->getAllMobiles();\n : $mobileRestHandler->getMobile(getId());\n break;\n case 'POST':\n $result = $mobileRestHandler->addMobile(getPost());\n break;\n case 'PUT':\n $result = $mobileRestHandler->editMobile(getIdAndPost());\n break;\n case 'DELETE':\n $result = $mobileRestHandler->deleteMobile(getId());\n break;\n default:\n $result = '404 - ' . $mobileRestHandler->getHttpStatusMessage(404);\n}\n\nexit($result);\n</code></pre>\n\n<p>Admittedly, my untested script doesn't validate, sanitize, or throw any errors, but your script didn't seem to mind these relevant topics.</p>\n\n<p>p.s. For the record, I don't endorse the technique of deleting a record based on <code>$_GET</code> data -- if a crawler would hapen to come upon your script and some valid ids, it could vanquish records during the simple act of crawling. When manipulating data stores, always use <code>$_POST</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T02:51:13.577",
"Id": "448178",
"Score": "1",
"body": "Much obliged for the thorough, well explained answer. I'm going to incorporate all of your recommendations and modify the record deletion so it uses an id from `$_POST`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T12:10:20.367",
"Id": "230154",
"ParentId": "230069",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "230154",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T00:52:52.793",
"Id": "230069",
"Score": "2",
"Tags": [
"php",
"api"
],
"Title": "controller design of a REST API in PHP"
} | 230069 |
<p>Good day, it's my first time doing something like this so I wanted to solve some of the challenges on project Euler, however I reached a block on my code, even before I submitted I was aware that I would be unable to compile within time limits for numbers well beyond the million or close to a million, still went along with it and of course, the test cases on the million(s)? [because they are hidden and I dont exactly know the numbers] expired due to time limits constraints.</p>
<p>I was wondering if I could receive some feedback on how to improve my code, given that at the minimum the value received would be a million of course.</p>
<pre><code>class Solution {
private static void mathSolver(long _number){
long _sum = 0;
for(long x = 0; x<_number; x++){
if((x % 3 == 0) || (x % 5 == 0)){
_sum += x;
}
}
Console.WriteLine(_sum);
}
static void Main(String[] args) {
int t = Convert.ToInt32(Console.ReadLine());
for(int a0 = 0; a0 < t; a0++){
int n = Convert.ToInt32(Console.ReadLine());
mathSolver(n);
}
}
}
</code></pre>
<p>I already tried of tinkering with it with some math sequences, trying to figure out a pattern that would allow me to jump between numbers, so that instead of iterating through every number on a million, I would, lets say, jump between 3's or 5s directly, however no operation that I could think of would give me the result I wanted as it was very prone to mistakes along the way. </p>
<p>A slight background of me if anyone is interested while reviewing, I'm not exactly new to C#, been doing it for slightly under 2 years however my first employer procured tons of bad practices and code disasters, this is why I want to expose myself to these kind of things, to improve efficiency while coding, to get better code readibility and presentation as well as trying to find solutions that aren't as forceful.</p>
<p>Thank you for your answers and may you have a nice day!</p>
| [] | [
{
"body": "<p>Hint:</p>\n\n<p><span class=\"math-container\">$$\n\\sum_{i=1}^ni = \\frac{n (n+1)}{2}\n$$</span></p>\n\n<p>With this you can compute the sum of <code>1</code> to <code>n</code> without looping. Can you figure out a way to do this for all digits with increments of 3? And 5?</p>\n\n<p>The last thing to consider is that with this method, you are counting all digits divisible by 15 double, since they are both divisible by 3 and 5.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T23:31:36.433",
"Id": "448014",
"Score": "0",
"body": "Thank you, I managed to solve this by using the math provided, it was very hard to understand at first so I checked for other sources, one of them explained the formula on detail, I'll annex the answer below as an answer to the question, it would be my pleasure if you could pin point me my mistakes!\n\nThank you very much !!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T07:44:55.547",
"Id": "230079",
"ParentId": "230073",
"Score": "2"
}
},
{
"body": "<p>I managed to solve it using the Math formulas both provided by user JAD, MJOLKA and Emily L.</p>\n\n<p>It's not pretty looking but tried to make it functional while retaining versatility as to modifications, a single method also means it can be re-used to determine different values since I left things a bit abstract and the behavior determined by the parameters sent.</p>\n\n<pre><code>class Solution {\n\n private static long mathSolver(long _endNumber){\n long _firstDivision = 0, _secondDivision = 0, _thirdDivision = 0;\n //We search for individual values\n _firstDivision = Division(_endNumber, 3, 1);\n _secondDivision = Division(_endNumber, 5, 5);\n _thirdDivision = Division(_endNumber, 15, 15);\n\n return _firstDivision + _secondDivision - _thirdDivision;\n }\n\n\n private static long Division(long _endNumber, int _divider, int _substracter){\n //We search for residues, if they dont exist we apply our own\n long _division = 0;\n if(_endNumber % _divider == 0){ \n _division = (_endNumber - _substracter)/_divider;\n }\n else{\n _division = (_endNumber- (_endNumber % _divider))/_divider;\n }\n return (_divider*((_division)*((_division +1))/2));\n }\n\n static void Main(String[] args) {\n long t = Convert.ToInt64(Console.ReadLine());\n for(int a0 = 0; a0 < t; a0++){\n long n = Convert.ToInt64(Console.ReadLine());\n long _sum = mathSolver(n);\n Console.WriteLine(_sum);\n }\n }\n}\n</code></pre>\n\n<p>It was very entertaining and I will check for more challenges whenever I have the time for them! you learn a lot of math-related subjects to make your code efficient!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T08:28:43.763",
"Id": "448065",
"Score": "2",
"body": "I have taken the liberty to remove the “request for feedback” from your answer. If that is desired then you should post a follow-up question."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T23:36:10.453",
"Id": "230123",
"ParentId": "230073",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "230079",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T03:37:43.267",
"Id": "230073",
"Score": "3",
"Tags": [
"c#",
"programming-challenge"
],
"Title": "Q: Project Euler #1 - C#"
} | 230073 |
<p>Coursera has a course for beginning Machine Learning and the code is written in Octave. This is the beginning of a solution to the week 3 exercises but written in python. Instead of a terminal app I'm also trying to learn Pyside2. The actual functionality of the program may seem silly but I hope that some of the things I'm learning in it will translate to other real world problems. My code so far has two files.</p>
<h2>DigitData.py</h2>
<pre><code>import tensorflow.keras.datasets.mnist as mnist
import numpy as np
class DigitData(object):
def __init__(self):
# load the data from data sets
(x_train, self.y_train), (self.x_test, self.y_test) = mnist.load_data()
# reshape x to flatten from 28 x 28 matrix to a single
# row for each example
row, column, z_column = x_train.shape
self.x_train = np.reshape(x_train, (row, column * z_column))
def example(self, index, train=True):
if train:
sel_ex = self.x_train[index, :]
else:
sel_ex = self.x_test[index, :]
return np.reshape(sel_ex, (28, 28))
def label(self, index, train=True):
if train:
return self.y_train[index]
else:
return self.y_test[index]
</code></pre>
<h2>mlgui.py</h2>
<pre><code>import sys
import numpy as np
from PySide2.QtWidgets import (QLabel, QApplication, QVBoxLayout, QDialog, QHBoxLayout,
QScrollArea, QWidget, QProgressBar, QPushButton)
from PySide2.QtGui import QImage, QPixmap, qRgb
from PySide2.QtCore import Qt, Signal
from DigitData import DigitData
class DigitLabel(QLabel):
def __init__(self, digit_matrix):
super(DigitLabel, self).__init__()
self.img = QImage(int(28), int(28), QImage.Format(24))
self.img.fill(125)
self.setPixmap(QPixmap(self.img))
square = np.reshape(digit_matrix, (28, 28))
# TODO: save pixel data in QImage as true grayscale 8 bit
# TODO: place data into QImage without loop
# TODO: deal with the j and i flipping fix
for i in range(28):
for j in range(28):
pass
pixel_intensity = square[j, i]
color = qRgb(pixel_intensity, pixel_intensity, pixel_intensity)
self.img.setPixel(i, j, color)
self.setPixmap(QPixmap(self.img))
class DigitTable(QWidget):
looped = Signal(int)
def __init__(self):
super(DigitTable, self).__init__()
self.load_flag = None
def loadDigits(self, digit_data):
# show some data
hor_layout = QHBoxLayout()
for j in range(10):
vert_layout = QVBoxLayout()
for i in range(600):
app.instance().processEvents()
if self.load_flag == "quit":
return 0
DigitLabel(digit_data.example(i+(j*600)))
vert_layout.addWidget(DigitLabel(digit_data.example(i+(j*600))))
self.looped.emit(i+(j*600))
hor_layout.addLayout(vert_layout)
# Set dialog layout
if self.load_flag is None:
self.setLayout(hor_layout)
return 1
class DigitDialog(QDialog):
def __init__(self, parent=None):
super(DigitDialog, self).__init__(parent)
# load data
self.data = DigitData()
v_layout = QVBoxLayout()
self.bar = QProgressBar()
self.button = QPushButton("View Digits")
self.button.clicked.connect(self.load_digits)
v_layout.addWidget(self.button)
v_layout.addWidget(self.bar)
self.setLayout(v_layout)
self.setFixedWidth(400)
# vars used in loading digits
self.scroll = None
self.dt = None
def load_digits(self):
# setup the button to stop the load if desired
self.button.setText("Quit Loading")
self.button.clicked.disconnect()
self.button.clicked.connect(self.quit_load)
# load the digits
self.scroll = QScrollArea()
self.scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.scroll.setWidgetResizable(False)
self.dt = DigitTable()
self.dt.looped.connect(self.bar.setValue)
self.bar.setMinimum(0)
self.bar.setMaximum(6000)
success = self.dt.loadDigits(self.data)
if success:
# load was not interrupted
self.scroll.setWidget(self.dt)
self.scroll.setFixedHeight(400)
self.layout().addWidget(self.scroll)
# setup button to remove digits
self.button.setText("Hide Digits")
self.button.clicked.disconnect()
self.button.clicked.connect(self.hide_digits)
self.bar.setValue(0)
else:
# set up button to view digits
# load was interrupted
self.dt.hide()
self.dt.deleteLater()
self.button.setText("View Digits")
self.button.clicked.disconnect()
self.button.clicked.connect(self.load_digits)
self.bar.setValue(0)
def hide_digits(self):
# destroy the scrolling widget
self.scroll.hide()
self.scroll.deleteLater()
# set up button to view digits
self.button.setText("View Digits")
self.button.clicked.disconnect()
self.button.clicked.connect(self.load_digits)
# set Dialog back to original size
self.adjustSize()
def quit_load(self):
self.dt.load_flag = "quit"
if __name__ == '__main__':
# Create the Qt Application
app = QApplication(sys.argv)
# Create and show the form
dialog = DigitDialog()
dialog.show()
# Run the main Qt loop
sys.exit(app.exec_())
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T08:16:36.657",
"Id": "447909",
"Score": "0",
"body": "Can you add a description of the exercise to make it easier to review? Questions should stand on their own."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T20:11:54.767",
"Id": "448156",
"Score": "0",
"body": "@Mast, This code loads a visualization (images) of the digits used in the exercise and isn't part of the solution to the exercise. Perhaps I should have updated what the code does do. That seems moot now, but in the future, I'll keep this in mind."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T06:49:12.850",
"Id": "448195",
"Score": "0",
"body": "Into the question itself, please. Comments are third-rate citizens on Stack Exchange and may be removed at any time."
}
] | [
{
"body": "<p>Most of your code looks pretty good, so I'll be highlighting the lines I have thoughts about.</p>\n\n<p>But first, are you using Python 3.x? Because if not, please be aware that core dev support for python 2.x will be <a href=\"https://www.anaconda.com/end-of-life-eol-for-python-2-7-is-coming-are-you-ready/\" rel=\"noreferrer\">dropped</a> at the end of this year. So even though you lack the python 3.x tag, I'll pretend you're using it, since all your code looks python 3.x compatible. A few of these things would make you code unable to run on 2.x - I will mark when this happens, to the best of my knowledge. </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class DigitData(object):\n# Should be:\nclass DigitData:\n</code></pre>\n\n<p>Inheritance from object is implicit in python 3.x only.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>(x_train, self.y_train), (self.x_test, self.y_test) = mnist.load_data()\n# Should be:\n(self.x_train, self.y_train), (self.x_test, self.y_test) = mnist.load_data()\n</code></pre>\n\n<p>You're using it later. </p>\n\n<pre class=\"lang-py prettyprint-override\"><code> def label(self, index, train=True):\n if train:\n return self.y_train[index]\n else:\n return self.y_test[index]\n</code></pre>\n\n<p>Any function returning from a conditional can be rewritten as:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> def label(self, index, train=True):\n if train:\n return self.y_train[index]\n return self.y_test[index]\n</code></pre>\n\n<p>Of course, in this specific limited case, you could even one-line it:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> def label(self, index, train=True):\n return (self.y_train if train else self.y_test)[index]\n</code></pre>\n\n<p>But that depends on if you still think this readable. Opinions may differ - I consider this acceptable, but not everyone will. If you do, you can also apply this to your DigitData.example() method.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>super(DigitLabel, self).__init__()\n# Can be:\nsuper().__init__()\n</code></pre>\n\n<p>For python 3.x only.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>self.img = QImage(int(28), int(28), QImage.Format(24))\n</code></pre>\n\n<p>You don't need to cast to ints here, the number 28 already is one. You might also be interested in making these \"magic\" numbers global constants, since you're using them again a few lines later.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for i in range(28):\n for j in range(28):\n pass\n pixel_intensity = square[j, i]\n color = qRgb(pixel_intensity, pixel_intensity, pixel_intensity)\n self.img.setPixel(i, j, color)\n</code></pre>\n\n<p>You're absolutely right that it shouldn't be done this way. Since you're already using numpy, consider putting that (or more specifically, it's buffer) behind a QIcon. I'm more of a PyQt guy myself rather than PySide, but I believe PySide should also be capable of this.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def loadDigits(self, digit_data):\n # ...\n</code></pre>\n\n<p>You're skipping a total of 6000 main loop iterations while executing this one method? That smells a bit like suboptimal solutions. Are you really sure you need 6000 widgets in your layouts here? </p>\n\n<p>I'm going to assume you really do need to - this isn't software engineering stack exchange after all. However, I still reccommend you only pause the loop around 1 in 10 iterations, perhaps even less. Same for it's progress bar signal. Especially after you finish optimizing <code>DigitLabel.__init__</code>a bit more - as often as you build it, you really cannot afford much.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>self.dt = DigitTable()\n</code></pre>\n\n<p>Qt does a lot of useful things with it's parent-child systems. You should really use them to. Add self as an argument here, and in the <code>__init__</code> of DigitTable, pass it to the super() call. </p>\n\n<pre class=\"lang-py prettyprint-override\"><code> def quit_load(self):\n self.dt.load_flag = \"quit\"\n</code></pre>\n\n<p>This should be a signal that connects to a slot of self.dt.</p>\n\n<p>In general, when loading a lot of data, you might want to look into offloading that into a another thread. Keep in mind that with Qt, you generally cannot do GUI work anywhere else but the main thread. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T07:20:32.520",
"Id": "230078",
"ParentId": "230074",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "230078",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T04:16:44.300",
"Id": "230074",
"Score": "5",
"Tags": [
"python",
"beginner",
"numpy",
"pyside"
],
"Title": "Beginning of a GUI Python solution to Andrew Ng's ML week 3 excercises"
} | 230074 |
<p>This is an interesting example from G.Lanaro's book, <a href="https://www.packtpub.com/eu/application-development/python-high-performance-second-edition" rel="nofollow noreferrer">Python High Performance</a>. The program is a simple simulator which describes movement of particles based on their positions and angular velocities (<code>x</code>, <code>y</code>, and <code>ang_v</code> attributes of a <code>Particle</code> class). The bottleneck of the program is the <code>evolve</code> method which is initially implemented using pure Python, and then the author tries to show how we can improve the performance of this specific method using NumPy operations. </p>
<p>My problem is that when I compare the run-time of NumPy version (<code>evolve_numpy</code>) versus the pure Python version (<code>evolve</code>), I can hardly see any improvement in terms of runtime; in fact, it seems like pure Python is a bit faster here.</p>
<p>I wrote all of this code myself, based off of what I learned in the book.</p>
<p>The initial version of <code>evolve</code> is as follows</p>
<pre><code> def evolve(self, dt):
timestep = .00001
nstep = int(dt / timestep)
for i in range(nstep):
for p in self.particles:
t_x_ang = timestep * p.ang_v
norm = (p.x ** 2 + p.y ** 2) ** .5
p.x, p.y = (p.x - t_x_ang * p.y / norm, p.y + t_x_ang * p.x/norm)
# repeat for all particles
# repeat for all time-steps
</code></pre>
<p>Here is the NumPy version of the same method,</p>
<pre><code> def evolve_numpy(self, dt):
timestep = 0.00001
nsteps = int(dt / timestep)
r_i = np.array([[p.x, p.y] for p in self.particles])
ang_vel_i = np.array([p.ang_v for p in self.particles])
for i in range(nsteps):
norm_i = np.sqrt((r_i ** 2).sum(axis=1))
v_i = r_i[:, [1, 0]]
v_i[:, 0] *= -1
v_i /= norm_i[:, np.newaxis]
d_i = timestep * ang_vel_i[:, np.newaxis] * v_i
r_i += d_i
for i, p in enumerate(self.particles):
p.x, p.y = r_i[i]
</code></pre>
<p>To test the runtime of both versions, a <code>benchmark2</code> function is defined as follows:</p>
<pre><code>def benchmark2(nparts, m):
particles = [Particle(uniform(-1, 1), uniform(-1, 1), uniform(-1, 1))
for i in range(nparts)]
sim = ParticleSimualtor(particles)
if m == 1:
sim.evolve(.1)
elif m == 2:
sim.evolve_numpy(.1)
else:
raise Exception('not a valid method')
</code></pre>
<p>You can access the complete code <a href="https://gist.github.com/OmidMiresmaeili/2891c4f1ce95f65cfab8ed0469e427d4" rel="nofollow noreferrer">here</a>: <a href="https://gist.github.com/OmidMiresmaeili/2891c4f1ce95f65cfab8ed0469e427d4" rel="nofollow noreferrer">https://gist.github.com/OmidMiresmaeili/2891c4f1ce95f65cfab8ed0469e427d4</a></p>
<p>My results are as follows:</p>
<p>1min 40s for NumPy version and 1min 29s for Python version
<a href="https://i.stack.imgur.com/RvopY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RvopY.jpg" alt="timeit benchmark results"></a></p>
<p>But the author claim (and I understand the reasoning) that the NumPy version runs much faster than the initial version of <code>evolve</code> without any NumPy operations:
<a href="https://i.stack.imgur.com/yGlXr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yGlXr.png" alt="Author's plot of runtimes"></a></p>
<p>This is a figure from page 71 of the book. It shows run-time for different particle size (<code>nparts</code> argument in the <code>benchmark2</code> function). The author then concludes:</p>
<blockquote>
<p>The plot shows that both the implementations scale linearly with particle size, but the runtime in the pure Python version grows much faster than the NumPy version; at greater sizes, we have a greater NumPy advantage. In general, when using NumPy, you should try to pack things into large arrays and group the calculations using the broadcasting feature.</p>
</blockquote>
<p>Now I'm not sure if it is a typo in the book or maybe I am not understanding this correctly. I would appreciate any input you can give me.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T13:52:20.370",
"Id": "447953",
"Score": "2",
"body": "I've rolled back the edit to your question, as Code Review doesn't allow revisions to your code based on feedback. *Technically* this is a little weird, because you didn't actually get an answer, but the comments did provide a review. Graipher/AlexV (unfortunately can't @ you both), I've posted Omid's update + your details as a CW answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T03:40:29.047",
"Id": "448036",
"Score": "0",
"body": "_I wrote all of this code myself, based off of what I learned in the book._ - Given this, why are there close votes claiming authorship issues?"
}
] | [
{
"body": "<p><em>Community wiki - update as posted by the OP in the question based on review by <a href=\"https://codereview.stackexchange.com/users/98493/graipher\">Graipher</a> and <a href=\"https://codereview.stackexchange.com/users/92478/alexv\">AlexV</a></em></p>\n\n<hr>\n\n<p>As <a href=\"https://codereview.stackexchange.com/users/98493/graipher\">Graipher</a> and <a href=\"https://codereview.stackexchange.com/users/92478/alexv\">AlexV</a> mentioned the problem with NumPy version was that the inner loop which updates particle positions (x and y) should be performed independently (not repeated in each timestep). The updated version is as follows,</p>\n\n<pre><code>def evolve_numpy(self, dt):\n timestep = 0.00001\n nsteps = int(dt / timestep)\n r_i = np.array([[p.x, p.y] for p in self.particles])\n ang_vel_i = np.array([p.ang_v for p in self.particles])\n for i in range(nsteps):\n norm_i = np.sqrt((r_i ** 2).sum(axis=1))\n v_i = r_i[:, [1, 0]]\n v_i[:, 0] *= -1\n v_i /= norm_i[:, np.newaxis]\n d_i = timestep * ang_vel_i[:, np.newaxis] * v_i\n r_i += d_i\n for i, p in enumerate(self.particles):\n p.x, p.y = r_i[i]\n</code></pre>\n\n<p>Doing this improves the results considerably (see the figure below) which shows that the results stated in the book were accurate and this was my mistake (as expected:)),</p>\n\n<p><a href=\"https://i.stack.imgur.com/UQxM7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/UQxM7.png\" alt=\"Updated timeit benchmarking results\"></a>\n(The runtime of numpy method is now less than 4 seconds.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T13:50:09.967",
"Id": "230099",
"ParentId": "230080",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "230099",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T07:51:42.437",
"Id": "230080",
"Score": "3",
"Tags": [
"python",
"performance",
"numpy",
"simulation"
],
"Title": "Particle simulator using Python - Why is the NumPy version slower than pure Python?"
} | 230080 |
<p>First time on this exchange, so giving this a title was already a challenge.
So let's start at the beginning. This kind professor <a href="https://people.bath.ac.uk/ge277/" rel="nofollow noreferrer">Güneş Erdoğan</a> has published an <a href="https://people.bath.ac.uk/ge277/clp-spreadsheet-solver/" rel="nofollow noreferrer">CLP (Container Loading Problem) solver</a>. His solution is made in a spreadsheet so it is VBA for Applications.</p>
<p>I have manually converted his code to a PHP script. I have everything working and running. But he has stated himself that there is room for improvement.</p>
<p>His algorithm has a while loop where it keeps making solutions based on random sorting. If the new solution is better than the current, the current gets replaced. Since the algorithm has a given time as input, for example 30, the code will keep doing this for 30 seconds and then return the best solution.</p>
<p>So I took the challenge to improve the code and try to get more iterations within the 30 seconds.
Using a profiling tool it shows me that the method called <code>addItemToContainer</code> takes up most of the time. I've already spend quite some time on this method to try and improve it but I honestly can't find anything.</p>
<p>Then I found this exchange and I'm curious if anyone here can help me any further.</p>
<p><code>addItemToContainer</code> code:</p>
<pre><code>public function addItemToContainer(Solution $solution, int $containerIndex, int $itemTypeIndex, int $addType): bool
{
$currentContainer = $solution->containers[$containerIndex];
$currentItemType = $this->itemTypeList[$itemTypeIndex];
$minX = $currentContainer->width + 1;
$minY = $currentContainer->height + 1;
$minZ = $currentContainer->length + 1;
$candidatePosition = -1;
$additionPointsCount = \count($currentContainer->addition_points);
// Checks if the item is able to fit into the current container based on volume
if (($currentContainer->volume_packed + $currentItemType->volume) > $currentContainer->volume_capacity) {
goto addItemToContainerFinish;
}
// Checks if the item is able to fit into the current container based on weight
if (($currentContainer->weight_packed + $currentItemType->weight) > $currentContainer->weight_capacity) {
goto addItemToContainerFinish;
}
// Checks each rotation, based on the rotation order of the solution
for ($i = 0; $i < 6; $i++) {
$rotationIndex = $i;
if ($candidatePosition !== -1) {
goto addItemToContainerFinish;
}
$currentRotation = $solution->rotation_order[$itemTypeIndex][$rotationIndex];
// Forbidden rotations
if ((($currentRotation === 3) || ($currentRotation === 4)) && ($currentItemType->xy_rotatable === false)) {
continue;
}
if ((($currentRotation === 5) || ($currentRotation === 6)) && ($currentItemType->yz_rotatable === false)) {
continue;
}
// Symmetry breaking
if (($currentRotation === 2) && (\abs($currentItemType->width - $currentItemType->length) < $this->epsilon)) {
continue;
}
if (($currentRotation === 4) && (\abs($currentItemType->width - $currentItemType->height) < $this->epsilon)) {
continue;
}
if (($currentRotation === 6) && (\abs($currentItemType->height - $currentItemType->length) < $this->epsilon)) {
continue;
}
// Loops through each addition point to find the next gap to put a new item
for ($j = 0; $j < $currentContainer->addition_point_count; $j++) {
if ($additionPointsCount - 1 >= $j) {
$additionPoint = $currentContainer->addition_points[$j];
$originX = $additionPoint->origin_x;
$originY = $additionPoint->origin_y;
$originZ = $additionPoint->origin_z;
} else {
$originX = 0;
$originY = 0;
$originZ = 0;
}
// set opposite positions based on the rotation which is calculated above
switch ($currentRotation) {
case 1:
$oppositeX = $originX + $currentItemType->width;
$oppositeY = $originY + $currentItemType->height;
$oppositeZ = $originZ + $currentItemType->length;
break;
case 2:
$oppositeX = $originX + $currentItemType->length;
$oppositeY = $originY + $currentItemType->height;
$oppositeZ = $originZ + $currentItemType->width;
break;
case 3:
$oppositeX = $originX + $currentItemType->width;
$oppositeY = $originY + $currentItemType->length;
$oppositeZ = $originZ + $currentItemType->height;
break;
case 4:
$oppositeX = $originX + $currentItemType->height;
$oppositeY = $originY + $currentItemType->length;
$oppositeZ = $originZ + $currentItemType->width;
break;
case 5:
$oppositeX = $originX + $currentItemType->height;
$oppositeY = $originY + $currentItemType->width;
$oppositeZ = $originZ + $currentItemType->length;
break;
case 6:
$oppositeX = $originX + $currentItemType->length;
$oppositeY = $originY + $currentItemType->width;
$oppositeZ = $originZ + $currentItemType->height;
break;
default:
$oppositeX = 0;
$oppositeY = 0;
$oppositeZ = 0;
break;
}
// Check the feasibility of all four corners, w.r.t. to the other items
if (($oppositeX > $currentContainer->width + $this->epsilon) || ($oppositeY > $currentContainer->height + $this->epsilon) || ($oppositeZ > $currentContainer->length + $this->epsilon)) {
continue;
}
// Check if there is conflict with other items within the container
foreach ($currentContainer->items as $item) {
if (
($oppositeX < $item->origin_x + $this->epsilon) ||
($item->opposite_x < $originX + $this->epsilon) ||
($oppositeY < $item->origin_y + $this->epsilon) ||
($item->opposite_y < $originY + $this->epsilon) ||
($oppositeZ < $item->origin_z + $this->epsilon) ||
($item->opposite_z < $originZ + $this->epsilon)
) {
// No conflict
} else {
// Conflict
continue 2 ;
}
}
// Support
if ($originY < $this->epsilon) {
$support = true;
} else {
$areaSupported = 0;
$support = false;
$containerItemsCount = \count($currentContainer->items);
for ($k = $containerItemsCount - 1; $k >= 0; $k--) {
$item = $currentContainer->items[$k];
if (\abs($originY - $item->opposite_y) < $this->epsilon) {
// Check for intersection
$intersectionRight = $oppositeX;
if ($intersectionRight > $item->opposite_x) {
$intersectionRight = $item->opposite_x;
}
$intersectionLeft = $originX;
if ($intersectionLeft < $item->origin_x) {
$intersectionLeft = $item->origin_x;
}
$intersectionTop = $oppositeZ;
if ($intersectionTop > $item->opposite_z) {
$intersectionTop = $item->opposite_z;
}
$intersectionBottom = $originZ;
if ($intersectionBottom < $item->origin_z) {
$intersectionBottom = $item->origin_z;
}
if (($intersectionRight > $intersectionLeft) && ($intersectionTop > $intersectionBottom)) {
$areaSupported += (($intersectionRight - $intersectionLeft) * ($intersectionTop - $intersectionBottom));
if ($areaSupported > (($oppositeX - $originX) * ($oppositeZ - $originZ)) - $this->epsilon) {
$support = true;
break;
}
}
}
}
}
if (!$support) {
continue;
}
// No conflicts at this point
if (
($originZ < $minZ) ||
(($originZ <= $minZ + $this->epsilon) && ($originY < $minY)) ||
(($originZ <= $minZ + $this->epsilon) && ($originY <= $minY + $this->epsilon) && ($originX < $minX))
) {
$minX = $originX;
$minY = $originY;
$minZ = $originZ;
$candidatePosition = $j;
$candidateRotation = $currentRotation;
}
}
}
// Portion of the function where the item gets added to the container
addItemToContainerFinish :
// If the candidate position is equal to -1 return
if ($candidatePosition === -1) {
return false;
} else {
$newItem = new Item();
$newItem->item_type = $itemTypeIndex;
if ($additionPointsCount - 1 >= $candidatePosition) {
$newItem->origin_x = $currentContainer->addition_points[$candidatePosition]->origin_x;
$newItem->origin_y = $currentContainer->addition_points[$candidatePosition]->origin_y;
$newItem->origin_z = $currentContainer->addition_points[$candidatePosition]->origin_z;
} else {
$newItem->origin_x = 0;
$newItem->origin_y = 0;
$newItem->origin_z = 0;
}
$newItem->rotation = $candidateRotation;
$newItem->mandatory = $currentItemType->mandatory;
// Based on the resulted rotation set the opposite position
switch ($candidateRotation) {
case 1:
$newItem->opposite_x = $newItem->origin_x + $currentItemType->width;
$newItem->opposite_y = $newItem->origin_y + $currentItemType->height;
$newItem->opposite_z = $newItem->origin_z + $currentItemType->length;
break;
case 2:
$newItem->opposite_x = $newItem->origin_x + $currentItemType->length;
$newItem->opposite_y = $newItem->origin_y + $currentItemType->height;
$newItem->opposite_z = $newItem->origin_z + $currentItemType->width;
break;
case 3:
$newItem->opposite_x = $newItem->origin_x + $currentItemType->width;
$newItem->opposite_y = $newItem->origin_y + $currentItemType->length;
$newItem->opposite_z = $newItem->origin_z + $currentItemType->height;
break;
case 4:
$newItem->opposite_x = $newItem->origin_x + $currentItemType->height;
$newItem->opposite_y = $newItem->origin_y + $currentItemType->length;
$newItem->opposite_z = $newItem->origin_z + $currentItemType->width;
break;
case 5:
$newItem->opposite_x = $newItem->origin_x + $currentItemType->height;
$newItem->opposite_y = $newItem->origin_y + $currentItemType->width;
$newItem->opposite_z = $newItem->origin_z + $currentItemType->length;
break;
case 6:
$newItem->opposite_x = $newItem->origin_x + $currentItemType->length;
$newItem->opposite_y = $newItem->origin_y + $currentItemType->width;
$newItem->opposite_z = $newItem->origin_z + $currentItemType->height;
break;
}
\array_push($solution->containers[$containerIndex]->items, $newItem);
// Update the volume and weight of the container
$currentContainer->volume_packed += $currentItemType->volume;
$currentContainer->weight_packed += $currentItemType->weight;
if ($addType === 2) {
$currentContainer->repack_item_count[$itemTypeIndex] = $currentContainer->repack_item_count[$itemTypeIndex] - 1;
}
// Update the addition points
for ($i = $candidatePosition; $i < $currentContainer->addition_point_count - 1; $i++) {
$currentContainer->addition_points[$i] = clone($currentContainer->addition_points[$i + 1]);
}
$currentContainer->addition_point_count = $currentContainer->addition_point_count - 1;
$itemsCount = \count($currentContainer->items);
$lastItem = $currentContainer->items[$itemsCount - 1];
// Add a new addition point to the container based on the last item
if (($lastItem->opposite_x < $currentContainer->width - $this->epsilon) &&
($lastItem->origin_y < $currentContainer->height - $this->epsilon) &&
($lastItem->origin_z < $currentContainer->length - $this->epsilon)) {
$currentContainer->addition_point_count = $currentContainer->addition_point_count + 1;
$additionPoint = new ItemLocation();
$additionPoint->origin_x = $lastItem->opposite_x;
$additionPoint->origin_y = $lastItem->origin_y;
$additionPoint->origin_z = $lastItem->origin_z;
if (\count($currentContainer->addition_points) < $currentContainer->addition_point_count) {
\array_push($currentContainer->addition_points, $additionPoint);
} else {
$currentContainer->addition_points[$currentContainer->addition_point_count - 1] = $additionPoint;
}
}
// Add a new addition point to the container based on the last item
if (($lastItem->origin_x < $currentContainer->width - $this->epsilon) &&
($lastItem->opposite_y < $currentContainer->height - $this->epsilon) &&
($lastItem->origin_z < $currentContainer->length - $this->epsilon)) {
$currentContainer->addition_point_count = $currentContainer->addition_point_count + 1;
$additionPoint = new ItemLocation();
$additionPoint->origin_x = $lastItem->origin_x;
$additionPoint->origin_y = $lastItem->opposite_y;
$additionPoint->origin_z = $lastItem->origin_z;
if (\count($currentContainer->addition_points) < $currentContainer->addition_point_count) {
\array_push($currentContainer->addition_points, $additionPoint);
} else {
$currentContainer->addition_points[$currentContainer->addition_point_count - 1] = $additionPoint;
}
}
// Add a new addition point to the container based on the last item
if (($lastItem->origin_x < $currentContainer->width - $this->epsilon) &&
($lastItem->origin_y < $currentContainer->height - $this->epsilon) &&
($lastItem->opposite_z < $currentContainer->length - $this->epsilon)) {
$currentContainer->addition_point_count = $currentContainer->addition_point_count + 1;
$additionPoint = new ItemLocation();
$additionPoint->origin_x = $lastItem->origin_x;
$additionPoint->origin_y = $lastItem->origin_y;
$additionPoint->origin_z = $lastItem->opposite_z;
if (\count($currentContainer->addition_points) < $currentContainer->addition_point_count) {
\array_push($currentContainer->addition_points, $additionPoint);
} else {
$currentContainer->addition_points[$currentContainer->addition_point_count - 1] = $additionPoint;
}
}
// Update the profit
if ($itemsCount === 1) {
$solution->net_profit += ($currentItemType->profit - $solution->containers[$containerIndex]->cost);
} else {
$solution->net_profit += $currentItemType->profit;
}
// Update the volume per container and the total volume
$solution->total_volume += $currentItemType->volume;
$solution->total_weight += $currentItemType->weight;
// Update the unpacked items
if ($addType === 1) {
$solution->unpacked_item_count[$itemTypeIndex] = $solution->unpacked_item_count[$itemTypeIndex] - 1;
}
return true;
}
}
</code></pre>
<p>So the main question is if maybe you can find something which possibly can improve the amount of iterations the algorithm can do.</p>
<p><a href="https://pastebin.com/wC2XBFY6" rel="nofollow noreferrer">(Since the code is pretty big, here is a pastebin)</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T08:34:27.540",
"Id": "447915",
"Score": "0",
"body": "(`giving this a title [is] already a challenge` that's the spirit!)(Sounds like [simulated annealing](https://en.m.wikipedia.org/wiki/Simulated_annealing) might be a better strategy.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T09:17:36.270",
"Id": "447919",
"Score": "0",
"body": "Wow, I've only ever read about the mythological creature `goto` in the php docs... I've never actually seen it in the wild!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T09:28:20.723",
"Id": "447922",
"Score": "0",
"body": "@mickmackusa haha yea, I can't think of the last time I've used it. But it seemed like the perfect fit!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T09:13:45.767",
"Id": "448640",
"Score": "0",
"body": "following `No conflicts at this point`, the condition `(($originZ <= $minZ + $this->epsilon) && ($originY < $minY))` is redundant (included in the last one)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T09:16:17.620",
"Id": "448641",
"Score": "0",
"body": "The coding of orientation independence (rotation) sucks (led to longish code with parts repeated with dimensions permuted), probably due to *naming* dimensions instead of enumeration/array usage."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T09:42:50.530",
"Id": "448642",
"Score": "0",
"body": "@greybeard In the last condition, if `(($originZ <= $minZ + $this->epsilon) && ($originY < $minY))` is true. The if statement doesn't return true when the last part (`($originX < $minX)`) is false. So it's not redundant I would say.. I can agree with your other comment, but using enumeration/array I would still have to use a switch for the rotation, so the longish code will always remain. That's how I look at it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T10:03:14.277",
"Id": "448646",
"Score": "0",
"body": "At the condition's top level, three (parenthesised) expressions are combined with *logical or*: I expect the last one to be true whenever the second one is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T10:13:15.003",
"Id": "448648",
"Score": "0",
"body": "@greybeard, Okay. Why isn't the first one redundant since it is included the exact same way in the third one?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T12:01:09.837",
"Id": "448663",
"Score": "0",
"body": "Never said it wasn't. That part does *not* impose any relation between `$originY` and `$minY`. To be explicit: while the algorithm isn't yours, the PHP implementation presented is?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T12:16:09.897",
"Id": "448668",
"Score": "0",
"body": "@greybeard Correct, had to write it all in PHP myself. After that I thought I should be able to change things up since VBA is ofcourse different then PHP. And the professor stated that there is 'clearly' room for improvement."
}
] | [
{
"body": "<ol>\n<li><p>I don't personally know of any advantage to prefixing php functions with a backslash, so consider removing the unnecessary character. (or tell me why it is useful)</p></li>\n<li><p>Perform arithmetic once. AKA \"Don't Repeat Yourself\" (<strong>D.R.Y.</strong>)</p>\n\n<pre><code>$additionPointsCount = \\count($currentContainer->addition_points);\n</code></pre>\n\n<p>becomes:</p>\n\n<pre><code>$lastPoint = count($currentContainer->addition_points) - 1;\n</code></pre></li>\n<li><p>I'd have to double check the docs to recommend a replacement for <code>goto()</code>, but I'm pretty sure that the php docs say to avoid it all costs. I recall a comic strip illustration that conveys the importance of its avoidance. Then again, unless I am overlooking something, perhaps this is a suitable use case which avoids having to manually transfer variables into a new curom function scope.</p></li>\n<li><p>If two separate sets if conditions lead to the same <code>goto</code>, then write D.R.Y. code and merge the conditions. Likewise with several conditions that lead to <code>continue</code>.</p></li>\n<li><p>To simplify conditions evaluating the same value with two or more sets of <code>||</code>, use <code>in_array()</code>. When ordering the conditions, write the least expensive evaluations first and the most taxing evaluations (that, say, make a function call) last. Because conditions short circuit on the first \"condition breaking\" false, the heavier checks are avoided and efficiency is gained. Also, try to remove excessive parentheses.</p>\n\n<pre><code>if ((($currentRotation === 3) || ($currentRotation === 4)) && ($currentItemType->xy_rotatable === false)) {\n continue;\n}\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>if ($currentItemType->xy_rotatable === false && in_array($currentRotation, [3, 4])) {\n continue;\n}\n</code></pre></li>\n<li><p>If you can't manage to reverse all of the logic in a multi-conditional expression (leading to <code>continue 2;</code>), then wrap all of the conditions in parentheses and write <code>!</code> before it to provide the opposite boolean evaluation, this way you don't need the <code>else</code> branch.</p></li>\n<li><p>When pushing just one element into an indexed array, just use square braced syntax and spare the <code>array_push()</code> call.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T11:35:14.213",
"Id": "230091",
"ParentId": "230082",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T08:21:03.560",
"Id": "230082",
"Score": "2",
"Tags": [
"performance",
"algorithm",
"php",
"laravel"
],
"Title": "Adding an item to a container, but first a lot of checks"
} | 230082 |
<p>Here's how I'd usually center align an item with absolute positioning:</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-css lang-css prettyprint-override"><code>img {
width: 100%;
height: auto;
}
.cat {
position: relative;
}
.center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 9999;
background: #fff;
padding: 12px;
}
a,
a:visited,
a:hover,
a:focus {
color: #000;
text-decoration: none;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="cat">
<a href="#" class="center">I want to center this</a>
<img src="https://hackernoon.com/hn-images/1*mONNI1lG9VuiqovpnYqicA.jpeg" alt="Cat being cool">
</div></code></pre>
</div>
</div>
</p>
<p>I've recently discovered that you can do the same with flexbox, like so:</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-css lang-css prettyprint-override"><code>img {
width: 100%;
height: auto;
}
.cat {
position: relative;
display: flex;
justify-content: center;
align-items: center;
}
.center {
position: absolute;
z-index: 9999;
background: #fff;
padding: 12px;
}
a,
a:visited,
a:hover,
a:focus {
color: #000;
text-decoration: none;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="cat">
<a href="#" class="center">I want to center this</a>
<img src="https://hackernoon.com/hn-images/1*mONNI1lG9VuiqovpnYqicA.jpeg" alt="Cat being cool">
</div></code></pre>
</div>
</div>
</p>
<p>Is there any benefit to using the flexbox solution? A major downside I'm seeing is browser compatibility. I can't find a solution that purely uses flexbox.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T10:28:35.207",
"Id": "448219",
"Score": "0",
"body": "What browser compatibility issues have you found? Flexbox is supported by the latest versions all major browsers. One or two may still have the odd bug."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T00:00:32.083",
"Id": "448313",
"Score": "0",
"body": "IE11 isn’t playing ball."
}
] | [
{
"body": "<blockquote>\n <p>Is there any benefit to using the flexbox solution?</p>\n</blockquote>\n\n<p>The principal benefit will be more concise, easier-to-maintain code.</p>\n\n<p>That's not to say there's anything wrong with <code>position: absolute</code> (there isn't). Just that with <code>display: flex</code> you can achieve more with less.</p>\n\n<p>That is, once you have declared <code>justify-content</code> and <code>align-items</code> on a <strong>flex parent</strong>, you don't necessarily need to apply any further positioning to <strong>flex-children</strong> at all - they will automatically display in the right position, regardless of browser viewport size and dimensions.</p>\n\n<hr>\n\n<blockquote>\n <p>IE11 isn’t playing ball.</p>\n</blockquote>\n\n<p>True: <a href=\"https://caniuse.com/#feat=flexbox\" rel=\"nofollow noreferrer\">https://caniuse.com/#feat=flexbox</a></p>\n\n<p>But IE11 is from October 2013.</p>\n\n<p>Even Microsoft says IE is not a browser and no-one should be using it:</p>\n\n<p><a href=\"https://www.zdnet.com/article/microsoft-security-chief-ie-is-not-a-browser-so-stop-using-it-as-your-default/\" rel=\"nofollow noreferrer\">https://www.zdnet.com/article/microsoft-security-chief-ie-is-not-a-browser-so-stop-using-it-as-your-default/</a></p>\n\n<hr>\n\n<p><strong>Flex Example:</strong></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>.cat {\n display: flex;\n justify-content: center;\n align-items: center;\n width: 340px;\n height: 180px;\n background: url('https://hackernoon.com/hn-images/1*mONNI1lG9VuiqovpnYqicA.jpeg') 0 0 / 100% 100%;\n}\n\n.center {\n background: rgba(255, 255, 255, 0.6);\n padding: 12px;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"cat\">\n <a href=\"#\" class=\"center\">I want to center this</a>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T12:15:27.933",
"Id": "236533",
"ParentId": "230087",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "236533",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T10:39:34.537",
"Id": "230087",
"Score": "2",
"Tags": [
"html",
"css"
],
"Title": "Centering an item over an image with absolute positioning and flexbox"
} | 230087 |
<p>My code is working correctly, but is resulting in a "Assignment branch condition too high" warning with a score of 12.08 on <a href="https://codebeat.co/about" rel="nofollow noreferrer">CodeBeat</a>. </p>
<p>Codebeat is an automated code review utility that helps developers write clean code. I have been using it lately in order to monitor the quality of my code since clean code is being a necessity in today's word. Codebeat calculates the complexity of the code written and assigns a score, so it seems that the complexity of this method seems a bit high that usual. I would be grateful if someone can tell me what is complex about this method.</p>
<pre><code>private void populateDictionary() {
try {
Files.walkFileTree(Paths.get(rootDirectory.getCanonicalPath()), EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
addToDictionary(path);
return FileVisitResult.CONTINUE;
}
});
}catch(IOException e) {
System.out.println(e.getMessage());
}
System.out.println(this.indexedFileContents.keySet().size() + " files read in directory " + this.rootDirectory);
}
</code></pre>
<p>Can anyone tell me what am I doing wrong and how I can improve my code?
Thanks in advance.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T13:55:06.217",
"Id": "447954",
"Score": "2",
"body": "Welcome to Code Review! I'm voting to close because you haven't provided enough context to understand what the code is intended to do, however I'd also like to address other close voters - as mentioned in the comments, the code is working as intended, but is being flagged by an automated review tool as being too complex. That doesn't fall under \"Code not implemented or working as intended\"."
}
] | [
{
"body": "<p>Well I figured out a way to refactor my code, and obtained a non-complex code by creating a method that returns the visitor named getSimpleFileVisitor(). I also created another method that will allow me to print the results that I named printFinalResults(). I have also refactored the method's name to walkFileTree().\nMaybe my question was a little bit ambiguous, sorry for any inconvenience.</p>\n\n<pre><code>private void walkFileTree() {\n try{\n Files.walkFileTree(Paths.get(rootDirectory.getCanonicalPath()), EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, getSimpleFileVisitor());\n }catch(IOException e) {\n System.out.println(e.getMessage());\n }\n printFinalResults();\n}\n\nprivate SimpleFileVisitor<Path> getSimpleFileVisitor(){\n SimpleFileVisitor<Path> simpleFileVisitor = new SimpleFileVisitor<Path>() {\n @Override\n public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {\n addToDictionary(path);\n return FileVisitResult.CONTINUE;\n }\n };\n return simpleFileVisitor;\n}\n\nprivate void printFinalResults() {\n System.out.println(this.indexedFileContents.keySet().size() + \" files read in directory \" + this.rootDirectory);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T17:49:26.250",
"Id": "447987",
"Score": "0",
"body": "`walkFileTree()` still has the result of populating the dictionary; why did you change the name? Also, does Codebeat complain if you return the `SimpleFileVisitor` directly without assigning it to a variable? Also, consider putting `printFinalResults()` in a `finally` block."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T14:13:13.087",
"Id": "230101",
"ParentId": "230093",
"Score": "1"
}
},
{
"body": "<p>The walkFileTree method is a sample of <a href=\"https://en.wikipedia.org/wiki/Dependency_inversion_principle\" rel=\"nofollow noreferrer\">dependency inversion</a> violation on method level. Instead of being given the path and the action to perform, the method is burdened with the depenendencies of finding the information itself. This is what increases the ABC value of the method. The problem is highlighted by the method having a very generic name <code>walkFileTree</code> but performing a very specific task instead : walking the directory beneath <code>rootDirectory</code> and adding the entries to a specific dictionary.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T05:31:20.943",
"Id": "230138",
"ParentId": "230093",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T12:49:15.223",
"Id": "230093",
"Score": "1",
"Tags": [
"java",
"cyclomatic-complexity"
],
"Title": "Files.walkTree is causing Assignment Branch Condition too high"
} | 230093 |
<p>I have been using and developing a simple ORM and query builder library that I have found useful in it's practical application. I am pretty sure there are improvements to be made, and I welcome any suggestion you might have to improve this.</p>
<p>the full code is on github:
<a href="https://github.com/rmalchow/dbutils" rel="nofollow noreferrer">https://github.com/rmalchow/dbutils</a></p>
<p>the two parts are first the actual reflection code i use to map between object and rows, and second the structure i am using for my query builder.</p>
<p><strong>1. ORM</strong></p>
<p>For the ORM part, i am using javax.persistence annotations with plain reflection to map between database columns and fields, at the heart of it, I have this class:</p>
<pre><code>public class ParsedEntity<T> {
private static Log log = LogFactory.getLog(ParsedEntity.class);
private String tableName;
private List<ParsedColumn> columns = new ArrayList<>();
public ParsedEntity(Class<T> clazz) {
Class<?> c = clazz;
List<String> x = new ArrayList<>();
do {
for(Field f : c.getDeclaredFields()) {
if(x.contains(f.getName())) continue;
x.add(f.getName());
if(f.getAnnotation(Column.class)!=null) {
Column column = f.getAnnotation(Column.class);
String name = f.getName();
if(!column.name().equals("")) {
name = column.name();
}
columns.add(new ParsedColumn(f, name));
}
}
c = c.getSuperclass();
if(c==null) break;
} while(clazz.getSuperclass()!=null);
tableName = clazz.getAnnotation(Table.class).name();
}
public String getTableName() {
return this.tableName;
}
public String getIdColumn() {
return "id";
}
public List<ParsedColumn> getColumns() {
return new ArrayList<>(columns);
}
public class ParsedColumn {
private Field field;
private String column;
public ParsedColumn(Field field, String column) {
this.field = field;
this.column = column;
this.field.setAccessible(true);
}
public String getColumnName() {
return column;
}
public void set(T target, ResultSet rs) throws IllegalArgumentException, IllegalAccessException {
try {
if(field.getType()==String.class) {
field.set(target,rs.getString(column));
} else if(field.getType()==BigDecimal.class) {
field.set(target,rs.getBigDecimal(column));
} else if(field.getType()==Integer.class || field.getType()==Integer.TYPE) {
int value = rs.getInt(column);
if (field.getType().isPrimitive() && rs.wasNull()) {
throw new NullPointerException("Cannot set NULL value to field with type int");
}
field.set(target, rs.wasNull() ? null : value);
} else if(field.getType()==Long.class || field.getType()==Long.TYPE) {
long value = rs.getLong(column);
if (field.getType().isPrimitive() && rs.wasNull()) {
throw new NullPointerException("Cannot set NULL value to field with type long");
}
field.set(target, rs.wasNull() ? null : value);
} else if(field.getType()==Boolean.class || field.getType()==Boolean.TYPE) {
boolean value = rs.getBoolean(column);
if (field.getType().isPrimitive() && rs.wasNull()) {
throw new NullPointerException("Cannot set NULL value to field with type boolean");
}
field.set(target, rs.wasNull() ? null : value);
} else if(Enum.class.isAssignableFrom(field.getType())) {
String value = rs.getString(column);
if(value==null) {
field.set(target, null);
} else {
for(Object o : field.getType().getEnumConstants()) {
if(o.toString().compareTo(value)==0) {
field.set(target, o);
}
}
}
} else {
field.set(target, rs.getObject(column));
}
log.debug("mapping column: "+column+" - "+rs.getObject(column));
} catch (Exception e) {
log.error("error mapping "+column+": ",e);
throw new IllegalArgumentException("error mapping "+column+": ",e);
}
}
public Object get(T target) throws IllegalArgumentException, IllegalAccessException {
if(Enum.class.isAssignableFrom(field.getType())) {
Object o = field.get(target);
if(o==null) return null;
return ((Enum)o).name();
}
return field.get(target);
}
}
}
</code></pre>
<p>which I then use to produce parameters for INSERT / UPDATE statements (this entire thing is baked into a generic class, thus the ):</p>
<pre><code>@SuppressWarnings("rawtypes")
protected MapSqlParameterSource unmap(T t) throws IllegalArgumentException, IllegalAccessException {
MapSqlParameterSource out = new MapSqlParameterSource();
for(ParsedColumn pc : getParsedEntity().getColumns()) {
Object o = pc.get(t);
out.addValue(pc.getColumnName(),o);
}
return out;
}
</code></pre>
<p>and also, from a result set to a new instance:</p>
<pre><code>@Override
public T mapRow(ResultSet rs, int c) throws SQLException {
T out = getClazz().newInstance();
for(ParsedColumn pc : getParsedEntity().getColumns()) {
try {
pc.set(out, rs);
} catch (Exception e) {
throw new RuntimeException("failed to map column: "+pc.getColumnName(),e);
}
}
return out;
}
</code></pre>
<p><strong>2. Query Builder</strong></p>
<p>the second main component is a query builder - which sails pretty close to actual SQL, and should in most cases be able to produce proper SQL for use with NamedParameterJdbcTemplate (so that everything from outside is properly escaped).</p>
<p>if it's too annoying to check this here, these interfaces can also be found here:</p>
<p><a href="https://github.com/rmalchow/dbutils/tree/master/dbutil-api/src/main/java/de/disk0" rel="nofollow noreferrer">https://github.com/rmalchow/dbutils/tree/master/dbutil-api/src/main/java/de/disk0</a></p>
<p>the main interfaces are:</p>
<p>the top level entity is pretty abstract. this represents a piece of SQL with named parameters (getSql) and the corresponding values (getParams), i.e.: <code>"SELECT * FROM foo WHERE x = :x"</code> and a map of <code>{ x : "ABC" }</code></p>
<pre><code>public interface SqlFragment {
public String getSql();
public Map<String, Object> getParams();
}
</code></pre>
<p>representing the "outer" SELECT statement, this contains functionality to add tables (and joins), modify the list of selected fields (and their aggregation) as well as the WHERE, LIMIT, ORDER and GROUP parts of the SQL statement.</p>
<pre><code>public interface Select {
//@Deprecated
public Field addSelect(Object value, String alias);
//@Deprecated
public Field addSelect(TableReference tableReference, String field, String alias);
//@Deprecated
public Field addSelect(Aggregate a, TableReference tableReference, String field, String alias);
public Field addSelect(Aggregate a, String alias, Field... references);
public Field addSelect(Field fr, String alias);
public TableReference fromTable(String table);
public TableReference fromTable(Class<? extends BaseEntity<?>> table);
public SubSelect from();
public Select union();
//@Deprecated
public Condition condition(Operator op, TableReference table1, String field1, Comparator c, TableReference table2, String field2);
//@Deprecated
public Condition condition(Operator op, TableReference table1, String field1, Comparator c, Object value);
public Condition condition(Operator op);
public Condition condition(Operator op, Field fr1, Comparator c, Field fr2);
public Condition isNull(Operator op, Field fr1);
public Condition isNotNull(Operator op, Field fr1);
public void limit(int offset, int max);
//@Deprecated
public void group(TableReference table, String field);
//@Deprecated
public void order(TableReference table, String field, boolean ascending);
public void group(Field reference);
public void order(Field reference, boolean ascending);
public String getSql();
public Map<String,Object> getParams();
public String getAlias();
}
</code></pre>
<p>keeping track of which table is referenced where. this is used as the inital table (or subselect):</p>
<p><code>SELECT * FROM [foo] <----</code>, and extended by JoinTable to represent :</p>
<pre><code>public interface TableReference extends SqlFragment {
public String getAlias();
public String getName();
public JoinTable leftJoin(String table);
public JoinTable leftJoin(Class<? extends BaseEntity<?>> table);
public JoinTable join(String table);
public JoinTable join(Class<? extends BaseEntity<?>> table);
public Field field(String fieldname);
public Field value(Object value);
public Field field(Aggregate a, Field... fr);
public Field field(Aggregate a, String fieldName);
}
</code></pre>
<p>representing a JOIN relationship - this is another TableReference, but extended by JOIN conditions.</p>
<pre><code>public interface JoinTable extends TableReference {
public Condition addOn(Operator op, TableReference table1, String field1, Comparator c, TableReference table2, String field2);
public Condition addOn(Operator op, TableReference table1, String field1, Comparator c, Object value);
public Condition addOn(Operator op, Field left, Comparator c, Field right);
public Condition addOn(Operator op);
}
</code></pre>
<p>a WHERE condition (possible with nested conditions) - this is the most critical part, because i find it quite difficult to deal with nesting in a way that feels both simple and natural. in this case, to create a NESTED condition (i.e. one in separate brackets), you would use the shortest "condition" call on the parent, i.e.</p>
<pre><code>s.condition(AND,tr.field("id"), EQ, tr.value("ABC"));
Condition c = s.condition(AND); // "c" represents the bracketed condition
c.condition(OR, tr.field("size"), LTE, tr.value(400);
c.condition(OR, tr.field("size"), GTE, tr.value(800);
</code></pre>
<p>would give you:</p>
<p>[WHERE]
id = :id
AND
(
size < :size_1
OR
size > :size_2
)</p>
<p>here's the interface:</p>
<pre><code>public interface Condition extends SqlFragment {
//@Deprecated
public Condition condition(Operator op, TableReference table1, String field1, Comparator c, Object value);
//@Deprecated
public Condition condition(Operator op, TableReference table1, String field1, Comparator c, TableReference table2, String field2);
public Condition condition(Operator op, Field fr1, Comparator c, Field fr2);
public Condition isNull(Operator op, Field fr1);
public Condition isNotNull(Operator op, Field fr1);
public Condition condition(Operator op);
public Operator getOp();
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T13:09:38.567",
"Id": "230094",
"Score": "2",
"Tags": [
"java",
"api",
"reflection",
"jdbc"
],
"Title": "Library/API: simple springboot / jdbc query builder and ORM"
} | 230094 |
<p>I've been learning C# for a few months now, and I've done some basic things in java last year. I made a solution for the problem the title states, this is the task description.</p>
<blockquote>
<p><strong><em>Task description</em></strong></p>
<hr>
<p>A DNA sequence can be represented as a string consisting of the
letters A, C, G and T, which correspond to the types of successive
nucleotides in the sequence. Each nucleotide has an impact factor,
which is an integer. Nucleotides of types A, C, G and T have impact
factors of 1, 2, 3 and 4, respectively. You are going to answer
several queries of the form: What is the minimal impact factor of
nucleotides contained in a particular part of the given DNA sequence?</p>
<p>The DNA sequence is given as a non-empty string S = S[0]S[1]...S[N-1]
consisting of N characters. There are M queries, which are given in
non-empty arrays P and Q, each consisting of M integers. The K-th
query (0 ≤ K < M) requires you to find the minimal impact factor of
nucleotides contained in the DNA sequence between positions P[K] and
Q[K] (inclusive).</p>
<p>For example, consider string S = CAGCCTA and arrays P, Q such that:</p>
<pre><code>P[0] = 2 Q[0] = 4
P[1] = 5 Q[1] = 5
P[2] = 0 Q[2] = 6
</code></pre>
<p>The answers to these M = 3 queries are as follows:</p>
<p>The part of the DNA between positions 2 and 4 contains nucleotides G
and C (twice), whose impact factors are 3 and 2 respectively, so the
answer is 2. The part between positions 5 and 5 contains a single
nucleotide T, whose impact factor is 4, so the answer is 4. The part
between positions 0 and 6 (the whole string) contains all nucleotides,
in particular nucleotide A whose impact factor is 1, so the answer is
1. Write a function:</p>
<p>class Solution { public int[] solution(string S, int[] P, int[] Q); }</p>
<p>that, given a non-empty string S consisting of N characters and two
non-empty arrays P and Q consisting of M integers, returns an array
consisting of M integers specifying the consecutive answers to all
queries.</p>
<p>Result array should be returned as an array of integers.</p>
<p>For example, given the string S = CAGCCTA and arrays P, Q such that:</p>
<pre><code>P[0] = 2 Q[0] = 4
P[1] = 5 Q[1] = 5
P[2] = 0 Q[2] = 6
</code></pre>
<p>the function should return the values [2, 4, 1], as explained above.</p>
<p>Write an efficient algorithm for the following assumptions:</p>
<p>N is an integer within the range [1..100,000]; M is an integer within
the range [1..50,000]; each element of arrays P, Q is an integer
within the range [0..N − 1]; P[K] ≤ Q[K], where 0 ≤ K < M; string S
consists only of upper-case English letters A, C, G, T.</p>
</blockquote>
<hr>
<p>This is my 100% task score solution in C#. What things can be improved?</p>
<hr>
<pre><code>/// <summary>
/// Find the minimum impact factor for every query in a given chain
/// </summary>
/// <returns>
/// An array of ints, every int represents the minimum impact factor found
/// within ranges in a given chain
/// </returns>
public int[] GetMinimumImpactFactors(string S, int[] P, int[] Q)
{
//nuc(s) is short for nucleotide(s)
Dictionary<char, int> nucsDict = new Dictionary<char, int>(){{'A',1},{'C',2},{'G',3},{'T',4}};
int[] result = new int[P.Length];
int[] nucsInOrder= new int[S.Length];
int nucsIndex = 0;
//iterate through dictionary, looking for A's, then C's, and so on...
foreach ( var searchedImpactPair in nucsDict )
{
//Appearances of <searchedImpactPair.Key> have a given position in <S> chain, those positions are saved
for (int currNucPos=0; currNucPos < S.Length; currNucPos++ )
{
if( S[currNucPos] == searchedImpactPair.Key )
{
nucsInOrder[nucsIndex++] = currNucPos ;
}
}
}
int start, end, minImpactValueFound, minNucFound;
char nucleotide;
for(int positionWithinRange = 0; positionWithinRange < P.Length; positionWithinRange++)
{
start = P[positionWithinRange];
end = Q[positionWithinRange];
for ( int nucInOrder = 0; nucInOrder < nucsInOrder.Length; nucInOrder++ )
{
minNucFound = nucsInOrder[nucInOrder];
if ( minNucFound >= start && nucsInOrder[nucInOrder] <= end)
{
nucleotide = S[minNucFound];
minImpactValueFound = nucsDict[nucleotide];
result[positionWithinRange] = minImpactValueFound;
break;
}
}
}
return result;
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T14:42:19.107",
"Id": "230103",
"Score": "1",
"Tags": [
"c#",
"performance",
"beginner",
"programming-challenge",
"array"
],
"Title": "Codility's GenomicRangeQuery solution in C#"
} | 230103 |
<p>What's better - to leave the <code>IF</code> block blank to do nothing, or to add a statement that basically does nothing (each link already has a <code>href</code> attribute)?</p>
<pre><code>export function fixRelativeLinksOutsideOfEpub(dom): void {
const content = dom.window.document.querySelectorAll('a');
content.forEach((element: HTMLElement) => {
const href = element.getAttribute('href');
if (href.indexOf('#') === 0) {
// do nothing
} else {
element.setAttribute('target', '_blank');
}
});
}
</code></pre>
<pre><code>export function fixRelativeLinksOutsideOfEpub(dom): void {
const content = dom.window.document.querySelectorAll('a');
content.forEach((element: HTMLElement) => {
const href = element.getAttribute('href');
if (href.indexOf('#') === 0) {
element.setAttribute('href', `${href}`);
} else {
element.setAttribute('target', '_blank');
}out
});
}
</code></pre>
| [] | [
{
"body": "<p>You should NEVER! add superfluous or unused code.</p>\n\n<p>Your code should have the single <code>if</code> statement checking for not equal.</p>\n\n<pre><code> const href = element.getAttribute('href');\n if (href.indexOf('#') !== 0) {\n element.setAttribute('target', '_blank');\n }\n</code></pre>\n\n<p>or better yet avoid the overly complex referencing via get set attribute, and not using a search to find a known location state the whole thing becomes.</p>\n\n<pre><code> if (element.href[0] === \"#\") { element.target = \"_blank\" }\n</code></pre>\n\n<p>And as a whole there is a huge amount of noise that can be removed</p>\n\n<pre><code>dom.window.document.querySelectorAll(\"a\")\n .forEach(el => el.href[0] === \"#\" && (el.target = \"_blank\"));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T15:19:01.983",
"Id": "230107",
"ParentId": "230104",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "230107",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T14:42:48.677",
"Id": "230104",
"Score": "1",
"Tags": [
"javascript",
"typescript"
],
"Title": "Best practice for asserting a positive IF condition"
} | 230104 |
<p>Recently I was studying about the benefits and uses of <code>std::optional</code> in C++17 (<a href="https://www.bfilipek.com/2018/05/using-optional.html" rel="noreferrer">Bartek's Blog</a>) and there I saw a line that said "<code>std::optional</code> can be used for Lazy Loading of Resources" . Upon digging a little bit, I saw that C++ does not have native support for Lazy evaluation. So I just gave it a try and wrote the following code for lazy evaluation in C++.</p>
<p><strong>Lazy.ixx</strong> - Visual Studio(Experimental :Modules)</p>
<p>To compile this (VS2019):</p>
<pre><code>cl /experimental:module /EHsc /TP /MD /std:c++latest Lazy.ixx /module:interface /module:output Lazy.pcm /Fo: Lazy.obj /c
</code></pre>
<pre><code>#include<optional>
#include<functional>
export module Lazy;
export namespace gstd
{
template<typename T>
class Lazy
{
std::optional<T> m_resource;
std::function<T()>m_ctor_func;
public:
Lazy(std::function<T()>ctor_func)
{
m_ctor_func=ctor_func;
}
std::optional<T> operator ->()
{
//If resource is not initialized(i.e Ctor not invoked/ first time use)
if(!m_resource)
{
m_resource=m_ctor_func();
}
return m_resource;
}
};
}
</code></pre>
<p>Now sorry for using modules! (I just love them). To use this class it's pretty simple: </p>
<pre><code>//main.cpp
#include<iostream>
import Lazy;
// A simple class called Resource
class Resource
{
public:
Resource()
{
std::cout<<"Welcome to new C++\n";
}
Resource(int a, int b)
{
std::cout<<"This also works : "<<a<<" "<<b<<"\n";
}
void func()
{
std::cout<<"Resource::func()\n";
}
};
int main()
{
gstd::Lazy<Resource>resx([](){ return Resource(4,5); });
std::cout<<"Before construction\n";
//Some code before using the resource
resx->func();
std::cin.get();
return 0;
}
</code></pre>
<p>To compile this:</p>
<pre><code>cl /experimental:module /module:reference Lazy.pcm /std:c++latest /TP /MD /EHsc /c /Fo: main.obj main.cpp
</code></pre>
<p>Get the executable by linking those two files:</p>
<pre><code>cl main.obj Lazy.obj
</code></pre>
<p>I am pretty much new to programming so please bear me with the silly mistakes. One problem that can be seen at the first glance is this class (Lazy) is not thread-safe. Implementing that would be easy with mutexes. But, other than that, how can I improve my code?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T17:07:16.500",
"Id": "447983",
"Score": "1",
"body": "Why are you storing/returning `std::optional` if you always return it with the value set?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T00:21:22.230",
"Id": "448017",
"Score": "0",
"body": "I am returning std::optional<T> because of the problem with operator-> According to docs \"It has additional, atypical constraints: It must return an object (or reference to an object) that also has a pointer dereference operator, or it must return a pointer that can be used to select what the pointer dereference operator arrow is pointing at.\" ** Now this behavior could be emulated by converting that to pointer and returning it but it will introduce a whole new set of problems among which the deadliest one is that people may get a false sense of assumption that the returned obj is a pointer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T00:23:28.483",
"Id": "448018",
"Score": "0",
"body": "Which may make people do weird stuff like deleting that pointer or trying to assign something else. On the other hand I feel that returning a std::optional<T> would keep the users aware about what type of object they are dealing with"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T00:25:29.847",
"Id": "448019",
"Score": "0",
"body": "Also using std::optional sometimes does have a memory penalty due to alignment issues"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T10:19:14.187",
"Id": "448650",
"Score": "0",
"body": "Just return a `T*`, people can't do strange things with it without explicitly calling `operator->`. That's what the standard facilities do (and is the intended method)."
}
] | [
{
"body": "<h3>Preface</h3>\n\n<p>I am using Apple Clang 10 and the following commands to build.</p>\n\n<pre><code>clang++ -std=c++17 -fmodules-ts --precompile Lazy.cppm -o Lazy.pcm\nclang++ -std=c++17 -fmodules-ts -c Lazy.pcm -o Lazy.o\nclang++ -std=c++17 -fmodules-ts -fprebuilt-module-path=. Lazy.o main.cpp\n</code></pre>\n\n<p>I'm using C++ 17 since that's the tag on the question, although I believe MSVC <code>/std:c++latest</code> corresponds to the parts of C++ 20 that are already implemented on MSVC.</p>\n\n<p>I had one compilation error when I first tried this:</p>\n\n<pre><code>In file included from main.cpp:3:\nLazy.cppm:10:21: error: definition of 'optional' must be imported from module 'Lazy.<global>'\n before it is required\n std::optional<T> m_resource;\n ^\nmain.cpp:26:24: note: in instantiation of template class 'gstd::Lazy<Resource>' requested here\n gstd::Lazy<Resource>resx([](){ return Resource(4,5); });\n</code></pre>\n\n<p>I solved it by adding <code>#include <optional></code> in main.cpp, but maybe there's a better way. Please let me know if there is a better solution. I have only toyed around with modules so I'm far from an expert.</p>\n\n<h3>Fix your indentation</h3>\n\n<p>Minor nitpick: use consistent indentation.\nYou have 4 spaces for most of it (which is fine) but 1 space in a few spots.\nAnd 0 spaces in a few spots too. There are tools that can do this for you automatically (although it's pretty\neasy to just do it by hand).</p>\n\n<h3>Consider using <code>operator T</code></h3>\n\n<p>C++ can implicitly convert your object into a T:</p>\n\n<pre><code>template <typename T>\nstruct Lazy {\n operator const T&() {\n ...\n }\n};\n\nint main() {\n Lazy<int> n(...);\n return n;\n}\n</code></pre>\n\n<h3>Consider making access <code>const</code></h3>\n\n<p>When you access an object, you don't expect to modify it. In other words, you should be able to write:</p>\n\n<pre><code>Lazy<int> const n(...);\nint x = n + 2;\n</code></pre>\n\n<p>This implies an object that looks something like</p>\n\n<pre><code>template <typename T>\nstruct Lazy {\n operator const T&() const {\n ...\n }\nprivate:\n std::optional<T> mutable opt;\n};\n</code></pre>\n\n<h3>Think about what kind of functions you want to support</h3>\n\n<p>As you've written it now, you have two std::functions: the argument to the ctor and the one in the object. You should at most have one. You could use std::move.</p>\n\n<pre><code>Lazy(std::function<T()> ctor_func)\n : m_ctor_func(std::move(ctor_func)) // at least do this!\n{}\n</code></pre>\n\n<p>At least use a member initializer list instead of initialization by assignment.</p>\n\n<p>It may be preferable to get rid of std::function completely and instead use a template parameter.\nThis would allow you to get rid of all the copying.\nYou could even have non-copyable types in the function object.\nYou could even go overboard and deduce the stored type based on the templated function. Then you could just write:</p>\n\n<pre><code>Lazy const n([nc=NonCopyable()]{ return 1; });\n</code></pre>\n\n<p>No template arguments! It's up to you to decide whether this is a good idea, but it may be a good exercise if you\nare new to templates.</p>\n\n<h3>Use optional::emplace</h3>\n\n<p>... instead of assignment.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-12T02:19:19.050",
"Id": "232222",
"ParentId": "230108",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T15:33:27.770",
"Id": "230108",
"Score": "7",
"Tags": [
"c++",
"c++17",
"lazy"
],
"Title": "Lazy Resource Loading class in C++"
} | 230108 |
<p>As we know, using PDO and prepared statements, binding a table or column using <code>bindParam</code> is not possible. So for this, I've figured out to use function parameters to do it by replacing the column names with the parameters, as shown in the example bellow.</p>
<pre><code>function search($filter,$input,$type,$order,$sort,$limit){
$st=$this->conn->prepare("SELECT Title,Type,Youtube,Score,Ratings,Singer,ID
FROM song WHERE $filter LIKE CONCAT('%',?,'%')
AND Type=? ORDER BY $order $sort LIMIT $limit");
$st->bindparam(1,$input);
$st->bindparam(2,$type);
$st->execute();
return $st->fetchall();
}
</code></pre>
<p>And I call this function here:</p>
<pre><code>$result=$search->search($_POST['filter'],$_POST['input'],$_POST['type'],$_POST['order'],$_POST['sort'],$_POST['limit']);
</code></pre>
<p>Where the values come from:</p>
<ul>
<li><code>$filter</code>----<code>select</code></li>
<li><code>$input</code>----<code>input</code></li>
<li><code>$type</code>----<code>radio</code></li>
<li><code>$order</code>----<code>select</code></li>
<li><code>$sort</code>----<code>radio</code></li>
<li><code>$limit</code>----<code>input</code></li>
</ul>
<p>As you see the table I'm selecting from is fix, that's not optional, but I have the option to choose which column I want the result to be ordered by(<strong><code>$order</code></strong>), which column I'd like to search(<strong><code>$filter</code></strong>), I want it to be ascending or descending(<strong><code>$sort</code></strong>), and how many I'd like to see(<strong><code>$limit</code></strong>).</p>
<p>And this code works fine, but I'm not sure if it's a safe way to do this. Are there some kind of risks of this solution, or it's safe to leave it like this?</p>
| [] | [
{
"body": "<p>You should be validating and sanitizing the variables that are not being parameterized.</p>\n\n<p>When there is a strict set of acceptable values, write an array of whitelisted values and check against that.</p>\n\n<p>If input is coming from a text type input or textarea, then it will be harder to validate, and you may have to settle for stripping html or characters which you deem to be out-of-bounds.</p>\n\n<p>You need to be as ruthless as possible without damaging the user experience because people that may attempt to compromise your system will not be pulling any punches.</p>\n\n<p>Some examples:</p>\n\n<ol>\n<li><p>There is only one sort value worth receiving / using in your query. <code>ASC</code> is just syntactic sugar. Because the form provides a radio input field, you don't need to bother with trimming whitespace.</p>\n\n<pre><code>$sort = $_POST['sort'] == 'DESC' ? 'DESC' : '';\n</code></pre></li>\n<li><p>Unless you are accepting the <em>offset</em> and <em>row count</em> as a single value, the limit value MUST be an integer. Since your form provides a text input field for this, it is possible that a well-intended user may accidentally pass whitespace. For this reason, it would be a sensible inclusion to trim the value before validating it.</p>\n\n<pre><code>$limit = ctype_digit(trim($_POST['limit'])) ? (int)$_POST['limit'] : '';\n</code></pre></li>\n<li><p><code>filter</code> and <code>$order</code> come from select input fields. This means you know exactly which values to expect. A lookup array will do the job in a tidy fashion.</p>\n\n<pre><code>$filterLookup = ['filter1', 'filter2', 'filter3'];\n$filter = in_array($_POST['filter'], $filterLookup) ? $_POST['filter'] : '';\n</code></pre>\n\n<p>In your project structure, you might even design a single reference point for <code>filter</code> and <code>order</code> column values so that everything stays in sync. You wouldn't want your lookup array to deviate from your form's select options -- that would lead to user frustration.</p></li>\n</ol>\n\n<hr>\n\n<p>As for how you treat values that do not fall within the predicted range -- that is up to you. You should inform the user when the request could not be processed due to invalid/missing data and let them know how they can fix up their submission. In some cases, you may wish to simply ignore faulty values and proceed with the query construction with that segment omitted -- again, that is your call.</p>\n\n<p>p.s. Consider these adjustments for the sake of readability (while this largely comes down to personal style, it is generally a good idea to write code that doesn't require horizontal scrolling to read):</p>\n\n<pre><code>$result = $search->search(\n $_POST['filter'],\n $_POST['input'],\n $_POST['type'],\n $_POST['order'],\n $_POST['sort'],\n $_POST['limit']\n);\n</code></pre>\n\n<p>and</p>\n\n<pre><code>function search($filter, $input, $type, $order, $sort, $limit) {\n $stmt = $this->conn->prepare(\n \"SELECT Title, Type, Youtube, Score, Ratings, Singer, ID\n FROM song\n WHERE $filter LIKE CONCAT('%', ?, '%')\n AND Type = ?\n ORDER BY $order $sort\n LIMIT $limit\"\n );\n $stmt->execute([$input, $type]);\n return $stmt->fetchall();\n}\n</code></pre>\n\n<hr>\n\n<p>Regarding your comment about sanitizing limit values, I recommend a min-max sandwich after casting the input as an integer... (<a href=\"https://3v4l.org/tNfX3\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>$inputs = ['7', '54', '3', 'foo'];\nforeach ($inputs as $input) {\n echo \"---\\n$input >>> \";\n $sanitized = min(max((int)$input, 5), 50);\n var_dump($sanitized);\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>---\n7 >>> int(7)\n---\n54 >>> int(50)\n---\n3 >>> int(5)\n---\nfoo >>> int(5)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T05:47:37.710",
"Id": "448046",
"Score": "0",
"body": "Oh I wanted to include more details about where the values come from, just forgot.\nThe `$limit` comes from an input field, with a number type, so only number can be entered. There is a minimum value of 5, and maximum one of 50. But since I can still actually type a number other than 5-50, I check if the number is between 5 and 50 with php, like: `if($_POST['limit']<5{ $_POST['limit']=5; }`.If it's less than 5, I set it to be 5. Same if it's more than 50."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T06:06:03.453",
"Id": "448047",
"Score": "0",
"body": "The form is not the only way to send data to your receiving file ...even if that is the only way that _you've_ built it. Naughty people will circumvent the constraints of your form."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T08:45:47.437",
"Id": "448071",
"Score": "0",
"body": "I added a limit sanitizing demo"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T22:09:18.430",
"Id": "230120",
"ParentId": "230109",
"Score": "1"
}
},
{
"body": "<blockquote>\n <p>Are there any risks of using function parameters for column names in prepared statement?</p>\n</blockquote>\n\n<p>Well, <strong>of course you shouldn't</strong>. \"Function parameters\" is not a protection measure in any sensible way. It's just a transport, to deliver some value into a function. As is.</p>\n\n<blockquote>\n <p>Are there some kind of risks of this solution,</p>\n</blockquote>\n\n<p><strong>ANY of them</strong>. All kinds of SQL injection are welcome in this code. </p>\n\n<p>Sorry for the harsh preface but I wanted to make it clear and make sure there are no such illusions left.</p>\n\n<p>So you have to change the approach entirely. Luckily, it is not hard to implement.</p>\n\n<ul>\n<li>For the field name and order by, you will need a <strong>white list filtering</strong>.</li>\n<li>For the limit, as it's not a column name, but a data literal, simply add it through a <strong>placeholder</strong>.</li>\n</ul>\n\n<p>I've got an article that explains the white list approach in detail, <a href=\"https://phpdelusions.net/pdo_examples/order_by\" rel=\"nofollow noreferrer\">Adding a field name in the ORDER BY clause based on the user's choice</a></p>\n\n<p>Using a helper function from this article, </p>\n\n<pre><code>function white_list(&$value, $default, $allowed, $message) {\n if (empty($value)) {\n return $default;\n }\n $key = array_search($value, $allowed, true);\n if ($key === false) { \n throw new InvalidArgumentException($message); \n }\n return $value;\n}\n</code></pre>\n\n<p>we can make your function 100% safe </p>\n\n<pre><code>function search($filter,$input,$type,$order,$sort,$limit)\n{\n $fields = ['name', 'text', 'whatever'];\n $filter = white_list($filter, $fields[0], $fields, \"Incorrect filter name\");\n $order = white_list($order, $fields[0], $fields, \"Incorrect order name\");\n $sort = white_list($sort, \"ASC\", [\"ASC\",\"DESC\"], \"Invalid ORDER BY direction\");\n\n $sql = \"SELECT Title,Type,Youtube,Score,Ratings,Singer,ID\n FROM song WHERE $filter LIKE CONCAT('%',?,'%')\n AND Type=? ORDER BY $order $sort LIMIT ?\"\n $st = $this->conn->prepare($sql);\n $st->execute([$input, $type, $limit]);\n return $st->fetchall();\n}\n</code></pre>\n\n<p>Just edit the list of fields allowed (or make two lists if they have to be different for the filter and order) and you're set. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T12:15:07.823",
"Id": "448092",
"Score": "0",
"body": "I thought the title would make no much sense. English is not my native language, and I didn't really know how to ask it. Couldn't even have asked it properly in my own language, let alone a foreign one.\nBTW, thanks for the help, I thought this code would be vulnerable to SQL injections, but didn't really know how I can defend against it in this case.\n\nTBH, what I found the most interesting in your answer is the way you bind the parameters in the `execute` method. I had no idea it can be done like this. It definitely looks better, I'll surely use this method in the future!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T12:16:37.390",
"Id": "448093",
"Score": "0",
"body": "Didn't you see the `execute()` in my answer then? @K.P."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T12:18:17.437",
"Id": "448094",
"Score": "0",
"body": "@K.P. The phrasing of the title makes a perfect sense, it is understandable and clear. It's the premise you expressed in it (implying that passing a variable as a function parameter would mitigate some risks somehow) is wrong."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T11:30:05.890",
"Id": "230152",
"ParentId": "230109",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T15:36:05.887",
"Id": "230109",
"Score": "2",
"Tags": [
"php",
"pdo"
],
"Title": "SQL prepared statement to search songs by various text fields"
} | 230109 |
<p>I have been using similar piece of code since a while. I have read some issues regarding <a href="https://stackoverflow.com/questions/33904180/parsing-mmaped-file-with-strtok">treating mapped memory as a string</a>. I am not sure about that though, so I just use <code>strndup(3)</code> to avoid it anyway.</p>
<p>It's often said to use <code>fopen</code>, <code>fwrite</code> and all those <code>f*</code> functions over <code>read(2)</code>, <code>write(2)</code> etc. The reason being, these functions handle the reading and writing quite well by intermediate buffering and are quite well organised too. But in my personal opinion, dealing with files with <code>mmap(2)</code> generally tends to be faster, gives nice control over the data because of <code>MAP_*</code> flags and making a structure yourself can organise data pretty well too. These things hold true except in some cases.</p>
<p>I wanted some reviews on this code and this way of working with files:</p>
<pre><code>#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct MyFile {
const char *filename;
int fd;
size_t size;
char *contents;
};
int setup_myfile(const char *filename, struct MyFile *file);
void clean_myfile(struct MyFile file);
int
main(int argc, char *argv[])
{
if (argc != 2) {
fprintf(stderr, "usage: %s filename\n", argv[0]);
exit(EXIT_FAILURE);
}
struct MyFile my_file;
char *contents, *line, *to_free;
int err = setup_myfile(argv[1], &my_file);
if (err == -1) {
fprintf(stderr, "setup_myfile() failed\n");
exit(EXIT_FAILURE);
}
to_free = contents = strndup(my_file.contents, my_file.size);
if (to_free == NULL) {
perror("strndup(3)");
exit(EXIT_FAILURE);
}
while ((line = strsep(&contents, "\n")) != NULL) {
// Print line by line or do anything with line
printf("%s", line);
}
free(to_free);
clean_myfile(my_file);
return 0;
}
int
setup_myfile(const char *filename, struct MyFile *file)
{
struct stat st;
file->filename = filename;
file->fd = open(file->filename, O_RDONLY);
if (file->fd == -1) {
perror("open(2)");
return -1;
}
if (fstat(file->fd, &st) == -1) {
perror("fstat(2)");
return -1;
}
file->size = st.st_size;
file->contents = mmap(NULL, file->size, PROT_READ | PROT_WRITE, MAP_PRIVATE, file->fd, 0);
if (file->contents == MAP_FAILED) {
perror("mmap(2)");
return -1;
}
return 0;
}
void
clean_myfile(struct MyFile file)
{
munmap(file.contents, file.size);
close(file.fd);
}
</code></pre>
| [] | [
{
"body": "<p>the posted code does not cleanly compile! </p>\n\n<p>Compile with warnings enabled, then fix those warnings. </p>\n\n<p>for <code>gcc</code>, at a minimum use: </p>\n\n<pre class=\"lang-none prettyprint-override\"><code>-Wall -Wextra -Wconversion -pedantic -std=gnu11\n</code></pre>\n\n<p>Note: other compilers use different options to produce the same results.</p>\n\n<p>in function: <code>setup_myfile()</code> there are statements like:</p>\n\n<pre><code>return -1;\n</code></pre>\n\n<p>However, that only gets execution back to the call in <code>main()</code></p>\n\n<pre><code>setup_myfile(argv[1], &my_file);\n</code></pre>\n\n<p>Which is ignoring the returned value. So, when <code>setup_myfile()</code> fails, <code>main()</code> will keep right on executing, as if everything is OK.</p>\n\n<p>Suggest, rather than: <code>return -1;</code> to use:</p>\n\n<pre><code>exit( EXIT_FAILURE );\n</code></pre>\n\n<p>which will properly exit the program</p>\n\n<p>regarding:</p>\n\n<pre><code>file->size = st.st_size;\n</code></pre>\n\n<p>This is performing an implicit conversion from <code>off_t</code> to <code>unsigned long int</code>. Probably better to declare <code>file->size</code> as an <code>off_t</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T03:10:10.900",
"Id": "448030",
"Score": "0",
"body": "+1,Thanks for the suggestions. Those are certainly helpful but my main question is about dealing with files this way and `mmap`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T00:53:20.087",
"Id": "448176",
"Score": "0",
"body": "If you want discussion about using `mmap()` then should have posted to `stackoverflow.com` rather than here. 'Here' is for working programs that the OP would like to discover problems and/or improve"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T04:45:39.223",
"Id": "448182",
"Score": "0",
"body": "New to this community, sorry for mistakes. In one way, its for improvement on how the code deals with files. There are various topics like performance differences, memory leak chances, security, code clarity etc etc. I will update my question to add more details. Thanks."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T23:58:54.140",
"Id": "230125",
"ParentId": "230111",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T18:17:56.900",
"Id": "230111",
"Score": "3",
"Tags": [
"c",
"file",
"unix",
"mmap"
],
"Title": "Code dealing with files and separate lines in them"
} | 230111 |
<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>let generatorButton = document.getElementById("generator");
generatorButton.addEventListener("click", () => {
let passwordLength = 16;
let characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~!@#$%^&*()_";
let password = "";
for (i = 0;i < passwordLength;i++){
password = password + characters.charAt(Math.floor(Math.random() * Math.floor(characters.length - 1)));
}
document.getElementById("textField").value = password;
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>:root {
--gray: #CBC4C4;
--blue: #029DF1;
--white: #FFF;
}
* {
font-family: Roboto, sas-serif;
margin: 0;
padding: 0;
margin-top: 15px;
}
body {
background: var(--blue);
}
.container {
width: 300px;
margin: 0 auto;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background: var(--gray);
font-size: large;
border-radius: 30px;
}
button {
background: var(--blue);
color: var(--white);
padding: 20px 20px;
margin: 10px 5px;
font-size: large;
cursor: pointer;
}
button:focus {
border: 2px solid var(--blue);
outline: none;
}
input {
font-size: large;
border: 3px solid var(--blue);
outline: none;
margin-bottom: 15px;
}
input::placeholder {
opacity: 0.6;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Password Generator</title>
</head>
<body>
<div class="container">
<h2>Password Generator</h2>
<button id="generator">Generate!</button>
<input type="text" id="textField" placeholder="Your password goes here...">
</div>
<script src="script.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>I could add a few things onto this, like having a way to copy onto the clipboard and such. But really what I want to know is, how can I make this code shorter and more efficient? Specifically, my CSS is long. Maybe I should start using a CSS framework? Let me know.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T00:37:26.893",
"Id": "448020",
"Score": "0",
"body": "Although discussing a C version, you should read some of the comments [here](https://codereview.stackexchange.com/questions/229927/my-first-random-password-generator/229938#229938) concerning the method and cryptographic security. They are relevant and easily translate into javascript."
}
] | [
{
"body": "<h2>JavaScript</h2>\n\n<p>You don't have to list down all characters. All printable characters in the ASCII range are found in 33-126. What you could do is generate a random number within this range, and convert them into characters using <code>String.fromCharCode()</code>.</p>\n\n<p>Also, it's always a good practice to separate business logic from view logic. You will want to be able to generate random passwords regardless of what your UI implementation is. In this case, I recommend putting your logic into its own function, and have the event handler call it.</p>\n\n<p>Store elements you get from <code>document.getElementById()</code> and similar APIs to a variable, and use that variable to operate on the element. DOM operations are slow, and you will want to reduce it if possible. This example is small, and the impact is negligible, but it's a good thing to keep in mind.</p>\n\n<h2>CSS</h2>\n\n<p>For your CSS, I discourage the use of element selectors, unless you're writing a globally applied style. The same goes for the <code>*</code> selector. The problem with using these selectors is that they apply styles globally and will affect not just your code, but code from other developers in your team.</p>\n\n<p>Elements have default styles provided by the browser, and some developers expect this when styling their CSS. If I build a perfectly fine component, but your styles globally turn the <code>font-size</code> to <code>10px</code>, that's not a nice developer experience.</p>\n\n<p>Use classes instead to target specific elements. I recommend you learn the <a href=\"https://css-tricks.com/bem-101/\" rel=\"nofollow noreferrer\">BEM</a> naming scheme. This allows you to namespace your CSS so that it's contained only to the component/widget you're working on. In this case, your password generator.</p>\n\n<p>Never do <code>outline: none;</code>. This is bad for accessibility and keyboard navigation. Also, do not remove visual cues for interactive elements as this makes your app look non-responsive. For example, the native styling of a button will make it look pressed when you click. If you replace the border color, you lose this. So you should provide an <code>:active</code> styling and style it to give feedback to the user that a press did happen.</p>\n\n<p>Also not a fan of <code>font: large</code> as this may be different on different browsers. Use a fixed value using the <code>rem</code> unit. <code>rem</code>s are based on the <code>font-size</code> of the <code><html></code> element. By default, <code><html></code> is <code>16px</code> which means <code>16px * 1rem = 16px</code>. <code>1.5rem</code> is <code>16px * 1.5rem = 24px</code>, and so on. The neat thing about <code>rem</code> is if the user has a bumped up or bumped down font-size, the your font scales with it as well.</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>const getRandomCharCode = (start, end) =>\n Math.floor(start + (Math.random() * ((end + 1) - start)))\n\n// Generate an array that's length long, and fill it with random characters\n// from 33 to 126 of the ascii range.\nconst generatePassword = length =>\n Array(length).fill()\n .map(_ => String.fromCharCode(getRandomCharCode(33, 126)))\n .join('')\n\nconst generatorButton = document.getElementById(\"generator\")\nconst generatorTextField = document.getElementById(\"textField\")\n\ngeneratorButton.addEventListener(\"click\", () => {\n generatorTextField.value = generatePassword(16)\n})</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>:root {\n --gray: #CBC4C4;\n --blue: #029DF1;\n --blue: #029DF1;\n --dark-blue: #007DD1;\n --white: #FFF;\n}\n\nbody {\n background: var(--blue);\n font-family: sans-serif;\n}\n\n.generator {\n width: 300px;\n margin: 0 auto;\n padding: 15px;\n background: var(--gray);\n border-radius: 30px;\n display: flex;\n flex-direction: column;\n justify-content: center;\n align-items: center;\n}\n\n.generator__button {\n background: var(--blue);\n color: var(--white);\n padding: 15px;\n margin: 0 0 15px;\n font-size: 1.25rem;\n cursor: pointer;\n border: 2px solid var(--blue);\n}\n\n.generator__button:active {\n background: var(--dark-blue);\n}\n\n.generator__field {\n margin: 0 0 15px;\n font-size: 1.25rem;\n border: 3px solid var(--blue);\n}\n\n.generator__field::placeholder {\n opacity: 0.6;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"generator\">\n <h2>Password Generator</h2>\n <button class=\"generator__button\" id=\"generator\">Generate!</button>\n <input class=\"generator__field\" id=\"textField\" type=\"text\" placeholder=\"Your password goes here...\">\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T23:22:49.900",
"Id": "230122",
"ParentId": "230113",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "230122",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T19:14:20.847",
"Id": "230113",
"Score": "3",
"Tags": [
"javascript",
"html",
"css",
"dom"
],
"Title": "Simple Password Generator in JavaScript"
} | 230113 |
<p>I have a custom system for data validation; it handles anything from method parameters, return values, objects, etc. The core of this system is <code>IValidationRule</code> and its generic twin. There is a base class for actual implementations of validation rules (things like string length, database entity exists,...).</p>
<p>Data can have multiple validation rules bound to them, and they are mostly specified via attributes. For brevity, I will omit the attributes, rules, and params definitions as I do not think they are necessary and would only make this more complicated.</p>
<pre><code>public interface IValidationRule {
bool Validate( object? value, object? @params, object? context );
}
public interface IValidationRule<in TData, in TParams, in TContext> : IValidationRule {
bool Validate( TData value, TParams @params, TContext context );
}
public abstract class ValidationRule<TData, TParams, TContext> : IValidationRule<TData, TParams, TContext> {
bool IValidationRule.Validate( object? value, object? @params, object? context ) {
#pragma warning disable CS8601 // Possible null reference assignment.
return Validate((TData)value, (TParams)@params, (TContext)context);
#pragma warning restore CS8601 // Possible null reference assignment.
}
public abstract bool Validate( TData value, TParams @params, TContext context );
}
</code></pre>
<p>There is a couple of things I'd like to consult.</p>
<ol>
<li><p>The generic interface uses the non-generic (in a similar fashion as <code>IEnumerable<T></code>). I remember reading somewhere how generics made "object as jack of all trades" obsolete and the only reason why <code>IEnumerable<T></code> was implemented this way was backwards compatibility. I do not think I can achieve my goal without this approach.</p></li>
<li><p>Since the library is currently being switched to use C# 8's ref type nullability, I had to disable some warnings. On the one hand, this feels wrong, but on the other hand, the <code>IValidationRule</code> must use the signature with nullable objects as some rules might use nullable types. However, the generic versions will often specify non-nullable types, such as int.</p></li>
<li><p>It cannot be seen in this example, but let's say the <code>IValidationRule</code> has a property of type <code>object</code>. Is it frowned upon to override this in the generic interface, using a generic type for the property? I think the answer is somewhat. While it is an indicator of possible code smell, some cases warrant this (mostly aggregated evaluation).</p></li>
</ol>
<p>What are your thoughts?</p>
<p>Some additional examples:</p>
<pre><code>public interface IValidationDescriptor {
string ErrorCode { get; }
object Params { get; }
Type Rule { get; set; }
ErrorSeverity Severity { get; set; }
ValidationTargets Targets { get; set; }
int Order { get; set; }
ExecutionConditions Conditions { get; set; }
}
public class Validator {
private readonly IErrorMessageProvider _messageProvider;
private readonly IPropertyNameProvider _propertyNameProvider;
private readonly IValidationRuleProvider _ruleProvider;
public Validator( IValidationRuleProvider ruleProvider, IErrorMessageProvider messageProvider,
IPropertyNameProvider propertyNameProvider ) {
_ruleProvider = ruleProvider;
_messageProvider = messageProvider;
_propertyNameProvider = propertyNameProvider;
}
private IEnumerable<IDataError> ValidateObject( object targetObject, Type parentType, string? path ) {
var errors = new List<IDataError>();
var props = targetObject.GetType().GetProperties().Where(p => p.CanRead);
foreach( var prop in props ) {
var propValue = prop.GetValue(targetObject);
var propPath = CombinePaths(path, _propertyNameProvider.GetName(prop));
errors.AddRange(Validate(prop.GetCustomAttributes<ValidationDescriptorAttribute>(), prop.GetCustomAttribute<ValidationOptionsAttribute>(),
propValue, prop.PropertyType,
targetObject, parentType,
propPath));
}
return errors;
}
private IEnumerable<IDataError> ValidateData( IEnumerable<IValidationDescriptor> descriptors,
object? value, Type valueType,
object? parentValue, Type parentType, string? path ) {
var errors = new List<IDataError>();
foreach( var descriptor in descriptors.OrderBy(d => d.Order) ) {
if( descriptor.Conditions.HasFlag(ExecutionConditions.NoError) && errors.Any() )
continue;
if( descriptor.Targets.HasFlag(ValidationTargets.Self) )
ApplyDescriptor(errors, descriptor, value, valueType, parentValue, parentType, path);
if( !descriptor.Targets.HasFlag(ValidationTargets.Children) || !(value is IEnumerable enumerable) )
continue;
var childType = (value as IEnumerable).AsQueryable().ElementType;
var i = 0;
foreach( var child in enumerable ) {
if( descriptor.Conditions.HasFlag(ExecutionConditions.NoError) && errors.Any() )
break;
ApplyDescriptor(errors, descriptor,
child, childType,
value, valueType,
CombinePaths(path, i.ToString()));
i++;
}
}
return errors;
}
private void ApplyDescriptor( ICollection<IDataError> errors, IValidationDescriptor descriptor,
object? value, Type valueType,
object? parentValue, Type parentType,
string path ) {
var isValid = _ruleProvider.Get(descriptor.Rule)
.Validate(value, descriptor.Params, parentValue);
if( isValid )
return;
var @params = TypeActivator.CreateGenericInstance(
typeof(ErrorGenerationParams<,,>),
new[] { valueType, parentType, descriptor.Params.GetType() },
new[] { value, parentValue, descriptor.Params, null }
);
var message = _messageProvider.Get( descriptor.ErrorCode,
(IErrorGenerationParams)@params );
errors.Add(new DataError(descriptor.ErrorCode, message, descriptor.Severity, path, value));
}
private static string CombinePaths( string path1, string path2 ) {
if( path1 == null )
return path2;
if( path2 == null )
return path1;
return $"{path1}.{path2}";
}
}
</code></pre>
<p>More implementation details:</p>
<pre><code>// an example rule
public class BoolValueRule : ValidationRule<bool, IBoolValueParams, object> {
public override bool Validate( bool value, IBoolValueParams @params, object context ) {
return value == @params.RequiredValue;
}
}
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true)]
public class ValidationDescriptorAttribute : Attribute, IValidationDescriptor {
public ValidationDescriptorAttribute( string errorCode, Type rule ) {
ErrorCode = errorCode;
Rule = rule;
}
public ValidationDescriptorAttribute( string errorCode, Type rule, int order, ExecutionConditions conditions ) {
ErrorCode = errorCode;
Rule = rule;
Order = order;
Conditions = conditions;
}
public string ErrorCode { get; }
public virtual object Params => new object();
public Type Rule { get; set; }
public ErrorSeverity Severity { get; set; } = ErrorSeverity.Error;
public ValidationTargets Targets { get; set; } = ValidationTargets.Self;
public int Order { get; set; }
public ExecutionConditions Conditions { get; set; }
}
public class BoolValueAttribute : ValidationDescriptorAttribute {
public BoolValueAttribute( string errorCode, bool requiredValue ) : base(errorCode, typeof(BoolValueRule)) {
RequiredValue = requiredValue;
}
public BoolValueAttribute( string errorCode, bool requiredValue, int order, ExecutionConditions conditions )
: base(errorCode, typeof(BoolValueRule), order, conditions) {
RequiredValue = requiredValue;
}
public bool RequiredValue { get; }
public override object Params => new BoolValueParams(RequiredValue);
}
public class BoolValueParams : IBoolValueParams {
public BoolValueParams( bool requiredValue ) {
RequiredValue = requiredValue;
}
public bool RequiredValue { get; }
}
// an object we want to validate
public class MyValidatableObject {
[BoolValue(true)]
public bool AcceptedToS { get; set; }
}
public enum ErrorSeverity {
Warning,
Error,
}
public interface IGenericError {
string Code { get; }
string Message { get; }
ErrorSeverity Severity { get; }
}
public interface IDataError : IGenericError {
string Path { get; }
object? Value { get; }
}
[Flags]
public enum ValidationTargets {
None = 0,
Self = 1,
Children = 2,
All = Self | Children
}
public enum TraversalMode {
Recursive,
RecursiveOnNoErrors,
Stop
}
[Flags]
public enum ExecutionConditions {
None = 0,
NoError = 1
}
public interface IErrorMessageProvider {
string Get( string code, IErrorGenerationParams? @params );
}
public interface IPropertyNameProvider {
string GetName( PropertyInfo property );
}
public interface IValidationRuleProvider {
IValidationRule Get( Type type );
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T08:38:43.377",
"Id": "448066",
"Score": "4",
"body": "\"*I do not think I can achieve my goal without this approach.*\" I think we'd need to see some actual usage of the interface to comment on whether that usage is achievable with a purely genericised interface."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T09:13:42.520",
"Id": "448074",
"Score": "0",
"body": "@PeterTaylor I added a simplified implementation of the Validator class. Is this sufficient?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T13:42:06.720",
"Id": "448101",
"Score": "0",
"body": "I vote to close this question becuase it's incomplete ( _For brevity, I will omit [..]_). The example contains several types that aren't defined anywhere and thus is incomprihesible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T13:44:16.697",
"Id": "448105",
"Score": "0",
"body": "@t3chb0t I can copy paste all the missing types, if you think they are any relevant. Keeping the question concise is also important."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T14:01:41.050",
"Id": "448111",
"Score": "2",
"body": "Yes, I think it would be benefical to post _all_ the code or at least enough so that the example makes sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T14:44:33.637",
"Id": "448266",
"Score": "4",
"body": "Keeping the code concise is not as important on Code Review as on Stack Overflow. Code review needs to see all the related code to provide a good review. Stack Overflow wants a concise block of code and/or description to provide an answer to a how to question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T15:07:20.633",
"Id": "448700",
"Score": "1",
"body": "I added more interface/type definitions and implementation details; I apologize for the delay."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T19:21:57.507",
"Id": "230114",
"Score": "1",
"Tags": [
"c#",
"validation",
"api",
"generics",
"reflection"
],
"Title": "Generics and aggregated evaluation of validation rules"
} | 230114 |
<p>Most quicksort examples online use C-style arrays and indexes. I have written below quicksort implementation with STL style iterators. It looks fine to me, but I feel like I may be making more than necessary copies of iterators. I am open for any suggestions/improvements:</p>
<pre><code>#include <iostream>
#include <vector>
#include <cassert>
#include <algorithm>
#include <iterator>
template <typename Iter>
inline Iter partition(const Iter& beg, const Iter& end) {
using std::swap;
assert(beg != end);
auto piv = end;
--piv; // Pivot is the last element
auto index_small = beg;
for (auto index_large = beg; index_large != piv; ++index_large) {
if (*index_large <= *piv) {
swap(*index_large, *index_small);
++index_small;
}
}
swap(*index_small, *piv);
return index_small;
}
template <typename Iter>
void quick_sort(const Iter& beg, const Iter& end) {
if (end - beg > 1) {
const auto& piv = partition(beg, end);
quick_sort(beg, piv);
quick_sort(piv, end);
}
}
// Test
int main() {
std::vector<int> vec{ 19, 54, 53, 9, 3, 96, 40, 36, 96, 43, 45,
78, 57, 6, 12, 100, 36, 15, 27, 45, 80, 39,
10, 71, 100, 15, 41, 43, 20, 32, 61, 2, 55,
33, 85, 32, 11, 50, 25, 17, 75, 74, 39, 49,
50, 17, 18, 55, 63, 81, };
quick_sort(vec.begin(), vec.end());
std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << '\n';
}
</code></pre>
| [] | [
{
"body": "<p><em>I usually try to stay away from these aspects of C++, so maybe take what I say with a grain of salt.</em></p>\n\n<hr>\n\n<p>From what I can see, your implementation heavily relies on <code>begin</code> and <code>end</code> being <a href=\"https://en.cppreference.com/w/cpp/experimental/ranges/iterator/RandomAccessIterator\" rel=\"nofollow noreferrer\">random access iterators</a>. If I'm not mistaken, your implementation should also work (see notes on complexity below) for <a href=\"https://en.cppreference.com/w/cpp/experimental/ranges/iterator/BidirectionalIterator\" rel=\"nofollow noreferrer\">bidirectional iterators</a> as present e.g. in <code>std::list</code>. A minor change should allow the implementation to work with these iterators as well:</p>\n\n<ul>\n<li><code>end - beg > 1</code> would have to become <code>std::distance(beg, end) > 1</code>. <code>std::distance</code> has linear complexity for birectional iterators and constant complexity for random access iterators. (See <a href=\"https://en.cppreference.com/w/cpp/iterator/distance\" rel=\"nofollow noreferrer\"><code>std::distance</code></a>).</li>\n</ul>\n\n<p>and you should be good to go. This is the <em>simplest</em> change that I could think of, but I'm pretty sure that there are more efficient solutions for this check.</p>\n\n<p><em>Note on complexity: As <a href=\"https://codereview.stackexchange.com/users/188857/\">@L.F.</a> pointed out in a comment, quicksort is not a suitable algorithm for bidirectional iterators with regards to complexity, though. Nevertheless, not all hope is lost since at least <code>std::list</code> has its own method <code>std::list::sort</code> which according to the <a href=\"https://en.cppreference.com/w/cpp/container/list/sort\" rel=\"nofollow noreferrer\">documentation</a> allows you to perform sorting within the <span class=\"math-container\">\\$\\mathcal{O}(n\\log{}n)\\$</span> complexity class for compares.</em></p>\n\n<p>You could also use the following iterator functions to express some of the parts of your code in a different way:</p>\n\n<ul>\n<li><code>auto piv = end; --piv;</code> could become <code>auto piv = std::prev(end);</code> (See <a href=\"https://en.cppreference.com/w/cpp/iterator/prev\" rel=\"nofollow noreferrer\"><code>std::prev</code></a>)</li>\n<li><code>++index_small;</code> could become <code>std::advance(index_small, 1);</code> (See <a href=\"https://en.cppreference.com/w/cpp/iterator/advance\" rel=\"nofollow noreferrer\"><code>std::advance</code></a>)</li>\n</ul>\n\n<p>These are not strictly necessary though, since bidirectional iterators also support <code>operator++</code> and <code>operator--</code>.</p>\n\n<p>You can check an example with <code>std::list</code> on <a href=\"http://cpp.sh/7r2io\" rel=\"nofollow noreferrer\">cpp.sh</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T22:19:30.350",
"Id": "448009",
"Score": "0",
"body": "I understand the suggestion about using `std::distance`, but bidirectional iterators support `operator++` and `operator--`, right? What is the point of using `std::prev` and `std::advance`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T22:24:43.497",
"Id": "448010",
"Score": "0",
"body": "using `std::distance` to check if the range has more than 1 element seems inefficient for bidirectional iterators. Perhaps an \"increase check if end, increase check if end\" approach would be better for bidirectional iterators, but I imagine that'd affect efficiency detrimentally for random-access iterators."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T22:25:59.953",
"Id": "448011",
"Score": "0",
"body": "The main reason why I assumed `begin` and `end` were random access iterators is that `std::sort` assumes the same."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T22:50:45.080",
"Id": "448012",
"Score": "0",
"body": "I wasn't able to find the reason why the standard dictates to only accept random access iterators in `std::sort` when looking at the draft. My best guess would be that it allows to use more sorting algorithms in the actual implementation, e.g. Wikipedia seems to hint towards a [hybrid algorithm](https://en.wikipedia.org/wiki/Sort_(C%2B%2B)#Complexity_and_implementations) in the GCC.implementation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T02:44:29.213",
"Id": "448023",
"Score": "0",
"body": "I am afraid I have to disagree. Quick sort isn’t suitable for non random access iterators. The time complexity will go beyond quadratic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T06:18:27.397",
"Id": "448048",
"Score": "0",
"body": "@L.F.: (Forgive me my bitterness) I forgot that we are in C++ here, where you cannot do something for the sake of doing it, because it might not be optimal ;-) I included your feedback on the complexity issue in the post."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T21:48:50.800",
"Id": "230118",
"ParentId": "230115",
"Score": "1"
}
},
{
"body": "<p>You have done a great job. Here’s my suggestions:</p>\n\n<ul>\n<li><p>Sort the include directives in alphabetical order. </p></li>\n<li><p>Instead of using the generic name <code>Iter</code>, it may be a good idea to express the random access requirement: something like <code>RandomIt</code>. </p></li>\n<li><p>Iterators should be passed by value, not const reference. Don’t be afraid to copy iterators — they are intended to be lightweight objects that are frequently copied, and passing them by const reference will incur overhead over passing them by value because of the additional indirection. </p></li>\n<li><p>It is more logical to use <code>auto piv = std::prev(end);</code>, because <code>int y = x - 1;</code> is more logical then <code>int y = x; --y;</code>, right? (Of course you can use <code>end - 1</code>, but that may be less efficient if the subtraction operator of the iterator isn’t inlined.)</p></li>\n<li><p>You can use <code>std::iter_swap</code> instead of manually ADL’ing <code>swap</code>. </p></li>\n<li><p>Instead of enforcing <code><=</code>, consider taking a custom comparator as the standard algorithms do. (Also note that the standard library facilities always use <code><</code> as the comparator by default. <code><=</code> is not required unless you provide a custom comparator.)</p></li>\n</ul>\n\n<p>Also, always choosing last element as the pivot can make the code vulnerable to reversely sorted sequences. You can consider taking a random number generator to randomize the choice if this becomes a problem.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T00:45:24.713",
"Id": "448453",
"Score": "0",
"body": "Perhaps add that the comparison operator used by the standard library for user-defined types is always `<`, unless a custom comparator is preferred."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T01:07:34.187",
"Id": "448454",
"Score": "0",
"body": "@Deduplicator Yep, thanks!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T02:53:52.393",
"Id": "230133",
"ParentId": "230115",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "230133",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T20:26:38.873",
"Id": "230115",
"Score": "7",
"Tags": [
"c++",
"sorting",
"quick-sort"
],
"Title": "Quick Sort Implementation with iterators"
} | 230115 |
<h2>Problem Statement</h2>
<p>Given a hexadecimal string (hascii) and its binary specification (a list of byte field names, their offsets, and byte lengths), design classes to parse all byte-fields, cast bytes into suitable types for storage, and allow the user to write to a byte-field. For this purpose, I've created a simple binary specification: </p>
<pre><code>string hasciiData = "07E30A0240490FD8402df8548000000048656C6C6F576F726C64218000000000000000";
</code></pre>
<p>With the following binary specification: </p>
<pre><code>string _year = "07E3"; // 2019 16-bit int, 0x07E3
string _month = "0A"; // 10 8-bit int, 0x0A
string _day = "02"; // 2 8-bit int, 0x02
string _pi = "40490FD8"; // IEEE-754 Single Precision Float, 0x4049 0FD8
string _eulers = "402DF854"; // IEEE-754 Single Precision Float, 0x402D F854
string _secretValue = "80000000"; // 32-bit int, 0x80000000 (Decimal -2147483648)
string _secretMsg = "48656C6C6F576F726C6421"; // ASCII string "HelloWorld!", 0x48656C6C6F576F726C6421
string _bigInt = "8000000000000000"; // 64-bit int, 0x8000 0000 0000 0000 (Decimal -9223372036854775808)
</code></pre>
<h2>Class Design</h2>
<p>The design separates byte-level specification from the code that reads bytes from the string. The "specification" encapsulates the logical structure of the hascii data (storing details like the names of byte fields, byte offsets and field lengths) so that it can be used to parse (read) and write to the hascii string. </p>
<p>Manipulation of hascii characters (hascii bytes are pairs of hascii characters) are handled by the <strong>HasciiParser</strong> class. The <strong>PD0Format</strong> class stores the specification, implemented using multiple dictionaries that map each byte field name (string) to a tuple (int, int) where <code>Tuple.Item1</code> is the base-1 byte position of hascii bytes (i.e., the index value, which starts at 0 and corresponds to byte position #1, increments by 2 since there are 2 hex characters per byte) and <code>Tuple.Item2</code> is the length of the byte field (in units of 'bytes' as in the "Year" bytefield begins at byte position #1 and contains 2 bytes).</p>
<pre><code>protected ByteSpecification dateSpec = new ByteSpecification()
{
{"Year", (1, 2)},
{"Month", (3, 1)},
{"Day", (4, 1)},
};
</code></pre>
<p>The specification also includes a dictionary mapping byte field names to functions that cast bytes to appropriate types (determined by the binary specification).</p>
<p>Hascii character manipulation is decoupled from the binary specification so that if you were to say, rearrange the order of bytefields or add additional byte fields, you need only change the <code>Specification</code> dictionaries.</p>
<h2>Code</h2>
<pre><code>using System;
using System.Collections.Generic;
using System.Text;
using ByteSpecification = System.Collections.Generic.Dictionary<string, (int, int)>;
using CastOperation = System.Collections.Generic.Dictionary<string, System.Func<string, object>>;
namespace ByteParsing
{
public class HasciiParser
{
public static string HexToString(string hascii)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hascii.Length; i += 2)
{
string hexByte = hascii.Substring(i, 2);
sb.Append(Convert.ToChar(Convert.ToUInt32(hexByte, 16)));
}
return sb.ToString();
}
public static string StringToHex(string str, int maxWidth, bool padLeft=true, char padChar='0')
{
StringBuilder sb = new StringBuilder();
foreach (char c in str)
{
sb.AppendFormat("{0:X}", Convert.ToInt32(c));
}
if (padLeft)
{
return sb.ToString().PadLeft(maxWidth, padChar);
}
return sb.ToString().PadRight(maxWidth, padChar);
}
public DateTime HexToDatetime(string hascii)
{
int year = Convert.ToInt32(hascii.Substring(0, 4), 16);
int month = Convert.ToInt32(hascii.Substring(4, 2), 16);
int day = Convert.ToInt32(hascii.Substring(6, 2), 16);
return new DateTime(year, month, day);
}
public static float HexToFloat(string hascii)
{
// https://stackoverflow.com/a/7903300/3396951
uint num = uint.Parse(hascii, System.Globalization.NumberStyles.AllowHexSpecifier);
byte[] floatVals = BitConverter.GetBytes(num);
return BitConverter.ToSingle(floatVals, 0);
}
}
public class PD0Format
{
public string _hasciiData; // Normally private
public PD0Format(string hasciiData)
{
_hasciiData = hasciiData;
}
protected CastOperation castop = new CastOperation()
{
{"Year", (hascii_str) => Convert.ToInt32(hascii_str, 16)},
{"Month", (hascii_str) => Convert.ToInt32(hascii_str, 16)},
{"Day", (hascii_str) => Convert.ToInt32(hascii_str, 16)},
{"Pi", (hascii_str) => HasciiParser.HexToFloat(hascii_str)},
{"EulersNumber", (hascii_str) => HasciiParser.HexToFloat(hascii_str)},
{"SecretValue", (hascii_str) => Convert.ToInt32(hascii_str, 16)},
{"SecretMessage", (hascii_str) => HasciiParser.HexToString(hascii_str)},
{"BigInt", (hascii_str) => Convert.ToInt64(hascii_str, 16)}
};
protected ByteSpecification dateSpec = new ByteSpecification()
{
{"Year", (1, 2)},
{"Month", (3, 1)},
{"Day", (4, 1)},
};
protected ByteSpecification mathConstantsSpec = new ByteSpecification()
{
{"Pi", (5, 4)},
{"EulersNumber", (9, 4)}
};
protected ByteSpecification secretsSpec = new ByteSpecification()
{
{"SecretValue", (13, 4)},
{"SecretMessage", (17, 11)},
{"BigInt", (28, 8)}
};
private string GetHasciiBytes(ByteSpecification byteSpec, string fieldName)
{
// ByteSpecification assumes base-1 indexing. Substring requires base-0 indexing so we must subtract 2 (reason below).
// Because there are two hex characters to a byte, we have to multiply the startIndex of string.Substring
// by 2. To get to the startIndex of a byte, we must substract by multiples of 2.
// Item2 of ByteSpecification's dictionary value represents the number of bytes. Since two hex characters represent
// a byte, the number of characters to extract using string.Substring is Item2 * 2
return _hasciiData.Substring(byteSpec[fieldName].Item1 * 2 - 2, byteSpec[fieldName].Item2 * 2);
}
public dynamic this[string category, string fieldName]
{
get
{
ByteSpecification spec = null;
switch (category.ToLower())
{
case "date":
spec = dateSpec;
goto case "cast";
case "constants":
spec = mathConstantsSpec;
goto case "cast";
case "secrets":
spec = secretsSpec;
goto case "cast";
case "cast":
string hascii_bytes = GetHasciiBytes(spec, fieldName); // Retrieve bytes from underlying string
return castop[fieldName](hascii_bytes); // Cast to appropriate type, according to mapping defined in CastOperation
}
return new ArgumentException();
}
set
{
switch (category.ToLower())
{
case "secrets":
int insertLocation = secretsSpec[fieldName].Item1 * 2 - 2;
int maxCharFieldWidth = secretsSpec[fieldName].Item2 * 2; // Used for padding when the number of hex chars isn't even
string val = null;
switch (fieldName)
{
case "SecretValue":
val = String.Format("{0:X}", value).PadLeft(maxCharFieldWidth, '0'); // Convert value to hascii representation
goto case "EmplaceString";
case "SecretMessage":
val = HasciiParser.StringToHex(value, maxCharFieldWidth);
goto case "EmplaceString";
case "BigInt":
val = String.Format("{0:X}", value).PadLeft(maxCharFieldWidth, '0');
goto case "EmplaceString";
case "EmplaceString":
_hasciiData = _hasciiData.Remove(insertLocation, maxCharFieldWidth); // Remove the characters currently present
_hasciiData = _hasciiData.Insert(insertLocation, val ?? throw new InvalidOperationException());
Console.WriteLine(_hasciiData);
break;
}
break;
case "date":
throw new NotImplementedException();
case "constants":
throw new NotImplementedException();
}
}
}
}
class Program
{
static void Main(string[] args)
{
/*
string _year = "07E3"; // 2019 16-bit int, 0x07E3
string _month = "0A"; // 10 8-bit int, 0x0A
string _day = "02"; // 2 8-bit int, 0x02
string _pi = "40490FD8"; // IEEE-754 Single Precision Float, 0x4049 0FD8
string _eulers = "402DF854"; // IEEE-754 Single Precision Float, 0x402D F854
string _secretValue = "80000000"; // 32-bit int, 0x80000000 (Decimal -2147483648)
string _secretMsg = "48656C6C6F576F726C6421"; // ASCII string "HelloWorld!", 0x48656C6C6F576F726C6421
string _bigInt = "8000000000000000"; // 64-bit int, 0x8000 0000 0000 0000 (Decimal -9223372036854775808)
*/
string hasciiData = "07E30A0240490FD8402df8548000000048656C6C6F576F726C64218000000000000000";
PD0Format ensemble = new PD0Format(hasciiData);
int recordYear = ensemble["date", "Year"];
int recordMonth = ensemble["date", "Month"];
int recordDay = ensemble["date", "Day"];
Console.WriteLine(new DateTime(recordYear, recordMonth, recordDay));
float Pi = ensemble["constants", "Pi"];
float exp1 = ensemble["Constants", "EulersNumber"];
Console.WriteLine($"Pi: {Pi}\nEuler's Number: {exp1}");
int secretValue = ensemble["secrets", "SecretValue"];
string secretMsg = ensemble["secrets", "SecretMessage"];
long bigInt = ensemble["secrets", "BigInt"];
Console.WriteLine($"Secret Value: {secretValue}\nSecret Msg: {secretMsg}\nbigInt: {bigInt}");
// Usage: Writing
string defaultData = "0000000000000000000000000000000000000000000000000000000000000000000000";
PD0Format defaultRecord = new PD0Format(defaultData);
// 35791394 corresponds to 0x02222222 written as "02222222" in hascii
defaultRecord["secrets", "SecretValue"] = 35791394;
// "FooBarBaz" corresponds to 0x00 0046 6F6F 4261 7242 617A written as "0000466F6F42617242617A" in hascii
defaultRecord["secrets", "SecretMessage"] = "FooBarBaz";
// 1229782938247303441 corresponds to 0x1111 1111 1111 1111 written as "1111111111111111" in hascii
defaultRecord["secrets", "BigInt"] = 1229782938247303441;
// Original defaultData: "0000000000000000000000000000000000000000000000000000000000000000000000"
// Modified defaultData: "000000000000000000000000022222220000466F6F42617242617A1111111111111111"
Console.WriteLine(defaultRecord._hasciiData);
Console.ReadLine(); // Prevent console from closing
}
}
}
</code></pre>
<h2>Program Output</h2>
<pre><code>10/2/2019 00:00:00
Pi: 3.141592
Euler's Number: 2.718282
Secret Value: -2147483648
Secret Msg: HelloWorld!
bigInt: -9223372036854775808
0000000000000000000000000222222200000000000000000000000000000000000000
000000000000000000000000022222220000466F6F42617242617A0000000000000000
000000000000000000000000022222220000466F6F42617242617A1111111111111111
000000000000000000000000022222220000466F6F42617242617A1111111111111111
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T17:34:52.280",
"Id": "448139",
"Score": "1",
"body": "They're C#'s \"[using](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-directive) alias directives\" (basically type aliases) whose definition must come before namespace declarations. It's at the very top."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T18:18:39.953",
"Id": "448148",
"Score": "1",
"body": "Oh boy, you have A LOT of `goto`s there o_O they are sometimes useful but they are pretty scarry here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T20:19:27.733",
"Id": "448157",
"Score": "0",
"body": "@t3chb0t It's a valid concern. The `switch/goto` pattern used here is a step towards cutting down repetition and improving readability. Ultimately, it was used as a substitute for \"method extraction\" because the number of cases is small. If the binary specification called for *hundreds* of fields, I'd convert it to a function. I hope the flow of execution is self-evident: exactly 1 `case`-statement runs initially to initialize a set of variables. Execution then jumps to `case` that does the actual work with those variables."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T16:39:27.743",
"Id": "448393",
"Score": "2",
"body": "I rollbacked your latest edit. After an answer is made, you should not edit the question anymore. This to avoid answer invalidation."
}
] | [
{
"body": "<blockquote>\n<pre><code> ByteSpecification spec = null;\n switch (category.ToLower())\n {\n case \"date\":\n spec = dateSpec;\n goto case \"cast\";\n case \"constants\":\n spec = mathConstantsSpec;\n goto case \"cast\";\n case \"secrets\":\n spec = secretsSpec;\n goto case \"cast\";\n case \"cast\":\n string hascii_bytes = GetHasciiBytes(spec, fieldName); // Retrieve bytes from underlying string\n return castop[fieldName](hascii_bytes); // Cast to appropriate type, according to mapping defined in CastOperation\n }\n return new ArgumentException();\n</code></pre>\n</blockquote>\n\n<p>As t3chb0t addresses in his comment the above concept is a rather unconventional use of the <code>switcth-case</code> statement. <code>switch</code> statements are ment to select between discrete values of the same type, but here you use the last case to effectively make a local function. For a small context as this, it is maybe readable for now, but in maintenance situations (in five years by another programmer) it may be cumbersome to figure out why this kind of design is chosen. In general: I would avoid to \"bend\" statements just to be \"smart\".</p>\n\n<p>Instead I would use a method to extract the value or you could just make the \"cast\" after the <code>switch</code>:</p>\n\n<pre><code> get\n {\n ByteSpecification spec = null;\n switch (category.ToLower())\n {\n case \"date\":\n spec = dateSpec;\n break;\n case \"constants\":\n spec = mathConstantsSpec;\n break;\n case \"secrets\":\n spec = secretsSpec;\n break;\n default:\n throw new ArgumentException();\n }\n\n string hascii_bytes = GetHasciiBytes(spec, fieldName); // Retrieve bytes from underlying string\n return castop[fieldName](hascii_bytes); // Cast to appropriate type, according to mapping defined in CastOperation\n }\n</code></pre>\n\n<p>By the way: you probably mean <code>throw new ArgumentException()</code> rather than returning it?</p>\n\n<hr>\n\n<blockquote>\n <p>ByteSpecification assumes base-1 indexing</p>\n</blockquote>\n\n<p>Why do you choose an one based indexing? I don't see it justified in the context. It's just used internally in the <code>PD0Format</code> class. IMO you make things more complicated than they have to be.</p>\n\n<hr>\n\n<p>Some of your conversions could be made a little more intuitively:</p>\n\n<blockquote>\n<pre><code>public static string HexToString(string hascii)\n{\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < hascii.Length; i += 2)\n {\n string hexByte = hascii.Substring(i, 2);\n sb.Append(Convert.ToChar(Convert.ToUInt32(hexByte, 16)));\n }\n return sb.ToString();\n}\n</code></pre>\n</blockquote>\n\n<p>=></p>\n\n<pre><code>public string HexToString(string hascii)\n{\n byte[] bytes = new byte[hascii.Length / 2];\n for (int i = 0; i < slice.Length; i += 2)\n {\n bytes[i / 2] = byte.Parse(hascii.Substring(i, 2), NumberStyles.HexNumber);\n }\n return Encoding.UTF8.GetString(bytes); // Or use Encoding.Default\n}\n</code></pre>\n\n<blockquote>\n<pre><code>public static string StringToHex(string str, int maxWidth, bool padLeft = true, char padChar = '0')\n{\n StringBuilder sb = new StringBuilder();\n foreach (char c in str)\n {\n sb.AppendFormat(\"{0:X}\", Convert.ToInt32(c));\n }\n\n if (padLeft)\n {\n return sb.ToString().PadLeft(maxWidth, padChar);\n }\n return sb.ToString().PadRight(maxWidth, padChar);\n}\n</code></pre>\n</blockquote>\n\n<p>=></p>\n\n<pre><code>public string StringToHex(string value)\n{\n byte[] bytes = Encoding.UTF8.GetBytes((string)value);\n string slice = string.Join(\"\", bytes.Select(b => b.ToString(\"X2\"))).PadLeft(Length, '0');\n return SetSlice(hasciiFormat, slice);\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> // Usage: Writing\n string defaultData = \"0000000000000000000000000000000000000000000000000000000000000000000000\";\n PD0Format defaultRecord = new PD0Format(defaultData);\n</code></pre>\n</blockquote>\n\n<p>It is very error prone to let the client provide a \"zero-string\" this way. Why not provide a default constructor: </p>\n\n<pre><code>public PD0Format()\n{\n _hasciiData = \"0000000000000000000000000000000000000000000000000000000000000000000000\";\n}\n</code></pre>\n\n<p>that sets the neutral <code>_hasciiData</code> value. </p>\n\n<hr>\n\n<p>Regarding the overall design of <code>PD0Format</code>, I don't like the <code>ByteSpecification</code> and <code>CastOperation</code> fields, because you have to address them via the <code>switch</code> statement.</p>\n\n<p>Instead I would make a dictionary, so it would be possible to write the indexer as:</p>\n\n<pre><code>public dynamic this[string category, string fieldName]\n{\n get\n {\n // TODO: check the input values for null and existence if default behavior of Dictionary<> isn't enough. \n return categories[category.ToLower()][fieldName.ToLower()].Extract(_hasciiData);\n }\n set\n {\n categories[category.ToLower()][fieldName.ToLower()].Insert(ref _hasciiData, value);\n }\n}\n</code></pre>\n\n<p><code>categories</code> is then defined as:</p>\n\n<pre><code>static Dictionary<string, Dictionary<string, PD0Entry>> categories;\n\nstatic PD0Format()\n{\n categories = new Dictionary<string, Dictionary<string, PD0Entry>>\n {\n { \"date\", new Dictionary<string, PD0Entry>\n {\n { \"year\", new PD0IntEntry(0, 2) },\n { \"month\", new PD0IntEntry(2, 1) },\n { \"day\", new PD0IntEntry(3, 1) },\n }\n },\n { \"constants\", new Dictionary<string, PD0Entry>\n {\n { \"pi\", new PD0FloatEntry(4, 4) },\n { \"eulersnumber\", new PD0FloatEntry(8, 4) },\n }\n },\n { \"secrets\", new Dictionary<string, PD0Entry>\n {\n { \"secretvalue\", new PD0IntEntry(12, 4) },\n { \"secretmessage\", new PD0StringEntry(16, 11) },\n { \"bigint\", new PD0LongEntry(27, 8) },\n }\n },\n };\n}\n</code></pre>\n\n<p>where <code>PD0Entry</code> is an abstract base class for classes that can handle sections of <code>int</code>, <code>float</code>, <code>long</code> and <code>string</code>:</p>\n\n<pre><code> abstract class PD0Entry\n {\n public PD0Entry(int start, int length)\n {\n Start = start * 2;\n Length = length * 2;\n }\n\n public int Start { get; }\n public int Length { get; }\n\n protected string GetSlice(string hasciiFormat) => hasciiFormat.Substring(Start, Length);\n protected string SetSlice(string hasciiFormat, string slice)\n {\n string prefix = hasciiFormat.Substring(0, Start);\n string postfix = hasciiFormat.Substring(Start + Length);\n return $\"{prefix}{slice}{postfix}\";\n }\n\n public abstract void Insert(ref string hasciiFormat, object value);\n public abstract object Extract(string hasciiFormat);\n }\n</code></pre>\n\n<p>The definition of this could be different - for instance after thinking about it, I don't like the definition of <code>Insert(...)</code> because of the <code>ref string..</code> argument...</p>\n\n<p><code>PD0IntEntry</code> as an example could then be defined as: </p>\n\n<pre><code> class PD0IntEntry : PD0Entry\n {\n public PD0IntEntry(int start, int length) : base(start, length)\n {\n }\n\n public override object Extract(string hasciiFormat)\n {\n string slice = GetSlice(hasciiFormat);\n return Convert.ToInt32(slice, 16);\n }\n\n public override void Insert(ref string hasciiFormat, object value)\n {\n hasciiFormat = SetSlice(hasciiFormat, ((int)value).ToString($\"X{Length}\"));\n }\n }\n</code></pre>\n\n<p>In this way it is easy to add/remove sections/entries to/from the categories because you'll only have to change the <code>categories</code> dictionary.</p>\n\n<p>Besides that, the responsibility is clear and separated.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T17:14:37.233",
"Id": "448404",
"Score": "1",
"body": "`... you could just make the \"cast\" after the switch.` Great suggestion - Implemented! `I would use method to extract the value ...` the call stack increases if we use method extraction. `get{}` would call a method that switch on a category name and do what is done here. There isn't anything else that needs to be done except return the byte field value so I chose to keep the call stack flat. `you probably mean throw new ArgumentException() rather than returning it?` Yes! Thanks for catching that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T17:14:58.270",
"Id": "448405",
"Score": "1",
"body": "`Why do you choose a one based indexing?` The binary specification I'm working with described byte field offsets using this convention and so I did this to maintain consistency."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T17:15:17.503",
"Id": "448406",
"Score": "1",
"body": "`Some of your conversions could be made a little more intuitively: HexToString()` Converting to byte[] and letting `Encoding.UTF8.GetString` do the conversion offers more flexibility, shortens code. Accepted!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T17:15:31.973",
"Id": "448407",
"Score": "1",
"body": "`Some of your conversions could be made a little more intuitively: StringToHex()` I like it. I've never used `Encoding.UTF8` API but will look into it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T17:15:48.687",
"Id": "448408",
"Score": "1",
"body": "`It is very error prone to let the client provide a \"zero-string\" this way. Why not provide a default constructor.` Great suggestion. Some features of the constructor need to be added here to allow the user to initialize byte fields from other `PD0Format` objects."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T17:17:18.823",
"Id": "448409",
"Score": "1",
"body": "`Regarding the overall design of PD0Format, I don't like the ByteSpecification and CastOperation fields, because you have to address them via the switch statement.` Great suggestion. I will simmer on this, try it out, and follow up with an answer featuring those suggested changes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T05:08:57.963",
"Id": "448619",
"Score": "1",
"body": "`The definition of this could be different - for instance after thinking about it, I don't like the definition of Insert(...) because of the ref string.. argument.` It makes sense for `categories` to be *static* since the binary specification does not change between instantiations of `PD0Format`. A consequence I didn't anticipate that you saw was not being able to pass `PD0Format._hasciiData` to `PD0Entry` constructors (you can't use field-initializers in static context)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T06:28:52.037",
"Id": "448623",
"Score": "1",
"body": "In `HexToString`, why use a `byte[]` at all instead of the natural `char[]`, avoiding any encoding issues?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T06:53:36.420",
"Id": "448624",
"Score": "0",
"body": "@RolandIllig: Good point. You can do that - that must be the same as using `Encoding.Default`."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T12:10:24.927",
"Id": "230263",
"ParentId": "230116",
"Score": "7"
}
},
{
"body": "<p>Implemented Henrik Hansen's suggested edits:</p>\n\n<ul>\n<li>Removed <code>goto</code> statements in <code>switch</code> statements of indexer</li>\n<li><code>HexToString()</code> now uses <code>Encoding.UTF.GetString()</code> to convert hex to strings</li>\n<li><code>StringToHex()</code> now uses LINQ <code>.SELECT(...)</code> to convert bytes of <code>byte[]</code> to string </li>\n<li>Added default constructor to initialize <code>_hasciiData</code> to string of 70 empty zeros</li>\n</ul>\n\n<p>Structural changes to come. </p>\n\n<h2>Code</h2>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.Linq;\nusing System.Text;\n\nusing ByteSpecification = System.Collections.Generic.Dictionary<string, (int, int)>;\nusing CastOperation = System.Collections.Generic.Dictionary<string, System.Func<string, object>>;\n\nnamespace ByteParsing\n{\n public class HasciiParser\n {\n public static string HexToString(string hascii)\n {\n byte[] bytes = new byte[hascii.Length / 2];\n for (int i = 0; i < hascii.Length; i += 2)\n {\n bytes[i / 2] = byte.Parse(hascii.Substring(i, 2), NumberStyles.HexNumber);\n }\n return Encoding.UTF8.GetString(bytes); // Or use Encoding.Default\n }\n\n public static string StringToHex(string str, int maxWidth)\n {\n byte[] bytes = Encoding.UTF8.GetBytes(str);\n return string.Join(\"\", bytes.Select(b => b.ToString(\"X2\"))).PadLeft(maxWidth, '0');\n }\n\n public DateTime HexToDatetime(string hascii)\n {\n int year = Convert.ToInt32(hascii.Substring(0, 4), 16);\n int month = Convert.ToInt32(hascii.Substring(4, 2), 16);\n int day = Convert.ToInt32(hascii.Substring(6, 2), 16);\n return new DateTime(year, month, day);\n }\n\n public static float HexToFloat(string hascii)\n {\n // https://stackoverflow.com/a/7903300/3396951\n uint num = uint.Parse(hascii, System.Globalization.NumberStyles.AllowHexSpecifier);\n byte[] floatVals = BitConverter.GetBytes(num);\n return BitConverter.ToSingle(floatVals, 0);\n }\n }\n\n public class PD0Format\n {\n public string _hasciiData; // Normally private\n\n public PD0Format()\n {\n _hasciiData = \"0000000000000000000000000000000000000000000000000000000000000000000000\";\n }\n\n public PD0Format(string hasciiData)\n {\n _hasciiData = hasciiData;\n }\n\n protected CastOperation castop = new CastOperation()\n {\n {\"Year\", (hascii_str) => Convert.ToInt32(hascii_str, 16)},\n {\"Month\", (hascii_str) => Convert.ToInt32(hascii_str, 16)},\n {\"Day\", (hascii_str) => Convert.ToInt32(hascii_str, 16)},\n {\"Pi\", (hascii_str) => HasciiParser.HexToFloat(hascii_str)},\n {\"EulersNumber\", (hascii_str) => HasciiParser.HexToFloat(hascii_str)},\n {\"SecretValue\", (hascii_str) => Convert.ToInt32(hascii_str, 16)},\n {\"SecretMessage\", (hascii_str) => HasciiParser.HexToString(hascii_str)},\n {\"BigInt\", (hascii_str) => Convert.ToInt64(hascii_str, 16)}\n };\n\n protected ByteSpecification dateSpec = new ByteSpecification()\n {\n {\"Year\", (1, 2)},\n {\"Month\", (3, 1)},\n {\"Day\", (4, 1)},\n };\n\n protected ByteSpecification mathConstantsSpec = new ByteSpecification()\n {\n {\"Pi\", (5, 4)},\n {\"EulersNumber\", (9, 4)}\n };\n\n protected ByteSpecification secretsSpec = new ByteSpecification()\n {\n {\"SecretValue\", (13, 4)},\n {\"SecretMessage\", (17, 11)},\n {\"BigInt\", (28, 8)}\n };\n\n private string GetHasciiBytes(ByteSpecification byteSpec, string fieldName)\n {\n // ByteSpecification assumes base-1 indexing. Substring requires base-0 indexing so we must subtract 2 (reason below).\n // Because there are two hex characters to a byte, we have to multiply the startIndex of string.Substring\n // by 2. To get to the startIndex of a byte, we must substract by multiples of 2.\n // Item2 of ByteSpecification's dictionary value represents the number of bytes. Since two hex characters represent\n // a byte, the number of characters to extract using string.Substring is Item2 * 2\n return _hasciiData.Substring(byteSpec[fieldName].Item1 * 2 - 2, byteSpec[fieldName].Item2 * 2);\n }\n\n public dynamic this[string category, string fieldName]\n {\n get\n {\n ByteSpecification spec = null;\n switch (category.ToLower())\n {\n case \"date\":\n spec = dateSpec;\n break;\n case \"constants\":\n spec = mathConstantsSpec;\n break;\n case \"secrets\":\n spec = secretsSpec;\n break;\n default:\n throw new ArgumentException($\"Unimplemented specification category `{category}`\");\n }\n string hasciiBytes = GetHasciiBytes(spec, fieldName); // Retrieve bytes from underlying string\n return castop[fieldName](hasciiBytes); // Cast to appropriate type, according to mapping defined in CastOperation\n }\n\n set\n {\n switch (category.ToLower())\n {\n case \"secrets\":\n int insertLocation = secretsSpec[fieldName].Item1 * 2 - 2;\n int maxCharFieldWidth = secretsSpec[fieldName].Item2 * 2; // Used for padding when the number of hex chars isn't even\n string val = null;\n switch (fieldName)\n {\n case \"SecretValue\":\n val = String.Format(\"{0:X}\", value).PadLeft(maxCharFieldWidth, '0'); // Convert value to hascii representation\n break;\n case \"SecretMessage\":\n val = HasciiParser.StringToHex(value, maxCharFieldWidth);\n break;\n case \"BigInt\":\n val = String.Format(\"{0:X}\", value).PadLeft(maxCharFieldWidth, '0');\n break;\n }\n _hasciiData = _hasciiData.Remove(insertLocation, maxCharFieldWidth); // Remove the characters currently present\n _hasciiData = _hasciiData.Insert(insertLocation, val ?? throw new InvalidOperationException());\n Debug.WriteLine(_hasciiData);\n break;\n case \"date\":\n throw new NotImplementedException();\n case \"constants\":\n throw new NotImplementedException();\n }\n }\n }\n }\n\n class Program\n {\n static void Main(string[] args)\n {\n /*\n string _year = \"07E3\"; // 2019 16-bit int, 0x07E3\n string _month = \"0A\"; // 10 8-bit int, 0x0A\n string _day = \"02\"; // 2 8-bit int, 0x02\n string _pi = \"40490FD8\"; // IEEE-754 Single Precision Float, 0x4049 0FD8\n string _eulers = \"402DF854\"; // IEEE-754 Single Precision Float, 0x402D F854\n string _secretValue = \"80000000\"; // 32-bit int, 0x80000000 (Decimal -2147483648)\n string _secretMsg = \"48656C6C6F576F726C6421\"; // ASCII string \"HelloWorld!\", 0x48656C6C6F576F726C6421 \n string _bigInt = \"8000000000000000\"; // 64-bit int, 0x8000 0000 0000 0000 (Decimal -9223372036854775808)\n */\n\n string hasciiData = \"07E30A0240490FD8402df8548000000048656C6C6F576F726C64218000000000000000\";\n\n PD0Format ensemble = new PD0Format(hasciiData);\n\n int recordYear = ensemble[\"date\", \"Year\"];\n int recordMonth = ensemble[\"date\", \"Month\"];\n int recordDay = ensemble[\"date\", \"Day\"];\n Debug.WriteLine(new DateTime(recordYear, recordMonth, recordDay));\n\n float Pi = ensemble[\"constants\", \"Pi\"];\n float exp1 = ensemble[\"Constants\", \"EulersNumber\"];\n Debug.WriteLine($\"Pi: {Pi}\\nEuler's Number: {exp1}\");\n\n int secretValue = ensemble[\"secrets\", \"SecretValue\"];\n string secretMsg = ensemble[\"secrets\", \"SecretMessage\"];\n long bigInt = ensemble[\"secrets\", \"BigInt\"];\n Debug.WriteLine($\"Secret Value: {secretValue}\\nSecret Msg: {secretMsg}\\nbigInt: {bigInt}\");\n\n // Usage: Writing\n PD0Format defaultRecord = new PD0Format();\n\n // 35791394 corresponds to 0x02222222 written as \"02222222\" in hascii\n defaultRecord[\"secrets\", \"SecretValue\"] = 35791394;\n // \"FooBarBaz\" corresponds to 0x00 0046 6F6F 4261 7242 617A written as \"0000466F6F42617242617A\" in hascii\n defaultRecord[\"secrets\", \"SecretMessage\"] = \"FooBarBaz\";\n // 1229782938247303441 corresponds to 0x1111 1111 1111 1111 written as \"1111111111111111\" in hascii\n defaultRecord[\"secrets\", \"BigInt\"] = 1229782938247303441;\n\n // Original defaultData: \"0000000000000000000000000000000000000000000000000000000000000000000000\"\n // Modified defaultData: \"000000000000000000000000022222220000466F6F42617242617A1111111111111111\"\n Debug.WriteLine(defaultRecord._hasciiData);\n\n Console.ReadLine(); // Prevent console from closing\n }\n }\n}\n</code></pre>\n\n<h2>Output</h2>\n\n<pre><code>10/2/2019 00:00:00\nPi: 3.141592\nEuler's Number: 2.718282\nSecret Value: -2147483648\nSecret Msg: HelloWorld!\nbigInt: -9223372036854775808\n0000000000000000000000000222222200000000000000000000000000000000000000\n000000000000000000000000022222220000466F6F42617242617A0000000000000000\n000000000000000000000000022222220000466F6F42617242617A1111111111111111\n000000000000000000000000022222220000466F6F42617242617A1111111111111111\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T16:09:44.770",
"Id": "230319",
"ParentId": "230116",
"Score": "4"
}
},
{
"body": "<p>Implemented Henrik Hansen's suggested edits:</p>\n\n<ul>\n<li><p>Define an abstract class, <code>PD0Bytefield</code>, to encapsulate how byte fields are specified (<code>PD0Bytefield.StartHexDigitIndex</code> and <code>PD0Bytefield.HexDigitLength</code>) with abstract methods to specify how they should be casted when read from (<code>PD0Bytefield.Extract()</code>) and how they should be written to the underlying string (<code>PD0Bytefield.Insert()</code>). </p>\n\n<p>This allows the indexer of <code>PD0Format</code> to defer implementation details to concrete implementations of <code>PD0Bytefield</code> (namely <code>PD0IntBytefield</code>, <code>PD0FloatBytefield</code>, <code>PD0StringBytefield</code>, <code>PD0LongBytefield</code>). This also makes <code>castop</code> obsolete — which is desirable since the current implementation requires matching keys in both <code>castop</code> and all <code>ByteSpecification</code> dictionaries, which is hard to maintain as the number of keys increases.</p></li>\n<li><p>Define a single dictionary, <code>PD0Format.Categories</code>, to map byte field names to concrete implementations of <code>PD0Bytefield</code>. Because the binary specification doesn't change between instantiations of <code>PD0Format</code>, this dictionary should be made <em><a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members#static-members\" rel=\"nofollow noreferrer\">static</a></em>. </p>\n\n<p>Because <code>PD0Format._hasciiData</code> is not a static field, it can't be used in a static context (i.e., we can't pass <code>PD0Format._hasciiData</code> to concrete classes of <code>PD0Bytefields</code> when they're initialized by <code>Categories</code>'s dictionary initializer). This forces us to pass <code>PD0Format._hasciiData</code>, an instance variable, to the abstract methods of <code>PD0Bytefield</code> <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref#passing-an-argument-by-reference\" rel=\"nofollow noreferrer\">by reference</a>. </p></li>\n</ul>\n\n<h2>Code</h2>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.Linq;\nusing System.Text;\n\nusing ByteSpecification = System.Collections.Generic.Dictionary<string, System.Collections.Generic.Dictionary<string, ByteParsing.Bytefield>>;\n\nnamespace ByteParsing\n{\n public class HasciiParser\n {\n public static int GetByteSize(string hascii)\n {\n return (int)Math.Ceiling(hascii.Length / 2.0);\n }\n\n public static string HexToString(string hascii)\n {\n byte[] bytes = new byte[hascii.Length / 2];\n for (int i = 0; i < hascii.Length; i += 2)\n {\n bytes[i / 2] = byte.Parse(hascii.Substring(i, 2), NumberStyles.HexNumber);\n }\n\n return Encoding.UTF8.GetString(bytes); // Or use Encoding.Default\n }\n\n public static string StringToHex(string str, int maxWidth)\n {\n byte[] bytes = Encoding.UTF8.GetBytes(str);\n return string.Join(\"\", bytes.Select(b => b.ToString(\"X2\"))).PadLeft(maxWidth, '0');\n }\n\n public DateTime HexToDatetime(string hascii)\n {\n int year = Convert.ToInt32(hascii.Substring(0, 4), 16);\n int month = Convert.ToInt32(hascii.Substring(4, 2), 16);\n int day = Convert.ToInt32(hascii.Substring(6, 2), 16);\n return new DateTime(year, month, day);\n }\n\n public static float HexToFloat(string hascii)\n {\n // https://stackoverflow.com/a/7903300/3396951\n uint num = uint.Parse(hascii, System.Globalization.NumberStyles.AllowHexSpecifier);\n byte[] floatVals = BitConverter.GetBytes(num);\n return BitConverter.ToSingle(floatVals, 0);\n }\n }\n\n public abstract class Bytefield\n {\n protected int StartHexDigitIndex { get; }\n protected int HexDigitLength { get; }\n public string BytefieldDescription { get; set; }\n public int ByteStart => (StartHexDigitIndex / 2) + 1;\n public int ByteLength => HexDigitLength / 2;\n\n protected Bytefield(int byteStartIndex, int byteLength)\n {\n // User provides startIndex, which follows base-1 indexing (to be consistent with convention used in binary specification)\n // but this constructor converts index to base-0. Indexing, here, refers to the indexing of hex digits (there are 2 hex-digits to a byte)\n // and NOT the indexing of bytes. \n StartHexDigitIndex = (byteStartIndex - 1) * 2;\n HexDigitLength = byteLength * 2;\n }\n\n protected Bytefield(int byteStartIndex, int byteLength, string bytefieldDescription) \n : this(byteStartIndex, byteLength)\n {\n BytefieldDescription = bytefieldDescription;\n }\n\n protected string GetBytes(ref string bytefieldData) => bytefieldData.Substring(StartHexDigitIndex, HexDigitLength);\n\n protected void SetBytes(ref string bytefieldData, string hexval)\n {\n // If the number of bytes occupied by the assigned value is greater than the byte length specfication of the bytefield,\n // ArgumentException will be thrown.\n if (HasciiParser.GetByteSize(hexval) != ByteLength)\n throw new ArgumentException($\"Bytefield length is {ByteLength} bytes. Tried to assign {HasciiParser.GetByteSize(hexval)} bytes.\");\n\n string prefix = bytefieldData.Substring(0, StartHexDigitIndex);\n string postfix = bytefieldData.Substring(StartHexDigitIndex + HexDigitLength);\n bytefieldData = $\"{prefix}{hexval}{postfix}\"; // Potentially inefficient for large number of SetBytes()\n }\n\n public abstract void Insert(ref string bytefieldData, object value);\n public abstract object Extract(ref string bytefieldData);\n }\n\n public class UInt16Bytefield : Bytefield\n {\n public UInt16Bytefield(int byteStartIndex, int byteLength) : base(byteStartIndex, byteLength)\n {\n }\n\n public UInt16Bytefield(int byteStartIndex, int byteLength, string bytefieldDescription) \n : base(byteStartIndex, byteLength, bytefieldDescription)\n {\n }\n\n public override void Insert(ref string bytefieldData, object value) =>\n SetBytes(ref bytefieldData, ((UInt16) value).ToString($\"X{HexDigitLength}\"));\n\n public override object Extract(ref string bytefieldData) => Convert.ToUInt16(GetBytes(ref bytefieldData), 16);\n }\n\n public class Int32Bytefield : Bytefield\n {\n public Int32Bytefield(int byteStartIndex, int byteLength) : base(byteStartIndex, byteLength)\n {\n }\n\n public Int32Bytefield(int byteStartIndex, int byteLength, string bytefieldDescription)\n : base(byteStartIndex, byteLength, bytefieldDescription)\n {\n }\n\n public override void Insert(ref string bytefieldData, object value) =>\n SetBytes(ref bytefieldData, ((Int32)(value)).ToString($\"X{HexDigitLength}\"));\n\n public override object Extract(ref string bytefieldData) =>\n Convert.ToInt32(GetBytes(ref bytefieldData), 16);\n }\n\n public class FloatBytefield : Bytefield\n {\n public FloatBytefield(int byteStartIndex, int byteLength) : base(byteStartIndex, byteLength)\n {\n }\n\n public FloatBytefield(int byteStartIndex, int byteLength, string bytefieldDescription) \n : base(byteStartIndex, byteLength, bytefieldDescription)\n {\n }\n\n public override void Insert(ref string bytefieldData, object value) => SetBytes(ref bytefieldData, ((Single) value).ToString($\"X{HexDigitLength}\"));\n public override object Extract(ref string bytefieldData) => HasciiParser.HexToFloat(GetBytes(ref bytefieldData));\n }\n\n public class StringBytefield : Bytefield\n {\n public StringBytefield(int byteStartIndex, int byteLength) : base(byteStartIndex, byteLength)\n {\n }\n\n public StringBytefield(int byteStartIndex, int byteLength, string bytefieldDescription)\n : base(byteStartIndex, byteLength, bytefieldDescription)\n {\n\n }\n\n public override void Insert(ref string bytefieldData, object value) => SetBytes(ref bytefieldData, HasciiParser.StringToHex((string) value, HexDigitLength));\n public override object Extract(ref string bytefieldData) => HasciiParser.HexToString(GetBytes(ref bytefieldData));\n }\n\n public class ULongBytefield : Bytefield\n {\n public ULongBytefield(int byteStartIndex, int byteLength) : base(byteStartIndex, byteLength)\n {\n }\n\n public ULongBytefield(int byteStartIndex, int byteLength, string bytefieldDescription) \n : base(byteStartIndex, byteLength, bytefieldDescription)\n {\n }\n\n public override void Insert(ref string bytefieldData, object value) => SetBytes(ref bytefieldData, ((UInt64) value).ToString($\"X{HexDigitLength}\"));\n public override object Extract(ref string bytefieldData) => Convert.ToUInt64(GetBytes(ref bytefieldData), 16);\n }\n\n public class PD0Format\n {\n private string _hasciiData;\n\n public string HasciiData\n {\n get => _hasciiData;\n set => _hasciiData = value;\n }\n\n public ByteSpecification ByteSpec { get; set; }\n\n public PD0Format()\n {\n HasciiData = new String('0', 70); // binary specification contains 280 bits/35 bytes, which is 70 hex digits\n ByteSpec = InitializeByteSpecification();\n }\n\n public PD0Format(string hasciiData)\n {\n _hasciiData = hasciiData;\n ByteSpec = InitializeByteSpecification();\n }\n\n protected ByteSpecification InitializeByteSpecification()\n {\n return new ByteSpecification()\n {\n {\n \"date\", new Dictionary<string, Bytefield>()\n {\n {\"year\", new UInt16Bytefield(1, 2, \"Today's four digit-year.\")},\n {\"month\", new UInt16Bytefield(3, 1, \"Today's four digit-month.\")},\n {\"day\", new UInt16Bytefield(4, 1, \"Today's four digit-day.\")},\n }\n },\n {\n \"constants\", new Dictionary<string, Bytefield>()\n {\n {\"mathconstant\", new FloatBytefield(5, 4, \"\")},\n {\"physicsconstant\", new FloatBytefield(9, 4, null)},\n }\n },\n {\n \"secrets\", new Dictionary<string, Bytefield>()\n {\n {\"secretvalue\", new Int32Bytefield(13, 4, \"Keep this value a secret.\")},\n {\"secretmessage\", new StringBytefield(17, 11, \"Keep this message a secret\")},\n {\"bigint\", new ULongBytefield(28, 8, HasciiData)},\n }\n }\n };\n }\n\n public dynamic this[string category, string fieldname]\n {\n get => ByteSpec[category.ToLower()][fieldname.ToLower()].Extract(ref _hasciiData);\n set => ByteSpec[category.ToLower()][fieldname.ToLower()].Insert(ref _hasciiData, value);\n }\n }\n\n class Program\n {\n static void Main(string[] args)\n { }\n }\n}\n</code></pre>\n\n<h2>Unit Test</h2>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\nusing ByteParsing;\n\nusing TestHexData = System.Collections.Generic.Dictionary<string, string>;\n\nnamespace ByteParsingTests\n{\n [TestClass]\n public class ByteParsingTests\n {\n public static readonly TestHexData hexdata = new TestHexData()\n {\n // string _year = \"07E3\"; // 2019, 16-bit int\n // string _month = \"0A\"; // 10, 8-bit int\n // string _day = \"02\"; // 2, 8-bit int\n // string _pi = \"40490FD8\"; // 3.141592, IEEE-754 Single Precision Float\n // string _eulers = \"402DF854\"; // 2.71828175, IEEE-754 Single Precision Float\n // string _secretValue = \"80000000\"; // Decimal -2147483648, 32-bit int\n // string _secretMsg = \"48656C6C6F576F726C6421\"; // ASCII string \"HelloWorld!\"\n // string _bigInt = \"8000000000000000\"; // Decimal 9223372036854775808, 64-bit long (uint64)\n {\"PiEuler\", \"07E30A0240490FD8402df8548000000048656C6C6F576F726C64218000000000000000\"},\n // string _year = \"07E3\"; // 2019, 16-bit int\n // string _month = \"0A\"; // 10, 8-bit int\n // string _day = \"09\"; // 9, 8-bit int\n // string _tau = \"40C90E56\"; // 6.282999, IEEE-754 Single Precision Float\n // string _speedOfLight = \"4F32D05E\"; // 3E9, IEEE-754 Single Precision Float\n // string _secretValue = \"11111111\"; // 286331153, 32-bit int\n // string _secretMsg = \"42697A7A7942757A7A2121\"; // ASCII string \"BizzyBuzz!!\"\n // string _bigInt = \"2222222222222222\"; // 2459565876494606882, 64-bit long (uint64)\n {\"TauSpeedOfLight\", \"07E30A0940C90E564F32D05E1111111142697A7A7942757A7A21212222222222222222\"},\n // string _year = \"07E3\"; // 2019, 16-bit int\n // string _month = \"0A\"; // 10, 8-bit int\n // string _day = \"0A\"; // 10, 8-bit int\n // string _root2 = \"3FB504D5\"; // 1.4142099, IEEE-754 Single Precision Float\n // string _electronCharge = \"203D217B\"; // 1.602E-19, IEEE-754 Single Precision Float\n // string _secretValue = \"33333333\"; // 858993459, 32-bit int\n // string _secretMsg = \"4F6365616E466C6F6F7221\"; // ASCII string \"OceanFloor!\"\n // string _bigInt = \"4444444444444444\"; // 4919131752989213764, 64-bit long (uint64)\n {\"root2Charge\", \"07E30A0A3FB504D5203D217B333333334F6365616E466C6F6F72214444444444444444\" }\n };\n\n public static bool NearlyEqual(float a, float b, float epsilon)\n {\n return NearlyEqual((double) a, (double) b, (double) epsilon);\n }\n\n public static bool NearlyEqual(double a, double b, double epsilon)\n {\n // Michael Borgwardt, https://stackoverflow.com/a/3875619/3396951\n const double MinNormal = 2.2250738585072014E-308d;\n double absA = Math.Abs(a);\n double absB = Math.Abs(b);\n double diff = Math.Abs(a - b);\n\n if (a.Equals(b))\n { // shortcut, handles infinities\n return true;\n }\n else if (a == 0 || b == 0 || absA + absB < MinNormal)\n {\n // a or b is zero or both are extremely close to it\n // relative error is less meaningful here\n return diff < (epsilon * MinNormal);\n }\n else\n { // use relative error\n return diff / (absA + absB) < epsilon;\n }\n }\n\n [TestMethod, TestCategory(\"ExceptionalCases\")]\n [ExpectedException(typeof(InvalidCastException))]\n public void IndexerAssignment_Int16Value_ThrowsInvalidCastException()\n {\n PD0Format record = new PD0Format(hexdata[\"PiEuler\"]);\n Assert.AreEqual((UInt16)2019, record[\"date\", \"year\"]);\n record[\"date\", \"year\"] = (Int16)2020; // Should be casted to (UInt16)\n }\n\n [TestMethod, TestCategory(\"ExceptionalCases\")]\n [ExpectedException(typeof(ArgumentException))]\n public void IndexerAssignment_UInt16Value_ThrowsInvalidCastException()\n {\n PD0Format record = new PD0Format(hexdata[\"PiEuler\"]);\n\n // This should be ok. 255 isn't a valid month but what determines whether a value can be \n // assigned is the range of values the underlying data type can store (0 - 2^16-1, in this case)\n // and the byte specification. If the number of bytes occupied by the assigned value is greater\n // than the byte length specfication of the bytefield, ArgumentException should be thrown.\n record[\"date\", \"month\"] = (UInt16) 0xFF;\n Assert.AreEqual((UInt16)255, record[\"date\", \"month\"]);\n\n // Values greater than 255 (0xFF) should throw ArgumentException. This is because the \"month\"\n // specification is defined to be one byte long. The underlying data type (UInt16, see PD0Format.ByteSpec)\n // can hold unsigned values that fit within two bytes but the assigned value occupies more bytes than \n // defined by the specification.\n record[\"date\", \"month\"] = (UInt16) 0x0100;\n }\n\n [TestMethod, TestCategory(\"TypicalUseCase\")]\n public void IndexerAssignment_UInt16MaxValue_SetsCorrectHexbytes()\n {\n PD0Format record = new PD0Format(hexdata[\"PiEuler\"]);\n\n record[\"date\", \"year\"] = (UInt16) 65535; // 0xFFFF\n Assert.AreEqual((UInt16)65535, record[\"date\", \"year\"]);\n Assert.AreEqual(\"FFFF\", record[\"date\", \"year\"].ToString(\"X4\"));\n }\n\n [TestMethod, TestCategory(\"TypicalUseCase\")]\n [DataRow(\"PiEuler\", (UInt16)2019, (UInt16)10, (UInt16)2, 3.141592F, 2.71828175F, (Int32)(-2147483648), \"HelloWorld!\", (UInt64)9223372036854775808)]\n [DataRow(\"TauSpeedOfLight\", (UInt16)2019, (UInt16)10, (UInt16)9, 6.282999F, 3000000000F, (Int32)(286331153), \"BizzyBuzz!!\", (UInt64)2459565876494606882)]\n [DataRow(\"root2Charge\", (UInt16)2019, (UInt16)10, (UInt16)10, 1.4142099F, 1.602000046096E-19F, (Int32)(858993459), \"OceanFloor!\", (UInt64)4919131752989213764)]\n public void IndexerAccess_ReturnsCorrectTypesAndValues(string hexdataField, UInt16 year, UInt16 month, UInt16 day, \n float mathConstant, float physicsConstants, Int32 secretValue, string secretMessage, ulong bigint)\n {\n var record = new PD0Format(hexdata[hexdataField]);\n Assert.AreEqual(year, record[\"date\", \"year\"]);\n Assert.AreEqual(month, record[\"date\", \"month\"]);\n Assert.AreEqual(day, record[\"date\", \"day\"]);\n Assert.IsTrue(NearlyEqual(mathConstant, record[\"constants\",\"mathconstant\"], .0000001));\n Assert.IsTrue(NearlyEqual(physicsConstants, record[\"constants\", \"physicsconstant\"], .0000001));\n Assert.AreEqual(secretValue, record[\"secrets\",\"secretvalue\"]);\n Assert.AreEqual(secretMessage, record[\"secrets\", \"secretmessage\"]);\n Assert.AreEqual(bigint, record[\"secrets\", \"bigint\"]);\n }\n\n [TestMethod, TestCategory(\"TypicalUseCase\")]\n public void IndexerAssignment_secretsCategory_SetsCorrectHexbytes()\n {\n PD0Format defaultRecord = new PD0Format();\n\n Assert.AreEqual(\"0000000000000000000000000000000000000000000000000000000000000000000000\", defaultRecord.HasciiData);\n\n // 35791394 = 0x02222222 = \"02222222\"\n // \"FooBarBaz\" = 0x0000466F6F42617242617A = \"0000466F6F42617242617A\"\n // 1229782938247303441 = 0x1111111111111111 = \"1111111111111111\"\n defaultRecord[\"secrets\", \"secretvalue\"] = (Int32) 35791394;\n defaultRecord[\"secrets\", \"secretmessage\"] = \"FooBarBaz\";\n defaultRecord[\"secrets\", \"bigint\"] = (UInt64)1229782938247303441;\n\n Assert.AreEqual(\"000000000000000000000000022222220000466F6F42617242617A1111111111111111\", defaultRecord.HasciiData);\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T06:17:01.643",
"Id": "230357",
"ParentId": "230116",
"Score": "1"
}
},
{
"body": "<p>What about a simpler approach?</p>\n\n<pre><code>public class PD0Format\n{\n public static PD0Format Empty => new PD0Format(new byte[35]);\n public static PD0Format Parse(string text) =>\n new PD0Format(Enumerable\n .Range(0, text.Length / 2)\n .Select(i => Convert.ToByte(text.Substring(i * 2, 2), 16))\n .ToArray());\n\n PD0Format(byte[] array)\n {\n Stream = new MemoryStream(array);\n Reader = new BinaryReader(Stream);\n Writer = new BinaryWriter(Stream);\n }\n\n MemoryStream Stream { get; }\n BinaryReader Reader { get; }\n BinaryWriter Writer { get; }\n\n public override string ToString() =>\n BitConverter.ToString(Stream.ToArray()).Replace(\"-\", \"\");\n\n public DateTime Date\n {\n get\n {\n Stream.Position = 0;\n return new DateTime(\n Reader.ReadInt32(), \n Reader.ReadInt32(), \n Reader.ReadInt32());\n }\n set\n {\n Stream.Position = 0;\n Writer.Write(value.Year);\n Writer.Write(value.Month);\n Writer.Write(value.Day);\n }\n }\n\n public float Pi\n {\n get\n {\n Stream.Position = 4;\n return Reader.ReadSingle();\n }\n set\n {\n Stream.Position = 4;\n Writer.Write(value);\n }\n }\n\n // etc...\n}\n</code></pre>\n\n<p>So you could extract <code>Pi</code> like this:</p>\n\n<pre><code>var pd0 = PD0Format.Parse(\"00000000D80F4940000000000000000000000000000000000000000000000000000000\");\nConsole.WriteLine(pd0.Pi); // 3.141592\n</code></pre>\n\n<p>or create a new packet in a way like this:</p>\n\n<pre><code>var pd0 = PD0Format.Empty;\npd0.Pi = 3.141592;\nConsole.WriteLine(pd0); // 00000000D80F4940000000000000000000000000000000000000000000000000000000\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T17:31:41.310",
"Id": "448707",
"Score": "1",
"body": "I'm afraid this solution, even if interesting, won't have many fans because it lacks explanation :-[ Could you `ToString` your thoughts? ;-P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T17:52:28.780",
"Id": "448709",
"Score": "1",
"body": "@t3chb0t I do believe that code is the best way to document design, and only bad code or bug requires text description. Here is the usage sample though, not sure if this is what you were looking for :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T17:56:50.970",
"Id": "448710",
"Score": "2",
"body": "In general I share your opinion, however, Code Review has slightly different rules concerning documentation and reviews. I mean that a casual reader might not see what we do and the reasoning is also not always obvious ;-]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T18:09:52.210",
"Id": "448713",
"Score": "1",
"body": "You get my unconditional upvote, but t3chb0t is right"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T20:11:35.930",
"Id": "448722",
"Score": "0",
"body": "I might need to associate each byte field name with a description of what the stored value represents (the binary specification is for sensor data output). `PD0Format` might be used by a GUI to display the byte field description in a tool-tip. The description itself will be a string."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T20:25:53.327",
"Id": "448723",
"Score": "0",
"body": "Storing the specifications in a data structure allows me to write them to a textfile, which I can then read in another programming language (Matlab, Python, C/C++) to recreate that data structure (I'd like to avoid IPC/serialization). This is to avoid having to spend time copy/pasting those descriptions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T20:31:06.323",
"Id": "448724",
"Score": "0",
"body": "All of this is to say that how I represent the specifications in memory also matters. It's time consuming to specify (there are many fields and we'd like to do that once and never have to do it again in any other language) and it is used not just for parsing hex strings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T20:32:38.440",
"Id": "448726",
"Score": "0",
"body": "@MinhTran I would make the `PD0Format` (a better name would be `PD0Packet`) to implement `IEnumerable<(string Name, object Value)>` to simplify View Model generation. It could also help to generate this class by Text Template (*.tt) from a json/xml spec, so you will have a strictly typed object which is a very recommended thing to have. Let me know if you interested to see `*.tt` file example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T20:57:40.520",
"Id": "448729",
"Score": "0",
"body": "`I would make the PD0Format (a better name would be PD0Packet) to implement IEnumerable<(string Name, object Value)>` this may be necessary in the future but is outside the scope of the problem statement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T21:02:52.253",
"Id": "448730",
"Score": "0",
"body": "@MinhTran This is just a way to deliver property labels. I would generate those tuples by using `LabelAttribute` on properties and reading `PropertyDescriptor`s. It will allow you to work in a type safe manner, which should definitely be a priority, while having all the features you need."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-08T17:02:07.027",
"Id": "230378",
"ParentId": "230116",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "230263",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T21:07:17.910",
"Id": "230116",
"Score": "7",
"Tags": [
"c#",
"object-oriented",
"parsing",
"formatting",
"converting"
],
"Title": "Code that reads/writes to bytes of an ascii-encoded hex string"
} | 230116 |
<p>The idea is to init garbage heap in the beginning of <code>main</code>, use <code>gmalloc</code>, <code>gcalloc</code> and <code>grealloc</code> wrappers and free all allocated memory in the end of main. It helps to avoid memory leaks when writing programs for ejudge systems. Would like to hear general feedback on the idea and advices on how to improve the code (beginner in C).</p>
<p><em>main.c</em></p>
<pre><code>/*
Example of usage of garbage heap.
No free() call but no memory leak.
*/
#include "garbage_heap.h"
int main() {
init_garbage_heap();
for (int i = 0; i < 1000; ++i)
{
char* str = gmalloc(1000*sizeof(char));
str = grealloc(str, 2000*sizeof(char));
}
free_garbage_heap();
return 0;
}
</code></pre>
<p><em>garbage_heap.h</em></p>
<pre><code>#ifndef GARBAGE_HEAP_H
#define GARBAGE_HEAP_H
#include <stddef.h>
void init_garbage_heap (void);
void free_garbage_heap (void);
void* gmalloc (size_t sizemem);
void* gcalloc (size_t number, size_t size);
void* grealloc (void* ptrmem, size_t sizemem);
#endif // GARBAGE_HEAP_H
</code></pre>
<p><em>garbage_heap.c</em></p>
<pre><code>#include <stdlib.h>
#include "garbage_heap.h"
typedef struct
{
void** buffer;
int len;
int capacity;
}
GarbageHeap;
static GarbageHeap garbage_heap;
void init_garbage_heap(void)
{
int len = 32;
garbage_heap.len = 0;
garbage_heap.capacity = len;
garbage_heap.buffer = (void**)malloc(sizeof(void*)*len);
for (int i = 0; i < len; ++i)
garbage_heap.buffer[i] = NULL;
}
void free_garbage_heap(void)
{
for (int i = 0; i < garbage_heap.len; ++i)
if (garbage_heap.buffer[i] != NULL)
free(garbage_heap.buffer[i]);
free(garbage_heap.buffer);
}
void resize_garbage_heap(void)
{
garbage_heap.capacity *= 2;
garbage_heap.buffer = (void**)realloc(garbage_heap.buffer, sizeof(void*) * garbage_heap.capacity);
for (int i = garbage_heap.len; i < garbage_heap.capacity; ++i)
garbage_heap.buffer[i] = NULL;
}
void* gmalloc(size_t sizemem)
{
if (garbage_heap.len == garbage_heap.capacity)
resize_garbage_heap();
garbage_heap.buffer[garbage_heap.len] = malloc(sizemem);
++garbage_heap.len;
return garbage_heap.buffer[garbage_heap.len - 1];
}
void* gcalloc(size_t number, size_t size)
{
if (garbage_heap.len == garbage_heap.capacity)
resize_garbage_heap();
garbage_heap.buffer[garbage_heap.len] = calloc(number, size);
++garbage_heap.len;
return garbage_heap.buffer[garbage_heap.len - 1];
}
void* grealloc(void* ptrmem, size_t sizemem)
{
if (ptrmem == NULL)
return gmalloc(sizemem);
int i = 0;
while (garbage_heap.buffer[i] != ptrmem)
++i;
void* tmp_ptr = realloc(ptrmem, sizemem);
if (tmp_ptr != NULL)
garbage_heap.buffer[i] = tmp_ptr;
return tmp_ptr;
}
</code></pre>
| [] | [
{
"body": "<p>Interesting concept, I'm going to guess that C is not your first programming language, and your first language did not require explicit memory management.</p>\n\n<p>The code is pretty good, but here are some things to consider:</p>\n\n<p><strong>A Good Programming Practice</strong><br>\nIn most of the <code>if</code> statements and loops the code in the question is hard to maintain because it doesn't provide complex statements for each path through the code. A complex statement is a code block encapsulated in the C language by <code>{</code> and <code>}</code>. </p>\n\n<p>An example of a complex statement is:\n {\n STATEMENT;\n STATEMENT;\n }</p>\n\n<p>An example of the code lacking this good programming practice is</p>\n\n<pre><code>void free_garbage_heap(void)\n{\n for (int i = 0; i < garbage_heap.len; ++i)\n if (garbage_heap.buffer[i] != NULL)\n free(garbage_heap.buffer[i]);\n free(garbage_heap.buffer);\n}\n</code></pre>\n\n<p>Let's say that someone maintaining the code has to add a statement to the <code>if</code> statement in the loop and they are looking to do it quickly or they come from a programming language that is positional rather than using braces to denote a complex statement. If they add it immediately below the <code>free(garbage_heap.buffer[i]);</code> without adding the braces, not only is the new statement not in the <code>if</code> statement, the new statement isn't even in the for loop. </p>\n\n<p>In languages such as C and C++ the following code is a safer programming practice:</p>\n\n<pre><code>void free_garbage_heap(void)\n{\n for (int i = 0; i < garbage_heap.len; ++i)\n {\n if (garbage_heap.buffer[i] != NULL)\n {\n free(garbage_heap.buffer[i]);\n }\n }\n free(garbage_heap.buffer);\n}\n</code></pre>\n\n<p>Where to add a new statement becomes much clearer.</p>\n\n<p><strong>Possible Improvements for the Function init_garbage_heap</strong><br>\nThe first thing to note in <code>init_garbage_heap()</code> is that there is no error checking after the call to <code>void* malloc(int number_of_bytes_to_allocate)</code>. The call to <code>malloc()</code> may fail, and if it does the value returned is <code>NULL</code>. If the code continues to process if <code>malloc()</code> returned an error, then there would be a memory access error in the for loop for <code>garbage_heap.buffer[i] = NULL;</code> that will probably cause the program to crash (exit improperly). In C++ if <code>new()</code> fails it throws an exception, the C programming language does not have exceptions so the test is required.</p>\n\n<p>The second thing to note in the following code is that the cast to <code>(void**)</code> is not necessary in C99 or later versions of C, in the original version of C <code>malloc()</code> return char* and required casting, now that it returns void* it does not. </p>\n\n<pre><code>void init_garbage_heap(void)\n{\n int len = 32;\n garbage_heap.len = 0;\n garbage_heap.capacity = len;\n garbage_heap.buffer = (void**)malloc(sizeof(void*)*len);\n for (int i = 0; i < len; ++i)\n garbage_heap.buffer[i] = NULL;\n}\n</code></pre>\n\n<p>The third thing to note is that the type of <code>garbage_heap.buffer</code> can change so it might be better if <code>sizeof(*garbage_heap.buffer) * len</code> was used rather than explicity stating <code>sizeof(void*)*len</code>. That way if the type of <code>buffer</code> changes the code only needs to change where <code>buffer</code> is declared rather than in multiple places.</p>\n\n<p>The for loop to initialize the contents of <code>garbage_heap.buffer</code> to NULL might be replaced with a call to <a href=\"http://www.cplusplus.com/reference/cstring/memset/\" rel=\"nofollow noreferrer\">void * memset ( void * ptr, int value, size_t num );</a>:</p>\n\n<pre><code> memset(garbage_heap.buffer, 0, sizeof(*garbage_heap.buffer) * len);\n</code></pre>\n\n<p>This may possibly perform better speed wise than the for loop depending on how <code>memset()</code> is written. It is also written in the terms of the rest of the code. </p>\n\n<p>If the call to <code>malloc()</code> is replaced by a call to <code>calloc()</code> neither the for loop or a call to <code>memset()</code> is required because <code>calloc()</code> will set the contents of the memory being returned to NULL.</p>\n\n<p>Possibly improved version of `init_garbage_heap(void):</p>\n\n<pre><code>void init_garbage_heap(void)\n{\n int len = 32;\n\n garbage_heap.len = 0;\n garbage_heap.capacity = len;\n garbage_heap.buffer = calloc(sizeof(*garbage_heap.buffer), len);\n if (!garbage_heap.buffer)\n {\n fprintf(stderr, \"Unable to allocate memory for garbage_heap.buffer, exiting program\");\n exit(EXIT_FAILURE);\n }\n}\n</code></pre>\n\n<p>It is not clear why len is being assigned <code>32</code>, it might be better to use a symbolic constant instead of <code>32</code>. It might also be nice if the user of these routines could set the initial allocation capacity. It would be better if the initial buffer size was larger than 32 to reduce the need for resizing.</p>\n\n<p><strong>Spacing</strong><br>\nThe code in garbage_heap.c might be more readable if there was vertical spacing inside the functions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T16:13:43.573",
"Id": "448130",
"Score": "0",
"body": "Thank you very much for detailed answer. \"vertical spacing inside the functions\" - do you mean empty lines?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T16:19:30.050",
"Id": "448131",
"Score": "0",
"body": "@sanyash yes, it needs some empty lines."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T16:22:51.347",
"Id": "448132",
"Score": "0",
"body": "You guessed correctly :) I am mostly a Python programmer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T16:00:05.870",
"Id": "230171",
"ParentId": "230119",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "230171",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T21:59:35.993",
"Id": "230119",
"Score": "4",
"Tags": [
"beginner",
"c",
"memory-management"
],
"Title": "C Garbage Heap aka simplest memory management tool"
} | 230119 |
<p>I want to be able to list every <code>Transaction</code> associated with a <code>Client</code> in date order. </p>
<p><code>Transaction</code> has 2 sub-types: <code>PaymentTransaction</code> and <code>ChargeTransaction</code>.</p>
<p>The key difference between them is:</p>
<ul>
<li><code>PaymentTransaction</code> should be associated directly with a <code>Client</code>. </li>
<li><code>ChargeTransaction</code> is associated with a <code>Proposal</code>, which in turn is associated with a <code>Client</code>.</li>
</ul>
<p></p>
<pre><code>public abstract class Transaction
{
public int Id { get; set; }
public decimal Amount { get; set; }
public DateTime Time { get; set; }
}
public class PaymentTransaction : Transaction
{
public int ClientId { get; set; }
public Client Client { get; set; }
}
public class ChargeTransaction : Transaction
{
public int ProposalId { get; set; }
public Proposal Proposal { get; set; }
}
public class Client
{
public int Id { get; set; }
public ICollection<Proposal> Proposals { get; set; }
public ICollection<PaymentTransaction> Payments { get; set; }
}
public class Proposal
{
public int Id { get; set; }
public int ClientId { get; set; }
public Client Client { get; set; }
public ICollection<ChargeTransaction> Charge { get; set; }
}
</code></pre>
<p>There will be 1000s of records for each <code>Client</code>. So I need to page the results. </p>
<p>I don't want to have to blend the results from 2 Db tables, so I have used Table per Hierarchy pattern: </p>
<pre><code>public DbSet<Transaction> Transactions { get; set; }
public DbSet<PaymentTransaction> PaymentTransactions { get; set; }
public DbSet<ChargeTransaction> ChargeTransactions { get; set; }
</code></pre>
<p>My problem is retrieving the results for a specific <code>ClientId</code>. For <code>db.ChargeTransactions</code> I would use <code>x => x.Proposal.ClientId</code>. And for <code>db.PaymentTransactions</code> I would use <code>x => x.ClientId</code>. But for <code>db.Transactions</code> I cannot use either of these. </p>
<hr>
<p><strong>My Solution</strong></p>
<p>I have put the <code>Proposal</code> and <code>Client</code> properties directly on the <code>Transaction</code> model and made them nullable. </p>
<p>I'm not convinced this is a good solution, but I don't know a better way. That is why I'm asking this question.</p>
<p>Can you suggest any improvements on this? Or a better approach?</p>
<pre><code>public abstract class Transaction
{
public int Id { get; set; }
public decimal Amount { get; set; }
public DateTime Time { get; set; }
public int? ClientId { get; set; }
public virtual Client Client { get; set; }
public int? ProposalId { get; set; }
public virtual Proposal Proposal { get; set; }
}
public class PaymentTransaction : Transaction
{
}
public class ChargeTransaction : Transaction
{
}
</code></pre>
<p>This means I can do: </p>
<pre><code>db.Transactions.Where(x => x.ClientId == clientId || x.Proposal.ClientId == clientId)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T05:30:52.360",
"Id": "448044",
"Score": "1",
"body": "I am afraid that the database tables and queries you generate might get greedy on locking and lock escalations (major performance hit). I think you need to consider if it is at all possible to have a transaction where a client Id is null."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T05:34:28.117",
"Id": "448045",
"Score": "1",
"body": "I think you need a M->M table with a \"charge nature\" you join via that table based on the nature. in code that would be Inheritance in code, https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/implementing-inheritance-with-the-entity-framework-in-an-asp-net-mvc-application"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T15:47:29.850",
"Id": "448126",
"Score": "0",
"body": "Thanks @PPann. I get the locks problem. (I had been wondering if I should just set the clientId manually.) But I'm having trouble understanding how the M->M charge nature table would work in relation to the TPT/TPC/TPH setups that the MS article describes. Any chance you could elaborate a little, maybe as an answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T19:25:11.937",
"Id": "448153",
"Score": "0",
"body": "I will put my thought in the answer below"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T20:28:28.183",
"Id": "448158",
"Score": "0",
"body": "Thank you appreciate it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T18:29:10.253",
"Id": "448427",
"Score": "1",
"body": "*I want to be able to list...* Is this only for reading data?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T21:33:31.637",
"Id": "448447",
"Score": "0",
"body": "Yes, yes it is. I just want to be able to list them along with the client info."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T12:15:38.817",
"Id": "448509",
"Score": "1",
"body": "Then I'd use a database view that blends the data from two transaction tables under one UserId column."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T14:06:20.393",
"Id": "448521",
"Score": "0",
"body": "Ah ok, that sounds like a plan. Thanks ever so much :) For anyone else finding this, I found a lot of useful info here: https://stackoverflow.com/questions/7461265/how-to-use-views-in-code-first-entity-framework/9351059#9351059"
}
] | [
{
"body": "<p>It's hard to answer your question with a definitive answer as so much information is missing and a lot, depends also on the other UI screens data that you need to fill or that other may have opened. You’re going to get issues when performing aggregates on the same table that you provide row data on as you might end-up in a deadlock, even with yourself. I'm going to give some basic data that goes through my mind, if you already know this, no harm done, just skip over it.</p>\n\n<p><strong>1 Transaction scope:</strong>\nSay you have a transaction summing over the charges and payments to get a balance, you also would like to return the last 10 charges as well as the last 10 payments. We all know that there is no guarantee that charges and payments sum-up you will get into partial payments. </p>\n\n<p>Then users will use a invoice reference number in the payments so you need to book a payment to that reference even if there are older charges that would incur late fees (this may actually be a business case for some companies as they charge more). </p>\n\n<p>You're may not be able to guarantee that the table is partitioned in a way that would facilitate transactional isolation levels to that detail so you will likely need to set your connections to allow for a snapshot isolation level (this will hit your tempdb with snapshot data so size for that) as you have no or little control over the TSQL generated by EF. If you can think of the data that you your using as ViewModel class in MVC that that would help, you do not need take the whole table into memory when you a limited subset. You will have less issues when you’re updating the data that another user might also be updating </p>\n\n<pre><code>public class FooViewConfiguration : EntityTypeConfiguration<FooView> \n{\n public FooViewConfiguration()\n {\n this.HasKey(t => t.Id);\n this.ToTable(\"dbo.myView\");\n }\n …\n}\n</code></pre>\n\n<p>You will find that you’re users are getting <a href=\"https://docs.microsoft.com/en-us/ef/ef6/saving/concurrency\" rel=\"nofollow noreferrer\">optimistic concurrency exceptions</a> (you never get them as you’re the only one changing the data in your database) so you’re data scope needs to deal with that. Have a look at </p>\n\n<pre><code>using (var context = new PaymentTransactionContext())\n{\n var payment = context.Payments.Find(1);\n payment.PayedByName = \"client Name\";\n payment.PaymentDate = UTCNow;\n\n\n bool saveFailed;\n do\n {\n saveFailed = false;\n\n try\n {\n context.SaveChanges();\n }\n catch (DbUpdateConcurrencyException ex)\n {\n saveFailed = true;\n\n // Update the values of the entity that failed to save from the store\n ex.Entries.Single().Reload();\n }\n\n } while (saveFailed);\n}\n</code></pre>\n\n<p>And only save that where you have a change.</p>\n\n<pre><code>using (var context = new MyContext())\n{\n context.ChangeTracker.TrackGraph(customer, e =>\n {\n e.Entry.State = EntityState.Unchanged;\n\n if((e.Entry.Entity as Invoice) != null)\n {\n if (e.Entry.IsKeySet)\n {\n e.Entry.State = EntityState.Modified;\n }\n else\n {\n e.Entry.State = EntityState.Added;\n }\n }\n });\n\n foreach (var entry in context.ChangeTracker.Entries())\n {\n Console.WriteLine(\"Entity: {0}, State: {1}\", entry.Entity.GetType().Name, entry.State.ToString());\n }\n context.SaveChanges();\n}\n</code></pre>\n\n<p>You limit this by using an (indexed) view and control the locking using TSQL, you can update data in a view either direct if only one table is involved or by using \"instead of\" triggers when you join several tables. </p>\n\n<p><strong>2 Indexing and locks:</strong> You might have some and you might find that your indexes are disabled (they get broken on ETL import errors) or those that you need are missing you will usually end-up with table locks as the dbms has alternative as the only option is a table scan or index scan (yes, both are bad). </p>\n\n<p>Adding to many indexes will really slow down the inserts as they need to be maintained as well. Depending on the size and quantity of an index that might get out of hand. (once worked on a project where I had to drop all indexes, then do a backup and re-create the indexes in order to backup and maintain the recovery time objectives). </p>\n\n<p>Also indexes, and covering indexes will widen the scope of the data as this needs to be locked as well. </p>\n\n<p>What one ends-up doing is design a database that has indexes on join fields first. The way you limit the scope and speed up your table is by \"removing unrelated data\" as early as possible, the smaller the scope the smaller the lock the less disk I.O. SQL server executes the plan after a given time, might not be the best plan, but you do not want to wait 2 seconds for him to figure it out (that's why you can pre-compile plans and attach them). Usually what I end-up doing is make 2 connections/ contexts. I normally have a database connection with a read-only intend. And one with a read-write intend. This way will save yourself quite a few locking issues and note that this is what makes working with large databases so slow, you quickly end up locking too much and read too much. The read-only will do most of the heavy lifting and cause little or no issues as the intend and transaction levels help.</p>\n\n<p><strong>3 Database are for storing data, they are not OO:</strong> Sql server does support <a href=\"https://docs.microsoft.com/en-us/sql/relational-databases/graphs/sql-graph-architecture?view=sql-server-2017\" rel=\"nofollow noreferrer\">graph</a>, and you would get some kick-ass performance however EF doesn’t as far as I know. So, if getting a bigger database I advice to not use OO design from the class as a mirror on the SQL tables, it’s not going to perform, go to the 6th nominal form and start duplicating data. Or create a physical table for all 3 using a 1-1 optional relationship (a foreign key that is disabled for query plans) and a trigger for data integrity\nAlso, I think that Proposal is a perhaps a ChargeTrasnaction that has a flag of being accepted… could this be</p>\n\n<p>I think, try having a customer with relationships on \"view model\"/\"unit of work\" scoped data using ICollection for all relations and really limit what you load using the above mentioned option. </p>\n\n<p>You can always use EF and SqlCommand and use the best of both worlds when ever you need. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T20:44:14.407",
"Id": "448159",
"Score": "0",
"body": "have a look at https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/infrastructure-persistence-layer-implemenation-entity-framework-core as it deals with some of the concepts mentions above."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T18:16:10.583",
"Id": "448298",
"Score": "0",
"body": "@Martin Hansen Lennox, does this solve your issue?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T21:40:12.880",
"Id": "448448",
"Score": "0",
"body": "it doesn't really. But it is such a detailed, well thought out and comprehensive answer I feel terrible for saying that. On this occasion I just want to list the data, selecting records by the clientId. It reflects poorly on my skills that I hadn't even considered the locking implications. So while it was a very helpful and interesting answer that gave me much food for thought, it didn't actually solve my issue."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T08:04:22.793",
"Id": "448480",
"Score": "0",
"body": "@MartinHansenLennox no need to feel bad, there is a lot of Technology in your stack. Try and make a List of dependent data and show that, keep it simple."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T09:59:31.647",
"Id": "448491",
"Score": "0",
"body": "The problem I'm having is getting a single list from `db.Transactions` based on the clientId."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T10:33:48.710",
"Id": "448496",
"Score": "0",
"body": "@MartinHansenLennox, ok, that's easy https://docs.microsoft.com/en-us/ef/core/querying/related-data"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T14:09:01.973",
"Id": "448522",
"Score": "0",
"body": "That helps me load the additional data for each type, but I don't see how it helps me select. Unless I'm missing something, which is quite likely."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T15:42:35.303",
"Id": "448546",
"Score": "0",
"body": "@MartinHansenLennox, You link your data based on the user's ID, that's the relationship between your client and your proposals and transaction are \"just relationships\" these you define in Navigation Properties, have a look at https://docs.microsoft.com/en-us/ef/core/modeling/relationships, if you are new to EF perhaps have a look at https://blog.codingmilitia.com/2019/01/16/aspnet-011-from-zero-to-overkill-data-access-with-entity-framework-core. and any time come and ask if somethings not clear"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T20:42:28.313",
"Id": "230187",
"ParentId": "230121",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T23:06:02.520",
"Id": "230121",
"Score": "1",
"Tags": [
"c#",
"entity-framework",
"inheritance",
"asp.net-mvc"
],
"Title": "Using nullable properties in a base class for record selection in Table per Hierarchy"
} | 230121 |
<p>Here's my android splash screen. I am trying to figure out a better way to write it. It just moves the logo up to the center of the screen. It's my third time creating a splash screen for an android app. I am just trying to figure out the best way to write more optimized code. </p>
<pre><code>import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
final public class Splash extends AppCompatActivity {
private final static int timeout = 3000;
final static Handler handler = new Handler();
static ImageView logo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
logo = findViewById(R.id.companylogo);
Animation animation = AnimationUtils.loadAnimation(Splash.this, R.anim.myanim);
logo.startAnimation(animation);
handler.postDelayed(new Runnable() {
@Override
public void run() {
Intent splashscreen = new Intent(Splash.this, Home.class);
startActivity(splashscreen);
}
}, timeout);
}
}
</code></pre>
| [] | [
{
"body": "<p>This code looks reasonably clean and seems to accomplish what it's intended to do.\nSome minor nitpicks can still be improved here and there:</p>\n\n<ul>\n<li><p>You're not consistent in visibility modifier ordering between class declaration and member declarations. It should either be <code>public final class</code> or <code>final private static int timeout</code>.<br>\nMost Java conventions that I've seen default to the <code>public static final</code> ordering.</p></li>\n<li><p><code>handler</code> and <code>logo</code> are currently package-private. It's very unusual for that visibility to be necessary and I think setting these to <code>private</code> if at all possible would be better. (I'm not recommending <code>protected</code>, because the class can not be extended.)</p></li>\n<li><p><code>static final</code> members are usually named in <code>SNAKE_CAPS</code> (also known as shout-case).</p></li>\n<li><p>the id <code>companylogo</code> might be better off named <code>companyLogo</code> to follow camel case conventions.</p></li>\n<li><p><code>myanimation</code> doesn't tell us anything about the animation. A better name would be <code>splashScreenAnimation</code> or <code>logoAnimation</code> </p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T13:13:16.170",
"Id": "230158",
"ParentId": "230124",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T23:58:27.737",
"Id": "230124",
"Score": "4",
"Tags": [
"java",
"android",
"animation"
],
"Title": "Android Java Splash Screen code"
} | 230124 |
<p>I've a function to split text on punctuation and leave the rest of the string (including whitespace in other items of the list):</p>
<pre><code>import unicodedata
def split_on_punc(text):
chars = list(text)
i = 0
start_new_word = True
output = []
while i < len(chars):
char = chars[i]
if is_punctuation(char):
output.append([char])
start_new_word = True
else:
if start_new_word:
output.append([])
start_new_word = False
output[-1].append(char)
i += 1
##print(output)
return ["".join(x) for x in output]
def is_punctuation(char):
return True if unicodedata.category(char).startswith("P") else False
</code></pre>
<p>E.g.</p>
<pre><code>split_on_punctuation("This, this a sentence. with lotsa' puncts!?@ hahaha looo world")
</code></pre>
<p>[out]:</p>
<pre><code>['This',
',',
' this a sentence',
'.',
' with lotsa',
"'",
' puncts',
'!',
'?',
'@',
' hahaha looo world']
</code></pre>
<p>It looks like a very complicated way to check through each character and then keep track of whether it's a start of a new word or not.</p>
<p>I'm looking for improvements in speed and simplicity.</p>
| [] | [
{
"body": "<h1>Return Simplification</h1>\n\n<p>This</p>\n\n<pre><code>def is_punctuation(char):\n return True if unicodedata.category(char).startswith(\"P\") else False\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>def is_punctuation(char):\n return unicodedata.category(char).startswith(\"P\")\n</code></pre>\n\n<p>Since <code>unicodedata.category(char).startswith(\"P\")</code> evaluates to a boolean expression, you can return the expression.</p>\n\n<h1>Type Hints</h1>\n\n<p>These function headers</p>\n\n<pre><code>def split_on_punc(text):\ndef is_punctuation(char):\n</code></pre>\n\n<p>can be this</p>\n\n<pre><code>def split_on_punc(text: str) -> list:\ndef is_punctuation(char: str) -> bool:\n</code></pre>\n\n<p>Type Hints allow you to show what types of parameters are supposed to be passed, and what types are returned by these functions.</p>\n\n<h1>Docstrings</h1>\n\n<p>You should include a <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"noreferrer\"><code>docstring</code></a> at the beginning of every function, class and module you write. This will allow you to describe what functions do what, and what modules contain what functions and their purpose.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T03:07:03.567",
"Id": "448027",
"Score": "0",
"body": "I think that the `chr` type hint is not correct, but I won't know for sure until this is answered: https://stackoverflow.com/questions/58229400/is-there-a-pep484-type-hint-for-character"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T03:08:54.153",
"Id": "448028",
"Score": "0",
"body": "@Reinderien The [python docs](https://docs.python.org/3/library/unicodedata.html) show that `unicodedata.category` takes a `chr`, from what I interpreted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T03:09:58.320",
"Id": "448029",
"Score": "1",
"body": "Those `chr` are variable names, not type hints."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T03:11:48.670",
"Id": "448031",
"Score": "0",
"body": "`chr` is not a valid type."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T03:12:34.967",
"Id": "448033",
"Score": "1",
"body": "@Reinderien That makes sense. Reading the comments on your stackoverflow post also point to the idea of using `str`. I will edit accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T10:28:42.940",
"Id": "448082",
"Score": "0",
"body": "using `from typing import List` you can give even further type-hinting with `split_on_punc(text: str) -> List[str]` - to show the returned list will be filled with only `str` objects."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T01:25:00.840",
"Id": "230129",
"ParentId": "230126",
"Score": "9"
}
},
{
"body": "<p>Billy Mays here for the <a href=\"https://pypi.org/project/regex/\" rel=\"noreferrer\"><code>regex</code></a> library!</p>\n\n<p>It's API-compatible with the standard Python <a href=\"https://docs.python.org/3/library/re.html?highlight=re#module-re\" rel=\"noreferrer\"><code>re</code></a> module. It's powered by open source, and it's safe for colored fabrics and carpets!</p>\n\n<p>The <code>regex</code> library offers things like <code>\\p{Punctuation}</code>, which is actually a shorthand form of <code>p{Punctuation=Yes}</code> which is really a shortening of <code>p{General_category=Punctuation}</code>.</p>\n\n<p>If you can make a Unicode query, <code>regex</code> supports it. Identifiers, Categories, Blocks, Diacritical Marks - it even does Coptic!</p>\n\n<p>It cleans! It brightens! It eliminates odors! All at the same time!</p>\n\n<pre><code>test_data = \"This, this a sentence. with lotsa' puncts!?@ hahaha looo world\"\nprint(f\"Test data: '{test_data}'\")\n\nimport regex\n\nPUNCT_RE = regex.compile(r'(\\p{Punctuation})') \n\nprint(PUNCT_RE.split(test_data))\n</code></pre>\n\n<p>The output looks like:</p>\n\n<pre><code>Test data: 'This, this a sentence. with lotsa' puncts!?@ hahaha looo world'\n['This', ',', ' this a sentence', '.', ' with lotsa', \"'\", ' puncts', '!', '', '?', '', '@', ' hahaha looo world']\n</code></pre>\n\n<p><code>regex</code> converts your code from a whopping 21 lines to a 1-line method call-- a 2000% reduction! But you gotta call now! </p>\n\n<p>Here's how to order:</p>\n\n<pre><code>pip install regex\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T03:47:55.240",
"Id": "448038",
"Score": "0",
"body": "Is `unicodedata.category(char).startswith(\"P\")` the same as regex's `\\p{Punctuation}`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T04:32:39.773",
"Id": "448039",
"Score": "0",
"body": "@alvas Yes, they both reflect the unicode-category of the underlying character."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T10:25:50.077",
"Id": "448081",
"Score": "1",
"body": "Is the capturing group required in `(\\p{Punctuation})`? If it isn't required, isn't it better to just do `\\p{Punctuation}` instead? (aka: no capturing group)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T10:52:03.810",
"Id": "448085",
"Score": "3",
"body": "\"I used to have a problem, so I used a regular-expression, now I have two problems.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T13:44:28.540",
"Id": "448106",
"Score": "2",
"body": "The capturing group is required, @IsmaelMiguel - otherwise the punctuation itself would be discarded in the split."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T15:33:14.357",
"Id": "448125",
"Score": "2",
"body": "Also, if you have Python 3, they already included regex as `re`, for free! What a deal!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T18:13:07.250",
"Id": "448147",
"Score": "0",
"body": "@IsmaelMiguel: This is the OP's use case. He wants the punctuation as well as the non-punctuation. That's a documented behavior of re.split, that if you use capture groups the capture text is included in the result."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T19:19:20.807",
"Id": "448152",
"Score": "0",
"body": "@AustinHastings I was asking because I didn't knew if it was required to capture the separator for it to be part of the result. But thinking about it, it would be pretty weird if the default behaviour was to include the separator, with no option to do *not* include it in the results. But thank you"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T03:36:48.263",
"Id": "230135",
"ParentId": "230126",
"Score": "15"
}
},
{
"body": "<h2>First things:</h2>\n\n<p>You can trim off a little just by making the loop tighter. Python does pretty cool \"for\" loops:</p>\n\n<p><code>for char in chars</code> will loop through every character in the list 'chars'. That means you don't need to deal with the variable 'i'. In fact, you don't even need to cast the input to a list called 'chars'. Python can iterate through a string as if it were a list. So your loop can be:</p>\n\n<p><code>for char in text</code> </p>\n\n<p>By my count, that saves you four lines of code right there.</p>\n\n<p>-</p>\n\n<h2>Next: Use fewer cases:</h2>\n\n<p>As written, you've effectively got three relevant paths through the loop, for three possible cases:</p>\n\n<ol>\n<li>The character is punctuation.</li>\n<li>The character isn't punctuation, and it's the first character after punctuation</li>\n<li>The character isn't punctuation, and it's not the first character after punctuation</li>\n</ol>\n\n<p>The distinction between (2) and (3) doesn't depend on the character you're dealing with. It depends on the previous character, which is why you've had to use the \"start_new_word\" variable to carry information over from one iteration of the loop into the next. I think loops are easier to deal with if you don't have to carry information over like that. So I'd want to find a way to eliminate it.</p>\n\n<p>You're effectively using \"start_new_word\" as a signal that tells you to do <code>output.append([])</code>, at the start of the next loop. But why wait until the next loop? If you replace the <code>start_new_word = true</code> instructions with <code>output.append([])</code> instructions, then you'll always have a clean 'word' sitting at the end of the output list, ready to accept characters. That way, whenever you have a non-punctuation character you just append it to <code>output[-1]</code>, and you don't have to worry about whether it's the first character.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T13:50:52.777",
"Id": "448108",
"Score": "0",
"body": "One snag: if you have two punctuation characters in a row, then this method will put an empty word in between them. ```[ \"text\", \"@\", \"\", \"?\"]```. - After you add an 'if' statement to deal with that, the function ends up just as long as it was before. But I think it's still 'cleaner' that way, without having to carry information over between loops."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T13:57:49.947",
"Id": "448110",
"Score": "0",
"body": "Also, you're working with lists of characters, and then converting them to strings at the end with a join method. You could just work directly with strings. \n\n\nInstead of ```output.append([])``` and ```output[-1].append(new_character)``` you can do ```output.append('')``` and ```output[-1] += new_character```\n\nThat saves you from having to do the .join at the end."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T13:45:16.470",
"Id": "230161",
"ParentId": "230126",
"Score": "3"
}
},
{
"body": "<p>This kind of function could be designated for an API and should be clear for every developer that would use it.</p>\n\n<p>As you probably know , there is already a <a href=\"https://docs.python.org/3/library/stdtypes.html#str.split\" rel=\"nofollow noreferrer\">split</a> method in string object. This method doesn't return separators (as they are usually useless).</p>\n\n<p>For example:</p>\n\n<pre><code>\"this.is.codereview\".split('.')\n</code></pre>\n\n<p>outputs:</p>\n\n<pre><code>['this', 'is', 'codereview']\n</code></pre>\n\n<p>The naming of <code>split_on_punc</code> could be modified to spotlight this difference, or at least be clarified with a docstring.</p>\n\n<p>I'll advise you to use explicit name of category in <code>is_ponctuation</code> to avoid ambiguities and unwilled split if another Category starts with 'P'.</p>\n\n<pre><code>def is_punctuation(char):\n return unicodedata.category(char) == \"Po\"\n</code></pre>\n\n<p>This function (inspired from <a href=\"https://stackoverflow.com/a/2136580/7281306\">this answer</a>) does quite the trick if you doesn't need to be too strict on ponctuation separators.</p>\n\n<pre><code>import string\nimport re\n\ndef split_on_punc(text):\n return [\n token\n for token in re.split(\"\\(W)\", text)\n if token not in string.whitespace\n ]\n</code></pre>\n\n<p>It splits the string considering every non-alphanumeric character as ponctuation using <a href=\"https://docs.python.org/3/library/re.html#re.split\" rel=\"nofollow noreferrer\">split</a> from re standard python library then removes whitespaces from list. It's a way far less precise than Austin answer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T17:09:43.757",
"Id": "448136",
"Score": "0",
"body": "Hey, good first answer, welcome on CodeReview :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-20T18:33:21.800",
"Id": "497346",
"Score": "0",
"body": "This did not work for me since the `if token` is executed only after the regex execution. And \\(W) cannot be right either, it causes unbalanced brackets because of the escape sign. I changed it to `import string\nimport re\n\ndef split_on_punc3(s):\n return [\n token\n for token in re.split(\"(\\W\" + '|'.join(string.whitespace) + \")\", s)\n ]` to check the speed, and then it is the fastest of all."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T15:44:15.093",
"Id": "230170",
"ParentId": "230126",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T01:07:11.067",
"Id": "230126",
"Score": "9",
"Tags": [
"python",
"strings"
],
"Title": "String Operation to Split on Punctuation"
} | 230126 |
<p>My current code implementing a depth-first search works well for puzzle 1. But my code is too slow; I think I use too many loops and I am not sure I am using the right data structure. So I have a problem in puzzle 3,4,5. Please help me to make my code run faster.</p>
<p><strong>Description:</strong>
The crossword file begins with a grid showing where the words go (represented by the * character) and the spaces around the words (represented by dots). Then there is a list of words, one per line, all in caps, that are to be placed into the crossword grid. The words should be placed in the grid so that they fit the number of asterisks and so that anywhere that words intersect each other, they share a letter. ( you can run puzzle1.txt to see the result)</p>
<p><a href="https://i.stack.imgur.com/T8lGu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T8lGu.png" alt="guild "></a></p>
<h2>puzzle1.txt</h2>
<pre class="lang-none prettyprint-override"><code> ..........
.******...
...*......
...*......
...*****..
...*..*...
......*...
......*...
......*...
..........
POLAND
LHASA
SPAIN
INDIA
puzzle3.txt
.*.*.*.
.*.*.*.
.*.*.*.
*******
*.*.*.*
*.*.*.*
*.*.*.*
ABCDEFG
AAAA
BBBB
CCCC
DDDD
EEEE
FFFF
GGGG
puzzle4.txt
...........**********......
...*.......*......*........
...*...******.....*........
...*.......*......*........
...*****...*......*........
...*..*....*......*........
......*******.....*........
......*..*........*...*....
......*..*........*********
.........*............*....
......******..........*....
......*...........*****....
......*...............*....
......*...............*....
......*....................
......*....................
......*....................
......*....................
AUSTRALIA
GUATEMALA
PANAMA
PORTUGAL
IRELAND
MYANMAR
LHASA
MONTENEGRO
MALTA
CHINA
SPAIN
BHUTAN
DENMARK
INDIA
</code></pre>
<h2>Source code</h2>
<pre><code>from collections import defaultdict
import os
import copy
import time
class search:
# Constructor
def __init__(self, file_name):
self.filename = file_name
self.board = [] ## list of board *..**
self.rows = 0
self.cols = 0
self.blank_tiles=[] ##pair row and col that have valid answer
self.answerlist =[] ## list of answer
self.count = 0
self.possibleboard = []
self.checkanswerlist = []
def addanswer(self,word):
self.answerlist.append(word)
def printverhorlist(self):
print(self.blank_tiles)
def verhorlist(self):
for j in range(self.rows):
col_lis = []
for i in range(self.cols):
# if current node is * append to row list , if rowlist >1 ( which mean it is a word) append row col to blank_tiles
if self.board[j][i] == "*":
col_lis.append((j, i))
elif len(col_lis) == 1:
col_lis = []
elif len(col_lis) > 1:
self.blank_tiles.append(col_lis)
col_lis = []
if j == self.cols-1 and len(col_lis) > 1:
self.blank_tiles.append(col_lis)
col_lis = []
for j in range(self.cols):
row_lis = []
for i in range(self.rows):
# if current node is * append to row list , if rowlist >1 ( which mean it is a word) append row col to blank_tiles
if self.board[i][j] == "*":
row_lis.append((i, j))
elif len(row_lis) == 1:
row_lis = []
elif len(row_lis) > 1:
self.blank_tiles.append(row_lis)
row_lis = []
if i == self.rows-1 and len(row_lis) > 1: # end of a column
self.blank_tiles.append(row_lis)
row_lis = []
def printboard(self,board):
print("#"*self.cols)
print("\n")
for row in board:
print("".join(row))
def printanswer(self):
for a in self.answerlist:
print(a, end = " ")
print("\n")
def openfile(self):
file = open(self.filename, "r")
a = file.readlines() # read in whole file as 1D list of strings
try:
for i in range(len(a)):
if a[i][0] == "*" or a[i][0] == ".":
self.board.append(a[i].strip())
else:
self.answerlist.append(a[i].strip())
except:
print("Cannot open file")
self.cols = len(self.board[0])
self.rows = len(self.board)
print(self.rows,self.cols)
def checkfill(self,board):
for m in range(self.rows):
for n in range(self.cols):
if board[m][n] == "*":
return 0
return 1
def startfind(self):
start = time.time()
self.find_match(self.board, self.blank_tiles, self.answerlist)
stop = time.time()
times = (stop - start) * 1000
print("Run time takes %d miliseconds" % times)
if not self.checkfill(self.board):
print("Cannot solve this puzzle")
else:
print("It takes %d step to solve this puzzle" % self.count)
print("There are %d possible board"%len(self.possibleboard))
def find_match(self,board, blank_tiles, lis):
if (self.checkfill(board) and len(blank_tiles) == 0): ## check no ** in board, and all the anwer in check answerlist
if board not in self.possibleboard:
self.board = board
self.possibleboard.append(board)
self.printboard(board)
# if no tiles left, print the board
if len(blank_tiles) == 0:
self.board = board
# p***
else:
for tile in blank_tiles: ##pair row and col that have valid answer
for word in lis: ## answerword
# check all word can place to the space or the space is all ***
#board[tile[i][0]][tile[i][1]] is current node
lengthanswer = len(tile)
if len(word) == len(tile) and all( board[tile[i][0]][tile[i][1]] == "*" or board[tile[i][0]][tile[i][1]] == word[i] for i in range(lengthanswer)):
new_board = copy.deepcopy(board) #create newboard
# if word not in self.checkanswerlist:
# self.checkanswerlist.append(word)
for i in range(len(tile)): #fill the word in a row and array
new_lis1 = list(new_board[tile[i][0]])
new_lis1[tile[i][1]] = word[i]
new_board[tile[i][0]] = "".join(new_lis1)
new_blank_tiles = blank_tiles[:] # remove an row and col already place in list
new_blank_tiles.remove(tile)
new_lis2 = lis[:] # remove word already place in
new_lis2.remove(word)
# self.printboard(new_board)
self.count = self.count +1
self.find_match(new_board, new_blank_tiles, new_lis2)
if __name__ == "__main__":
g = search("puzzle1.txt")
g.openfile()
g.printboard(g.board)
g.verhorlist()
g.printverhorlist()
g.printanswer()
g.startfind()
#g.printanswer()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T03:12:11.440",
"Id": "448032",
"Score": "2",
"body": "Can you add some description indicating what this code is supposed to do and what is a correct output and what this puzzle is about?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T05:05:41.400",
"Id": "448040",
"Score": "0",
"body": "The crossword file begins with a grid showing where the words go (represented by the * character) and the spaces around the words (represented by dots). Then there is a list of words, one per line, all in caps, that are to be placed into the crossword grid. The words should be placed in the grid so that they fit the number of asterisks and so that anywhere that words intersect each other, they share a letter. ( you can run puzzle1.txt to se the result)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T05:06:54.970",
"Id": "448041",
"Score": "0",
"body": "I want my code to be run faster, like you can see the runtime guides, because for now, my code run puzzle 3 -4 -5 is takes forever"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T05:18:20.743",
"Id": "448042",
"Score": "1",
"body": "Thank you for accepting my review however, I suggest you undo the accept and just tick the upvote ^ sign for now to give other reviewers a chance to give some reviews and if my review or anyone's turns out to be the best, you might accept it at the end. I'm editing your code to add the description you indicated in the comment above."
}
] | [
{
"body": "<h1>Style</h1>\n\n<p>I suggest you check <strong>PEP0008</strong>, <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 which will be your guide to write a Pythonic code and Flake8 <a href=\"http://flake8.pycqa.org/en/latest/\" rel=\"nofollow noreferrer\">http://flake8.pycqa.org/en/latest/</a> as a tool for style enforcement.</p>\n\n<ul>\n<li><p><strong>Clean up:</strong> <code>from collections import defaultdict</code> and \n<code>import os</code> are unused import statements and should be cleaned up as well as <code># g.printanswer()</code> at the last line of the code.</p></li>\n<li><p><strong>Class Names</strong>\nClass names should normally use the CapWords convention. Example: <code>ClassNameExample</code> and <code>class search:</code> should be: <code>class Search:</code></p></li>\n<li><p><strong>Function/method names</strong>\nFunction names should be lowercase, with words separated by underscores as necessary to improve readability. Example: <code>def first_method(self, param):</code>\n<code>def addanswer(self,word):</code> should be: <code>def add_answer(self, word):</code></p>\n\n<p>Note the comma <code>,</code> is separated by space on the right side for readability \nand same applies to all other methods <code>def printverhorlist(self):</code> \n<code>def verhorlist(self):</code> ...</p></li>\n<li><p><strong>Docstrings</strong> Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. You should indicate docstrings to your classes/methods/functions indicating what they do, what they return and type hints when necessary.\nExample: </p>\n\n<pre><code>class MyClass:\n \"\"\"Description goes here.\"\"\"\n\n def first_method(self, param1: int, param2: str):\n \"\"\"Do things and return stuff.\"\"\"\n</code></pre>\n\n<p>And this applies to all your methods defined under your <code>search</code> class as long as they are not meant for internal use(private methods) which are written with a leading underscore: <code>def _private_method(self, param):</code></p></li>\n<li><p><strong>Blank lines</strong> Surround top-level function and class definitions with two blank lines. Method definitions inside a class are surrounded by a single blank line.\nExtra blank lines may be used (sparingly) 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).</p></li>\n<li><p><strong>Comments</strong> Comments should be complete sentences. The first word should be capitalized, unless it is an identifier that begins with a lower case letter (never alter the case of identifiers!) and start with a single # and 2 spaces are left for inline comments example: </p>\n\n<p><strong>This line:</strong></p>\n\n<pre><code> self.blank_tiles=[] ##pair row and col that have valid answer\n</code></pre>\n\n<p><strong>should be written:</strong></p>\n\n<pre><code> self.blank_tiles = [] # Pair row and col that have valid answer.\n</code></pre>\n\n<p>And same applies to all other comments</p></li>\n<li><strong>Typos</strong> <code>def printverhorlist(self):</code> and <code>def verhorlist(self):</code> names that do not have any sense 'verhor' as well as spelling errors should be replaced with corrects words that have meanings.</li>\n<li><strong>Long lines</strong> Lines should not exceed 79 characters (lines 29, 44 in your code)</li>\n</ul>\n\n<h1>Code</h1>\n\n<p>A general comment is most of your code is very hard to read/understand due to the lack of documentation and description and it is not possible for anyone to tell what's a wrong/right output for not so obvious parts of the code. As per rules of this website the code should be running properly as of to the author best of knowledge, I'm going to assume that it's working correctly and I cannot tell again due to the absence of documentation and bad structure however here are some things to note:</p>\n\n<ul>\n<li><p>As the title states, this should be a depth-first search(DFS) with pseudocode found here: <a href=\"https://en.wikipedia.org/wiki/Depth-first_search\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Depth-first_search</a>, I can't seem to find a proper implementation of a DFS search which is generally implemented using a stack (which is absent in your code). This might be an improper DFS implementation maybe leading to correct output somehow and maybe not(I cannot tell without a description or proper documentation) so I suggest you at least provide a proper description with a proper expected output if you need a decent feedback and here are a few points:</p></li>\n<li><p><code>def __init__(self, file_name):</code> a class with a single parameter is not a good class and you may define functions that pass results to each other instead of the over-engineered code. And since most of the instance attributes are lists, you can define these lists inside of their corresponding functions that use them without using a class in the first place.</p></li>\n<li><p><strong>Methods do return</strong></p>\n\n<pre><code>def printverhorlist(self):\n print(self.blank_tiles)\n</code></pre>\n\n<p>This is the same as <code>print(self.blank_tiles)</code> so there is no need for defining a method for printing and for a specific/custom print/display of the user-defined objects, you might use <code>__str__</code> method that returns a string in case someone is using your code and wants to print your defined object. </p></li>\n<li><p><code>With as</code> <strong>context managers:</strong>\n<code>file = open(self.filename, \"r\")</code> in <code>openfile()</code> method, it is generally better to use <code>with</code> and <code>as</code> context managers that automatically close the file without using <code>file_object.close()</code> method you forgot to use after manually opening the file. Some Python files will close files automatically when they are no longer referenced, while others will not and it's up to the OS. to close files when the Python interpreter exits. So it's generally a bad practice not to close your files after opening them, to forget about this hassle, use with and as in the following way:</p>\n\n<pre><code>with open(my_file) as example:\n # do stuff\n</code></pre></li>\n<li><p><strong>Improper use of try except:</strong> </p>\n\n<pre><code>except:\n print(\"Cannot open file\")\n</code></pre>\n\n<p>what kind of exception are you catching here? if the exception is the failure to open the file, you're opening the file outside the <code>try</code> body so the whatever exception you're trying to catch is never caught in the first place.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T12:32:28.587",
"Id": "448095",
"Score": "1",
"body": "_this is not a full review_ - Sure it is! CR policy is that your answer have at least one insightful comment, and you have many. I'd omit that couching phrase altogether."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T16:53:14.513",
"Id": "448134",
"Score": "0",
"body": "Looks like OP is using recursion instead of an explicit stack, so it looks like a DFS to me."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T05:06:47.203",
"Id": "230137",
"ParentId": "230131",
"Score": "5"
}
},
{
"body": "<p><strong>A bug:</strong> the first set of nested loops in <code>verhorlist</code>, which is said to find columns but actually finds rows, tests <code>j == self.cols-1</code> but should test <code>i == self.cols-1</code>. </p>\n\n<p>This is why for puzzle 3, the horizontal tile in the middle row is not found. As a secondary effect, a ton of broken solutions is printed for puzzle 3, because as we lack a tile, <code>len(blank_tiles) == 0</code> even though not all words have been assigned.</p>\n\n<p><strong>The algorithm</strong>:</p>\n\n<p>The algorithm can be switched from:</p>\n\n<ul>\n<li>For each tile\n\n<ul>\n<li>Try each fitting word</li>\n</ul></li>\n</ul>\n\n<p>To:</p>\n\n<ul>\n<li>For each tile\n\n<ul>\n<li>Try <em>one</em> fitting word</li>\n</ul></li>\n</ul>\n\n<p>This is also complete: every (fitting) combination of tile and word is tried, but by backtracking and then trying to put the same word somewhere else, not by every node in the recursion tree trying all combinations. The effect is that the branching factor of the recursion tree is dramatically reduced. </p>\n\n<p>The time to solve a puzzle still depends dramatically on the search order, puzzle 3 can be solved on my PC in 2 ms or up to 240 ms (perhaps my PC is faster than the guidelines anticipate?), depending on the order of the word list. If \"ABCDEFG\" is put down first, everything just falls into place. If anything else is placed first, some trial-and-error likely results - but not an impossibly large number of tries.</p>\n\n<p>Further improvement is possible, by intentionally using a good search order. \"The order the words are in the file\" is accidentally a good order for puzzle 3, but in general it may not be. The word that should go first is the word that has the fewest places it can go, this is an example of the Most Constraining Variable (MCV) heuristic for constraint satisfaction problem solvers. The other famous heuristic, LCV (least constraining value), is harder to give meaning in this modelling of the problem. Perhaps it is good to try to assign a word to a tile where it already crosses some other word, trying to eagerly cross words with each other when possible, so that the other place where the word also fits stays \"unpolluted\" for longer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T15:24:47.407",
"Id": "230168",
"ParentId": "230131",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "230137",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T01:52:08.207",
"Id": "230131",
"Score": "5",
"Tags": [
"python",
"performance",
"depth-first-search",
"sliding-tile-puzzle"
],
"Title": "Optimize depth-first search for sliding tile puzzle"
} | 230131 |
<p>This function takes in a string and a fixed list of vocab:</p>
<ul>
<li>splits a string into words by spaces</li>
<li>for each word, check in the dictionary/vocab and find the longest matching substrings, if none matching use the <code>[UNK]</code> word</li>
<li>if a word is longer than a predefined length, it'll also become <code>[UNK]</code></li>
</ul>
<p>Code:</p>
<pre><code>def tokenize(text, vocab, max_input_chars_per_word=10, unk_token="[UNK]"):
output_tokens = []
for token in text.split():
chars = list(token)
if len(chars) > max_input_chars_per_word:
output_tokens.append(unk_token)
continue
is_bad = False
start = 0
sub_tokens = []
while start < len(chars):
end = len(chars)
cur_substr = None
while start < end:
substr = "".join(chars[start:end])
if start > 0:
substr = "##" + substr
if substr in vocab:
cur_substr = substr
break
end -= 1
if cur_substr is None:
is_bad = True
break
sub_tokens.append(cur_substr)
start = end
if is_bad:
output_tokens.append(unk_token)
else:
output_tokens.extend(sub_tokens)
return output_tokens
</code></pre>
<p>And example input and expected output: </p>
<pre><code>vocab = ["the", "go", "##es", "to", "eat", "pum", "##pkins", "of", "##gos", "##stein"
"#400", "1", "boredom", "##folk", "man", "##go", "out", "folks", "##0",
"un", "##aff", "##able"]
s = "the unaffable folks goes to eat 1400 folkspkinsgosgo pumpkins and 10 mangos out of boredom"
tokenize(s, vocab)
</code></pre>
<p>[out]:</p>
<pre><code>['the',
'un',
'##aff',
'##able',
'folks',
'go',
'##es',
'to',
'eat',
'[UNK]',
'[UNK]',
'pum',
'##pkins',
'[UNK]',
'1',
'##0',
'man',
'##gos',
'out',
'of',
'boredom']
</code></pre>
<p>The nested while loop looks a complicated and checking each token isn't parallelized since it looks like it's independent of other tokens. <strong>How can this function be improved?</strong></p>
<p><strong>Simpler loops, or checking in parallel or maybe an easier to find longest matching substring from a list when iterating through the tokens?</strong> Or regexes?</p>
| [] | [
{
"body": "<p>The following is a basic syntax and usage pass without looking into your algorithm in too much depth. I'll first show the suggested code and then highlight significant differences where it can offer improvements on the original.</p>\n\n<pre><code>#!/usr/bin/env python3\n\nfrom typing import Iterable, Set\n\n\ndef tokenize(\n text: str,\n vocab: Set[str],\n max_input_chars_per_word=10,\n unk_token=\"[UNK]\"\n) -> Iterable[str]:\n for token in text.split():\n n = len(token)\n if n > max_input_chars_per_word:\n yield unk_token\n continue\n\n start = 0\n sub_tokens = []\n\n while start < n:\n end = n\n cur_substr = None\n while start < end:\n substr = token[start:end]\n if start > 0:\n substr = \"##\" + substr\n if substr in vocab:\n cur_substr = substr\n break\n end -= 1\n if cur_substr is None:\n yield unk_token\n break\n sub_tokens.append(cur_substr)\n start = end\n else:\n yield from sub_tokens\n\n\ndef test():\n vocab = {\"the\", \"go\", \"##es\", \"to\", \"eat\", \"pum\", \"##pkins\", \"of\", \"##gos\", \"##stein\"\n \"#400\", \"1\", \"boredom\", \"##folk\", \"man\",\n \"##go\", \"out\", \"folks\", \"##0\",\n \"un\", \"##aff\", \"##able\"}\n\n s = \"the unaffable folks goes to eat 1400 folkspkinsgosgo pumpkins and 10 mangos out of boredom\"\n\n result = tokenize(s, vocab)\n assert list(result) == [\n 'the',\n 'un',\n '##aff',\n '##able',\n 'folks',\n 'go',\n '##es',\n 'to',\n 'eat',\n '[UNK]',\n '[UNK]',\n 'pum',\n '##pkins',\n '[UNK]',\n '1',\n '##0',\n 'man',\n '##gos',\n 'out',\n 'of',\n 'boredom']\n\n\ntest()\n</code></pre>\n\n<h2>Rationale</h2>\n\n<ul>\n<li>Add PEP484 type hints such as <code>Iterable</code> for the return of your function.</li>\n<li>Require that you accept a <code>set</code> for <code>vocab</code>. All you do on it is membership testing, i.e. <code>if substr in vocab:</code>, so a set will be much faster.</li>\n<li>Make this function a generator and <code>yield</code> instead of building up an <code>output_tokens</code> list.</li>\n<li>Store the token length in a variable such as <code>n</code>, considering you need it so often.</li>\n<li>Do not split out <code>token</code> into <code>chars</code>, and do not call <code>join</code>. All you need is the <code>token</code> string.</li>\n<li>Do not track an <code>is_bad</code> flag. Use a <code>for</code>/<code>else</code> to detect whether a <code>break</code> occurred.</li>\n<li>Use your test data in actual <code>assert</code> tests.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-14T19:51:48.093",
"Id": "230721",
"ParentId": "230136",
"Score": "2"
}
},
{
"body": "<p>Here's my take on it. I split the vocab into 2 set. The first set, <code>heads</code> if for substrings that start at the beginning of the string, and the second set <code>tails</code> for other substrings.</p>\n\n<p>The <code>else</code> clause on a loop gets executed when the loop terminates \"normally\", but is skipped when <code>break</code> is used. Some people don't like these <code>else</code> clauses, but I find them handy.</p>\n\n<pre><code>def tokenize(text, heads, tails, max_token_length=10, unknown_token=\"[UNK]\"):\n output_tokens = []\n\n for token in text.split():\n\n if len(token) > max_token_length:\n output_tokens.append(unknown_token)\n continue\n\n sub_tokens = []\n\n substrs, flag = heads, ''\n while token:\n for end in range(len(token),0,-1):\n if token[:end] in substrs:\n sub_tokens.append(f\"{flag}{token[:end]}\")\n token = token[end:]\n substrs, flag = tails, '##'\n break\n\n else:\n output_tokens.append(unknown_token)\n break\n\n else:\n output_tokens.extend(sub_tokens)\n\n return output_tokens\n</code></pre>\n\n<p>Used like so:</p>\n\n<pre><code>heads = set(v for v in vocab if v[:2]!='##')\ntails = set(v[2:] for v in vocab if v[:2]=='##')\n\ntokenize(s, heads, tails)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-18T04:19:29.707",
"Id": "230934",
"ParentId": "230136",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T04:15:10.820",
"Id": "230136",
"Score": "5",
"Tags": [
"python",
"strings",
"regex"
],
"Title": "Splitting each word using longest substring that matches in a vocab/dictionary"
} | 230136 |
<p>I'm writing a utility method which pipes given <code>ResponseSpec</code>'s body and gives to the caller a change to read it.</p>
<pre><code>static <R> Mono<R> pipeBodyAndApply(
final WebClient.ResponseSpec spec,
final ExecutorService executor,
final Function<? super ReadableByteChannel, ? extends R> function) {
return using(
Pipe::open,
p -> {
final Future<Disposable> future = executor.submit(
() -> write(spec.bodyToFlux(DataBuffer.class), p.sink())
.log()
.doFinally(s -> {
try {
p.sink().close();
log.debug("p.sink closed");
} catch (final IOException ioe) {
throw new RuntimeException(ioe);
}
})
.subscribe(DataBufferUtils.releaseConsumer())
);
return just(function.apply(p.source()))
.log()
.doFinally(s -> {
try {
final Disposable disposable = future.get();
assert disposable.isDisposed();
} catch (InterruptedException | ExecutionException e) { e.printStackTrace();
}
});
},
p -> {
try {
p.source().close();
log.debug("p.source closed");
} catch (final IOException ioe) {
throw new RuntimeException(ioe);
}
}
);
}
</code></pre>
<p>Now I'm wondering am I doing it right.</p>
<ul>
<li>Is this method written right for the purpose?</li>
<li>Is there any mis-usages regarding <code>Mono</code> or <code>Flux</code>?</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T13:47:18.977",
"Id": "448107",
"Score": "1",
"body": "Hey Jin, could you maybe try to rework your indentation? It makes the code really hard to read and I'd guess it's because of the way the code is formatted here. Could you also give a little bit more information on what the code is supposed to do?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T05:13:45.063",
"Id": "448185",
"Score": "0",
"body": "@IEatBagels I want to pipe given `ResponseSpec` body and give caller an opportunity to read the body as a `ReadableByteChannel`. Thanks."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T07:40:47.940",
"Id": "230140",
"Score": "1",
"Tags": [
"java",
"spring",
"reactive-programming"
],
"Title": "Pipe ResponseSpec's Body"
} | 230140 |
<p>I am writing a small program which reads some JSON files, passes the content to an API, then saves the response in some more JSON files. A pretty simple task, and the code works fine, but I have been away from node for a few years and wanted to make sure I'm using all this new async stuff right! Any comments welcome.</p>
<p>Node version 10.16.3</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>'use strict'
require('dotenv').config()
const fs = require("fs")
const util = require("util")
const request = require("request-promise-native")
const pLimit = require("p-limit")
const inputPath = "./input-files/"
const outputPath = "./output-files/"
const limit = pLimit(2) // api limits to 2 concurrent requests on free account
const readFile = util.promisify(fs.readFile)
const writeFile = util.promisify(fs.writeFile)
async function readInputFile(filePath) {
return JSON.parse(await readFile(filePath))
}
async function callApi(content) {
const options = {
uri: "https://api.example.com",
headers: {
"key": process.env.API_KEY,
"Content-Type": "application/x-www-form-urlencoded"
},
form: {
"field": content
}
}
return await request(options)
}
async function processFile(fileName) {
return readInputFile(inputPath + fileName)
.then(data => callApi(data))
.then(response => writeFile(outputPath + fileName, response))
}
const fileNames = fs.readdirSync(inputPath, {
withFileTypes: true
}).map(item => item.name)
const promises = fileNames.map(fileName => {
return limit(() => {
return processFile(fileName)
})
})
(async() => {
const result = await Promise.all(promises)
console.log(`${result.length} files transferred`)
})()</code></pre>
</div>
</div>
</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T08:31:49.323",
"Id": "230143",
"Score": "2",
"Tags": [
"javascript",
"node.js",
"async-await"
],
"Title": "Passing JSON files through an API - node async"
} | 230143 |
<blockquote>
<p>I have a class <code>Installment</code> and a method <code>executeTransaction</code>. The field <code>totalBalance</code> represents the difference between total due and total paid. Inside method <code>executeTransaction</code> the installment object is modified using setters. And after every setter the updateTotalBalance is called.</p>
</blockquote>
<pre><code>public class Installment {
private BigDecimal principalDue;
private BigDecimal principalPaid;
private BigDecimal interestDue;
private BigDecimal interestPaid;
private BigDecimal feeDue;
private BigDecimal feePaid;
private BigDecimal penaltyDue;
private BigDecimal penaltyPaid;
private BigDecimal totalBalance;
public void updateTotalBalance() {
this.totalBalance = this.principalDue.subtract(this.penaltyPaid)
.add(this.interestDue).subtract(this.interestPaid)
.add(this.feeDue).subtract(this.feePaid)
.add(this.penaltyDue).subtract(this.penaltyPaid);
}
//seters
//getters
}
</code></pre>
<p>Transaction method:</p>
<pre><code>public void executeTransaction(Installment installment){
//code
installment.setPrincipalPaid(bigDecimalValue);
installment.updateTotalBalance();
//code
installment.setPenaltyDue(bigDecimalValue);
installment.updateTotalBalance();
}
</code></pre>
<p>I was thinking about putting the <code>updateTotalBalance</code> inside the setters, but for me both of these approaches seem contradictory with the best design principles.</p>
<p>Q: I want to know if there are better solutions to update a field in a class when others fields are modified.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T09:42:52.380",
"Id": "448075",
"Score": "0",
"body": "May be the [_Observer_ design pattern](https://sourcemaking.com/design_patterns/observer) would be a more generic and flexible solution for that problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T13:34:42.847",
"Id": "448100",
"Score": "0",
"body": "If it's not clear, the problem with this post is that it doesn't actually update the total balance when other fields are modified. It updates when execute transaction is run. So it does not actually accomplish the task that you say you're attempting. You've also elided out all the context, so we can't suggest changes outside the code that you've posted. This is required on Stack Overflow but is a close reason here. Code here should be specific, not general."
}
] | [
{
"body": "<p>The simplest solution would be to drop the <code>totalBalance</code> field and simply have <code>getTotalBalance</code> calculate the value:</p>\n\n<pre><code>public BigDecimal getTotalBalance() {\n return this.principalDue.subtract(this.penaltyPaid)\n .add(this.interestDue).subtract(this.interestPaid)\n .add(this.feeDue).subtract(this.feePaid)\n .add(this.penaltyDue).subtract(this.penaltyPaid);\n}\n</code></pre>\n\n<p>There is no real reason to store the total inside the object, unless you know it has to called multiple times (and with that I mean a very large number of times, not 3 or 4 times) without being able to be cached.</p>\n\n<p>Generally with data classes it's always prudent to look into the possibility of having it be immutable (= no setters), then you only need calculate the total once in the constructor. I can't say for sure without more context, but this actually looks like a prime example where immutability could make sense.</p>\n\n<p>Again with out more context its difficult to say, but IMO the class seems to contain too much information/data. It may make sense to break in down into smaller classes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T12:15:52.617",
"Id": "230155",
"ParentId": "230147",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "230155",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T09:36:19.780",
"Id": "230147",
"Score": "-1",
"Tags": [
"java",
"design-patterns"
],
"Title": "update field when others fields are motifed"
} | 230147 |
For code that uses memory-mapped files. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T10:28:52.697",
"Id": "230150",
"Score": "0",
"Tags": null,
"Title": null
} | 230150 |
<p>As a component of some trading software, I wrote function <code>parse_ticks()</code>, as part of an <code>Exchange</code> class that models the Bitcoin derivatives exchange BitMEX.</p>
<p>The purpose of <code>parse_ticks()</code> is to convert the previous minutes stored tick data (a list of individual trades, obtained by calling <code>all_ticks = self.ws.get_ticks()</code>) into a dictionary which aggregates the OHLCV values from the list of previous minutes ticks. The list of trades is a list of dict's, each dict containing a timestamp, size of trade, if the tick was a buy or sell, etc.</p>
<p><code>parse_ticks()</code> gets invoked once per instrument when minute elapses. In this scenario, I am watching two instruments, so <code>parse_ticks()</code> gets called twice at the start of each minute.</p>
<p>I timed <code>parse_ticks()</code> run time for 2400 minutes (2400 observations) with as many background processes and programs disabled as possible, and obtained these results (in seconds):</p>
<p>mean run time: 0.0318425</p>
<p>min run time: 0.00458</p>
<p>max run time: 0.07958</p>
<p>std dev: 0.02276709988</p>
<p>Theres a massive range here, with the min and max substantially different, and the std dev is almost as large as the mean.</p>
<p><strong>How would I lower the std. dev of <code>parse_ticks()</code> run time, and get the mean run time closer the minimum observation of 0.00458?</strong></p>
<p>Is this kind of optimisation within the scope of python?</p>
<p><strong>EDIT:</strong> To answer the questions in comments (thank you all for your help):</p>
<p><code>ws.get_ticks()</code> has no outbound API calls, it looks like this:</p>
<pre><code>def get_ticks(self):
return self.data['trade']
</code></pre>
<p>where <code>data['trade']</code> is a list containing ticks saved from a websocket stream in realtime. The <code>'trade'</code> list is trimmed by 30% if it goes above 10000 elements, so that aspect (constantly-increasing amount of data to parse) is constant, once the limit is reached. So the data is already available when <code>parse_ticks()</code> is called.</p>
<p>The amount of ticks DOES vary, so some variance can be explained by that. But surely not the extreme range of 0.075? (min - max).</p>
<p>The run times are seemingly random, there are long and short runs interspersed throughout all the observations.</p>
<pre><code>self.bars = {}
self.symbols = ["XBTUSD", "ETHUSD"]
self.ws = Bitmex_WS()
def parse_ticks(self):
"""Return a 1-min OHLCV dict, given a list of the previous
minutes tick data."""
all_ticks = self.ws.get_ticks()
target_minute = datetime.datetime.utcnow().minute - 1
ticks_target_minute = []
tcount = 0
# search from end of tick list to grab newest ticks first
for i in reversed(all_ticks):
try:
ts = i['timestamp']
if type(ts) is not datetime.datetime:
ts = parser.parse(ts)
except Exception:
self.logger.debug(traceback.format_exc())
# scrape prev minutes ticks
if ts.minute == target_minute:
ticks_target_minute.append(i)
ticks_target_minute[tcount]['timestamp'] = ts
tcount += 1
# store the previous-to-target-minute bar's last
# traded price to use as the open price for target bar
if ts.minute == target_minute - 1:
ticks_target_minute.append(i)
ticks_target_minute[tcount]['timestamp'] = ts
break
ticks_target_minute.reverse()
# reset bar dict ready for new bars
self.bars = {i: [] for i in self.symbols}
# build 1 min bars for each symbol
for symbol in self.symbols:
ticks = [i for i in ticks_target_minute if i['symbol'] == symbol]
bar = self.build_OHLCV(ticks, symbol)
self.bars[symbol].append(bar)
# self.logger.debug(bar)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T13:18:09.490",
"Id": "448096",
"Score": "2",
"body": "If that short amount of time is important to you, then questioning whether Python is suitable is warranted. However, the folks over at https://softwareengineering.stackexchange.com/ would be better suited in answering that. To optimize for speed this way, you may need a lower-level language and correspondingly invest more time in development."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T13:29:18.643",
"Id": "448098",
"Score": "0",
"body": "Could it be branch prediction?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T13:32:44.390",
"Id": "448099",
"Score": "3",
"body": "Is the amount of ticks constant or not? If the amount of work you have to do varies, then that would also cause the runtime to vary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T13:42:35.760",
"Id": "448102",
"Score": "0",
"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-10-04T14:10:06.260",
"Id": "448113",
"Score": "2",
"body": "If you examine the run times, are they random or do they get bigger as the 2400 minutes pass? If so then I would suggest that searching for the newest tick starting at the oldest is going to take progressively longer and you may want to find some way of remembering where you are at each pass. Similarly the last loop, building the bars, will get progressively longer for the same reason, more data to process each time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T22:21:51.567",
"Id": "448172",
"Score": "0",
"body": "Thanks for input, updated question to answer comments."
}
] | [
{
"body": "<p>We (and it sounds like you as well) do not have enough information to answer this question. But some good news first: I cannot see any region where your method is obviously wasting time (like searching with <code>in</code> for some item in a growing list).</p>\n\n<p>Before you concern yourself more with this, consider that even if the variance is large, your maximum time is less than a tenth of a second, for two instruments. In other words, you could be monitoring more than 1500 instruments before you get close to a maximum processing time on the order of your frequency (one minute). So ask yourself if you are performing needless premature optimization. Will this code run with <span class=\"math-container\">\\$\\mathcal{O}(1000)\\$</span> instruments, for longer than two days? If not, you can stop right here. If yes, or as an academic exercise, continue on.</p>\n\n<hr>\n\n<p>As far as I can see, the runtime of this code will be largely determined by two factors:</p>\n\n<ol>\n<li><p>How long <code>self.ws.get_ticks()</code> takes. Does this method connect to the internet to get it's data? Then the variance might actually be the variance in establishing the connection and getting the data. This could be influenced by your internet connection, but also the current load on the server you are trying to connect to. In this case there is nothing you can do.</p></li>\n<li><p>How many elements are returned. The actual function getting the data might take longer for more elements, but also the processing would, since you iterate over all elements of the list.</p></li>\n</ol>\n\n<p>The only way to know is to gather more data. Individually time the call to <code>self.ws.get_ticks()</code>, collect the <code>len(all_ticks)</code> and plot everything in a time-ordered way. Maybe this will help you to discover something interesting.</p>\n\n<p>Here are some possibilities of what you could discover:</p>\n\n<ul>\n<li>The server where you get the information also has some updating frequency, so only every five minutes will there be data for you.</li>\n<li>They have a rate limit, which makes all requests in-between fail (which is faster than transmitting a bunch of data).</li>\n<li>The call actually returns <em>all</em> data every time, and you just <code>break</code> when you have reached the point of the last minute. In this case each successive call is more expensive, so of course this increases the standard deviation. Try to find a way to pass the start date to the call.</li>\n</ul>\n\n<hr>\n\n<p>And here is a small class that can help you keep track of different timers I just came up with:</p>\n\n<pre><code>from time import perf_counter\nfrom statistics import mean, median, stdev\nfrom collections import defaultdict\n\nclass Timer:\n durations = defaultdict(list)\n\n def __init__(self, name=\"\"):\n self.name = name\n\n def __enter__(self):\n self.start = perf_counter()\n\n def __exit__(self, *args):\n Timer.durations[self.name].append(perf_counter() - self.start)\n\n @staticmethod\n def calc_stats(x):\n return {\"mean\": mean(x),\n \"std\": stdev(x),\n \"median\": median(x),\n \"min\": min(x),\n \"max\": max(x)}\n\n @staticmethod\n def stats():\n return {name: Timer.calc_stats(x) for name, x in Timer.durations.items()}\n</code></pre>\n\n<p>With some example usage:</p>\n\n<pre><code>from time import sleep\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom timer import Timer\n\nfor n in range(10):\n with Timer(\"a\"):\n sleep(0.5)\n with Timer(\"b\"):\n sleep(0.1 * n)\n\nprint(pd.DataFrame(Timer.stats()))\n# a b\n# mean 0.500559 0.450504\n# std 0.000021 0.303079\n# median 0.500552 0.450502\n# min 0.500534 0.000006\n# max 0.500602 0.901003\n\nplt.plot(Timer.durations[\"a\"], label=\"a\")\nplt.plot(Timer.durations[\"b\"], label=\"b\")\nplt.legend()\nplt.xlabel(\"Iteration\")\nplt.ylabel(\"Time [s]\")\nplt.show()\n</code></pre>\n\n<h2><a href=\"https://i.stack.imgur.com/h0JBu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/h0JBu.png\" alt=\"enter image description here\"></a></h2>\n\n<p>Some other comments:</p>\n\n<ul>\n<li>Instead of <code>self.bars = {i: [] for i in self.symbols}</code> you can use <code>self.bars = defaultdict(list)</code>, like I did in the <code>Timer</code> class.</li>\n<li>Try to avoid single letter variables. They are OK in a few cases, but <code>i</code> (and <code>n</code>) are usually reserved for integers. Use <code>x</code>, or maybe even better, <code>tick</code>.</li>\n<li>Don't directly compare <code>type</code>, use <code>isinstance(datetime.datetime, s)</code> instead. This also allows subclasses.</li>\n<li>Don't lie in your docstring. You say \"Return a 1-min OHLCV dict, given a list of the previous minutes tick data.\", but almost <strong>none</strong> of this is true. The method does not return anything and it also does not take any parameters as input!</li>\n<li>If you know the exception to expect, catch only that. At least you don't have a bare <code>except</code>, but <code>except KeyError</code> and maybe some specific error from the parser would be better. This way you don't miss an unexpected error. You should also ask yourself what your code does if an error occurs. I think it will just use the previous iterations <code>ts</code>, which would duplicate data. Just hope that you never have a problem in the first timestamp!</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T22:34:32.663",
"Id": "448173",
"Score": "0",
"body": "Thanks @Graphier, updated the question to address a few points raised. In regards to maximum processing time, i'd be monitoring 50-100 instruments in this manner (parsing tick data), with all parsing needing to be completed as close to the turn of each new minute as possible (i.e all instruments done in > 0.1 sec). The other way I'd thought to scale is use more machines, running maybe 10 instruments in this way, per machine, if it is possible to get individual parse times under 0.01, as the minimum score of 0.00458 would suggest. Or as someone suggested, perhaps python is the wrong choice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T06:48:13.737",
"Id": "448194",
"Score": "0",
"body": "@s_dbq Usually we disallow code edits after answers have arrived. However, since Graipher admits to a lack of information and his is the only answer, I'll leave it up to him whether or not this is acceptable. Do note a mess might be created if other answers pop-up in the meantime."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T15:34:46.680",
"Id": "230169",
"ParentId": "230157",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "230169",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T13:01:37.403",
"Id": "230157",
"Score": "0",
"Tags": [
"python",
"performance",
"algorithm",
"python-3.x",
"parsing"
],
"Title": "Aggregating recent trading data from Bitcoin derivatives exchange"
} | 230157 |
<p>I am developing an Angular application who also consumes an external REST API. I am also trying the <a href="https://openapi-generator.tech/" rel="nofollow noreferrer">OpenAPI generator</a> using a TypeScript template.</p>
<p>The OK path is the following:</p>
<ul>
<li>call a method that requires a username + password and get a token</li>
<li>set the token on a configuration object </li>
<li>update the generated instance API client with that configuration (which should also receive a base path)</li>
<li>use the instance API client to call a method</li>
</ul>
<p><strong><code>DataLakeSecurityClientCustomizationService</code></strong> </p>
<p>This takes care of initializing the API clients and setting the token when this is refreshed.</p>
<pre><code>@Injectable({providedIn: "root"})
export class DataLakeSecurityClientCustomizationService {
constructor(
private readonly defaultService: DefaultService,
private readonly securityTagsService: SecurityTagsService,
/* other generated API client service instances will be here */) {
}
init() {
this.defaultService.configuration.basePath = environment.dataLakeSecurityApiBasePath;
this.securityTagsService.configuration.basePath = environment.dataLakeSecurityApiBasePath;
}
setToken(token: string) {
this.securityTagsService.configuration.accessToken = token;
// all other used services will get the token here
}
}
</code></pre>
<p><strong>app.component.ts</strong></p>
<pre><code> private initDataLakeExtAuth() {
this.dataLakeCustService.init();
// trying to get a token ASAP to use for subsequent calls
this.store.dispatch(RequestNewTokenAction());
}
ngOnInit(): void {
this.initDataLakeExtAuth();
}
</code></pre>
<p><strong>Authentication effect</strong></p>
<p>This handles getting the token which is happening outside of reducer's pure functions. I am using ngrx/store framework (Angular 8 version).</p>
<pre><code>@Injectable()
export class DataLakeExtAuthEffects {
constructor(
private readonly actions$: Actions,
private readonly dataLakeExtAuthService: DataLakeExtAuthService,
private readonly store: Store<AppState>,
private readonly logger: LoggingService,
private readonly dataLakeSecurityClientCustomizationService: DataLakeSecurityClientCustomizationService
) { }
getNewToken$ = createEffect(() => this.actions$.pipe(
ofType(RequestNewTokenAction),
switchMap(_ => {
this.store.dispatch(LoadingStartedAction({ message: "Performing security level authentication ..."}));
return this.dataLakeExtAuthService.getLoginToken().pipe(
tap(() => this.store.dispatch(LoadingEndedAction())),
catchError(err => {
this.store.dispatch(LoadingEndedAction());
this.logger.logErrorMessage("Error getting a Data Lake Security View token: " + err);
this.store.dispatch(NewTokenLoadCancelledAction());
return of<string>();
}));
}),
map((token: string) => {
this.dataLakeSecurityClientCustomizationService.setToken(token);
return NewTokenLoadedAction({token});
}))
);
}
</code></pre>
<h3>The authentication service for the external REST API</h3>
<pre><code>@Injectable({providedIn: "root"})
export class DataLakeExtAuthService {
credentials = DataLakeCredentials;
constructor(private readonly defaultService: DefaultService,
private readonly logger: LoggingService) {
}
getLoginToken(): Observable<string> {
const token$ = this.defaultService.loginTokenPost(this.credentials.username, this.credentials.password)
.pipe(
map((payload: { access_token: string }) => payload.access_token),
tap((token: string) => {
this.logger.logTrace("Received token: ", token);
})
);
return token$;
}
}
</code></pre>
<p><code>DefaultService</code> is an automatically generated TypeScript class that actually performs the API call.</p>
<p>I am looking for improvement suggestions for this pattern I am using. Also, I cannot control what code is generated through the OpenAPI generator.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T13:17:14.660",
"Id": "230159",
"Score": "1",
"Tags": [
"javascript",
"authentication",
"angular-2+",
"reactive-programming"
],
"Title": "Setting the token for API client generated instances in an Angular application"
} | 230159 |
<p><strong>This code relies on Python3.7.4</strong></p>
<p>I'm learning Heapsort in python 3. Please show me the errors in my code. Runs on my computer but tell me if Python rules or not.</p>
<pre><code>class Heap:
'''constructor'''
def __init__(self,lis):
self.lis=lis
self.a=[]
def heapify(self,i):
self.r=(i-1)//2 #To get the root node
'''To swap value'''
if self.lis[i]<self.lis[self.r]:
self.lis[i],self.lis[self.r]=self.lis[self.r],self.lis[i]
def heapSort(self):
# Build a minheap.
for j in range(len(self.lis)):
for i in range(len(self.lis)-1,-1,-1):
if i==0:
self.a.append(self.lis[0])
self.lis.remove(self.lis[0])
else:
self.heapify(i)
else:
return self.a
obj=Heap([5,4,3,2,1])
print(obj.heapSort())
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T15:53:11.350",
"Id": "448128",
"Score": "2",
"body": "Does it produce the requested output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T01:36:37.793",
"Id": "448177",
"Score": "3",
"body": "_tell me if Python rules or not._ Yes, Python rules."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T05:03:29.367",
"Id": "448183",
"Score": "0",
"body": "Yes, it gives output."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T06:45:33.397",
"Id": "448193",
"Score": "1",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] | [
{
"body": "<p>Most of what I say here is covered in <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>.</p>\n\n<ul>\n<li>In assignment statements, surround an \"=\" with a space on either side.</li>\n<li>Function parameters are separated by a comma followed by another space</li>\n<li>If <code>'''To swap value'''</code> is a docstring, it needs up one line.</li>\n<li>Comparison operators like \"<\" also need a space on either side.</li>\n<li>Use variables with meaningful names. a, lis, j, and i are not meaningful.</li>\n<li>Comma seperation in tuple assignment should also have a space after each comma.</li>\n<li><code>if i==0:</code> can be replaced with <code>if not i:</code></li>\n</ul>\n\n<p>I myself lack experience with sorts and time-complexity, so I'll leave that to others.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T05:11:15.747",
"Id": "448184",
"Score": "0",
"body": "Thank a lot Gloweye to spending your valuable time to get the review of my code. Let me correct as per your suggestion and get back to you. Today I learned many coding fundamentals and styles from your suggestions. Thanks a lot once again"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T05:21:36.250",
"Id": "448186",
"Score": "0",
"body": "if `i == 0:` can be replaced with `if not i:` and not `if i:`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T07:37:54.487",
"Id": "448325",
"Score": "0",
"body": "Derp, im stupid. Thanks."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T13:53:30.947",
"Id": "230162",
"ParentId": "230160",
"Score": "6"
}
},
{
"body": "<h1>Style</h1>\n\n<p>I suggest you check PEP0008 <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">https://www.python.org/dev/peps/pep-0008/</a> the official Python style guide when you write your code and Flake8 for style enforcement. The following goes accordingly:</p>\n\n<ul>\n<li><strong>Blank lines:</strong> Surround top-level function and class definitions with two blank lines. Method definitions inside a class are surrounded by a single blank line. Extra blank lines may be used (sparingly) 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). No blank lines are left between your function definitions.</li>\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. Whenever someone using your code is running <code>help(Heap)</code> this will print 'Constructor' which is invalid to what the help function is made for, you should include a description to the class. I suggest you run <code>help(list)</code> might give you some insights on how docstrings might look like. And none of your methods contain docstrings while they should.</p>\n\n<pre><code>def heapSort(self):\n # Build a minheap.\n</code></pre>\n\n<p>instead of writing a comment, use a docstring:</p>\n\n<pre><code>def heap_sort(self):\n \"\"\"Build a min heap.\"\"\"\n</code></pre></li>\n<li><p><strong>Space around binary operators:</strong> a space should be left on both sides of an operator (+-/*&^**//==!=) <code>self.lis=lis</code> should be <code>self.lis = lis</code> <code>self.a=[]</code> should be <code>self.a = []</code> <code>if i==0:</code> should be <code>if i == 0:</code> ...</p></li>\n<li><strong>Descriptive variable names:</strong> <code>self.lis=lis</code> what is <code>lis</code>? if you're referring to <code>list</code> the common convention is when an identifier conflicts with a built-in function/type it should be written with a trailing underscore: <code>list_</code>\n<code>self.a=[]</code> what is <code>a</code> a name should reflect the object it represents. <code>self.r=(i-1)//2</code> what is <code>r</code>? what is <code>i</code>? ...</li>\n<li><strong>Variable names:</strong> method names should be <code>lower_case_with_underscores</code> as well as variable names. <code>def heapSort(self):</code> should be <code>def heap_sort(self):</code></li>\n<li><strong>Comments:</strong> <code>'''To swap value'''</code> in <code>heapify()</code> second line should be replaced with an inline comment <code># To swap value</code></li>\n</ul>\n\n<h1>Code</h1>\n\n<ul>\n<li><code>def __init__(self,lis):</code> a class with a single parameter is not a good class, only functions that pass stuff are sufficient.</li>\n<li><code>self.r=(i-1)//2</code> instance attribute defined outside the constructor in <code>heapify()</code> method.</li>\n<li><p><strong>main guard:</strong> Use <code>if __name__ == '__main__':</code> guard at the end of your script which allows your module to be imported without running the whole script.</p>\n\n<pre><code>obj=Heap(xyz)\nprint(obj.heapSort())\n</code></pre>\n\n<p><strong>should be written:</strong></p>\n\n<pre><code>if __name__ == '__main__':\n obj = Heap(xyz)\n print(obj.heapSort())\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T06:20:02.633",
"Id": "448191",
"Score": "0",
"body": "Thank a lot bullseye to spending your valuable time to get the review of my code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T06:34:44.750",
"Id": "448192",
"Score": "0",
"body": "You're welcome. You might want to use an upvote (^ sign) if you found that helpful and whenever you decide a best answer, you might accept (check sign) the review to indicate that you no longer need answers."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T05:50:08.390",
"Id": "230206",
"ParentId": "230160",
"Score": "6"
}
},
{
"body": "<p><strong>Code after the suggestion</strong></p>\n\n<pre><code>class Heap:\n def __init__(self,List):\n self.List = List\n self.a = []\n def heapify(self,i):\n #To swap variable\n # (i-1) // 2 = is get the root node\n if self.List[i] < self.List[(i-1) // 2]:\n self.List[i] , self.List[(i-1) // 2] = self.List[(i-1) // 2] , self.List[i] \n def heapSort(self):\n # Build a minheap.\n for i in range(len(self.List)-1,-1,-1):\n if not i:\n self.a.append(self.List[0])\n self.List.remove(self.List[0])\n else: \n self.heapify(i)\n else:\n if self.List:\n self.heapSort()\n return self.a\n\nif __name__==\"__main__\":\n obj=Heap([5,4,3,2,1])\n print(obj.heapSort())\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-06T18:46:06.993",
"Id": "448441",
"Score": "4",
"body": "Could you explain what has changed to initial code? A code dump doesn't do so well around here."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T06:56:11.713",
"Id": "230207",
"ParentId": "230160",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "230206",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-04T13:37:21.827",
"Id": "230160",
"Score": "-2",
"Tags": [
"python",
"python-3.x",
"reinventing-the-wheel",
"heap-sort"
],
"Title": "Heap sort implementation in Python 3"
} | 230160 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.