body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<h2>Problem</h2>
<p>The problem definition is <a href="https://adventofcode.com/2019/day/2" rel="nofollow noreferrer">here</a>. For a quick summary: </p>
<ul>
<li>an IntCode program is an array of ints</li>
<li>the program counter starts from index 0, where it reads an opcode, followed by 0 or more arguments at the next indices, then proceeds to the index after the last argument</li>
<li>opcode 1 takes 3 arguments, <code>a</code>, <code>b</code>, and <code>z</code>, and sets <code>program[z] = program[a] + program[b]</code></li>
<li>opcode 2 does the same but multiplies instead</li>
<li>opcode 99 takes 0 arguments and halts the program</li>
</ul>
<p>In part 1, we take <a href="https://adventofcode.com/2019/day/2/input" rel="nofollow noreferrer">the input</a>, replace index 1 with 12 and index 2 with 2 (<code>restore 12 2</code>), run the program and return index 0.</p>
<p>In part 2 (not shown in the link unless you solve part 1), we find which ints to replace index 1 and 2 with to produce a result where index 0 equals 19690720.</p>
<hr>
<p>My thoughts on this code are that it could probably be simpler. I tried to separate the program counter logic from the instruction execution logic (<code>interpret</code> vs <code>step</code>), but it seems like that resulted in the need for a strange combinator <code>whileWith</code>. I was wondering whether there are better combinators to express this kind of loop, or if there's another approach entirely.</p>
<p>I considered wrapping <code>step</code> in <code>ContT</code> or <code>ExceptT</code>, which would allow some of the nesting to be flattened by using early exit instead, but I wasn't sure which way is best in terms of extensibility.</p>
<p>Any suggestions on this code are welcome, including style, structure, algorithm, etc!</p>
<h2>Code</h2>
<pre class="lang-hs prettyprint-override"><code>import Control.Arrow (second)
import Control.Monad
import Control.Monad.ST
import Data.Array
import Data.Array.ST
import Data.List (find)
data Status = InvalidOp | Terminated | Running | InvalidAddress
deriving (Show, Eq)
newtype Program = Program {
getInts :: Array Int Int
} deriving (Show)
-- Execute the instruction starting at `start`
step :: STArray s Int Int -> Int -> Int -> ST s Status
step arr len start = do
op <- readArray arr start
case op of
99 -> return Terminated
_ -> do
[i, j, store] <- forM [start+1..start+3] (readArray arr)
if not $ all inBounds [i, j, store] then
return InvalidAddress
else do
[a, b] <- forM [i, j] (readArray arr)
case op of
1 -> writeArray arr store (a+b) >> return Running
2 -> writeArray arr store (a*b) >> return Running
_ -> return InvalidOp
where inBounds ix = 0 <= ix && ix < len
interpret :: Program -> Program
interpret (Program prog) = Program $ runSTArray $ do
let len = succ . uncurry subtract $ bounds prog
mArr <- thaw prog
whileWith (== Running) [0, 4..len-1]
(step mArr len)
return mArr
readProgram :: String -> Program
readProgram str =
let nums = fmap read $ split ',' str
in
Program $ listArray (0, length nums - 1) nums
restore :: Int -> Int -> Program -> Program
restore a b = Program . (// [(1, a), (2, b)]) . getInts
-- pt 2
findNounVerb :: Program -> Int -> Maybe (Int, Int)
findNounVerb prog target =
find ((== target) . (! 0) . getInts . interpret . ($ prog) . uncurry restore) $
[(n, v) | n <- [0..1000], v <- [0..n]]
-- util --
split :: Eq a => a -> [a] -> [[a]]
split _ [] = []
split k xs = curr : split k rest
where (curr, rest) = second (drop 1) $ span (/= k) xs
whileWith :: (Monad m) => (ret -> Bool) -> [inp] -> (inp -> m ret) -> m ()
whileWith _ [] _ = return ()
whileWith pred (x:xs) step = do
res <- step x
when (pred res) $
whileWith pred xs step
-- end util --
main :: IO ()
main = do
prog <- readProgram <$> getContents
-- pt 1:
putStrLn "Part 1:"
let output = (! 0) . getInts . interpret . restore 12 2 $ prog
putStrLn $ "Output: " ++ show output
putStrLn ""
-- pt 2:
putStrLn "Part 2:"
let Just (noun, verb) = findNounVerb prog 19690720
putStrLn $ "Noun: " ++ show noun ++ "\n" ++ "Verb: " ++ show verb
print $ 100*noun + verb
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-16T13:39:40.833",
"Id": "461544",
"Score": "0",
"body": "Compare https://codereview.stackexchange.com/questions/233696/advent-of-code-2-haskell-solution"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T03:40:41.020",
"Id": "235334",
"Score": "1",
"Tags": [
"haskell"
],
"Title": "Advent of Code 2 - Intcode Interpreter in Haskell"
}
|
235334
|
<p>This is my first post, I am very new to coding and Python especially,</p>
<p>This code intends to do an excel SUMIF between two tables with different indexes. The first tables has GPS data with timestamp, vehicle ID and distance The second table has vehicle ID and timestamps of events I want to measure the distance run during events</p>
<p>Thanks</p>
<pre><code>for x in range(1,34):
df = pd.read_csv("file"
+ str(x) + '.csv',
parse_dates=[10])
red = 0
green = 0
black = 0
output = [[], [], [], []]
for i in range(len(lista[1])):
for j in range(len(listc[1])):
if listc[1][j] <= lista[3][i] or listc[1][j] >= lista[2][i]:
if lista[7][i] >= listc[1][j] and lista[6][i] <= listc[1][j] and lista[0][i] == listc[0][j] and lista[8][i] == 'intended value' :
red += listc[2][i]
if lista[3][i] >= listc[1][j] and lista[7][i] <= listc[1][j] and lista[0][i] == listc[0][j] and lista[8][i] != 'intended value' :
red += listc[2][i]
if lista[6][i] >= listc[1][j] and lista[2][i] <= listc[1][j] and lista[0][i] == listc[0][j] and lista[8][i] == 'intended value' :
green += listc[2][i]
if lista[7][i] >= listc[1][j] and lista[2][i] <= listc[1][j] and lista[0][i] == listc[0][j] and lista[8][i] != 'intended value' :
green += listc[2][i]
if lista[2][i] >= listc[1][j] and lista[3][i - 1] <= listc[1][j] and lista[0][i] == listc[0][j]:
black += listc[2][i]
toc = timeit.default_timer()
if i % 100 == 0:
print('processing algorithm: {}'.format(toc - tic))
print('we are at row {}'.format(i))
output[0].append(lista[1][i])
output[1].append(red)
output[2].append(green)
output[3].append(black)
red = 0
green = 0
black = 0
toc = timeit.default_timer()
np.savetxt("outfile" + str(x)
+ ".csv", np.column_stack((output[0], output[1], output[2], output[3])), delimiter=",", fmt='%s')
tac = timeit.default_timer()
print('exporting {}'.format(tac - toc))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T07:17:44.087",
"Id": "460528",
"Score": "7",
"body": "Welcome to code review, as this looks very ambiguous, I suggest you explain what is the purpose of this code and you might provide examples of sample input and desired output as well as the csv files you're working with to make it easier for people to understand what is a wrong/right output and review your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T08:25:32.510",
"Id": "460540",
"Score": "3",
"body": "Could you prodie a Minimum Working Exemple ? For the moment, without the data, i'm unable to run your code and hence i cant tests eventual improvements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T08:45:00.930",
"Id": "460542",
"Score": "1",
"body": "Please fix the block nesting/indentation of the first `for`-loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T14:51:26.557",
"Id": "460596",
"Score": "3",
"body": "Your edit is a decent improvement - for the motivation part. Please roll back the changes in the code, see [What should I *not* do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) (You are welcome to ask a cross-linked follow-up question.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T14:40:57.540",
"Id": "460762",
"Score": "0",
"body": "Done. I am really stumbling my way through this. I'll post a new question after I've made it work, thanks guys"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T14:42:39.473",
"Id": "460763",
"Score": "1",
"body": "Welcome to Code Review! Please edit your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. In particular, if \"bad performance\" isn't part of the requirement, then it probably doesn't belong in the title. Thanks!"
}
] |
[
{
"body": "<p>For me, the problem starts with the nested loops showing no specification of <em>what is to be achieved</em>, not even a suggested abstraction (being the body of a function given a <em>name</em>). </p>\n\n<p>Observations:</p>\n\n<ul>\n<li>the output does seem to depend on the order of elements of <code>lista</code><br>\n(even beyond its order: <code>lista[3][i-1]</code>)<br>\n• hope <code>lista[2][i] >= listc[1][j]</code> is never True for <code>i</code> 0<br>\n (unless you <em>want</em> <code>lista[3][-1]</code> accessed)</li>\n<li>the output does <em>not</em> seem to depend on the order of elements of <code>listc</code> </li>\n<li>both <code>lista</code> and <code>listc</code> are not changed<br>\n→ the \"range conditions\" won't change unless at least one index changes </li>\n<li>all of \"the increments\" share the condition <code>lista[0][i] == listc[0][j]</code></li>\n<li>the conditions between <code>lista[6/7][i]</code> and <code>listc[1][j]</code> are <em>not</em> complementary for including equality in both cases\n\n<ul>\n<li>implying <code>red</code>/<code>green</code> possibly getting incremented twice in a single iteration (not using <code>else</code>)</li>\n</ul></li>\n</ul>\n\n<p>idea: </p>\n\n<ul>\n<li>document, in the code, what is to be achieved<br>\nPython supports this with <a href=\"https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring\" rel=\"noreferrer\">docstrings</a></li>\n<li>use telling names</li>\n<li>have a tool help you sticking to <a href=\"https://www.python.org/dev/peps/pep-0008/#a-foolish-consistency-is-the-hobgoblin-of-little-minds\" rel=\"noreferrer\">The Python Style Guide</a></li>\n<li>order <code>listc</code></li>\n<li>for each <code>i</code>, iterate only that part of the ordered <code>listc</code> where <code>lista[0][i] == listc[0][j]</code></li>\n<li>ignore if <code>lista</code> and <code>listc</code> are not \"rectangular\":</li>\n</ul>\n\n<p>food for thought: untested result of refactoring (get tool support for such, too)<br>\n(here extracting local variables, mostly)</p>\n\n<pre><code>list_c = sorted(listc)\nfor i in range(len(lista[1])):\n red = green = black = 0\n a0i = lista[0][i]\n first = bisect_left(list_c[1], a0i)\n beyond = bisect_right(list_c[1], a0i, first)\n if first < beyond:\n a2i = lista[2][i]\n a3i = lista[3][i]\n c2i = list_c[2][i]\n a8i_intended = lista[8][i] == 'intended value'\n for j in range(first, beyond):\n c1j = list_c[1][j]\n if (c1j <= a3i or c1j >= a2i):\n if lista[7][i] >= c1j and lista[6][i] <= c1j and a8i_intended:\n red += c2i\n if a3i >= c1j and lista[7][i] <= c1j and not a8i_intended:\n red += c2i\n if lista[6][i] >= c1j and a2i <= c1j and a8i_intended:\n green += c2i\n if lista[7][i] >= c1j and a2i <= c1j and not a8i_intended:\n green += c2i\n if a2i >= c1j and lista[3][i - 1] <= c1j:\n black += c2i\n toc = timeit.default_timer()\n if i % 100 == 0:\n print('processing algorithm: {}'.format(toc - tic))\n print('we are at row {}'.format(i))\n output[0].append(lista[1][i])\n output[1].append(red)\n output[2].append(green)\n output[3].append(black)\n</code></pre>\n\n<p>afterthought: it may be better to handle <code>listc[1][j] <= lista[3][i]</code> and <code>lista[2][i] <= listc[1][j]</code> separately</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T11:30:26.307",
"Id": "235351",
"ParentId": "235337",
"Score": "7"
}
},
{
"body": "<p>The code does not look appetizing, readable.</p>\n\n<p>I reduced the conditionals which indeed brought some structure into the whole:</p>\n\n<pre><code>red = 0\ngreen = 0\nblack = 0\n\n c1 = listc[1][j]\n if c1 <= lista[3][i] or c1 >= lista[2][i]:\n if lista[0][i] == listc[0][j]:\n c2 = listc[2][i]\n if lista[8][i] == 'intended value':\n if lista[6][i] <= c1 <= lista[7][i]:\n red += c2\n if lista[2][i] <= c1 <= lista[6][i]:\n green += c2\n else:\n if lista[7][i] <= c1 <= lista[3][i]:\n red += c2\n if lista[2][i] <= c1 <= lista[7][i]:\n green += c2\n if lista[3][i - 1] <= c1 <= lista[2][i]:\n black += c2\n</code></pre>\n\n<p>The variables red, green, black to be initialized at the start of the for-i step.</p>\n\n<p>Notice the <em>between</em> expression <code>... <= ... <= ...</code>, a pearl in the Python language.</p>\n\n<p>Introducing variables, especially with good names enormously helps in reading, and simplifies all. Unfortunately here it does not seem to work for indices 6, 7, 2, 6 etcetera.</p>\n\n<p>The algorithm could have been smaller, without repetitive <code>[i]</code> and <code>[j]</code>, when one would not have lista and listc with <code>[column][row]</code> but <code>[row][column]</code>. That is not doable without altering too much.</p>\n\n<p>But one could make columns with meaningful names (<em>not</em> <code>lista3</code>):</p>\n\n<pre><code>lista3 = lista[3]\n...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T13:36:29.170",
"Id": "460583",
"Score": "0",
"body": "I missed the pairs of comparisons constituting \"betweens\" for all the indices and identifiers floating around."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T13:38:49.263",
"Id": "460584",
"Score": "2",
"body": "The *between* expression is sadly not vectorised in numpy. But `~`,`|` and `&` are !"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T12:42:27.750",
"Id": "235355",
"ParentId": "235337",
"Score": "6"
}
},
{
"body": "<p>Working from @JoopEgen answer, i wrote a numpy version that will usualy speed up the whole thing by a huge factor (but since no data are given, i cant test it...)</p>\n\n<p>Well, while doing it, i remarked that you use : </p>\n\n<pre><code>for i in range(len(lista[1])):\n ...\n lista[1][i-1]\n</code></pre>\n\n<p>which is wierd. I then consider that you intended that the last value will be used as the first, as a previous comment proposed. Anyway here is a probably faster version :</p>\n\n<pre><code>import numpy as np\n\n# Rename all this and make them numpy arrays to profit from broadcasting :\nx = [np.array(lista[n]) for n in [1,2,3,6,7]] # becomes 0,1,2,3,4\nx.append(np.array(lista[8]) == 'intended value') # 5\nx.append(np.array(listc[0])) # 6\nx.append(np.array(listc[1])) # 7\nx.append(x[0]) # 8\nfor j in np.arange(len(lista[1])):\n x[8][j] = lista[3,j-1] # the shifted values for the last conditions.\n\n# the final values for the output :\nval = np.array(listc[2])\n\n# Selectors :\ncommon = (x[1] == x[6]) & ((x[7] <= x[2]) | (x[7] >= x[1]))\nred = common & ((x[3] <= x[7]) & (x[7] <= x[4]) & x[5]) | ((x[4] <= x[7]) & (x[7] <= x[2]) & (~x[5]))\ngre = common & ((x[1] <= x[7]) & (x[7] <= x[3]) & x[5]) | ((x[1] <= x[7]) & (x[7] <= x[4]) & (~x[5]))\nbla = common & ( x[8] <= x[7]) & (x[7] <= x[1])\n\n# the result :\noutput = np.array([val,val[reds],val[greens],val[blacks]])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T13:36:52.767",
"Id": "235359",
"ParentId": "235337",
"Score": "2"
}
},
{
"body": "<p>After reviewing some of the answers I rewrited the code and added some descriptions\nThis does not work because I have a index error in pandas... </p>\n\n<p>'''</p>\n\n<p>This code intends to do an excel SUMIF between two tables with different indexes.\nThe first tables has GPS data with timestamp, vehicle ID and distance\nThe second table has vehicle ID and timestamps of events\nI want to measure the distance run during events</p>\n\n<p>Initially I tried to join the tables (dataframes) somehow while working with pandas but I failed\nAfter that I made them lists</p>\n\n<p>'''</p>\n\n<pre><code>import pandas as pd\nfrom datetime import datetime\nimport xlrd\nimport numpy as np\nimport timeit\n\ntic = timeit.default_timer()\n\ndfRaw = pd.read_excel(\"C:\\\\Users\\\\pavlo\\\\PycharmProjects\\\\PEXproject1\\\\DataCleaning\\\\sample data\\\\VehicleEvents.xlsx\", sheet_name=\"vhcllist\") #reading the vehicle event list\ndfRaw = dfRaw.fillna(2000, inplace=False) #replacing the NaN values with 2000 to avoid datetime errors\n\nbook = xlrd.open_workbook(\"C:\\\\Users\\\\pavlo\\\\PycharmProjects\\\\PEXproject1\\\\DataCleaning\\\\sample data\\\\VehicleEvents.xlsx\") #I re-open the file, not sure why...\ndatemode = book.datemode\n\ndfRaw[\"Engineon\"].map(lambda x: # Because the date-times in xls were saved with the excel float format, I found this way to make it into datetime\n xlrd.xldate_as_tuple(x, datemode))\ndfRaw[\"Engineoff\"].map(lambda x:\n xlrd.xldate_as_tuple(x, datemode))\ndfRaw[\"WorkStart\"].map(lambda x:\n xlrd.xldate_as_tuple(x, datemode))\ndfRaw[\"WorkEnd\"].map(lambda x:\n xlrd.xldate_as_tuple(x, datemode))\ndfRaw[\"ParkStart\"].map(lambda x:\n xlrd.xldate_as_tuple(x, datemode))\ndfRaw[\"ParkEnd\"].map(lambda x:\n xlrd.xldate_as_tuple(x, datemode))\n\ndfRaw[\"ENGINEON\"] = dfRaw[\"Engineon\"].map(lambda x: # I made new columns in the dataframe because I had trouble updating the current ones\n datetime(*xlrd.xldate_as_tuple(x,\n datemode)))\ndfRaw[\"ENGINEOFF\"] = dfRaw[\"Engineoff\"].map(lambda x:\n datetime(*xlrd.xldate_as_tuple(x,\n datemode)))\ndfRaw[\"WORKSTART\"] = dfRaw[\"WorkStart\"].map(lambda x:\n datetime(*xlrd.xldate_as_tuple(x,\n datemode)))\ndfRaw[\"WORKEND\"] = dfRaw[\"WorkEnd\"].map(lambda x:\n datetime(*xlrd.xldate_as_tuple(x,\n datemode)))\ndfRaw[\"PARKSTART\"] = dfRaw[\"ParkStart\"].map(lambda x:\n datetime(*xlrd.xldate_as_tuple(x,\n datemode)))\ndfRaw[\"PARKEND\"] = dfRaw[\"ParkEnd\"].map(lambda x:\n datetime(*xlrd.xldate_as_tuple(x,\n datemode)))\n\ndfRaw['TMP'] = dfRaw['ID']\ndfRaw = dfRaw.drop('ID', axis=1)\ndfRaw['ID'] = dfRaw['Vhcl']\n\ntemplist = dfRaw[['ID', 'TMP', # I make the dataframe into a temp list\n 'ENGINEON', 'ENGINEOFF', 'WORKSTART',\n 'WORKEND', 'PARKSTART', 'PARKEND', 'Mode', 'Vhcl']]\n\nvehiclist = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Now it is a list of lists with the indexes I need\nvehiclist[0] = templist['ID'].tolist()\nvehiclist[1] = templist['TMP'].tolist()\nvehiclist[2] = templist['ENGINEON'].tolist()\nvehiclist[3] = templist['ENGINEOFF'].tolist()\nvehiclist[4] = templist['WORKSTART'].tolist()\nvehiclist[5] = templist['WORKEND'].tolist()\nvehiclist[6] = templist['PARKSTART'].tolist()\nvehiclist[7] = templist['PARKEND'].tolist()\nvehiclist[8] = templist['Mode'].tolist()\n\nfor x in range(1,34): # here the code will read from 34 csv files containing GPS informations into a dataframe\n df = pd.read_csv(\"C:\\\\Users\\\\pavlo\\\\PycharmProjects\\\\PEXproject1\\\\DataCleaning\\\\sample data\\\\GpsData\"\n + str(x) + '.csv',\n parse_dates=[10])\n\n df['ID'] = df['gps_id']\n\n gps = df[['ID','Timestamp','distance']] # here I copy the data from the dataframe to a list\n gpslist = [1,2,3] # I make the list of lists\n gpslist[0] = gps['ID'].tolist()\n gpslist[1] = gps['Timestamp'].tolist()\n gpslist[2] = gps['distance'].tolist()\n\n driving = 0\n idle = 0\n working = 0\n\n dists = [[], [], [], []] #this list of lists will capture the distances in the various states\n for i in range(len(vehiclist[1])): #I go through all rows of vehicle list\n driving = idle = working = 0\n for j in range(len(gps[1])): #I go through all rows of gps list\n if gps[1][j] <= vehiclist[3][i] or gps[1][j] >= vehiclist[2][i]: #I want to exclude if the vehicle was off at the gps timestamp\n if vehiclist[0][i] == gps[0][j]:\n c1 = gps[2][i]\n c2 = gps[1][j]\n if vehiclist[8][i] == 'Manual' :\n if vehiclist[6][i] <= c1 <= vehiclist[7][i] :\n driving += c2\n if vehiclist[2][i] <= c1 <= vehiclist[6][i] :\n idle += c2\n else:\n if vehiclist[7][i] <= c1 <= vehiclist[3][i] :\n driving += c2\n if vehiclist[2][i] <= c1 <= vehiclist[7][i] :\n idle += c2\n if vehiclist[3][i] <= c1 <= vehiclist[2][i - 1] :\n working += c2\n toc = timeit.default_timer()\n if i % 100 == 0:\n print('processing algorithm: {}'.format(toc - tic))\n print('we are at row {}'.format(i))\n dists[0].append(vehiclist[1][i])\n dists[1].append(driving)\n dists[2].append(idle)\n dists[3].append(working)\n driving = 0\n idle = 0\n working = 0\n toc = timeit.default_timer()\n np.savetxt(\"outfile\" + str(x)\n + \".csv\", np.column_stack((dists[0], dists[1], dists[2], dists[3])), delimiter=\",\", fmt='%s')\n tac = timeit.default_timer()\n print('exporting {}'.format(tac - toc))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T14:40:00.730",
"Id": "235421",
"ParentId": "235337",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T05:27:54.173",
"Id": "235337",
"Score": "5",
"Tags": [
"python",
"beginner"
],
"Title": "Nested If, working like an excel SUMIF for two unequal lists summing the distance if GPS timestamp meets criteria"
}
|
235337
|
<p>For my website needs I made a custom procedural MySQL function in PHP which can INSERT, UPDATE, SELECT or DELETE data from database. I would like a review and any suggestions for improvement or addition of new features.</p>
<pre><code>function mysqli_database_query($sql, $values, $param = NULL, $result_param = NULL) {
require "dbconn.script.php";
// String to array conversion
if (!is_array($values)) {
$values_array = array($values);
} else {
$values_array = $values;
}
// Number of values checker and string of parameter types creation
$number_of_values = count($values_array);
if ($number_of_values > 1) {
$param_types = implode("", array_map(function($val) { return gettype($val)[0]; }, $values_array));
} else {
$param_types = gettype($values_array[0])[0];
}
// SQL query execution
$stmt = mysqli_stmt_init($conn);
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, $param_types, ...$values_array);
mysqli_stmt_execute($stmt);
// SQL query results management
if (preg_match("/^SELECT.*/", $sql)) {
$results = mysqli_stmt_get_result($stmt);
# RETURN ASSOCIATIVE AND NUMERIC ARRAY COMBINED EVEN IF RESULT PARAMETER IS INVALID
if ($result_param === NULL || $result_param !== "assoc" || $result_param !== "num" || $result_param !== "row") {
return mysqli_fetch_array($results, MYSQLI_BOTH);
# RETURN ASSOCIATIVE ARRAY
} else if ($result_param === "assoc") {
return mysqli_fetch_array($results, MYSQLI_ASSOC);
# RETURN NUMERIC ARRAY
} else if ($result_param === "num") {
return mysqli_fetch_array($results, MYSQLI_NUM);
# RETURN ONE ROW
} else if ($result_param === "row") {
if ($param === NULL || $param !== "id") {
return mysqli_fetch_row($results);
}
# RETURN ONE ROW ID
if ($param === "id") {
$result = mysqli_fetch_row($results);
return $result["id"];
}
}
}
if (preg_match("/^INSERT.*/", $sql)) {
# RETURN LAST INSERTED ID
if ($param === "insert_id") {
return mysqli_insert_id($conn);
# RETURN NUMBER OF AFFECTED ROWS
} else if ($param === "affected_rows") {
return mysqli_affected_rows($conn);
} else {
return false;
}
}
if (preg_match("/^UPDATE.*/", $sql)) {
# RETURN NUMBER OF AFFECTED ROWS
if ($param === "affected_rows") {
return mysqli_affected_rows($conn);
} else {
return false;
}
}
if (preg_match("/^DELETE.*/", $sql)) {
# RETURN NUMBER OF AFFECTED ROWS
if ($param === "affected_rows") {
return mysqli_affected_rows($conn);
} else {
return false;
}
}
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T11:46:57.047",
"Id": "460570",
"Score": "0",
"body": "In your place I would add some usage examples, to demonstrate how this function is going to be used."
}
] |
[
{
"body": "<p>This monster of a function is hard to use and hard to maintain. Besides, it is bloated with duplicated and/or unnecessary code. Last but not least, the way <code>require "dbconn.script.php";</code> is called will make your code run slower and make some features (such as transactions) unavailable.</p>\n<h3>Too many connections</h3>\n<p>Your current code is connecting to the database every time it runs a query. You shouldn't do that. Always connect strictly <strong>once</strong> and then pass a connection variable as a function parameter.</p>\n<h3>Useless regexp</h3>\n<p>You already control the return type buy means of $param variable. No need to check the query type manually. It is useless <em>and</em> error prone. What if your query is <code>CALL</code>? <code>SET</code>? <code>REPLACE</code>?</p>\n<h3>Passing values as array is not that hard.</h3>\n<p>With your function you have a choice, whether to pass $values as array or not. It makes the code hard to read. At the same time adding two square brackets to your $values is not a big deal. So just just make $values an array mandatory.</p>\n<h3>Too much tasks for a function</h3>\n<p>The first question I must ask, <em>why only a single function</em> to perform so many tasks? All right, I can make it you are not familiar with OOP and don't want to use a class (which would be the best solution of course). But why not to make a set of functions, each serving for its own purpose? Why following that horrible practice of procedural mysqli when you have to write a helluvalot of words every time you calling a simple function (<code>mysqli_stmt_get_result($stmt)</code> vs. <code>$stmt->get_result()</code>)?</p>\n<p>Here is your intended function call</p>\n<pre><code>$rows = mysqli_database_query($sql, $id, "affected_rows");\n</code></pre>\n<p>compare it with with a code which is shorter but more meaningful and readable at the same time:</p>\n<pre><code>$rows = mysqli_delete($sql, [$id]);\n</code></pre>\n<p>A function name should be meaningful and tell you what does this function do. It should be a function name, not a parameter.</p>\n<p>In your place I would create a set of functions. Say, a basic one that just performs a query</p>\n<pre><code>function mysqli_database_query($conn, $sql, $values, $return_result = true)\n{\n $types = $types ?: str_repeat("s", count($params));\n $stmt = $conn->prepare($sql);\n $stmt->bind_param($types, ...$params);\n $stmt->execute();\n return ($return_result) ? $stmt->get_result() : $stmt;\n}\n</code></pre>\n<p>and then add some helper functions for various tasks</p>\n<pre><code>function mysqli_delete($conn, $sql, $values)\n{\n $stmt = mysqli_database_query($conn, $sql, $values, false);\n $return $stmt->affected_rows();\n}\nfunction mysqli_assoc($conn, $sql, $values)\n{\n $result = mysqli_database_query($conn, $sql, $values);\n $return $result->fetch_assoc();\n}\nfunction mysqli_all($conn, $sql, $values)\n{\n $result = mysqli_database_query($conn, $sql, $values);\n $return $result->fetch_all(MYSQLI_ASSOC);\n}\n</code></pre>\n<p>you can use the following function instead of that awkward $param = "id" of yours, for any column, not only id. Just select the desired column, i.e. <code>SELECT user_id FROM table ...</code>:</p>\n<pre><code>function mysqli_cell($conn, $sql, $values)\n{\n $result = mysqli_database_query($conn, $sql, $values);\n $row = $return $result->fetch_row();\n return ($row) ? $row[0] : false;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T17:17:25.960",
"Id": "460616",
"Score": "0",
"body": "Thank you for the detailed review of my code. I want to tell you that I am just a beginner in programming, so I still stick to the procedural PHP. I know a little about OOP. I have a few questions more:\n- I didn't quite understand what did you mean by passing values as array mandatory. If I have an array of values and I want to add them to my function with ``[]`` as you suggested, it would convert it to a multidimensional array that will not work in my case (I think).\n- I cannot grasp this: ``return ($return_result) $stmt->get_result() : $stmt;``. Can you explain it to me?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T17:20:27.690",
"Id": "460618",
"Score": "0",
"body": "And one more thing. How do you call a custom function within another custom function if they are defined within same page? I only succeeded in this by having separate files and the I include file with function1 in file with function2 which uses function1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T17:28:41.803",
"Id": "460619",
"Score": "0",
"body": "Thank you for the good questions. In your code you have a function that converts $values to array if it is not, `if (!is_array($values))`. What I suggest is to always send $values as array and thus remove this code. A $return_result code is a ternary operator you can Google it up. Based in this variable's value it tells a function to return either a statement or a result"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T17:36:14.897",
"Id": "460620",
"Score": "0",
"body": "Ok, I think I understand now. Can you explain me why did you decided to use this code ``$types = $types ?: str_repeat(\"s\", count($params));`` for generating variable types, instead of my version - ``$param_types = implode(\"\", array_map(function($val) { return gettype($val)[0]; }, $values_array));``?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T17:37:44.840",
"Id": "460622",
"Score": "0",
"body": "MySQL will gladly accept all types as strings, no need for anything else. Besides, such a code like yours could lead to problems. I wrote about it several times, let me find it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T17:42:12.280",
"Id": "460624",
"Score": "0",
"body": "Also, as I understand this code ``$types = $types ?: str_repeat(\"s\", count($params));`` it evaluated if $types are set. If not, it will generate it from the number of array members? Am I correct? And if I am, where should those be set previously? As one of the function arguments?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T17:57:05.757",
"Id": "460626",
"Score": "0",
"body": "I am terribly sorry, it's a bad copy paste from my [function](https://phpdelusions.net/mysqli/simple) that accepts an optional types variable"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T18:33:36.440",
"Id": "460636",
"Score": "0",
"body": "Ok, everything is clear now. Thank you very much for your help."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T12:20:48.973",
"Id": "235354",
"ParentId": "235343",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235354",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T08:19:07.837",
"Id": "235343",
"Score": "1",
"Tags": [
"php",
"mysql",
"mysqli"
],
"Title": "Custom PHP MySQL database queries function - Suggestions for improvement or additions"
}
|
235343
|
<p>I took a stab at implementing <code>Promise.all()</code>:</p>
<pre class="lang-js prettyprint-override"><code>"use strict";
function all (...promises) {
const promise = new Promise((resolve, reject) => {
let counter = 0;
const values = [];
let rejected = false;
promises.forEach(
(promise, idx) => {
promise.then(val => {
counter++;
values[idx] = val;
if (counter === promises.length)
resolve(values);
},
() => {
if (!rejected) {
reject(new Error(`${promise} was rejected!`));
rejected = true;
}
}
);
}
);
});
return promise;
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T09:09:35.953",
"Id": "460548",
"Score": "1",
"body": "What is it supposed to do? What made you write this? How will it be used?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T09:31:25.660",
"Id": "460556",
"Score": "0",
"body": "I was learning about promises. It would probably not be used since it's a reimplementation of something that already exists as a built in."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T12:16:57.770",
"Id": "460574",
"Score": "0",
"body": "Whoa whoa hold your horses why is resolve suddenly called fulfill?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T12:30:27.727",
"Id": "460578",
"Score": "0",
"body": "I guess I'll change that. I'm still learning promises, and the answer would be that I don't understand why it's called `resolve()` and not `fulfill()` in the first place."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T12:33:47.970",
"Id": "460579",
"Score": "2",
"body": "When someone suggests a change to the *code* in a comment, don't edit your question, just note it, and maybe make a change to your actual code"
}
] |
[
{
"body": "<p>Good job using <code>const</code> for <code>values</code>, as well as <code>let</code> for re-assignable values like <code>counter</code> and <code>rejected</code>.</p>\n\n<p>Did you test this code? My presumption is that it didn't happen, because when <a href=\"https://jsbin.com/zumeculobe/edit?js,console,output\" rel=\"nofollow noreferrer\">I tried running it</a>, I see the following error:</p>\n\n<blockquote>\n <p>error promise.then is not a function</p>\n</blockquote>\n\n<p>This is because the promises are spread out:</p>\n\n<blockquote>\n<pre><code>function all (...promises) {\n</code></pre>\n</blockquote>\n\n<p>Without the spread operator it appears to run as I would expect, as long as each entry in <code>promises</code> is a promise. </p>\n\n<p>I must admit I compared with <a href=\"https://medium.com/@muralikv/implementing-promise-all-in-javascript-732076497946\" rel=\"nofollow noreferrer\">another implementation of <code>Promise.all()</code></a>. In comparison with that function, yours tracks <code>rejected</code>, whereas the other one simply calls <code>reject</code> whenever a promise is rejected.</p>\n\n<p>Another thing I noticed is that the variable name <code>promise</code> is reused - both for the outer promise to be returned by <code>all()</code> as well as the callback to <code>promises.forEach()</code>. It would be wise to use different names to improve readability. In fact there is little need to assign the outer promise - it can simply be returned without being assigned to a variable since it isn't modified after being instantiated.</p>\n\n<p>Another aspect to consider is that <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all\" rel=\"nofollow noreferrer\"><code>Promise.all()</code></a> can accept promises or non-promises - e.g. the MDN documentation gives an example like this:</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 promise1 = Promise.resolve(3);\nconst promise2 = 42; // <- not really a promise\nconst promise3 = new Promise(function(resolve, reject) {\n setTimeout(resolve, 100, 'foo');\n});\n\nPromise.all([promise1, promise2, promise3]).then(function(values) {\n console.log(values);\n}).catch(error => {\n console.log('error: ', error.message); \n});\n// expected output: Array [3, 42, \"foo\"]</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>With your code, it throws the error <code>promise.then is not a function</code> so it might be wise to check if each item is a promise before calling <code>.then()</code> on it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T12:06:36.933",
"Id": "464899",
"Score": "0",
"body": "I did test the function, we probably just used it differently. It's been a while, but IIRC I went with spread because it was how I used the function."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T00:52:47.523",
"Id": "237116",
"ParentId": "235344",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T08:26:18.237",
"Id": "235344",
"Score": "3",
"Tags": [
"javascript",
"beginner",
"ecmascript-6",
"asynchronous",
"promise"
],
"Title": "Implementing `Promise.all()`"
}
|
235344
|
<p>I've written the following code to check if a value in a data frame changes. I'm looking at the last 5 values. If there was no change at all I want my code to return 1, if a single one (or multiple) of the last 5 are different to the value that is being checked return 0. Finally I want the returned values in a new column in my data frame.</p>
<p>Here's my code so far. It works but I think there is a nicer (and more clean) way to do it.</p>
<pre><code>mydata <- data.frame("id" = 1:100, "ta" = c(sample(x = c(-5:20), size = 94, replace = T), rep(1,6))) # include a repetition to check if code works
nums <- mydata$id # create a dummy for iteration
qc_dummy <- vector(mode = "list", length = length(nums)) # create a dummy vector for the values computed in the for loop
for(i in 1:length(nums)) {
qc_dummy[[i]] <- ifelse(mydata[nums[i], 2] - mydata[nums[i-1], 2] == 0,
ifelse(mydata[nums[i], 2] - mydata[nums[i-2], 2] == 0,
ifelse(mydata[nums[i], 2] - mydata[nums[i-3], 2] == 0,
ifelse(mydata[nums[i], 2] - mydata[nums[i-4], 2] == 0,
ifelse(mydata[nums[i], 2] - mydata[nums[i-5], 2] == 0, 1, 0) ,0), 0) ,0) ,0)
}
mydata$qc1 <- as.vector(c(0,unlist(qc_dummy))) # first value of list is skipped by unlist (logi(0)) -> add 0
</code></pre>
|
[] |
[
{
"body": "<p>I reduced the example data, for easier viewing</p>\n\n<pre><code># new example data:\nmydata <- data.frame(ta = 1:13)\nmydata[2:3, 1] <- 1L\nmydata[6:12, 1] <- 2L\n\nn <- 3 # how many equal values we need\n\nrequire(data.table)\nsetDT(mydata) # convert to data.table\nmydata\nmydata[, mathcPrev := fifelse((ta - shift(ta, 1)) == 0L, T, F, F)]\nmydata[, g := cumsum(!mathcPrev)] # grouping value, if value has changed\nmydata[, count := cumsum(mathcPrev), by = g]\nmydata[, qc2 := fifelse(count >= n, 1L, 0L)]\nmydata\n# ta mathcPrev g count qc2\n# 1: 1 FALSE 1 0 0\n# 2: 1 TRUE 1 1 0\n# 3: 1 TRUE 1 2 0\n# 4: 4 FALSE 2 0 0\n# 5: 5 FALSE 3 0 0\n# 6: 2 FALSE 4 0 0\n# 7: 2 TRUE 4 1 0\n# 8: 2 TRUE 4 2 0\n# 9: 2 TRUE 4 3 1\n# 10: 2 TRUE 4 4 1\n# 11: 2 TRUE 4 5 1\n# 12: 2 TRUE 4 6 1\n# 13: 13 FALSE 5 0 0\n</code></pre>\n\n<p>So, the idea is to create index <code>mathcPrev</code>, that shows if this value matches previous, and then we can count how many equal values we have in a row.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T09:12:13.953",
"Id": "235346",
"ParentId": "235345",
"Score": "1"
}
},
{
"body": "<p>To my understanding you want a new column <code>qc1</code> that takes value 1 if the current element matches the previous 5 elements and takes value 0 otherwise.</p>\n\n<p>This feels like a great application of run-length encoding. I'll borrow the great example data from @minem:</p>\n\n<pre><code>mydata <- data.frame(ta = 1:13)\nmydata[2:3, 1] <- 1L\nmydata[6:12, 1] <- 2L\nmydata$ta\n# [1] 1 1 1 4 5 2 2 2 2 2 2 2 13\n</code></pre>\n\n<p>The run-length encoding tells us how many times each value is repeated in a row:</p>\n\n<pre><code>rle(mydata$ta)\n# Run Length Encoding\n# lengths: int [1:5] 3 1 1 7 1\n# values : int [1:5] 1 4 5 2 13\n</code></pre>\n\n<p>We read from this output that we have 5 runs: 1 repeated 3 times, 4 repeated 1 time, 5 repeated 1 time, 2 repeated 7 times, and 13 repeated 1 time. For each run, we know the first 5 values won't be preceded by 5 identical elements (<code>0</code> in the output), while elements 6 and onward will (<code>1</code> in the output). So the number of <code>0</code>s at the beginning of each run is:</p>\n\n<pre><code>with(rle(mydata$ta), pmin(lengths, 5))\n# [1] 3 1 1 5 1\n</code></pre>\n\n<p>And the number of <code>1</code>s at the end of each run is:</p>\n\n<pre><code>with(rle(mydata$ta), pmax(lengths-5, 0))\n# [1] 0 0 0 2 0\n</code></pre>\n\n<p>So we just need to <a href=\"https://stackoverflow.com/a/25961969/3093387\">interleave these two vectors</a> within a call to <code>rep</code> to yield your eventual one-liner for this operation:</p>\n\n<pre><code>mydata$qc1 <- with(rle(mydata$ta),\n rep(rep(0:1, length(values)), c(rbind(pmin(lengths, 5), pmax(lengths-5, 0)))))\nmydata\n# ta qc1\n# 1 1 0\n# 2 1 0\n# 3 1 0\n# 4 4 0\n# 5 5 0\n# 6 2 0\n# 7 2 0\n# 8 2 0\n# 9 2 0\n# 10 2 0\n# 11 2 1\n# 12 2 1\n# 13 13 0\n</code></pre>\n\n<p>If you were planning to do this with a bunch of different window sizes, then a function would make the most sense, which would take the window size as an argument. Here I'll split up the calculation into smaller pieces for readability:</p>\n\n<pre><code>window.repeat <- function(vals, window.size) {\n r <- rle(vals)\n num.run <- length(r$values)\n run.0s <- with(r, pmin(lengths, window.size))\n run.1s <- with(r, pmax(lengths-window.size, 0))\n rep(rep(0:1, num.run), c(rbind(run.0s, run.1s)))\n}\n</code></pre>\n\n<p>Now we could, for instance, label each element with whether it had 2 or more repeats before it:</p>\n\n<pre><code>mydata$qc1 <- window.repeat(mydata$ta, 2)\nmydata\n# ta qc1\n# 1 1 0\n# 2 1 0\n# 3 1 1\n# 4 4 0\n# 5 5 0\n# 6 2 0\n# 7 2 0\n# 8 2 1\n# 9 2 1\n# 10 2 1\n# 11 2 1\n# 12 2 1\n# 13 13 0\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T15:23:36.830",
"Id": "235369",
"ParentId": "235345",
"Score": "1"
}
},
{
"body": "<p>If you are willing to use additional packages, then this could be cleanly handled by performing a rolling apply on your vector. For instance, you could compute if the rolling minimum of your vector with window length 6 equals the rolling maximum with the same window length:</p>\n\n<pre><code>library(RcppRoll)\nas.numeric(roll_min(mydata$ta, 6) == roll_max(mydata$ta, 6))\n# [1] 0 0 0 0 0 1 1 0\n</code></pre>\n\n<p>All we need to do is add 0 for the first 5 elements (which have been removed from this calculation), yielding our one-liner:</p>\n\n<pre><code>mydata$qc1 <- c(rep(0, 5), roll_min(mydata$ta, 6) == roll_max(mydata$ta, 6))\nmydata\n# ta qc1\n# 1 1 0\n# 2 1 0\n# 3 1 0\n# 4 4 0\n# 5 5 0\n# 6 2 0\n# 7 2 0\n# 8 2 0\n# 9 2 0\n# 10 2 0\n# 11 2 1\n# 12 2 1\n# 13 13 0\n</code></pre>\n\n<p>You could also wrap this into a function to allow variable window sizes:</p>\n\n<pre><code>window.repeat <- function(vals, window.size) {\n c(rep(0, window.size), roll_min(vals, window.size+1) == roll_max(vals, window.size+1))\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T15:42:37.560",
"Id": "235372",
"ParentId": "235345",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "235346",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T08:32:42.313",
"Id": "235345",
"Score": "2",
"Tags": [
"r",
"iteration"
],
"Title": "Flagging system: Check for changing values in a data frame"
}
|
235345
|
<p>I have <code>Grade</code> enum and there is a static method to convert a string value to the particular enum value.</p>
<pre><code>public enum Grade {
None("N"),
NotAccepted("-"),
Accepted("+"),
Uncertain("?");
private final String gradeSymbol;
Grade(String gradeSymbol) {
this.gradeSymbol = gradeSymbol;
}
public String getGradeSymbol() {
return gradeSymbol;
}
public static Grade fromGradeSymbol(final String gradeSymbol) {
switch (gradeSymbol) {
case "N":
return None;
case "-":
return NotAccepted;
case "+":
return Accepted;
case "?":
return Uncertain;
default:
throw new IllegalArgumentException("Unexpected grade symbol: " + gradeSymbol);
}
}
@Override
public String toString() {
return this.gradeSymbol;
}
}
</code></pre>
<p>My question is, what is better way to handle unexpected grade symbol in the static <code>fromGradeSymbol()</code> method.</p>
<p>Another option I consider is the approach using <code>Optional</code> and returning <code>Optional.empty()</code> instead of throwing <code>IllegalArgumentException</code>.</p>
<p>Like this:</p>
<pre><code>public static Optional<Grade> fromGradeSymbol(final String gradeSymbol) {
switch (gradeSymbol) {
case "N":
return Optional.of(None);
case "-":
return Optional.of(NotAccepted);
case "+":
return Optional.of(Accepted);
case "?":
return Optional.of(Uncertain);
default:
return Optional.empty();
}
}
</code></pre>
<p>My thoughts:</p>
<p>Throwing exception looks more logical, because it is being thrown in not expected case, when wrong value has been passed. But throwing exception makes it necessary to catch this exception anywhere where I convert string to the enum.</p>
<p>Use of <code>Optional</code> does not involve exceptions and makes cleaner code, without try-catch construct. But it somehow <code>hides</code> the unexpected input.</p>
<p>Sure, I can assume that every time when Optional does not contain a value we have an unexpected input. But it feels like code smell.</p>
<p>What do you think?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T11:03:10.690",
"Id": "460561",
"Score": "0",
"body": "You should at least be looping over `Grade.values()`. If you need to call `fromGradeSymbol` frequently, then you should build a static `Map<String, Grade>` and use that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T11:13:43.040",
"Id": "460564",
"Score": "0",
"body": "Thank you. What do you think about the main question regarding using `Optional` and throwing `IllegalArgumentException`? Do you share my thoughts or have different opinion ?"
}
] |
[
{
"body": "<p>All enumerations have a default <code>valueOf(String)</code> method that throw an <code>IllegalArgumentException</code> so your first idea is coherent.</p>\n\n<p>I would say that it depends (..). It depends of your use cases:</p>\n\n<ul>\n<li>If he conversion would be called form an unsafe (user/api) input, then there are chances that you receive an unexpected symbol. And using <code>Optional</code> will force the developer to handle that case more explicitely. </li>\n<li>If the convesrion is made from a safe input (code/config), then you can live with the exception.</li>\n</ul>\n\n<p>In the book <em>Effective Java</em> from <em>Joshua Bloch</em> (Addison-Wesley Professional, 978-0134685991) there is a full chapter on that subject (in the 2nd edition):</p>\n\n<blockquote>\n <p>Enum types have an automatically generated valueOf(String) method that\n translates a constant’s name into the constant itself.</p>\n \n <p>[..]</p>\n \n <p>The following code\n (with the type name changed appropriately) will do the trick for any enum, so long\n as each constant has a unique string representation: </p>\n</blockquote>\n\n<pre><code>// Implementing a fromString method on an enum type\nprivate static final Map<String, Operation> stringToEnum\n = new HashMap<String, Operation>();\nstatic { // Initialize map from constant name to enum constant\n for (Operation op : values())\n stringToEnum.put(op.toString(), op);\n }\n\n// Returns Operation for string, or null if string is invalid\npublic static Operation fromString(String symbol) {\n return stringToEnum.get(symbol);\n}\n</code></pre>\n\n<p>That chapter (and the whole book) is worth the read: <em>CHAPTER 6 ENUMS AND ANNOTATIONS</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T11:16:23.787",
"Id": "460565",
"Score": "0",
"body": "Thank you. Conversion would be called from unsafe input (received text files from outside). So, using `Optional` is better in this case ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T11:24:40.503",
"Id": "460567",
"Score": "0",
"body": "As said in my answer, and in my opinion, yes. Except if you want to \"fail\" the whole process for an unknown symbol."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T11:26:10.197",
"Id": "460569",
"Score": "0",
"body": "Understood. Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T16:49:54.643",
"Id": "460614",
"Score": "0",
"body": "Do not use Optional in this case at all. See my answer."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T11:13:12.507",
"Id": "235350",
"ParentId": "235348",
"Score": "4"
}
},
{
"body": "<p><strong>Single Responsibility</strong></p>\n\n<p>My rule of thumb is that no extra methods or data should be added to an enum. If input has to be converted to an enum (or enum to output), a separate <code>Function</code> is created to handle the transformation. This way the enum does not get piggybacked with any additional responsibilities. The enum should be used for computation only.</p>\n\n<p>Once you do that your problem becomes simple, as the responsibility of the unknown grade symbol is no longer responsibility of the enum. It becomes the responsibility of the component that should be responsible for incorrect input: the input handler. Now the correct action can be chosen from the specification that was made for the input handler. The Operation enum no longer has to worry about situations where it doesn't exist. It always exists.</p>\n\n<p>This follows the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">single responsibility principle</a>.</p>\n\n<p>Thus:</p>\n\n<pre><code>public class SymbolToOperationConverter implements Function<String, Operation> {\n\n // Copy gervais.b's init routine.\n private static final Map<String, Operation> CONVERSION_MAP = ...;\n\n public Operation apply(String symbol) {\n Operation op = CONVERSION_MAP.get(symbol);\n if (op != null) {\n return op;\n } else {\n // My spec chooses to throw an excepotion.\n throw new InvalidInputException(...);\n }\n }\n}\n</code></pre>\n\n<p><strong>Useless Use Of Optional</strong></p>\n\n<p><code>Optionals</code> are to Java programmers what <code>cat</code> is to Unix admins. More often than not they are completely unnecessary. Optionals were intended to be a way to communicate the possibility of null values in public interfaces in a code level (as opposed to documentation or annotations). The <code>fromGradeSymbol</code> method is completely internal to your application so you should know that it can return nulls and have unit tests for those use cases (that is, if you choose to not follow my advice above). There is literally nothing evil with returning a null value or testing for null with an if statement. The evil is <em>not knowing if a third party library you use might return null or not</em>. <a href=\"https://stackoverflow.com/questions/26327957/should-java-8-getters-return-optional-type/26328555#26328555\">Optional was created to fight that evil</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T17:14:25.817",
"Id": "460615",
"Score": "0",
"body": "\"for computation only\"? I think you meant \"for grouping the possible choices and storing one of them only\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T19:31:13.933",
"Id": "460652",
"Score": "0",
"body": "Maybe my vocabulary isn't perfect but I meant that the enum is used \"in algorithmic computation,\" as opposed to \"in format transformation.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T19:32:16.893",
"Id": "460653",
"Score": "2",
"body": "I disagree about the uselessness of optionals and being only for third party interfaces. Being internal is irrelevant if you're a client of your own code. They're semantically useful for any reader including yourself, and in my opinion are more readable than annotations. \n\nEither way, you could have had a comparable question of returning null versus throwing an exception. Both implementations have valid use cases, so pick the one that's actually more useful to you. If both are necessary, you can implement both and differentiate by name."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T20:02:56.523",
"Id": "460656",
"Score": "1",
"body": "You can disagree as much as you like, but the post I linked was written by one of the Java architects who were responsible for designing them. I didn't actually invent the claim out of thin air. :) Anyway, being a client of your own code is relevant because you know the code. You're really supposed to know what you are doing when you use your own code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T20:10:35.507",
"Id": "460659",
"Score": "1",
"body": "Using an optional requires three method calls, one object allocation and one if statement at minimum. A null check requires one if statement. You're not supposed to just whip out code for fun when you actually know you don't need an optional. Especially when the option is not a least bit worse. People like to use optionals because they have the incorrect ifea that null checks are bad. Again what is bad is not knowing if null is possible. And with your own code you always know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T07:53:52.373",
"Id": "460719",
"Score": "1",
"body": "This is an interesting, and strongly opinionated, point of view. The linked article from Brian Goetz Does not say that \"you should not use Optional\" but more \"do not abuse\". I disagree when @TorbenPutkonen say that we are supposed to \"know what you are doing\", I know it for today but not in 3 months and my colleagues does not know. Again, if the probability of receiving an unknown symbol is not exceptional, then don't use an exception or, at least, provide a test method to avoid using exception to control the flow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T08:06:09.890",
"Id": "460720",
"Score": "0",
"body": "Well that went into semantics now. :) Use of Optional in this particular case is abuse, so it shouldn't be used in this particular case. And anyway, the need for Optionals in this case stemmed from the incorrect use of enumerations. We can discuss general aspects of Optionals in chat."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T16:28:43.027",
"Id": "235374",
"ParentId": "235348",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "235350",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T09:37:56.933",
"Id": "235348",
"Score": "4",
"Tags": [
"java",
"enum"
],
"Title": "Better approach on handling unexpected string upon converting it to the enum value"
}
|
235348
|
<h1>Background info</h1>
<p>I have just started using/ learning how to use Next.js and developed a basic application which allows users to view several pages, some of which are authentication protected. Users must sign in/ up, in order to view content on other pages.</p>
<p>I'm using Firebase's Google Authentication to handle my user login.</p>
<p>The code I will be referring to in my question exists in the following repository:
<a href="https://github.com/myamazingthrowaway/nextjswebsite" rel="noreferrer">https://github.com/myamazingthrowaway/nextjswebsite</a></p>
<p>A live demo of the app can be found here:<br/>
<a href="https://nextjswebsite-kappa-sand.now.sh/" rel="noreferrer">https://nextjswebsite-kappa-sand.now.sh/</a></p>
<p>(it uses cross-site cookies to handle firebase google login - I don't know how to change this default behaviour, so if it doesn't work first time, make sure your browser allows cross-site cookies)</p>
<p>I based my authentication logic on the following repository:<br/>
<a href="https://github.com/taming-the-state-in-react/nextjs-redux-firebase-authentication" rel="noreferrer">https://github.com/taming-the-state-in-react/nextjs-redux-firebase-authentication</a></p>
<h1>What I'd like to achieve</h1>
<p>I'd like to know how to improve my logic and code, to utilise the power of next.js and server side rendering. I'd like to make sure I'm using appropriate, safe & efficient code for my user authentication. Most importantly, I'm here to learn from my mistakes and expand my knowledge of user authentication, higher order components and the next.js workflow.</p>
<h1>My Code</h1>
<p>In my <code>_app.js</code> file, I have a <code>Shell</code> component which handles my sidebar & navbar for the entire web app. It accepts child components to be rendered within the confines of the sidebar etc. </p>
<p>Perhaps this isn't the best way to handle how the application flows and would be more than happy to accept suggestions on how to improve this.</p>
<p>The <code>_app.js</code> file looks like this: </p>
<pre><code>import React from "react";
import App from "next/app";
import CssBaseline from "@material-ui/core/CssBaseline";
import { ThemeProvider } from "@material-ui/styles";
import { Provider } from "react-redux";
import withRedux from "next-redux-wrapper";
import initStore from "../src/store";
import theme from "../src/theme";
import Shell from "../src/components/Shell";
class EnhancedApp extends App {
static async getInitialProps({ Component, ctx }) {
return {
pageProps: Component.getInitialProps
? await Component.getInitialProps(ctx)
: {}
};
}
componentDidMount() {
const jssStyles = document.querySelector("#jss-server-side");
if (jssStyles) {
jssStyles.parentNode.removeChild(jssStyles);
}
}
render() {
const { Component, pageProps, store } = this.props;
return (
<>
<Provider store={store}>
<ThemeProvider theme={theme}>
<title>Next.js</title>
<CssBaseline />
<Shell>
<Component {...pageProps} />
</Shell>
</ThemeProvider>
</Provider>
</>
);
}
}
export default withRedux(initStore)(EnhancedApp);
</code></pre>
<p>My <code>Shell</code> component looks like this:</p>
<pre><code>import React from "react";
import Router from "next/router";
import { connect } from "react-redux";
import {
Drawer,
List,
Divider,
ListItem,
ListItemIcon,
ListItemText,
Hidden,
AppBar,
Toolbar,
IconButton,
Button
} from "@material-ui/core";
import { ProfileIcon } from "../index";
import MonetizationOnOutlinedIcon from "@material-ui/icons/MonetizationOnOutlined";
import AccountBalanceWalletRoundedIcon from "@material-ui/icons/AccountBalanceWalletRounded";
import AccountBoxRoundedIcon from "@material-ui/icons/AccountBoxRounded";
import VpnKeyRoundedIcon from "@material-ui/icons/VpnKeyRounded";
import ExitToAppRoundedIcon from "@material-ui/icons/ExitToAppRounded";
import MenuIcon from "@material-ui/icons/Menu";
import { makeStyles } from "@material-ui/core/styles";
import * as routes from "../../constants/routes";
import { auth } from "../../firebase/firebase";
const drawerWidth = 180;
const useStyles = makeStyles(theme => ({
content: {
flexGrow: 1,
padding: theme.spacing(3)
},
root: {
display: "flex"
},
container: {
flexGrow: 1
},
toolbar: theme.mixins.toolbar,
drawer: {
[theme.breakpoints.up("md")]: {
width: drawerWidth,
flexShrink: 0
}
},
drawerPaper: {
width: drawerWidth
},
appBar: {
background: "linear-gradient(45deg, #FF8E53 30%, #ff4d73 90%)",
marginLeft: drawerWidth,
[theme.breakpoints.up("md")]: {
width: `calc(100% - ${drawerWidth}px)`
}
},
logoContainer: {
background: "linear-gradient(45deg, #ff4d73 30%, #FF8E53 90%)",
justifyContent: "center",
flexDirection: "column",
height: "15rem"
},
menuButton: {
marginRight: theme.spacing(2),
[theme.breakpoints.up("md")]: {
display: "none"
}
},
rightAlign: {
marginLeft: "auto",
marginRight: -12,
cursor: "pointer"
},
hoverCursor: {
cursor: "pointer"
}
}));
const Shell = ({ children, authUser }) => {
const classes = useStyles();
const [mobileOpen, setMobileOpen] = React.useState(false);
const handleGoToEarnPage = () => {
Router.push(routes.EARN);
if (mobileOpen) handleDrawerToggle();
};
const handleGoToSignInPage = () => {
Router.push(routes.SIGN_IN);
if (mobileOpen) handleDrawerToggle();
};
const handleGoToWithdrawPage = () => {
Router.push(routes.WITHDRAW);
if (mobileOpen) handleDrawerToggle();
};
const handleGoToProfilePage = () => {
Router.push(routes.PROFILE);
if (mobileOpen) handleDrawerToggle();
};
const handleDrawerToggle = () => {
setMobileOpen(!mobileOpen);
};
const handleGoToHomePage = () => {
Router.push(routes.LANDING);
if (mobileOpen) handleDrawerToggle();
};
const handleSignOut = () => {
auth.signOut();
if (mobileOpen) handleDrawerToggle();
};
const drawer = (
<>
<AppBar position="static">
<Toolbar className={classes.logoContainer}>
<img
src="/images/logo/logo.png"
alt="my logo"
height="120rem"
onClick={handleGoToHomePage}
className={classes.hoverCursor}
/>
</Toolbar>
</AppBar>
<List>
<ListItem button key="Earn" href="/earn" onClick={handleGoToEarnPage}>
<ListItemIcon>
<MonetizationOnOutlinedIcon />
</ListItemIcon>
<ListItemText primary="Earn" />
</ListItem>
<ListItem
button
key="Withdraw"
href="/withdraw"
onClick={handleGoToWithdrawPage}
>
<ListItemIcon>
<AccountBalanceWalletRoundedIcon />
</ListItemIcon>
<ListItemText primary="Withdraw" />
</ListItem>
<Divider variant="middle" />
{!authUser && (
<List>
<ListItem
button
key="Sign In"
href="/signin"
onClick={handleGoToSignInPage}
>
<ListItemIcon>
<VpnKeyRoundedIcon />
</ListItemIcon>
<ListItemText primary="Sign In" />
</ListItem>
</List>
)}
{authUser && (
<List>
<ListItem
button
key="Profile"
href="/profile"
onClick={handleGoToProfilePage}
>
<ListItemIcon>
<AccountBoxRoundedIcon />
</ListItemIcon>
<ListItemText primary="Profile" />
</ListItem>
<ListItem button key="Sign Out" onClick={handleSignOut}>
<ListItemIcon>
<ExitToAppRoundedIcon />
</ListItemIcon>
<ListItemText primary="Sign Out" />
</ListItem>
</List>
)}
</List>
</>
);
return (
<div className={classes.root}>
<AppBar position="fixed" className={classes.appBar}>
<Toolbar>
<IconButton
color="inherit"
aria-label="open drawer"
edge="start"
onClick={handleDrawerToggle}
className={classes.menuButton}
>
<MenuIcon />
</IconButton>
<div className={classes.rightAlign}>
{authUser && <ProfileIcon className={classes.hoverCursor} />}
{!authUser && (
<Button color="inherit" onClick={handleGoToSignInPage}>
Sign In
</Button>
)}
</div>
</Toolbar>
</AppBar>
<nav className={classes.drawer} aria-label="sidebar">
<Hidden mdUp>
<Drawer
variant="temporary"
anchor={classes.direction === "rtl" ? "right" : "left"}
open={mobileOpen}
onClose={handleDrawerToggle}
classes={{
paper: classes.drawerPaper
}}
ModalProps={{
keepMounted: true // Better open performance on mobile.
}}
>
{drawer}
</Drawer>
</Hidden>
<Hidden smDown>
<Drawer
classes={{
paper: classes.drawerPaper
}}
variant="permanent"
open
>
{drawer}
</Drawer>
</Hidden>
</nav>
<main className={classes.content}>
<div className={classes.toolbar} />
{children}
</main>
</div>
);
};
const mapStateToProps = state => ({
authUser: state.sessionState.authUser
});
export default connect(mapStateToProps)(Shell);
</code></pre>
<p>As you can see, the <code>Shell</code> component uses a HOC to wrap it with an <code>authUser</code> prop from the session state.</p>
<p>My <code>signin.js</code> page looks like this:</p>
<pre><code>import React from "react";
import Router from "next/router";
import Button from "@material-ui/core/Button";
import { AppWithAuthentication } from "../src/components/App";
import { auth, provider } from "../src/firebase/firebase";
import { db } from "../src/firebase";
import * as routes from "../src/constants/routes";
const SignInPage = () => (
<AppWithAuthentication>
<h1>Sign In</h1>
<SignInForm />
</AppWithAuthentication>
);
const updateByPropertyName = (propertyName, value) => () => ({
[propertyName]: value
});
const INITIAL_STATE = {
user: null,
error: null
};
class SignInForm extends React.Component {
constructor(props) {
super(props);
this.state = { ...INITIAL_STATE };
if (auth.currentUser) {
console.log(`already signed in`);
Router.push(routes.HOME);
}
}
componentDidMount() {
auth.onAuthStateChanged(user => {
if (user) {
console.log(user);
// add them to the db and then redirect
db.doCreateUser(
user.uid,
user.email,
user.displayName,
user.photoURL,
false
)
.then(() => {
this.setState(() => ({ ...INITIAL_STATE }));
Router.push(routes.HOME);
})
.catch(error => {
this.setState(updateByPropertyName("error", error));
});
} else {
console.log(`No active user found. User must log in`);
}
});
}
onClick = () => {
auth.signInWithRedirect(provider);
};
render() {
return (
<Button variant="contained" color="primary" onClick={this.onClick}>
Sign In with Google
</Button>
);
}
}
export default SignInPage;
export { SignInForm };
</code></pre>
<p>Where <code>AppWithAuthentication</code> looks like this:</p>
<pre><code>import React from "react";
import { compose } from "recompose";
import withAuthentication from "../Session/withAuthentication";
import withAuthorisation from "../Session/withAuthorisation";
const App = ({ children }) => (
<div className="app">
{children}
</div>
);
const AppWithAuthentication = compose(
withAuthentication,
withAuthorisation(false)
)(App);
const AppWithAuthorisation = compose(
withAuthentication,
withAuthorisation(true)
)(App);
export { AppWithAuthentication, AppWithAuthorisation };
</code></pre>
<p>So whenever a user goes onto my website and tries to access any 'authenticated only' route, they will get redirected to the sign in page. Additionally, when a signed in user visits the sign in page, they will automatically get redirected to the <code>home</code> page.</p>
<h1>Difficulties I'm facing</h1>
<p>After a user logs in, it takes a little while for the 'authentication protected' content to load on the page. It seems like the page loads, then the app waits for the session state to be updated, then it renders the appropriate content (in the sidebar and appbar - part of the <code>Shell</code>). I'm not sure if this is expected behaviour but I'd like to understand why this happens and whether I can do anything about it?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T21:35:33.983",
"Id": "461044",
"Score": "0",
"body": "I didn't take a full look at your work but I noticed a big no no in your react app, you are using react hooks in a component and a class-based component in other places and that's anti-pattern cause why use hooks if you still use class-based components, react hooks are here to replace and eliminate the need for class-based components because functional components are more efficient the class-based components."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T08:58:10.803",
"Id": "461087",
"Score": "0",
"body": "@ChamsddineBouzaine Thanks for the comment. This suggests I should prioritise on converting all of my existing codebase to utilise react hooks first before continuing with anything else?"
}
] |
[
{
"body": "<ul>\n<li>stop using recompose because it got deprecated and you don't need it if you use react hooks.</li>\n<li>transform your components and use react hooks because it's an anti-pattern to use them with class components.</li>\n<li>Try to decompose your components more like for the shell components it's a heavy component try to extract for say the drawer component to its own file Drawer.JS then use it in Shell component also try to extract the style object that you pass to the makeStyles function for material-UI this all to make your code more maintainable.</li>\n<li>try to avoid repeating your self like in the shell component try to optimize your algorithm.</li>\n<li>separate the view logic from the service logic like for the sign in components componentDidMount() function you have to separate that two logic and create a new level of abstraction \"basically a function that handles the DB logic \" and just execute it there.</li>\n<li>now for the last question the difficulty you are having I don't quite understand it, I have reviewed your demo and i didn't encounter a problem after I signed in.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T08:32:17.817",
"Id": "461240",
"Score": "0",
"body": "Thanks for your reply. As for the last point, The issue can also be seen on the following site (signing in with google demonstrates what I mean).\n\nSteps to reproduce:\n1. Go to: https://kage.saltycrane.com/\n2. Press 'Sign In'\n3. Press 'Sign In with Google'\n\nYou will get redirected to the google sign in page, select an account etc. (to sign in)\n\nThen you will be redirected back to the site in step 1, where the menu bar at the top still remains 'Sign in'.. for a moment or two, before it changes to your email address.The same thing happens to my web app"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T08:58:30.810",
"Id": "461242",
"Score": "0",
"body": "As for my web app, the issue still persists. I'm not sure how you managed to miss it. The icon that replaces the 'Sign in' at the top right does not get updated until at least 2-4 seconds after the page has loaded. Links in the sidebar do not get updated until at least 2-4 seconds after the page has loaded. Same applies if you refresh the page or navigate to the `/home` or `/index` routes manually (via the URL bar at the top of the page)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T22:06:26.990",
"Id": "235579",
"ParentId": "235352",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "235579",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T11:54:04.163",
"Id": "235352",
"Score": "6",
"Tags": [
"javascript",
"react.js",
"authentication",
"firebase"
],
"Title": "Handling google authentication with firebase in nextjs web app"
}
|
235352
|
<p>I'm trying to make some <strong>JS</strong> code more browser compatible. So I've written an alternative to <strong>JS</strong>'s <code>classList</code> providing its <code>.add()</code>, <code>.remove()</code> and <code>.toggle()</code> functionality because it is not or just partially supported in IE.</p>
<p>(I know there are exiting polyfills, but I like to have a good overview regarding my code.)</p>
<p>My test were successful but before I use it extensively I wanted to check with someone if they see any issues.</p>
<pre><code> function classes(type, element, targetClass){
var classArray = element.className.split(/\s/);
var index = classIndex(classArray, targetClass);
// if target class is in class list
if(index !== null){
// multiple classes
if(classArray.length > 1){
if(type == "remove" || type == "toggle") {
classArray.splice(index, 1);
element.className = classArray.join(" ");
}
}
// single class
else {
if(type == "remove" || type == "toggle") {
element.className = "";
}
}
}
// if target class is not in class list
else {
if(type == "add" || type == "toggle") {
element.className += " " + targetClass;
}
}
// check if target class is in class list (returns index or null)
function classIndex(array, targetClass){
for(i=0; i<array.length; i++){
if(array[i]==targetClass){
return i;
}
if(i==(array.length-1)){
return null;
}
}
}
}
</code></pre>
<p>Usage:</p>
<pre><code>classes("toggle", myElement, "classToToggle")
</code></pre>
|
[] |
[
{
"body": "<p>I'm not a big fan of neither the function name <code>classes</code> nor the parameter name <code>type</code>. Something like <code>modifyClassOfElement</code> and <code>action</code> would be better fitting. </p>\n\n<p>You should define constants for the <code>type</code>/<code>action</code> values.</p>\n\n<p>It's convention in JavaScript to have a space between keywords and a following open bracket: <code>if (</code></p>\n\n<p>In <code>classIndex</code> the second <code>if</code> is unnecessary. Just put <code>return null;</code> after the loop. Or, even better, you can replace the whole function with an <code>.indexOf()</code> call. </p>\n\n<p>Move <code>if (type == \"remove\" || type == \"toggle\") {</code> up one level so you don't need it twice. Alternatively I'd just drop the special case for a single class, as it's an tiny optimization that is hardly worth it.</p>\n\n<p>Remove one level of brackets on the final else: </p>\n\n<pre><code>else if (type == \"add\" || type == \"toggle\") {\n element.className += \" \" + targetClass;\n}\n</code></pre>\n\n<p>I'd consider throwing an exception, if the <code>type</code>/<code>action</code> is unknown to aid debugging.</p>\n\n<p>It would be nice for the function to use <code>classList</code> if it's available. Personnally I'd implement this as a function that returns an existing <code>classList</code> or an object that implements the same interface (<a href=\"https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList\" rel=\"nofollow noreferrer\"><code>DOMTokenList</code></a>)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T19:00:29.107",
"Id": "235521",
"ParentId": "235353",
"Score": "3"
}
},
{
"body": "<p>@RoToRa: thanks for your suggestions, I edited my code:</p>\n\n<ul>\n<li>called it <code>classAction</code> (wanted something short but hey - anyone could name it to gusto)</li>\n<li>made the suggested simplifications</li>\n<li>couldn't replace the <code>classIndex()</code> function with <code>indexOf()</code> though since <code>Array.prototype.indexOf()</code> is only supported by IE9+ (thus it would defeat the whole purpose of using this)\n<a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Browser_compatibility\" rel=\"nofollow noreferrer\">MDN on Array.prototype.indexOf()</a></li>\n<li>added <code>.contains()</code> functionality</li>\n<li>checks if <code>classList</code> is available in <code>Element.prototype</code></li>\n</ul>\n\n<blockquote>\n <p>You should define constants for the type/action values.</p>\n</blockquote>\n\n<p>why/how would I do that?</p>\n\n<p><strong>New Code:</strong></p>\n\n<pre><code>function classAction(action, element, targetClass) {\n if (!('classList' in Element.prototype)) {\n var classArray = element.className.split(/\\s/);\n var index = classIndex(classArray, targetClass);\n if (index !== null) {\n if (action == \"remove\" || action == \"toggle\") {\n if (classArray.length > 1) {\n classArray.splice(index, 1);\n element.className = classArray.join(\" \");\n } \n else {\n element.className = \"\";\n }\n } \n else if (action == \"contains\") {\n return true;\n }\n } \n else if (action == \"add\" || action == \"toggle\") {\n element.className += \" \" + targetClass;\n } \n else if (action == \"contains\") {\n return false;\n }\n function classIndex(array, targetClass) {\n for (i = 0; i < array.length; i++) {\n if (array[i] == targetClass) {\n return i;\n }\n }\n return null;\n }\n } \n else {\n switch (action) {\n case \"add\":\n element.classList.add(targetClass);\n break;\n case \"remove\":\n element.classList.remove(targetClass);\n break;\n case \"toggle\":\n element.classList.toggle(targetClass);\n break;\n case \"contains\":\n if (element.classList.contains(targetClass)) {\n return true;\n } \n else {\n return false;\n }\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T11:42:30.310",
"Id": "235652",
"ParentId": "235353",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T12:03:10.043",
"Id": "235353",
"Score": "3",
"Tags": [
"javascript",
"reinventing-the-wheel",
"cross-browser"
],
"Title": "classList fallback (IE & older browsers)"
}
|
235353
|
<p>I've only been writing code for about 2 weeks.</p>
<p>I have no idea how to fix this, and it's getting extremely repetitive. If there is a way to simplify the idea, how would I go about doing that?</p>
<p>As you can see, it'll start the combat, assign goblin to 30 then keep on doing the same combat regime over and over and over.</p>
<pre><code>def combatGoblinOne():
goblin = 30
goblindam = 5
print("\nYou enter combat!")
print("What would you like to do?")
print('[1]', myPlayer.aone, ', [2]', myPlayer.atwo)
print("\n-------------------------")
print("Goblin ----------- Player")
print("HP =", goblin, " HP =", myPlayer.hp)
print("-------------------------")
spellChoice = int(input('-> '))
if spellChoice == 1:
goblin = goblin - 10
print("\nGoblin loses 10 health!", goblin, "health left!")
print("\n-------------------------")
print("Goblin ----------- Player")
print("HP =", goblin, " HP =", myPlayer.hp)
print("-------------------------")
print("\nGoblin slashes you, dealing", goblindam, "damage.")
myPlayer.hp = myPlayer.hp - goblindam
print("\n-------------------------")
print("Goblin ----------- Player")
print("HP =", goblin, " HP =", myPlayer.hp)
print("-------------------------")
print("\nWhat would you like to do?")
print('[1]', myPlayer.aone, ', [2]', myPlayer.atwo)
spellChoice1 = int(input('-> '))
if spellChoice1 == 1:
goblin = goblin - 10
print("\nGoblin loses 10 health!", goblin, "health left!")
print("\n-------------------------")
print("Goblin ----------- Player")
print("HP =", goblin, " HP =", myPlayer.hp)
print("-------------------------")
if spellChoice1 == 2:
myPlayer.hp = 80
print("\nYou return to 80 HP")
print("\n-------------------------")
print("Goblin ----------- Player")
print("HP =", goblin, " HP =", myPlayer.hp)
print("\nGoblin slashes you, dealing", goblindam, "damage.")
myPlayer.hp = myPlayer.hp - goblindam
print("\n-------------------------")
print("Goblin ----------- Player")
print("HP =", goblin, " HP =", myPlayer.hp)
print("-------------------------")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T13:55:57.547",
"Id": "460586",
"Score": "1",
"body": "Welcome to Code Review! This question lacks any indication of what the code is intended to achieve. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436)."
}
] |
[
{
"body": "<p>Start by writing and calling <em><a href=\"https://docs.python.org/3/tutorial/controlflow.html#defining-functions\" rel=\"nofollow noreferrer\">functions</a></em>: as soon as you are writing the same code two times, you should write a function.</p>\n\n<p>Then, for this kind of application, you should learn about <a href=\"https://docs.python.org/3/tutorial/classes.html\" rel=\"nofollow noreferrer\"><code>class</code>es</a>, allowing you to define a <code>goblin</code> object and a <code>player</code> object, to simplify your code drasticaly. I wrote some functions for you:</p>\n\n<pre><code>def print_state(goblin,player_hp):\n print(\"\\n-------------------------\")\n print(\"Goblin ----------- Player\")\n print(\"HP =\", goblin, \" HP =\", player_hp)\n print(\"-------------------------\")\n\n\ndef goblin_loss_10life(goblin,player_hp):\n goblin = goblin - 10\n print(\"\\nGoblin loses 10 health!\"+ str(goblin) +\"health left!\")\n print_state(goblin, player_hp)\n return goblin\n\ndef you_loose_life(goblin,player_hp,goblindam):\n player_hp = player_hp - goblindam\n print(\"\\nGoblin slashes you, dealing\"+str(goblindam), \"damage.\")\n print_state(goblin, player_hp)\n return player_hp\n\ndef return_to_80(goblin,player_hp):\n print(\"\\nYou return to 80 HP\")\n print_state(goblin, myPlayer.hp)\n return 80\n\n\ndef combatGoblinOne():\n\n goblin = 30\n goblindam = 5\n\n print(\"\\nYou enter combat!\")\n print(\"What would you like to do?\")\n print('[1]', myPlayer.aone, ', [2]', myPlayer.atwo)\n\n print_state(goblin,myPlayer.hp)\n\n spellChoice = int(input('-> '))\n\n if spellChoice == 1:\n goblin = goblin_loss_10life(goblin,myPlayer.hp)\n myPlayer.hp = you_loose_life(goblin, myPlayer.hp, goblindam)\n\n print(\"\\nWhat would you like to do?\")\n print('[1]', myPlayer.aone, ', [2]', myPlayer.atwo)\n spellChoice1 = int(input('-> '))\n if spellChoice1 == 1:\n goblin = goblin_loss_10life(goblin,myPlayer.hp)\n\n if spellChoice1 == 2:\n myPlayer.hp = return_to_80(goblin,player_hp)\n myPlayer.hp = you_loose_life(goblin, myPlayer.hp, goblindam)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T19:16:29.637",
"Id": "460649",
"Score": "1",
"body": "Why do you switch between `camelCase` and `snake_case` when naming methods and variables? `snake_case` is the standard for naming in Python, according to PEP 8."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T16:56:13.327",
"Id": "460784",
"Score": "0",
"body": "I did not. I used only `snake_case`, but i left the original `cameCase` nomenclature since i thought the OP might need it's names to stay the same. But you a right, this is not uniform."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T13:57:02.223",
"Id": "235360",
"ParentId": "235358",
"Score": "-3"
}
},
{
"body": "<p>This is my suggestion, create classes for the player which you may already have done and another for the enemy. Then write some functions to handle the combat that way you dont have to repeat yourself.</p>\n\n<pre><code>class Player():\n\n def __init__(self):\n super().__init__()\n self.aone='cast'\n self.atwo='heal'\n self.hp=80\n\nclass Enemy():\n def __init__(self):\n super().__init__()\n self.name = 'Goblin'\n self.hp = 30\n self.dmg = 5\n\ndef combat(spell, myPlayer, enemy):\n if spell == 1:\n enemy.hp = enemy.hp - 10\n print(\"\\n{} loses 10 health! {} health left!\".format(enemy.name, enemy.hp))\n print(\"\\n-------------------------\")\n print(\"Goblin ----------- Player\")\n print(\"HP =\", enemy.hp, \" HP =\", myPlayer.hp)\n print(\"-------------------------\")\n if enemy.hp > 0:\n enemyAttack(myPlayer, enemy)\n\n if spell == 2:\n myPlayer.hp = 80\n print(\"\\nYou return to 80 HP\")\n print(\"\\n-------------------------\")\n print(\"Goblin ----------- Player\")\n print(\"HP =\", enemy.hp, \" HP =\", myPlayer.hp)\n if enemy.hp > 0:\n enemyAttack(myPlayer, enemy)\n\n\n\ndef enemyAttack(myPlayer, enemy):\n print(\"\\n{} slashes you, dealing {} damage.\".format(enemy.name, enemy.dmg))\n myPlayer.hp = myPlayer.hp - enemy.dmg\n print(\"\\n-------------------------\")\n print(\"Goblin ----------- Player\")\n print(\"HP =\", enemy.hp, \" HP =\", myPlayer.hp)\n print(\"-------------------------\")\n\ndef combatGoblinOne(myPlayer, goblin):\n\n print(\"\\nYou enter combat!\")\n while(goblin.hp > 0 and myPlayer.hp > 0):\n print(\"What would you like to do?\")\n print('[1]', myPlayer.aone, ', [2]', myPlayer.atwo)\n print(\"\\n-------------------------\")\n print(\"Goblin ----------- Player\")\n print(\"HP =\", goblin.hp, \" HP =\", myPlayer.hp)\n print(\"-------------------------\")\n spellChoice = int(input('-> '))\n combat(spellChoice, myPlayer, goblin)\n\n\nmyPlayer = Player()\ngoblin = Enemy()\ncombatGoblinOne(myPlayer, goblin)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T16:12:17.690",
"Id": "460609",
"Score": "0",
"body": "Welcome to code review. I voted for this answer because of two insightful observations, one that it needs classes and functions and two that the code is repeating itself. We don't generally provide alternate solutions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T19:07:04.717",
"Id": "460645",
"Score": "1",
"body": "Why are you calling `super().__init__()` in `Player` and `Enemy` when they're not inheriting from a superclass? Also, PEP 8 naming conventions say that `enemyAttack` should be `enemy_attack`, and `myPlayer` should be `my_player`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T14:36:56.760",
"Id": "235364",
"ParentId": "235358",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T13:20:08.573",
"Id": "235358",
"Score": "-2",
"Tags": [
"python"
],
"Title": "This combat loop is too complicated. How do I simplify/fix it?"
}
|
235358
|
<p>I have an associative array of the states of some country, and the states names are the keys:</p>
<pre><code>array:13 [
"Ontario" => null
"Manitoba" => null
"New Brunswick" => null
"Yukon" => null
"Saskatchewan" => null
"Prince Edward Island" => null
"Alberta" => null
"Quebec" => null
"Nova Scotia" => null
"British Columbia" => null
"Nunavut" => null
"Newfoundland and Labrador" => null
"Northwest Territories" => null
]
</code></pre>
<p>And I have anothe associative array that contains all states that have values:</p>
<pre><code>array:8 [
"Alberta" => 17
"Cairo" => 1
"Calgary" => 1
"ddd" => 4
"gfdxf" => 1
"New Cairo" => 1
"Ontario" => 1
"secret" => 30
]
</code></pre>
<p>Now I need to map the second array to the first one so that the result would be:</p>
<pre><code>array:13 [
"Ontario" => 1
"Manitoba" => 0
"New Brunswick" => 0
"Yukon" => 0
"Saskatchewan" => 0
"Prince Edward Island" => 0
"Alberta" => 17
"Quebec" => 0
"Nova Scotia" => 0
"British Columbia" => 0
"Nunavut" => 0
"Newfoundland and Labrador" => 0
"Northwest Territories" => 0
]
</code></pre>
<p>I created a nested loop and it works fine, but the code is very ugly, now is there a more efficent way to do it?</p>
<p>My code:</p>
<pre><code>foreach ($all_states as $state_x => $value_x) {
foreach ($country_states as $state_y => &$value_y) {
if (strtolower($state_x) == strtolower($state_y)) {
$value_y = $value_x;
} elseif ($value_y == NULL) {
$value_y = 0;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T16:08:44.797",
"Id": "460608",
"Score": "0",
"body": "What is it you want to review, there isn't a lot of code here to review?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T18:21:09.377",
"Id": "460631",
"Score": "0",
"body": "In RDBS terms, that looks like a left join with a default of `0`. Does that help?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T10:25:41.327",
"Id": "461095",
"Score": "1",
"body": "@pacmaninbw Sometimes there simply isn't more to it. It would be preferable to see how the result of this operation is used as well, but afar from that, it's close enough to be reviewable."
}
] |
[
{
"body": "<p>There is no reason for the multiple nested foreach loops as the keys are the same. Therefore, we can reduce the need for a second iterator, which can be slow. Also, we can simplify the statement by making use of the null coalescing operator.</p>\n\n<pre><code>$results = [];\nforeach ($country_all as $key => $value) {\n $results[$key] = $country_values[$key] ?? 0;\n}\nvar_dump($results);\n</code></pre>\n\n<p>Using your data. </p>\n\n<pre><code>$country_all = [\n \"Ontario\" => null,\n \"Manitoba\" => null,\n \"New Brunswick\" => null,\n \"Yukon\" => null,\n \"Saskatchewan\" => null,\n \"Prince Edward Island\" => null,\n \"Alberta\" => null,\n \"Quebec\" => null,\n \"Nova Scotia\" => null,\n \"British Columbia\" => null,\n \"Nunavut\" => null,\n \"Newfoundland and Labrador\" => null,\n \"Northwest Territories\" => null\n];\n\n$country_values = [\n \"Alberta\" => 17,\n \"Cairo\" => 1,\n \"Calgary\" => 1,\n \"ddd\" => 4,\n \"gfdxf\" => 1,\n \"New Cairo\" => 1,\n \"Ontario\" => 1,\n \"secret\" => 30\n];\n</code></pre>\n\n<p>I hope this helps!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T21:06:57.037",
"Id": "235383",
"ParentId": "235361",
"Score": "0"
}
},
{
"body": "<p><code>array_replace()</code> is the perfect call here -- it can be used to overwrite the master array with the array containing actual integer values.</p>\n\n<p>Code: (<a href=\"https://3v4l.org/lF1P7\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>var_export(array_replace(array_map('intval', $all_states), $country_states));\n</code></pre>\n\n<p>To streamline the process futher, you should declare your master list with <code>0</code> values instead of <code>null</code> values, then you can omit the <code>array_map()</code> call like this:</p>\n\n<p>Code: (<a href=\"https://3v4l.org/9HvSn\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>var_export(array_replace($all_states, $country_states));\n</code></pre>\n\n<p>Additional suggestions, caveats, and considerations:</p>\n\n<ul>\n<li>You might reconsider your variable names, as they don't seem to do a great job of describing the data that they contain. <code>$all_states</code> might be <code>$statesLookup</code> or <code>$statesDefault</code>. I don't know what is being counted in the second array, but <code>$country_states</code> might be better declared as <code>$state_counts</code> or something.</li>\n<li>If <code>$country_states</code> has any elements with keys that are not represented in <code>$all_states</code>, then these new elements WILL be appended to the end of the output array. If this is a legitimate concern, you can call <code>array_intersect_key($country_states, $all_states)</code> to filter out any expected elements.</li>\n<li>The order of the elements in the output array will be ordered by <code>$all_states</code>. No matter what order the <code>country_states</code> are in.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T23:22:32.367",
"Id": "235391",
"ParentId": "235361",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T14:00:40.920",
"Id": "235361",
"Score": "4",
"Tags": [
"php",
"array",
"laravel"
],
"Title": "Map associative array to another array php"
}
|
235361
|
<p>(repost: <a href="https://stackoverflow.com/questions/59665338/censoring-words-in-lua#comment105491094_59665338">https://stackoverflow.com/questions/59665338/censoring-words-in-lua#comment105491094_59665338</a>, as advised)</p>
<p>Im currently making a discord censor bot for my friend, and I was wondering if anyone with experience could help me, or if theres an easier way to complete my code.</p>
<pre class="lang-lua prettyprint-override"><code>local BadWords = {
['poop']=true,
}
client:on('messageCreate', function(msg)
Msg = msg.content
local msgs = string.split(Msg,' ')
for i,v in pairs(msgs) do
if BadWords[v:lower()] then
msg:reply({
embed = {
fields = {
{name = "Bad Word",value=v,inline = true},
},
color = discordia.Color.fromRGB(114, 137, 218).value,
--footer = os.time(),
}
})
--msg:reply(('Blacklisted word: %s'):format(v))
end
end
--[[table.foreach(msgs,function(i,v)
if BadWords[i] or BadWords[v] then
msg:reply(('Blacklisted word: %s'):format(v))
end
end)--]]
end)
client:run(Settings.Token)
</code></pre>
<p>There's nothing wrong with it, nor is it complete but my idea was to split, or concatenate all the words they send respectively, mutate into all versions of the word (i.e. farm, f4rm, type shit) and then checking the BadWord list.</p>
<p>Mostly what I was wondering was if there's a more efficient way to do this, or if I just gotta do what I gotta do</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T16:25:09.660",
"Id": "460612",
"Score": "0",
"body": "This won't catch words like poop, and several others."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T18:42:39.887",
"Id": "460639",
"Score": "0",
"body": "It works, I dont know what you're talking about, im j wondering if theres a efficient way to parse a sentence and check for bad words, and then mutated bad words aswell. im not that advanced in string manipulation, or regex."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T00:45:49.380",
"Id": "460695",
"Score": "1",
"body": "Sorry, it was a bit hard to understand. What I really mean was: If you let your code analyze my first comment, it won't flag the word `poop` as a bad word since it is followed by a comma. This is because you are splitting the string at spaces and you further assume that everything between these spaces is a word."
}
] |
[
{
"body": "<p>If you care about performance, you should have a look at <a href=\"http://www.inf.puc-rio.br/~roberto/lpeg/\" rel=\"nofollow noreferrer\">LPeg</a>. It makes it way easier to handle large numbers of string matching and substitution rules.</p>\n\n<p>For example, you could define patterns and their substitution values like this:</p>\n\n<pre class=\"lang-lua prettyprint-override\"><code>local lpeg = require 'lpeg'\n\nlocal p = lpeg.P\nlocal bad_word = \n p\"bad\" / \"good\" +\n (p\"dumb\" + p\"stupid\") / \"$#&*\"\n\nlocal sanitize = lpeg.Cs( (bad_word + p(1))^1 )\n\nprint(sanitize:match(\"this is a bad word\"))\nprint(sanitize:match(\"python is dumb!\"))\n</code></pre>\n\n<p>Which makes it much easier both to add new entries and to eventually move them into a table or even a separate file.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-18T10:46:33.317",
"Id": "237488",
"ParentId": "235367",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T14:57:53.947",
"Id": "235367",
"Score": "3",
"Tags": [
"strings",
"lua"
],
"Title": "Censoring words in lua"
}
|
235367
|
<p>For my programming class I had to make a sudoku solver.</p>
<pre class="lang-py prettyprint-override"><code>import time # Used to add a delay for user readability
ROWS = COLS = possibleValues = 9 # The rows and columns of the board
GRID_ROWS = GRID_COLS = 3 # The rows and columns in which there are lines
possibleBoard = []
"""Functions"""
def board_filler():
"""Creates the sudoku board from user input"""
board = [[] for _ in range(ROWS)] # Creates the nested list to contain the board
for x in range(ROWS):
for y in range(COLS):
# Takes an input makes sure it is good, and if not ask for another one, if it is add it to the list
while True:
number = input(
f"Please enter an integer for the square in column {x + 1} and in row {y + 1} (hit enter for no number): ")
try:
number = int(number) # Makes the input that was a string into a number
if number > 9 or number < 1:
raise ValueError
else:
board[x].append(number) # Add the number to the list
break # Exit the loop and let it move on to the next number
# If its not a number, or a number more 9 or less than 1 runs this
except (TypeError, ValueError):
# If its empty, adds just a space to the list
if not number:
board[x].append(" ")
break
else:
print("Please enter an integer between 1 and 9, or just hit enter")
return board
def board_printer(board):
"""Prints the sudoku board"""
counter = 0 # Makes sure it does not print extra lines
for row in range(ROWS):
s = '' # A variable to contain the row before its printed
# Adds the items from the list to the variable
for col in range(COLS):
s += str(board[row][col]) + ' '
if not (col + 1) % GRID_COLS:
s += '| '
s = s[:-2] # Removes trailing characters
print(s)
# Prints the line of lines
if not (row + 1) % GRID_ROWS and counter < 2:
print('-' * len(s))
counter += 1
def line_solver(board):
"""Remove confirmed values from the possible values in the lines"""
global possibleBoard
# Checks to see if there are any duplicate numbers in each row, then removes them from the possible board
for x in range(ROWS):
for y in range(COLS):
if board[x][y] == " ":
for z in range(COLS):
try:
possibleBoard[x][y].remove(board[x][
z]) # Removes values from the possibleBoard that are in the same row as a number on the board
# If the number that the code is trying to remove has already been removed, do nothing
except (ValueError, AttributeError):
pass
for x in range(ROWS):
for y in range(COLS):
if board[x][y] == " ":
for z in range(ROWS):
try:
possibleBoard[x][y].remove(board[z][
y]) # Removes values from the possibleBoard that are in the same row as a number on the board
# If the number that the code is trying to remove has already been removed, do nothing
except (ValueError, AttributeError):
pass
return board
def square_solver(board):
"""Remove confirmed values from the possible values in the squares"""
global possibleBoard
# Sets up a modulator to multiply by to get the 3x3 grid of one square with the first value being the rows and the second being the column
blockNum = [0, 0]
for _ in range(9):
# A loop that checks the 9 numbers in one of the squares
for x in range(3):
for y in range(3):
if not board[(blockNum[0] * 3) + x][(blockNum[1] * 3) + y] == " ": # Checks if that square a number
# Checks all the empty spots in one of the squares for that number, then removes them
for z in range(3):
for w in range(3):
try:
# Removes the number from the possible board
possibleBoard[(blockNum[0] * 3) + z][(blockNum[1] * 3) + w].remove(
board[(blockNum[0] * 3) + x][(blockNum[1] * 3) + y])
# If it can't do anything, run this
except (ValueError, AttributeError):
pass
blockNum = block_num(blockNum)
return board
def board_updater(board):
"""Makes it so if there is any number on the board, that that number is a definite on the possible board"""
global possibleBoard
for x in range(ROWS):
for y in range(COLS):
if not board[x][y] == " ":
possibleBoard[x][y] = board[x][y]
def solver(board):
"""Solves a few number of the sudoku board"""
global possibleBoard
board_updater(board)
board = line_solver(board)
board = square_solver(board)
# Sets up the counter and a modulator to multiply by to get the 3x3 grid of one square with the first value being the rows and the second being the column
counter = [0] * 9
blockNum = [0, 0]
for _ in range(9):
for x in range(3):
for y in range(3):
# Checks the possible board and counts how many time a possible number appears
if type(possibleBoard[(blockNum[0] * 3) + x][(blockNum[1] * 3) + y]) == list:
for z in range(len(possibleBoard[(blockNum[0] * 3) + x][(blockNum[1] * 3) + y])):
counter[possibleBoard[(blockNum[0] * 3) + x][(blockNum[1] * 3) + y][z] - 1] += 1
for x in range(len(counter)):
# Checks to see if there was any times only one number appeared
if counter[x] == 1:
for y in range(3):
for z in range(3):
try:
# Finds the solo number, and makes that number definite
if (x + 1) in possibleBoard[(blockNum[0] * 3) + y][(blockNum[1] * 3) + z]:
board[(blockNum[0] * 3) + y][(blockNum[1] * 3) + z] = x + 1
except TypeError:
pass
blockNum = block_num(blockNum)
# Rests the counter
counter = [0] * 9
for x in range(ROWS):
for y in range(COLS):
# If there is only one number in the possibleBoard list, set that as a definite value on the possibleBoard list and add it to the board list
if type(possibleBoard[x][y]) == list and len(possibleBoard[x][y]) == 1:
board[x][y] = possibleBoard[x][y][0]
return board
def filler():
"""Fills the possible board"""
listOfLists = [[], [], [], [], [], [], [], [], []]
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] # All numbers are possible on an empty board so it fills it with all numbers
# Adds 9 empty lists to the row list to represent the 9 squares
for x in range(ROWS):
for _ in range(ROWS):
listOfLists[x].append([])
# Puts the list with the numbers 1-9 in each square
for x in range(ROWS):
for y in range(COLS):
listOfLists[x][y] = numbers.copy()
return listOfLists
def solve_check():
"""Checks if board is solved"""
for x in range(ROWS):
for y in range(COLS):
if type(possibleBoard[x][y]) == list:
return False
return True
"""Repeated code segments"""
def block_num(blockNum):
"""Increments the square"""
blockNum[1] += 1
if blockNum[1] > 2:
blockNum[0] += 1
blockNum[1] = 0
return blockNum
possibleBoard = filler()
board = board_filler()
# Solves some numbers, prints the new board then waits to allow user to see changes
while True:
if solve_check():
break
board_printer(board)
time.sleep(1)
prevBoard = board
board = solver(board)
print("")
# Loops so that if entered from the command line, it does not close
while True:
pass
</code></pre>
<p>As this was the most complicated program I have ever done,I focused on making it work, rather than making it pretty or readable (which caused lots of headache when doing solver function). Looking at the code, there is a lot of things that I wish I had done differently.</p>
<p><strong>Things I Don't Like</strong></p>
<ul>
<li>There are a lot of nested for loops that get very confusing</li>
<li>It's not modular</li>
<li><code>solver</code> is really long</li>
<li>It takes longer to solve then I like</li>
</ul>
<p>What would be the best way to fix these things, and is there any other things I should change?</p>
<p><strong>Things to Note</strong></p>
<ul>
<li><code>board_filler</code> and <code>board_printer</code> were reviewed in <a href="https://codereview.stackexchange.com/questions/232753/displaying-a-sudoku-board">this</a> question</li>
<li><code>solver</code> was made after everything else, as I forgot to add it originally</li>
<li>The reason it goes into the loop at the end is so that if it is run in the command line, it does not close once it is done solving it</li>
<li>Despite wanting it to go faster, I still want to user to still be able to see it solve the sudoku puzzle</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T13:31:45.980",
"Id": "460750",
"Score": "0",
"body": "In `filler` you put `for _ in range(ROWS):`, I think this may be a mistake, it works because sudoku have the same amount of rows as columns though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T20:36:24.553",
"Id": "460808",
"Score": "1",
"body": "I have a C++ solution on my GitHub that I wrote several years back. If it brings you any inspiration, feel free to borrow from it: https://github.com/jselbie/sudokusolver"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T20:47:24.683",
"Id": "460810",
"Score": "1",
"body": "If you are interested in the design of a more general solver which can solve sudokus as a special case, I wrote a series of articles about that, starting here: https://docs.microsoft.com/en-us/archive/blogs/ericlippert/graph-colouring-with-simple-backtracking-part-one -- the code is in C#, but everything in there could be done in Python without any particular difficulty. The algorithm is quite efficient for \"newspaper\" level sudoku puzzles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T20:03:34.080",
"Id": "460813",
"Score": "1",
"body": "Check this out https://github.com/TakLee96/sudoku_solver Contains the backbone of Sudoku and a few algorithms."
}
] |
[
{
"body": "<ul>\n<li>I think you're over-commenting, but you're a student, so your professor probably is requiring more than needed.</li>\n<li>I think your code has some pretty big problems even after my answer. Over use of globals, lack of SRP, and I don't think your code works with all Sodoku boards. But my answer is long enough.</li>\n</ul>\n\n<p>In <code>board_filler</code>:</p>\n\n<ul>\n<li>I'd prefer the name <code>create_board</code>, it's not really filling something passed to it, it's creating something.</li>\n<li>Don't raise types, raise instances. <code>raise ValueError(...)</code></li>\n<li>When raising an error always enter a description.</li>\n<li>Don't use errors for standard control flow. Your <code>if</code> that raises the error can very easily be in the <code>else</code> of the <code>try</code>.</li>\n<li>You can clean up the function by only using two <code>if</code>s to handle correct numbers and empty cells.</li>\n<li>You can populate <code>board</code> when you are in the loops. You can use a generator function to make the entire function a little more clean too.</li>\n<li>IMO your code violates SRP. By making the innermost <code>while</code> loop be it's own function, you can easily use two comprehensions to make <code>create_board</code> really clean.</li>\n<li>Stop relying on globals and enter the cols and rows.</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>def get_cell(x, y):\n \"\"\"Get cell from user input.\"\"\"\n number = input(\n f\"Please enter an integer for the square in column {x + 1}\"\n f\" and in row {y + 1} (hit enter for no number): \"\n )\n while True:\n try:\n number = int(number)\n except TypeError:\n if not number:\n return \" \"\n else:\n if 1 <= number <= 9:\n return number\n print(\"Please enter an integer between 1 and 9\"\n \", or just hit enter\")\n\n\ndef create_board(cols, rows):\n \"\"\"Create a Sudoku board from user input.\"\"\"\n return [\n [get_cell(x, y) for y in range(cols)]\n for x in range(rows)\n ]\n</code></pre>\n\n<p>In <code>board_printer</code>:</p>\n\n<ul>\n<li>Stop relying on globals. You're just limiting the functionality and reusability of your code without really any benefit.</li>\n<li>Use <code>enumerate</code>, rather than <code>range</code> and indexes.</li>\n<li>Rather than using modulo arithmetic for each row, you can just make a new list using slices.</li>\n<li>You don't need to use modulo arithmetic to display the line. You can just check if the row index is 3 or 6.</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>def board_printer(board):\n \"\"\"Prints the sudoku board.\"\"\"\n for y, row in enumerate(board, 1):\n format_row = (\n row[0:3]\n + ['|']\n + row[3:6]\n + ['|']\n + row[6:9]\n )\n line = ' '.join(map(str, format_row))\n print(line)\n if y in (3, 6):\n print('-' * len(line))\n</code></pre>\n\n<p>In <code>filler</code>:</p>\n\n<ul>\n<li>You should merge both loops into one. You can also merge <code>listOfLists</code> into this loop too.</li>\n<li>Your name <code>listOfLists</code> isn't PEP 8 compliant.</li>\n<li>To make the code more reliable you can pass the amount of rows and columns. And also pass what you want to default to.</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>import copy\n\n\ndef filler(rows, columns, value):\n \"\"\"Fills the possible board.\"\"\"\n board = []\n for _ in range(rows):\n row = []\n for _ in range(columns):\n row.append(copy.deepcopy(value))\n return board\n</code></pre>\n\n<p>in <code>line_solver</code>:</p>\n\n<ul>\n<li>You don't need two nested loops. <code>if board[x][y] == \" \":</code> and the proceeding loops are the same.</li>\n<li>Make two new functions for filling vertically and horizontally.</li>\n<li>There is no need to return.</li>\n<li>Stop relying on globals and just use <code>enumerate</code>.</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>def remove_existing_horizontal(board, x, y):\n for z in range(len(board[0])):\n try:\n possibleBoard[x][y].remove(board[x][z])\n except (ValueError, AttributeError):\n pass\n\ndef remove_existing_vertical(board, x, y):\n for z in range(len(board)):\n try:\n possibleBoard[x][y].remove(board[z][y])\n except (ValueError, AttributeError):\n pass\n\n\ndef line_solver(board):\n \"\"\"Remove confirmed values from the possible values in the lines.\"\"\"\n for x, row in enumerate(board):\n for y, item in enumerate(row):\n if item == \" \":\n remove_existing_horizontal(board, x, y)\n remove_existing_vertical(board, x, y)\n</code></pre>\n\n<p>In <code>square_solver</code>:</p>\n\n<ul>\n<li><code>blockNum</code> is a PEP 8 naming violation.</li>\n<li>Use <code>!=</code> rather than <code>not foo == bar</code>.</li>\n<li>You can simplify your code by making a function that does all the <code>blockNum[0] * 3 + x</code> noise.</li>\n<li>Don't return <code>board</code>.</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>def square_positions(x, y):\n x *= 3\n y *= 3\n return (\n (x + i, y + j)\n for i in range(3)\n for j in range(3)\n )\n\n\ndef square_solver(board):\n \"\"\"Remove confirmed values from the possible values in the squares\"\"\"\n for block_y in range(3):\n for block_x in range(3):\n for x, y in square_positions(block_x, block_y):\n if board[x][y] != \" \":\n for i, j in square_positions(block_x, block_y):\n try:\n possibleBoard[i][j].remove(board[x][y])\n except (ValueError, AttributeError):\n pass\n</code></pre>\n\n<p>In <code>solver</code>:</p>\n\n<ul>\n<li>Use <code>square_positions</code> that we defined before.</li>\n<li>Use <code>isinstance</code> not <code>type</code> to check the type of a value.</li>\n<li>Use <code>enumerate</code> not <code>for i in range(len(foo)): foo[i]</code>.</li>\n<li>Stop using <code>ROWS</code> and <code>COLS</code> and instead use <code>enumerate</code>.</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>def solver(board):\n \"\"\"Solves a few number of the sudoku board\"\"\"\n global possibleBoard\n board_updater(board)\n line_solver(board)\n square_solver(board)\n\n counters = [0] * 9\n for block_y in range(3):\n for block_x in range(3):\n for x, y in square_positions(block_x, block_y):\n if isinstance(possibleBoard[x][y], list):\n for z in range(len(possibleBoard[x][y])):\n counters[possibleBoard[x][y][z] - 1] += 1\n for i, counter in enumerate(counters, 1):\n # Checks to see if there was any times only one number appeared\n if counter == 1:\n for x, y in square_positions(block_x, block_y):\n try:\n if i in possibleBoard[x][y]:\n board[x][y] = i\n except TypeError:\n pass\n counters = [0] * 9\n for x, row in enumerate(possibleBoard):\n for y, item in enumerate(row):\n if (isinstance(item, list)\n and len(item) == 1\n ):\n board[x][y] = item[0]\n return board\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T17:17:38.640",
"Id": "460617",
"Score": "1",
"body": "The reason it doesn't solve all sudoku puzzles is because it only uses two solving methods, so it can't do harder puzzles."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T17:12:13.553",
"Id": "235375",
"ParentId": "235368",
"Score": "9"
}
},
{
"body": "<pre><code>while True:\n if solve_check():\n break\n</code></pre>\n\n<p>would be a lot more obvious as:</p>\n\n<pre><code>while not solve_check():\n</code></pre>\n\n<p>And I'd be tempted to change conditions like this:</p>\n\n<pre><code>if not (row + 1) % GRID_ROWS and counter < 2:\n</code></pre>\n\n<p>to one of:</p>\n\n<pre><code>if (not (row + 1) % GRID_ROWS) and counter < 2:\nif not ((row + 1) % GRID_ROWS and counter < 2):\n</code></pre>\n\n<p>to make it more obvious which you really meant.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T22:34:02.670",
"Id": "460820",
"Score": "0",
"body": "Your \"more obvious\" method is really not much better than the `row in (3, 6)` that I suggested."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T01:03:35.823",
"Id": "460858",
"Score": "0",
"body": "@Peilonrayz, in fact, your suggestion is better. My point was a generalization. This is not common usage, so someone that isn't thoroughly familiar with python syntax, reading this, might misinterpret what it means. Or worse, a few years from now the person that has to maintain the code might know what it means but wonder whether the original author got it right or not. If there's any chance of confusion, it should be made clear."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T00:52:53.320",
"Id": "235394",
"ParentId": "235368",
"Score": "5"
}
},
{
"body": "<p>It may not be what you are supposed to be learning, but if you use brute force to solve Sudoku, you'll do fine with easy ones (30 clues, asymmetric), but you'll struggle with difficult ones (fewer than 20 clues, symmetrical diagonally) - so why not use a SAT solver library like Google OR Tools to do the solving? Learning to use 3rd party libraries in your program would be an invaluable software development skill, and you'll probably get the fastest solver in your class!</p>\n\n<p>If you choose to do this, your solver will need 9 binary variables for each square - one for each of the possible numbers 1-9.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T16:19:17.957",
"Id": "235425",
"ParentId": "235368",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235375",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T15:16:17.617",
"Id": "235368",
"Score": "12",
"Tags": [
"python",
"beginner",
"python-3.x",
"sudoku"
],
"Title": "Basic Sudoku Solver"
}
|
235368
|
<p>I wrote a thread pool where the user can submit jobs through <code>ThreadTask</code> objects. These objects bundle the job priority, the task as a function, and some arbitrary number of function parameters.</p>
<p>After much frustration I ended up with something like this:</p>
<pre><code>struct ThreadTask
{
template <typename Func, typename... Args>
ThreadTask(exrFloat priority, Func&& func, Args&&... args)
{
// package task function with its arguments
auto pTask = std::make_shared<std::packaged_task<void()>>(std::bind(std::forward<Func>(func), std::forward<Args>(args)...));
// convert packaged task to a void std::function
m_Task = ([pTask]() { (*pTask)(); });
m_Priority = priority;
};
...
std::function<void()> m_Task;
};
...
m_Task();
</code></pre>
<p>This allows the user to schedule jobs like this:</p>
<pre><code>threadPool.ScheduleTask(priority, [&](int customParam1, int customParam2)
{
...
}, param1Val, param2Val);
</code></pre>
<p>This was the only way I knew how to package variadic parameters with the function itself. It works, but looks really ugly. Is there some way I could simplify this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T21:19:24.833",
"Id": "460665",
"Score": "0",
"body": "Why not just consume a packaged task directly, and let the client figure out how to make it? Then you're just storing objects with a very minimal interface and calling them later. Additionally, why is the task a shared pointer?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T19:38:39.547",
"Id": "235378",
"Score": "1",
"Tags": [
"c++",
"variadic"
],
"Title": "Simplifying a packaged task for a threadpool implementation"
}
|
235378
|
<p>I'm filling a list of items from the database, which is taking extremly long time to run (Approx 60 seconds)</p>
<p>Here is the code with the relevant breakdown</p>
<p>97% of the performance issues come in the foreach loop at the bottom. Is there a better way to match list items on the nested object.</p>
<pre><code>private List<ROPSetting> TestMethod()
{
using DataSet ds = DB.GetDs($"EXEC GetSupplyChainROP_C @DateFrom={DateTime.Now.AddYears(-1).ToDbQuote()}");
// load DS takes 3 seconds.
using var itemReader = ds.Tables[0].CreateDataReader();
var items = itemReader.ParseList<ROPSetting>().ToList();
using var usageReader = ds.Tables[1].CreateDataReader();
var usageItems = usageReader.ParseList<ItemUsage>().ToList();
// 97% of the performance impact is below. Is there a better way to match
foreach (var itm in items)
{
itm.Usage = usageItems
.Where(a => a.ItemCode == itm.ItemCode && a.WarehouseCode == itm.WarehouseCode).ToList();
}
return items;
}
public class ItemUsage
{
public DateTime Date { get; set; }
public decimal Quantity { get; set; }
internal string ItemCode { get; set; } // for matching
internal string WarehouseCode { get; set; } // for matching
}
public class ROPSetting
{
public string ItemCode { get; set; }
public string PartNumber { get; set; }
public decimal AverageCost { get; set; }
public string SupplierCode { get; set; }
public string SupplierName { get; set; }
public int TotalLeadTime { get; set; }
public int IntervalTime { get; set; }
public int ReorderPoint { get; set; }
public string WarehouseCode { get; set; }
public IList<ItemUsage> Usage { get; set; }
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T21:22:09.763",
"Id": "460667",
"Score": "0",
"body": "if you edit the store procedure, and add the filtering part on the store procedure (from the DBMS), it'll perform faster and would also short your code as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T21:25:39.360",
"Id": "460668",
"Score": "0",
"body": "@iSR5 how? I need the 2 result sets in a separate table, i don't want to go down the track of returning a single table and then grouping."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T21:42:25.537",
"Id": "460672",
"Score": "0",
"body": "you'll only do it once, and get the results. You can create new or modify `GetSupplyChainROP_C` procedure. You just want to join the two tables, and select the columns you want from both, then just call the procedure, and get its result."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T22:06:46.097",
"Id": "460675",
"Score": "0",
"body": "I assume the child table is already filtered down to just the rows that have parents in the first table. Otherwise it's best to do that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T22:24:37.360",
"Id": "460678",
"Score": "0",
"body": "@CharlesNRice yes that's correct. First table has approx 6500 parents, second table about 25000 children"
}
] |
[
{
"body": "<p>Option 1) You can create a <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.data.datarelation?view=netframework-4.8\" rel=\"nofollow noreferrer\">DataRelations</a> between the two Data Tables and change the loop to fill in both classes at the same time. This would require you do change the code that converts the results set into C# classes. Microsoft has an example of GetChildRows and navigation <a href=\"https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/dataset-datatable-dataview/navigating-datarelations\" rel=\"nofollow noreferrer\">here</a> </p>\n\n<p>Option 2) Otherwise you could also create a DataView and set the Sort property on the child Data Table and use FindRows method. Again will require you to change how you convert from datatable to C# classes. I'd lean toward the first option instead of creating another set of data objects just for sorting.</p>\n\n<p>Option 3) I'm guessing it will not be much better performance but you can try is using the Linq <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.groupjoin?view=netframework-4.8#System_Linq_Enumerable_GroupJoin__4_System_Collections_Generic_IEnumerable___0__System_Collections_Generic_IEnumerable___1__System_Func___0___2__System_Func___1___2__System_Func___0_System_Collections_Generic_IEnumerable___1____3__\" rel=\"nofollow noreferrer\">GroupJoin</a> </p>\n\n<pre><code>foreach (var data in items.GroupJoin(usageItems,\n x => new {x.ItemCode, x.WarehouseCode},\n x => new {x.ItemCode, x.WarehouseCode},\n (itm, usg) => new\n {\n item = itm,\n usage = usg.ToList()\n }))\n{\n data.item.Usage = data.usage;\n} \n</code></pre>\n\n<p>Update #1 - Couple more options. </p>\n\n<p>Option 4) Parallel the finding of data. Take Option 3 and add the AsParallel()</p>\n\n<pre><code>foreach (var data in items.AsParallel().GroupJoin(usageItems.AsParallel(),\n x => new {x.ItemCode, x.WarehouseCode},\n x => new {x.ItemCode, x.WarehouseCode},\n (itm, usg) => new\n {\n item = itm,\n usage = usg.ToList()\n }))\n{\n data.item.Usage = data.usage;\n} \n</code></pre>\n\n<p>I still think option 1 would be the best option as it will create a binary search tree for the relationship and give best performance. </p>\n\n<p>Option 5) if you know the usageItems are sorted by the ItemCode and WarehouseCode you could just iterate over the list once and fill in the Item as it scans over the list. This would be the most efficient but would require more complex code and also required that sort order is always correct. While having this sort order would help Option 1 it wouldn't be required. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T22:01:45.453",
"Id": "235385",
"ParentId": "235382",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T21:02:34.790",
"Id": "235382",
"Score": "1",
"Tags": [
"c#",
"performance"
],
"Title": "Increase Perfomance of Nested Object Instantiation C#"
}
|
235382
|
<p>I have a dataframe with measurement data of different runs at same conditions. Each row contains both the constant conditions the experiment was conducted and all the results from the different runs.</p>
<p>Since I am not able to provide a real dataset, the code snippet provided below will generate some dummy data.</p>
<p>I was able to achieve the desired output, but my function <code>transform_columns()</code> seems to be unecessary complicated:</p>
<pre><code>import pandas as pd
import numpy as np
np.random.seed(seed=1234)
df = pd.DataFrame(np.random.randint(0, 100, size=(100, 6)), columns=['constant 1', 'constant 2', 1, 2, 3, 4])
def transform_columns(data):
factor_columns = []
response_columns = []
for col in data:
if isinstance(col, int):
response_columns.append(col)
else:
factor_columns.append(col)
collected = []
for index, row in data.iterrows():
conditions = row.loc[factor_columns]
data_values = row.loc[response_columns].dropna()
for val in data_values:
out = conditions.copy()
out['value'] = val
collected.append(out)
df = pd.DataFrame(collected).reset_index(drop=True)
return df
print(transform_columns(df))
</code></pre>
<p>Is there any Pythonic or Pandas way to do this nicely?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T23:44:06.087",
"Id": "460690",
"Score": "0",
"body": "It looks like the docs discourage the use of `np.random.seed()`, do you know how to change it? _the desired output_ Can you explain what that is? It's much better for everyone than having to reverse-engineer your code."
}
] |
[
{
"body": "<p>It is probably easier to work with the underlying Numpy array directly\nthan through Pandas. Ensure that all factor columns comes before all\ndata columns, then this code will work:</p>\n\n<pre><code>import pandas as pd\nimport numpy as np\n\nnp.random.seed(seed=1234)\n\nn_rows = 100\nn_cols = 6\nn_factor_cols = 2\nn_data_cols = n_cols - n_factor_cols\narr = np.random.randint(0, 100, size=(n_rows, n_cols))\nfactor_cols = arr[:,:n_factor_cols]\ndata_cols = [arr[:,i][:,np.newaxis] for i in range(n_factor_cols, n_cols)]\nstacks = [np.hstack((factor_cols, data_col)) for data_col in data_cols]\noutput = np.concatenate(stacks)\n</code></pre>\n\n<p>The above code assumes that order is not important. If it is, then use\nthe following instead of <code>np.concatenate</code>:</p>\n\n<pre><code>output = np.empty((n_rows * n_data_cols, n_factor_cols + 1),\n dtype = arr.dtype)\nfor i, stack in enumerate(stacks):\n output[i::n_data_cols] = stack\n</code></pre>\n\n<p>This is the best I can do, but I wouldn't be surprised if someone\ncomes along and rewrites it as a Numpy one-liner. :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T11:45:49.583",
"Id": "235410",
"ParentId": "235384",
"Score": "2"
}
},
{
"body": "<p><strong><code>pandas</code></strong> library has rich functionality and allows to build a complex pipelines as a chain of routine calls.\n<br>In your case the whole idea is achievable with the following single pipeline:</p>\n\n<pre><code>import pandas as pd\nimport numpy as np\n\nnp.random.seed(seed=1234)\ndf = pd.DataFrame(np.random.randint(0, 100, size=(100, 6)), \n columns=['constant 1', 'constant 2', 1, 2, 3, 4])\n\n\ndef transform_columns(df):\n return df.set_index(df.filter(regex=r'\\D').columns.tolist()) \\\n .stack().reset_index(name='value') \\\n .drop(columns='level_2', axis=1)\n\n\nprint(transform_columns(df))\n</code></pre>\n\n<hr>\n\n<p><em>Details:</em></p>\n\n<ul>\n<li><p><code>df.filter(regex=r'\\D').columns.tolist()</code> <br><a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.filter.html?highlight=filter#pandas.DataFrame.filter\" rel=\"nofollow noreferrer\"><code>df.filter</code></a> returns a subset of columns enforced by specified regex pattern <code>regex=r'\\D'</code> (ensure the column name contains non-digit chars)</p></li>\n<li><p><a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html?highlight=set_index\" rel=\"nofollow noreferrer\"><code>df.set_index(...)</code></a> - set the input dataframe index (row labels) using column names from previous step</p></li>\n<li><p><code>.stack()</code> - reshape the dataframe from columns to index, having a multi-level index</p></li>\n<li><p><code>.reset_index(name='value')</code><br>\n<a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.reset_index.html?highlight=reset_index#pandas.Series.reset_index\" rel=\"nofollow noreferrer\"><code>pandas.Series.reset_index</code></a> resets/treats index as a column; <code>name='value'</code> points to a desired column name containing the crucial values</p></li>\n<li><p><code>.drop(columns='level_2', axis=1)</code> - drops supplementary label <code>level_2</code> from columns (<code>axis=1</code>) </p></li>\n</ul>\n\n<p>You may check/debug each step separately to watch how the intermediate series/dataframe looks like and how it's transformed.</p>\n\n<hr>\n\n<p>Sample output:</p>\n\n<pre><code> constant 1 constant 2 value\n0 47 83 38\n1 47 83 53\n2 47 83 76\n3 47 83 24\n4 15 49 23\n.. ... ... ...\n395 16 16 80\n396 16 92 46\n397 16 92 77\n398 16 92 68\n399 16 92 83\n\n[400 rows x 3 columns]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T20:42:29.303",
"Id": "235434",
"ParentId": "235384",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T21:42:26.857",
"Id": "235384",
"Score": "3",
"Tags": [
"python",
"pandas"
],
"Title": "Convert rows with multiple values to row with single value"
}
|
235384
|
<p>I've come up with this code for a tic tac toe game with and AI that the player can go against, please help me optimise my code and help me grow better habits haha.</p>
<pre><code>import random # I want 'random' so I can randomize the AI's choices
# whenever it cant win or 'intercept' the player
board_tiles = ['-', '-', '-',
'-', '-', '-', # Here I declare some variables globaly
'-', '-', '-'] # so i can use them later
board_rows = ''
board_columns = ''
board_diagonals = ''
board_layout = ''
def board_update():
global board_rows, board_columns, board_diagonals, board_layout # In this function I update the variables above
board_rows = [(board_tiles[0], board_tiles[1], board_tiles[2]), # this is called all the time in the program so
(board_tiles[3], board_tiles[4], board_tiles[5]), # that the game knows exactly how is the board
(board_tiles[6], board_tiles[7], board_tiles[8])] # at all times
board_columns = [(board_tiles[0], board_tiles[3], board_tiles[6]),
(board_tiles[1], board_tiles[4], board_tiles[7]),
(board_tiles[2], board_tiles[5], board_tiles[8])]
board_diagonals = [(board_tiles[0], board_tiles[4], board_tiles[8]),
(board_tiles[2], board_tiles[4], board_tiles[6])]
board_layout = ''' {} | {} | {}
{} | {} | {}
{} | {} | {}'''.format(board_tiles[0], board_tiles[1], board_tiles[2], board_tiles[3], board_tiles[4],
board_tiles[5], board_tiles[6], board_tiles[7], board_tiles[8])
def board_display():
board_update() # Here I make a function to display the board
print('-----------') # I declare it because it's used a lot
print(board_layout)
def check_if_tie():
board_update()
if '-' not in board_tiles and check_winner() is None: # These two functions are needed to check if the game tied
return True # or if there is a winner, and if there is, if it's the AI
else: # or the player. The 'tie' one can either return True or
return False # False, and the 'winner' one can return 'X' or 'O'
# depending on which won the game
def check_winner(): # ('X' being the player and 'O' being the AI)
board_update()
for i in board_rows + board_columns + board_diagonals:
if i.count('X') == 3:
return 'X'
elif i.count('O') == 3:
return 'O'
return None
def player_turn():
board_update() # In this function I get the input from the
selected_tile = int(input('Select a tile (1 - 9): ')) - 1 # player in the form of a number (1 - 9),
while board_tiles[selected_tile] != '-': # the numbers refer to the tiles on the board
selected_tile = int(input('Insert another tile (1 - 9): ')) - 1 # as seen on the right: 1 | 2 | 3
board_tiles[selected_tile] = 'X' # There's a section that 4 | 5 | 6
# checks if the input is 7 | 8 | 9
def ai_tile(): # valid (if the tile is already occupied)
intercept_tile = 0
win_tile = 0
for row in board_rows:
if row.count('O') == 2 and row.count('X') == 0: # This function is needed so the AI can know where
for i in row: # to place it's tile, his decision can be:
if i == '-': # - To end the game if it's possible.
return win_tile # - To 'intercept' the player from winning.
win_tile += 1 # - To randomly select a tile.
win_tile += 3 # (this is the hierarchy of it's decisions, meaning
win_tile = 0 # that the AI will prefer to win the game over
for column in board_columns: # intercepting the player or playing randomly)
if column.count('O') == 2 and column.count('X') == 0:
for i in column: # The function checks for a row, column or diagonal
if i == '-': # that either has 2 'O' and no 'X' or for one that
return win_tile # has 2 'X' and no 'O', so that it can either 'win'
win_tile += 3 # or intercept the player from winning, if none
win_tile += 1 # meets this condition, then it picks a tile randomly
win_tile = 0
x = 4 # The 'x' variable that is local to this function is
for diagonal in board_diagonals: # used to keep track of the tile in which the AI has
if diagonal.count('O') == 2 and diagonal.count('X') == 0: # to win or intercept the player in diagonals, my
for i in diagonal: # idea was that for each diagonal, the number of tiles
if i == '-': # that are needed to be skipped are different
return win_tile # (in the first iteration of the loop 'x' is 4, meaning
win_tile += x # that the tiles jump from 1 to 5 to 9, in the second
x -= 2 # iteration, 'x' is 2, then the tiles jump from 3 to 5
win_tile += x # to 7, 1 - 5 - 9 and 3 - 5 - 7 being the diagonals)
for row in board_rows:
if row.count('X') == 2 and row.count('O') == 0:
for i in row:
if i == '-':
return intercept_tile
intercept_tile += 1
intercept_tile += 3
intercept_tile = 0
for column in board_columns:
if column.count('X') == 2 and column.count('O') == 0:
for i in column:
if i == '-':
return intercept_tile
intercept_tile += 3
intercept_tile += 1
intercept_tile = 0
x = 4
for diagonal in board_diagonals:
if diagonal.count('X') == 2 and diagonal.count('O') == 0:
for i in diagonal:
if i == '-':
return intercept_tile
intercept_tile += x
x -= 2
intercept_tile += x
random_tile = random.randint(0, 8)
while board_tiles[random_tile] != '-': # Here it decides to randomly choose a tile.
random_tile = random.randint(0, 8)
return random_tile
def ai_turn(): # In this funcion, I did all the aesthetics of the ai turn
board_update() # like printing which tile it chose and everything
print('-----------') # 'ai_tile()' is used here, and it returns the tile that
ai_choice = ai_tile() # the AI picked.
board_tiles[ai_choice] = 'O'
print('AI chooses tile {}'.format(ai_choice + 1))
def game():
while check_winner() is None and check_if_tie() is False:
board_display() # This function is the main one, it checks if
player_turn() # the game is over, sequences the turns,
if check_winner() is None and check_if_tie() is False: # displays the board and announces the winner.
ai_turn()
else:
break
if check_winner() is 'X':
board_display()
print('The player won!')
print('-----------')
else:
board_display()
print('The AI won!')
print('-----------')
game()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T22:38:30.057",
"Id": "460679",
"Score": "0",
"body": "Can you indicate what version of python you're using?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T22:46:25.053",
"Id": "460683",
"Score": "0",
"body": "I believe its python3.x that I used"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T03:19:03.923",
"Id": "460712",
"Score": "2",
"body": "`habits` are important in programming. Keep commenting your code with motivation for pieces of code."
}
] |
[
{
"body": "<p>The really big suggestion (which I'm sure you're going to hear a lot) is to not use <code>global</code> variables. Declaring global <em>constants</em> is fine, but when you have state that any function might modify at any time it rapidly gets hard to figure out what state your app is in at any given point.</p>\n\n<p>So with that in mind, your <code>board_update</code> function should not exist. I see that the main point of it is to be able to identify the board spaces that make up a win condition. Here's how you could restructure that logic to not rely on global variables:</p>\n\n<pre><code>from random import choice\nfrom typing import List, Optional\n\nwinning_rows = [\n # horizontal\n (0, 1, 2),\n (3, 4, 5),\n (6, 7, 8),\n # vertical\n (0, 3, 6),\n (1, 4, 7),\n (2, 5, 8),\n # diagonal\n (0, 4, 8),\n (2, 4, 6),\n]\n\ndef check_winner(board: List[str]) -> Optional[str]:\n \"\"\"Return the winning player (if any).\n Players are 'X' (human) and 'O' (computer).\"\"\"\n for player in ['X', 'O']:\n for row in winning_rows:\n if all([board[space] == player for space in row]):\n return player\n return None\n\ndef ai_move(board: List[str]) -> int:\n \"\"\"Compute the best move for player 'O' (the AI).\"\"\"\n\n def winning_move(\n player: str, \n opponent: str\n ) -> Optional[int]:\n \"\"\"Return the winning move for the given player vs the opponent, \n or None if there's no winning move.\"\"\"\n for spaces in winning_rows:\n row = [board[space] for space in spaces]\n if row.count(player) == 2 and not opponent in row:\n return next(s for s in spaces if board[s] != player)\n return None # no winning move\n\n # Check to see if there's a move that would win the game for O.\n move = winning_move(board, 'O', 'X')\n if move is not None:\n return move # Winner!\n\n # Check to see if there's a move that would win the game for X.\n move = winning_move(board, 'X', 'O')\n if move is not None:\n return move # Blocked!\n\n # Otherwise make a random move.\n return choice([\n space for space in range(len(board)) if board[space] not in ('O', 'X')\n ])\n</code></pre>\n\n<p>Note that the board itself (because it will change) should not be a global, but the set of <code>winning_rows</code> can be a global constant since it's defined by the rules of the game rather than a particular game in progress.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T23:09:30.197",
"Id": "460685",
"Score": "0",
"body": "Yeah, thanks, but then instead of having my board_rows, board_columns and board_diagonals, I would have only this ''winning_rows'' list?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T00:27:37.097",
"Id": "460693",
"Score": "1",
"body": "Yes -- I don't think you need to have them separated into different variables, since they're all treated equally (i.e. any one of them defines a win). I didn't look too hard at your `ai_tile` function but I'm pretty sure it doesn't need to separate them out either -- if you're stuck on a clean way to implement that I could take another look at it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T00:45:56.513",
"Id": "460696",
"Score": "1",
"body": "btw the thing of doing your comment in a \"column\" next to the code is not great for reasons that will rapidly become obvious as you edit the code :P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T01:54:48.853",
"Id": "460703",
"Score": "0",
"body": "in my ai_tile i have to keep track of the tile that i need the AI to choose, and for that it skips 1, 2, 3 or even 4 tiles from the board_tiles so that i can stay on that row, column or diagonal, i thought of putting them all in a joined list but then for each iteration i would have to have a different number to add or subtract, idk if i explained it clearly, but i have a more detailed explanation on that in my comments on the code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T01:55:19.873",
"Id": "460704",
"Score": "0",
"body": "yeah, how could i have written the comments? I need to learn these things so i can code in a way that other people can understand my code right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T05:57:46.387",
"Id": "460717",
"Score": "0",
"body": "Unless a comment pertains to a specific line of code (and is short), it should be on its own line(s). If nothing else, trying to do the column thing is really hard to maintain because you're going to have to reformat your comments every time you add a line of code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T06:14:57.303",
"Id": "460718",
"Score": "0",
"body": "Added more to my answer to give an implementation of `ai_move`. It's a *lot* shorter than your version but I'm pretty sure it does the same thing. :) The key is being able to succinctly define what a winning move is in general terms (it's one where you can claim the 3rd in a row where you already own 2) and then define the AI move in terms of the winning move for each player."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T13:03:26.720",
"Id": "460748",
"Score": "0",
"body": "I get it, the comments should be above the code so whenever i need to edit that code the comments wont be a problem"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T13:07:07.783",
"Id": "460749",
"Score": "0",
"body": "I liked your suggestion on the 'winning move' thing because I don't have to separate two types of movements like 'win' or 'intercept'. The thing is I don't understand much of that 'typing, list, optional', is that a thing that I need to learn and should have as a priority?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T16:05:36.103",
"Id": "460774",
"Score": "1",
"body": "Typing is something you should absolutely learn if you want to write better code, yes. :) When you use types you can use `mypy` to automatically catch bugs: http://mypy-lang.org/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T16:18:37.960",
"Id": "460778",
"Score": "0",
"body": "I'll take a look on that, thank you for your help and suggestions!"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T22:56:28.747",
"Id": "235389",
"ParentId": "235387",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "235389",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T22:07:11.887",
"Id": "235387",
"Score": "4",
"Tags": [
"python",
"beginner",
"python-3.x",
"tic-tac-toe"
],
"Title": "Beginner python tic tac toe with AI"
}
|
235387
|
<p>I have the following class </p>
<pre><code>public class ExrDepthMapExtractor : IDepthMapExtractor
{
public RawDepthMap GetDepthMap(string filePath)
{
return DepthMapExtractorService.ExtractDepthMapAs1DArray(filePath, Callbacks.ProgressCallback);
}
}
</code></pre>
<p>This calls the static C++ API wrapper </p>
<pre><code>public static class DepthMapExtractorService
{
[DllImport("Blundergat.OpenExr.Adapter.dll", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
private static unsafe extern bool ExtractDepthMapAs1DArray(
out ItemsSafeHandle vectorHandle,
out double* points,
out int width,
out int height,
string filePath,
Callbacks.ProgressFunc progressCallback);
[DllImport("Blundergat.OpenExr.Adapter.dll", CallingConvention = CallingConvention.Cdecl)]
private static unsafe extern bool Release(IntPtr itemsHandle);
public static unsafe RawDepthMap ExtractDepthMapAs1DArray(string filePath,
Callbacks.ProgressFunc progressCallback)
{
using (InternalExtractDepthMapAs1DArrayWrapper(filePath, out RawDepthMap rdm, progressCallback))
{
rdm.Source = filePath;
return rdm;
}
}
private static unsafe ItemsSafeHandle InternalExtractDepthMapAs1DArrayWrapper(
string filePath, out RawDepthMap rdm, Callbacks.ProgressFunc progressCallback)
{
double* pixels;
int width, height;
ItemsSafeHandle itemsHandle;
if (!ExtractDepthMapAs1DArray(out itemsHandle, out pixels, out width, out height, filePath, progressCallback))
throw new InvalidOperationException();
var pixelList = new List<double>();
for (int i = 0; i < width * height; i++)
pixelList.Add(pixels[i]);
rdm = new RawDepthMap()
{
Source = filePath,
DepthMapArray = pixelList,
Height = height,
Width = width
};
return itemsHandle;
}
public class ItemsSafeHandle : SafeHandleZeroOrMinusOneIsInvalid
{
public ItemsSafeHandle() : base(true) { }
protected override bool ReleaseHandle()
{
return Release(handle);
}
}
}
</code></pre>
<p>In my C++ I Release the <code>ArrayHandle</code> as follows </p>
<pre><code>#include "wrappers.h"
bool ExtractDepthMapAs1DArray(ArrayHandle* arrayHandle,
double** pixels,
int* width,
int* height,
const char* filePath,
ProgressFunc progressCallback)
{
try
{
auto v = new std::vector<double>();
ExrDepthMapExtractor exrExtractor;
*v = exrExtractor.extractDepthMap(filePath, *width, *height, progressCallback);
*arrayHandle = reinterpret_cast<ArrayHandle>(v);
*pixels = v->data();
if (progressCallback != NULL)
{
std::string strFilePath(filePath);
std::string message = "Extracted depth map from \"" + strFilePath + "\" successfully";
if (progressCallback != NULL)
progressCallback(message.c_str());
}
return true;
}
catch (...)
{
return false;
}
}
bool Release(ArrayHandle arrayHandle)
{
auto items = reinterpret_cast<std::vector<double>*>(arrayHandle);
delete items;
return true;
}
</code></pre>
<p>I have not used this before and the implementation was taken from [SO] (<a href="https://stackoverflow.com/questions/31417688/passing-a-vector-array-from-unmanaged-c-to-c-sharp">https://stackoverflow.com/questions/31417688/passing-a-vector-array-from-unmanaged-c-to-c-sharp</a>), however, the way this is done does not look right to me and <a href="https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.safehandle?view=netframework-4.8" rel="nofollow noreferrer">MSDN</a> is different. The code seems to work fine with no memory leaks, but am I doing this the right way? </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T23:25:22.810",
"Id": "460688",
"Score": "0",
"body": "Can you link to the MSDN implementation?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T23:28:46.367",
"Id": "460689",
"Score": "0",
"body": "Sorry I got this wrong way around. Links added."
}
] |
[
{
"body": "<p>What don't you like about it? There's a very small space where a C++ exception could occur leaking the vector memory. If the <code>ExrDepthMapExtractor</code> or <code>extractDepthMap</code> throws, there's no way to clean the vector memory. You could just put something in the catch block. </p>\n\n<p>You could memcpy the pixel memory from C++ to C# instead of looping. Or share memory the other direction, by pinning it and having the C++ side write into the provided memory. That's nice because it allows the garbage collector safely deal with the memory, but requires safeguards to prevent .NET from doing anything to the memory while C++ is using it. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T23:58:58.293",
"Id": "235392",
"ParentId": "235390",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T23:02:00.687",
"Id": "235390",
"Score": "1",
"Tags": [
"c#",
"c++",
"api"
],
"Title": "C++ Wrapper and Correctly Disposing Unmanaged Resources using ArrayHandle"
}
|
235390
|
<p>I did Advent of Code recently and enjoyed <a href="https://adventofcode.com/2019/day/15" rel="nofollow noreferrer">Day 15</a>, which involves exploring a maze (<a href="https://github.com/crummy/adventofcode2019/blob/master/src/main/kotlin/com/malcolmcrum/adventofcode2019/Day15.kt" rel="nofollow noreferrer">my attempt in Kotlin</a>). I've tried to recreate it partially in Python, minus the emulator:</p>
<p><a href="https://repl.it/@MalcolmCrum/ReflectingFarNaturaldocs" rel="nofollow noreferrer">https://repl.it/@MalcolmCrum/ReflectingFarNaturaldocs</a></p>
<p>It works but my code is largely 1:1 from Kotlin, and I'm not certain if I'm doing things in a Pythonic way. For example, I use this pattern regularly in Kotlin:</p>
<pre><code>val direction = when (path.first()) {
position + NORTH -> NORTH
position + SOUTH -> SOUTH
position + EAST -> EAST
position + WEST -> WEST
else -> error("Can't find first step from $position towards $destination in $path")
}
</code></pre>
<p>The Python equivalent I found is this, which while nice and concise is maybe a little too "clever"? (ignore the 1 offset, I changed path logic slightly)</p>
<pre><code>direction: Direction = {self.position + d: d for d in Direction}[path_to_destination[1]]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T01:28:50.227",
"Id": "460701",
"Score": "3",
"body": "Using a dict to function as a `when` statement is a normal python practice, and people with mild python experience should know what you're doing if they see it.\n\nHowever you might consider revising your direction class. The index value of the tuple seems unnecessary, and perhaps could consider a method that returns a direction from two positions. Overloading the - operator might be reasonable, but it looks like a direction should only have a magnitude of length=1 which could not be guaranteed by subtracting two positions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T09:57:41.847",
"Id": "460731",
"Score": "4",
"body": "@butt please don't use coments to write answers. Instead put answers into the answer box. Thanks!"
}
] |
[
{
"body": "<p>You have:</p>\n\n<pre><code>direction: Direction = {self.position + d: d for d in Direction}[path_to_destination[1]]\n</code></pre>\n\n<p>The dict is just mapping each <code>key</code> to <code>key - self.position</code> (I don't know your exact data models, but I'm going to assume that these are some kind of vector and that <code>+</code> and <code>-</code> behave in intuitive ways). Hence:</p>\n\n<pre><code>direction = path_to_destination[1] - self.position\n</code></pre>\n\n<p>and maybe:</p>\n\n<pre><code>assert abs(direction) == 1\n</code></pre>\n\n<p>if you want to require that <code>direction</code> is a unit vector (again, I'm assuming your vector representation is reasonable and implements <code>__abs__</code> to return the magnitude).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T08:09:47.410",
"Id": "235401",
"ParentId": "235393",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "235401",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T00:38:57.633",
"Id": "235393",
"Score": "5",
"Tags": [
"python"
],
"Title": "Advent of Code 2019 Day 15 in Python"
}
|
235393
|
<p>I wrote the following function in order to handle some data from a QR code:</p>
<pre class="lang-swift prettyprint-override"><code>func genInt(fromBitArray array: [Int]) -> Int {
var n = 0
for i in 0...array.count - 1 {
n += array[i] << ((array.count - 1) - i)
}
return n
}
</code></pre>
<p><code>genInt(fromBitArray: [1, 1, 0])</code> would return <code>6</code>.</p>
<p>Is there a better/more efficient way to do this?</p>
|
[] |
[
{
"body": "<h3>Improving the code</h3>\n\n<p>Your code computes\n<span class=\"math-container\">$$\n a_0 2^{n-1} + a_1 2^{n-2} + \\ldots a_{n-2} 2 + a_{n-1} \\, ,\n$$</span>\nthat is the polynomial\n<span class=\"math-container\">$$\n P(x) = a_0 x^{n-1} + a_1 x^{n-2} + \\ldots a_{n-2} x + a_{n-1} \\,\n$$</span>\nevaluated at <span class=\"math-container\">\\$ x=2 \\$</span>. A well-known, efficient method to evaluate polynomials is <a href=\"https://en.wikipedia.org/wiki/Horner%27s_method\" rel=\"noreferrer\">Horner's method</a>:\n<span class=\"math-container\">$$\n P(x) = (\\ldots ((a_0 x + a_1) x + a_2) x + \\ldots ) x + a_0 \\, .\n$$</span></p>\n\n<p>Applied to your task that gives</p>\n\n<pre><code>func genInt(fromBitArray array: [Int]) -> Int {\n var n = 0\n for i in 0...array.count - 1 {\n n = 2 * n + array[i]\n }\n return n\n}\n</code></pre>\n\n<p>Instead of the bit shift (by a variable amount) we have now multiplications by the fixed factor <span class=\"math-container\">\\$ 2 \\$</span>. But this can be simplified further. Inside the loop we need now only the array element at the current index, but not the index itself. Therefore we can enumerate the array instead:</p>\n\n<pre><code>func genInt(fromBitArray array: [Int]) -> Int {\n var n = 0\n for digit in array {\n n = 2 * n + digit\n }\n return n\n}\n</code></pre>\n\n<p>And for this kind of combining array (or more general: sequence) elements there is a dedicated method in the Swift standard library, <a href=\"https://developer.apple.com/documentation/swift/sequence/2907677-reduce\" rel=\"noreferrer\"><code>reduce()</code></a>:</p>\n\n<pre><code>func genInt(fromBitArray array: [Int]) -> Int {\n return array.reduce(0) { (accum, digit) in\n return 2 * accum + digit\n }\n}\n</code></pre>\n\n<h3>Naming</h3>\n\n<p>The “official” Swift naming conventions are describe in the <a href=\"https://swift.org/documentation/api-design-guidelines/\" rel=\"noreferrer\">API Design Guidelines</a>, e.g.</p>\n\n<ul>\n<li>Name variables, parameters, and associated types according to their roles, rather than their type constraints.</li>\n<li>Begin names of factory methods with “make”, e.g. <code>x.makeIterator()</code>.</li>\n<li>Avoid abbreviations.</li>\n</ul>\n\n<p>With these rules in mind I would suggest something like</p>\n\n<pre><code>func makeInteger(fromBits array: [Int]) -> Int\n</code></pre>\n\n<p>Or if one sees this as a way to <em>construct</em> an integer then a custom initializer would be appropriate</p>\n\n<pre><code>extension Int {\n init(bits array: [Int]) {\n self = array.reduce(0) { (accum, digit) in\n return 2 * accum + digit\n }\n }\n}\n\n// Example:\nlet value = Int(bits: [1, 1, 0])\n</code></pre>\n\n<h3>Miscellaneous</h3>\n\n<p>It is expected that the array contains only the values zero and one. With an <em>assertion</em> this can be verified during the test phase, without performance impact on the released code:</p>\n\n<pre><code>extension Int {\n init(bits array: [Int]) {\n self = array.reduce(0) { (accum, digit) in\n assert(digit == 0 || digit == 1, \"invalid binary digit\")\n return 2 * accum + digit\n }\n }\n}\n</code></pre>\n\n<p>If you want to create other integer types from a bit array in the same manner then you can defined the initializer on the <code>BinaryInteger</code> protocol instead:</p>\n\n<pre><code>extension BinaryInteger {\n init(bits array: [Int]) {\n self = array.reduce(0) { (accum, digit) in\n assert(digit == 0 || digit == 1, \"invalid binary digit\")\n return 2 * accum + Self(digit)\n }\n }\n}\n\n// Example:\nlet value = Int16(bits: [1, 1, 0])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T21:08:24.867",
"Id": "235435",
"ParentId": "235397",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "235435",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T02:58:58.227",
"Id": "235397",
"Score": "5",
"Tags": [
"swift"
],
"Title": "Function to generate an Int from a series of bits"
}
|
235397
|
<p>Simple console tip calculator app in JavaScript. I would like to get some feedback on improving my code. Thank you beforehand. </p>
<p><strong>Source code:</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>//header
const headerMessage = () => {
console.log('Tip Calculator')
}
//service quality
const serviceQuality = (billEntered, userOption ) => {
const userInput = Number(userOption);
switch(userInput){
case 1:
return (billEntered * 0.3)
break;
case 2:
return(billEntered * 0.2)
break;
case 3:
return(billEntered * 0.1)
break;
case 4:
return(billEntered * 0.05)
break;
}
}
const tipCalulcator = () => {
headerMessage()
const enterBill = prompt('Please tell me bill amount: $ ');
console.log(`Bill amount was $ ${enterBill}`)
console.log(`How was your service ? Please enter number of the options`)
const enterOption = prompt(` 1) Outstanding (30%)
2) Good (20%)
3) It was ok (10%)
4) Terrible (5%)`)
const result = serviceQuality(enterBill, enterOption);
console.log(`Tip amount ${result}`)
const total = Number(enterBill) + result;
console.log(`Overall paycheck ${total}`)
}
tipCalulcator();</code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T14:30:29.237",
"Id": "460760",
"Score": "0",
"body": "Return is not a function. It does not need parenthesis, and you should put a space between it and the expression being returned."
}
] |
[
{
"body": "<p>A couple of things to consider:</p>\n\n<ol>\n<li><p>When dealing with a <code>switch</code> statement, if a <code>case</code> utilizes the <code>return</code> keyword then you do not need to also include a <code>break</code>. When the <code>return</code> is hit, no further code in that function will be reached.</p></li>\n<li><p>You should handle unexpected inputs; for example, <code>serviceQuality</code> should account for non-numeric inputs, or a number that is not 1-5. Look into <code>try</code>/<code>catch</code> statements and using a <code>default</code> case on your switch.</p></li>\n<li><p>Because you are not reusing <code>headerMessage</code>, this function is not really required.</p></li>\n<li><p>Your variable names are fairly unintuitive; consider changing them so that it's more obvious what each thing is such as <code>enterBill</code> -> <code>billAmount</code> and <code>enterOption</code> -> <code>serviceOption</code>. It might be worth using those same names as the <code>serviceQuality</code> arguments too.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T14:29:21.487",
"Id": "460759",
"Score": "0",
"body": "To add: Spacing between return and the expressions"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T12:20:05.650",
"Id": "235414",
"ParentId": "235398",
"Score": "2"
}
},
{
"body": "<p>There are a few suggestions I could make, but the one that really stands out is that your <code>serviceQuality</code> function is misnamed. It doesn't return a service quality, it returns a calculated tip amount.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T12:36:24.297",
"Id": "235415",
"ParentId": "235398",
"Score": "1"
}
},
{
"body": "<p>Additionally to the other comments, i would think about the following:</p>\n\n<h1>Magic values vs. constants</h1>\n\n<p>The percentage for the tips (30%, 20%, 10%, 5%) are \"magic numbers\" that are used in the text and in the calculation. In bigger programs, when you have to change such a value (30% to 31%) you can nearly bet, that one of the occurances is missed. The replacement gets even harder, because here the 30% is about the tip, but in other places of the programm (if it gets bigger) you may use the same value for a different purpose. -> That means you can not just search and replace them.<br>\n==> Therefor i would use constants for those values. That allows to use the same value at multiple places, but it is still easy changeable. Also the code is much easier to read when there is a \"TIP_FOR_OUTSTANDING_QUALITY\" instead of a \"30%\".</p>\n\n<h1>Splitting code</h1>\n\n<p>Also i would split the code in multiple parts. Currently the \"serviceQuality\" method is calculating AND converting the user input. When you want to add input validation or more complex convertings, then this gets messy. Therefor i would take the user input. convert it, and then use the clean and save number to feed the serviceQuality method.<br>\nYou could move it even further by having a method asking for the input, a method for the conversion, one for the calculation and one for the output.</p>\n\n<h1>Resumee</h1>\n\n<p>My suggestions result in a lot more code. But i think that code is easier to read and to maintain. And the most time is consumed by bugfixes and changes of code. Only a small part is really used for the initial creation. </p>\n\n<p>Or as a rule of thumb: Code is read 100 times more often than it is written -> It makes sense to put quite some effort into the readability :-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T14:26:34.747",
"Id": "460758",
"Score": "0",
"body": "How do you have magic variables? That's impossible. If you define it as a variable, it isn't \"magic\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T14:34:15.237",
"Id": "460761",
"Score": "1",
"body": "Since these numbers are not defined as variables, they are called \"magic numbers\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T15:13:21.550",
"Id": "460769",
"Score": "0",
"body": ":-) Stupid me, you are right. Its corrected now. Thanks"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T14:15:25.403",
"Id": "235420",
"ParentId": "235398",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "235414",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T03:02:10.073",
"Id": "235398",
"Score": "0",
"Tags": [
"javascript"
],
"Title": "Simple Tip Calculator with JavaScript Console App"
}
|
235398
|
<p>I am working on moving some complex script logging from functions to classes. In the functional version I would use a string like this</p>
<pre><code>"{header-[cf][0][:12]}_Started: 11:30:21"
</code></pre>
<p><strong>{????}_</strong> is the identifying info, here I have a header item <strong>header-</strong> (which has formatting implications), it will log to both console and file <strong>[cf]</strong>, have no initial indentation <strong>[0]</strong>, and will pad the following string to provide 12 characters before the : that follows Started <strong>[:12]</strong>, so 5 spaces of padding. I had functions to increment the tab value, change the destination (console, file or both), etc. All driven with complicated RegularExpressions to extract the identifying info from the start of the string.
Now, as I move to classes, I have</p>
<pre><code>Enum PxLogType {
blankLine
header
milieuCondition
}
class Px_LogItem {
[PxLogType]$type
[bool]$logToConsole
[bool]$logToFile
[int]$indent
[char]$alignToSymbol
[int]$alignSymbolLocation
[string]$string
# Constructor
Px_LogItem ([PxLogType]$type, [bool]$logToConsole, [bool]$logToFile, [int]$indent, [string]$string) {
$this.type = $type
$this.logToConsole = $logToConsole
$this.logToFile = $logToFile
$this.indent = $indent
$this.string = $string
}
Px_LogItem ([PxLogType]$type, [bool]$logToConsole, [bool]$logToFile, [int]$indent, [char]$alignToSymbol, [int]$alignSymbolLocation, [string]$string) {
$this.type = $type
$this.logToConsole = $logToConsole
$this.logToFile = $logToFile
$this.indent = $indent
$this.alignToSymbol = $alignToSymbol
$this.alignSymbolLocation = $alignSymbolLocation
$this.string = $string
}
}
</code></pre>
<p>Ultimately I will have more enumerations, a method to increase the tab indent, etc. This is working, but </p>
<pre><code>$logItem = [Px_LogItem]::New([PxLogType]::header, $true, $true, 0, ':', 12, "Started: 11:30:21")
</code></pre>
<p>is not as readable to my eye. Especially the two instances of <code>$true</code> that replace <code>[cf]</code> to define the target for the log. And depending on where I go, I can see having a few more constructor variations, which starts to get messy. At least, messy in my eyes that are as yet not so familiar with the way constructors are so... specific.</p>
<p>So, I wonder if I am on the right track, and just not familiar enough yet with how class based code looks, or am I off track? I imagine I could do another enum for the log target, with valid values of c, f & cf. Or even have a version that doesn't take those arguments, and defaults both to true to simplify things. That would require method chaining for the constructors, which might actually be a good idea, but how many constructors is considered the threshold for that change? I realize this is all pretty non specific and basically just opinion, but I hope specific enough for some folks to weigh in with their opinions, since I'm too ignorant to have a valid opinion yet.</p>
|
[] |
[
{
"body": "<p>Having a default value is a good idea.<br/>\nAlso, instead of of using the constructor directly, there is a way to convert from a hash table.<br/>\nThis way only works if the class has a default (no-argument) constructor. (If you define a constructor that takes several arguments, you must also explicitly define a no-argument constructor.)</p>\n\n<pre><code>Enum PxLogType { BlankLine; Header; MilieuCondition }\n[Flags()] Enum OutputDestination { Console = 1; File = 2 }\n\nclass Alignment {\n [char] $Symbol\n [int] $Location\n\n [string] ToString() { return \"{{Symbol='{0}', Location={1}}}\" -f $this.Symbol,$this.Location }\n}\n\nclass PxLogItem {\n [PxLogType] $Type = 'BlankLine'\n [OutputDestination] $Destination = 'Console'\n [int] $Indent = 0\n [Alignment] $Alignment\n [string] $String = ''\n}\n</code></pre>\n\n<p>You can write as follows.</p>\n\n<pre><code>@(\n New-Object PxLogItem -Property @{ Destination = 'File'; String = 'ABC' }\n [PxLogItem]@{ Indent = 12; String = 'DEF' }\n [PxLogItem]@{ Type = 'Header'; Destination = 'Console,File'; Alignment = @{ Symbol = '#'; Location = 10 }; String = 'GHI' }\n\n) | Format-Table -AutoSize\n</code></pre>\n\n<p>The result:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> Type Destination Indent Alignment String\n ---- ----------- ------ --------- ------\nBlankLine File 0 ABC \nBlankLine Console 12 DEF \n Header Console, File 0 {Symbol='#', Location=10} GHI\n</code></pre>\n\n<p>You can also convert strings to objects. This way requires defining a <code>Parse()</code> method.</p>\n\n<pre><code>Enum PxLogType { BlankLine; Header; MilieuCondition }\n[Flags()] Enum OutputDestination { Console = 1; File = 2 }\n\nclass Alignment {\n [char] $Symbol\n [int] $Location\n\n [string] ToString() { return \"{{Symbol='{0}', Location={1}}}\" -f $this.Symbol,$this.Location }\n static [Alignment] Parse($str) { $s,$l = $str.Trim().Split(',', 2); return @{ Symbol = $s; Location = $l } }\n}\n\nclass PxLogItem {\n\n [PxLogType] $Type = 'BlankLine'\n [OutputDestination] $Destination = 'Console'\n [int] $Indent = 0\n [Alignment] $Alignment\n [string] $String = ''\n\n static [PxLogItem] Parse($str) {\n $regex = '^(?:{(?<type>[a-z]+),(?<dest>[cf]+),(?<idt>[0-9]+)(?:,align=(?<align>\\S,[0-9]+))?})?(?<text>.*)$'\n if ($str -notmatch $regex) { throw }\n\n $result = @{ String = $Matches['text'] }\n if ($Matches['type']) {\n $result.Add('Type', $Matches['type'])\n $result.Add('Destination', $Matches['dest'].ToCharArray().ForEach{ \"$_\" })\n $result.Add('Indent', $Matches['idt'])\n }\n if ($Matches['align']) {\n $result.Add('Alignment', $Matches['align'])\n }\n return $result\n } \n}\n</code></pre>\n\n<p>All of the following are valid conversions.</p>\n\n<pre><code>@(\n [PxLogItem]@{ Destination = 'Console,File'; Indent = 12; Alignment = '=,15'; String = 'ABC' }\n [PxLogItem]'DEF'\n [PxLogItem]'{m,f,8}GHI'\n [PxLogItem]'{header,cf,4,align=#,10}JKL'\n\n) | Format-Table -AutoSize\n</code></pre>\n\n<p>The result:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> Type Destination Indent Alignment String\n ---- ----------- ------ --------- ------\n BlankLine Console, File 12 {Symbol='=', Location=15} ABC \n BlankLine Console 0 DEF \nMilieuCondition File 8 GHI \n Header Console, File 4 {Symbol='#', Location=10} JKL\n</code></pre>\n\n<p>Using functions makes them more readable.</p>\n\n<pre><code>function New-PxLogItem {\n\n Param(\n [Parameter(Mandatory, Position=0)]\n [string]\n $String = '',\n\n [Parameter(Position=1)]\n [PxLogType]\n $Type = 'BlankLine',\n\n [Parameter(Position=2)]\n [ValidateRange(0,1000)]\n [int]\n $Indent = 0,\n\n [Parameter(Position=3)]\n [Alignment]\n $Alignment,\n\n [switch]\n $Console,\n\n [switch]\n $File\n )\n\n if (!$Console -and !$File) { $Console = $true }\n $PSBoundParameters.Add('Destination', !!$Console + 2 * !!$File)\n ('Console','File').ForEach{ [void]$PSBoundParameters.Remove($_) }\n\n [PxLogItem]$PSBoundParameters\n}\n</code></pre>\n\n<pre><code>$item1 = New-PxLogItem \"Hello\" Header -indent 4 -align \"#,10\" -c -f\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T22:16:10.773",
"Id": "235486",
"ParentId": "235403",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T08:25:02.033",
"Id": "235403",
"Score": "3",
"Tags": [
"object-oriented",
"powershell"
],
"Title": "Function to class migration: constructor best practice"
}
|
235403
|
<p>I working on optimizing some code for speed in a python module. I have pinned down the bottleneck and is a code snippet which calculates three <code>np.ndarray</code>s. Namely the following code: </p>
<pre><code>xh = np.multiply(K_Rinv[0, 0], x )
xh += np.multiply(K_Rinv[0, 1], y)
xh += np.multiply(K_Rinv[0, 2], h)
yh = np.multiply(K_Rinv[1, 0], x)
yh += np.multiply(K_Rinv[1, 1], y)
yh += np.multiply(K_Rinv[1, 2], h)
q = np.multiply(K_Rinv[2, 0], x)
q += np.multiply(K_Rinv[2, 1], y)
q += np.multiply(K_Rinv[2, 2], h)
</code></pre>
<p>where <code>x</code>, <code>y</code> and <code>h</code> are <code>np.ndarray</code>s with shape (4206, 5749) and <code>K_Rinv</code> is a <code>np.ndarray</code> witch shape (3, 3). This code snippet is called multiple times and takes more than 50% of the time of the whole code. Is there a way to speed this up ? Or is it just as it is and can't be speed up.</p>
<p>Every idea and criticism is welcome. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T10:26:58.070",
"Id": "460733",
"Score": "1",
"body": "Can you please [title your post for what the code presented is to accomplish](https://codereview.stackexchange.com/help/how-to-ask)? Possibly, you get advice even more helpful answers when you provide more context."
}
] |
[
{
"body": "<p>First a quick non-performance related mode: <code>np.multiply</code> could simply be replaced by <code>*</code> in your case since it's basically scalar x array. That would make the code less verbose.</p>\n\n<pre><code>xh = K_Rinv[0, 0] * x \nxh += K_Rinv[0, 1] * y \nxh += K_Rinv[0, 2] * h\n</code></pre>\n\n<p>My first intuition on your problem was that it lends itself to be rewritten as scalar product. See the following example:</p>\n\n<pre><code>import numpy as np\n\nK_Rinv = np.random.rand(3, 3)\n\nx = np.random.rand(4206, 5749)\ny = np.random.rand(4206, 5749)\nh = np.random.rand(4206, 5749)\nxyh = np.stack((x, y, h))\n\nxh_dot = np.dot(xyh, K_Rinv[0, :])\n</code></pre>\n\n<p>But it turns out, that this is 4x slower than what you have.</p>\n\n<p>The \"vectorized\" version below still turns is about 1.5x slower than what you have for my toy dataset.</p>\n\n<pre><code>xh_vec = (xyh * K_Rinv[0, :]).sum(axis=2)\n</code></pre>\n\n<p>A quick check with <code>np.allclose(...)</code> does however confirm, that the results are indeed (numerically) equivalent.</p>\n\n<p>You might see some improvement by putting your code into a separate function and apply the <code>@jit(nopython=True)</code> decorator from <a href=\"https://numba.pydata.org/numba-doc/latest/user/5minguide.html\" rel=\"nofollow noreferrer\">numba</a> if that's an option. numba is a Just-in-Time compiler for Python code, and is also aware of some, but not all, numpy functions. For the simple test above, the time was a bit more than half than that without using numba. When measuring, take care to exclude the first run, since that's when the compilation takes place.</p>\n\n<hr>\n\n<p>Unfortunately, I'm a little bit short on time at the moment to look into this further.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T10:45:36.700",
"Id": "235409",
"ParentId": "235404",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T09:02:59.280",
"Id": "235404",
"Score": "1",
"Tags": [
"python",
"performance",
"numpy"
],
"Title": "Optimization fo code snippet including multiple np.multipy statements"
}
|
235404
|
<p>My question is about proper testing procedures for Django models.
The project is for a startup building a very basic HR system due to excel sheet data integrity problems. I am trying to figure out the best way to unit test the documents and models they will be managing.</p>
<p>Based on how I wrote this test, what are some ways I could make it better?
I will be writing 8 more tests like this so don't want to repeat any mistakes due to ignorance.</p>
<p>Models:</p>
<pre class="lang-py prettyprint-override"><code>
class Passport(models.Model):
owner = models.OneToOneField(Employee, on_delete=models.CASCADE)
issue_date = models.DateField(blank=False)
expiration_date = models.DateField(blank=False)
dob = models.DateField()
"https://pypi.org/project/django-countries/"
place_of_issue = CountryField(blank=False,null=True)
#place_of_issue = models.CharField(_("Country code as displayed in passport"),max_length=5)
image = models.ImageField(storage=PrivateMediaStorage(), upload_to='passports')
def __str__(self):
return f"Employee: {self.owner.first_name}"
class Employee(AbstractBaseUser, PermissionsMixin):
employment_statuses = (
('ap','Applicant'),
('trial', 'Initial Training'),
('em', 'Employed'),
('ps','Pause')
)
genders = (('M', 'male'),('F', 'female'))
# core information
full_name = models.CharField(_('Surname, Given Names as on passport'), validators=[name_validator], max_length=25, blank=False, null=True)
#employment data
gender = models.CharField(max_length=10, choices=genders)
employee_id_code = models.CharField(_('employee id number'),max_length=20, null=True)
# activity Status
employment_status = models.CharField(choices=employment_statuses, max_length=30)
employment_status_note = models.TextField(max_length=500)
# contact information
phone_number = models.CharField(max_length=14, unique=True)
email = models.EmailField(_('-redacted- email address'), unique=True)
personal_email = models.EmailField(_('Personal Email Address'), unique=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(_('date joined'), auto_now_add=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = CustomUserManager()
def first_name(self):
try:
return str(self.full_name.split()[1])
except:
pass
def middle_name(self):
try:
return str(self.full_name.split()[2])
except:
pass
def last_name(self):
try:
return str(self.full_name.split()[0])
except:
pass
def __str__(self):
return f"{self.full_name} {self.email}"
</code></pre>
<p>Testing Code (test_passport.py) in testing module in the documents app</p>
<pre class="lang-py prettyprint-override"><code> import faker
from django.test import TestCase
from core_hr.models import Passport
from users.models import Employee
from django_countries.fields import CountryField
from django.contrib.auth import get_user_model
import random
fake = faker.Faker()
def get_mock_user():
full_name = f"{fake.first_name()} {fake.last_name()} {fake.last_name()}"
gender = random.choice([x[0] for x in Employee.genders])
employee_id_code =f"G-{fake.ean8()}"
employment_status = random.choice([x[0] for x in Employee.employment_statuses])
employment_status_note = fake.bs()
phone_number = fake.phone_number()
email = fake.email()
personal_email = fake.email()
date_joined = fake.past_date(start_date="-120d", tzinfo=None)
user = Employee.objects.create_user(
full_name=full_name,
gender=gender,
employee_id_code=employee_id_code,
employment_status=employment_status,
employment_status_note= employment_status_note,
phone_number=phone_number,
personal_email=personal_email,
date_joined=date_joined,
email=email,
password='foo'
)
return user
def get_mock_passport(employee):
owner = Employee.objects.get(id=employee.id)
dob = fake.date_between(start_date="-9y", end_date="-1m")
date_of_expiration = fake.date_between(start_date="+3m", end_date="+9y")
place_of_issue = fake.country_code()
date_of_issue = fake.date_between(start_date="-9y", end_date="-1m")
passport = Passport.objects.create(
owner=owner,
place_of_issue=place_of_issue,
issue_date=date_of_issue,
expiration_date=date_of_expiration,
dob=dob
)
return passport
class PassportTestCase(TestCase):
def setUp(self):
self.employee = get_mock_user()
self.passport = get_mock_passport(self.employee)
def test_passport_has_fields(self):
retrieved_passport = Passport.objects.get(id=self.passport.pk)
self.assertEqual(self.passport, retrieved_passport)
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T09:05:30.240",
"Id": "235405",
"Score": "1",
"Tags": [
"python",
"unit-testing",
"django"
],
"Title": "Document storage models and Django Unit Testing"
}
|
235405
|
<p>I took a stab at implementing <code>Promise.race()</code>:</p>
<pre class="lang-js prettyprint-override"><code>"use strict";
function race (...promises) {
return new Promise((resolve, reject) => {
let [resolved, rejected] = [false, false];
promises.forEach(promise => {
promise.then(value => {
if (!resolved) {
resolve(value);
resolved = true;
}
},
reason => {
if (!rejected) {
reject(reason);
rejected = true;
}
})
});
});
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T14:39:57.333",
"Id": "464921",
"Score": "3",
"body": "Given the issue I described when I tried to run your code for `Promise.all()` in [my answer for that post](https://codereview.stackexchange.com/a/237116/120114), please [edit] your post to include sample inputs and expected/actual output- perhaps with a runnable snippet..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T06:52:30.953",
"Id": "466803",
"Score": "0",
"body": "I’m voting to close this as *not working* because in [this sample bin](https://jsbin.com/jidarod/edit?js,output) that uses the code above there is an error in the console `TypeError: promise.then is not a function`"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T09:17:24.550",
"Id": "235406",
"Score": "1",
"Tags": [
"javascript",
"beginner",
"asynchronous",
"promise"
],
"Title": "Implementation of Promise.race"
}
|
235406
|
<p>I use the following command to get specific entries between certain dates from Apache log files. Then I filter out my own address and some bots, then I print out the IP, sort it, get the uniques, output the ip with count, and for summary I count lines to get a total.</p>
<p>Is there a way to improve this, reducing the amount of awk commands?
Or to get this process down more efficient? I'm not that proficient with awk, but I have the feeling this should be accomplish able in maybe one awk instruction.</p>
<pre><code>zgrep '"GET /my/path/to/page.html' other_vhosts_access*
| awk -F'[][]'
-v dstart=`date -d"2019-12-09" +%Y%m%dT%0H:%0M:%0S`
-v dend=`date -d"2020-01-09" +%Y%m%dT%0H:%0M:%0S`
'{ $2 = substr($2,8,4)sprintf("%02d",(match("JanFebMarAprMayJunJulAugSepOctNovDec",substr($2,4,3))+2)/3)substr($2,1,2)"T"substr($2,13,8);
if ($2 >= dstart && $2 < dend) print }'
| awk '$0 !~ /127\.0\.0\.1|bot\.|bot\/|dotbot|crawler/'
| awk '{print $2}'
| sort
| uniq -c
| sort -n
| wc -l
</code></pre>
<p>the one liner: </p>
<pre><code>zgrep '"GET /my/path/to/page.html' other_vhosts_access* | awk -F'[][]' -v dstart=`date -d"2019-12-09" +%Y%m%dT%0H:%0M:%0S` -v dend=`date -d"2020-01-09" +%Y%m%dT%0H:%0M:%0S` '{ $2 = substr($2,8,4)sprintf("%02d",(match("JanFebMarAprMayJunJulAugSepOctNovDec",substr($2,4,3))+2)/3)substr($2,1,2)"T"substr($2,13,8); if ($2 >= dstart && $2 < dend) print }' | awk '$0 !~ /127\.0\.0\.1|bot\.|bot\/|dotbot|crawler/' | awk '{print $2}' | sort | uniq -c | sort -n | wc -l
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T18:37:40.627",
"Id": "460798",
"Score": "2",
"body": "A small sample of the log file would be useful for testing and also validating your logic."
}
] |
[
{
"body": "<p>I assume there's a simply copy-paste error where you have <code>|</code> at the start of a line, instead of at the end of the preceding line?</p>\n\n<p>If we're just going to count lines, there's no need for <code>sort | uniq -c | sort -n</code> - we can replace all that with <code>sort -u</code>.</p>\n\n<p>These two Awk programs can be trivially combined:</p>\n\n<blockquote>\n<pre><code>awk '$0 !~ /127\\.0\\.0\\.1|bot\\.|bot\\/|dotbot|crawler/' | awk '{print $2}'\n</code></pre>\n</blockquote>\n\n<p>That would become</p>\n\n<pre><code>awk '$0 !~ /127\\.0\\.0\\.1|bot\\.|bot\\/|dotbot|crawler/ {print $2}'\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T15:21:03.107",
"Id": "460770",
"Score": "0",
"body": "I guess the remaining two Awk scripts can also be combined; just `split()` the value of ` $2` and print the second element from the resulting array if `$2` matches the regex."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T15:25:18.227",
"Id": "460771",
"Score": "0",
"body": "@tripleee, I'm only an occasional Awk user; I recommend that you make that your answer. If you really don't want to write your own answer, then edit mine to add your recommendation (but I'd prefer you to write your own!)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T16:24:22.070",
"Id": "460779",
"Score": "0",
"body": "There is no copy paste error. I basically used the pipes as a newline to make the scrip easier to read. All the pipes are also in the oneliner. The newlines are just there for the ease of reading."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T16:32:18.600",
"Id": "460781",
"Score": "0",
"body": "`zgrep '\"GET /path/to/page HTTP' other_vhosts_access* | awk -F'[][]' -v dstart=``date -d\"2019-12-09\" +%Y%m%dT%0H:%0M:%0S`` -v dend=``date -d\"2020-01-09\" +%Y%m%dT%0H:%0M:%0S`` '{ $2 = substr($2,8,4)sprintf(\"%02d\",(match(\"JanFebMarAprMayJunJulAugSepOctNovDec\",substr($2,4,3))+2)/3)substr($2,1,2)\"T\"substr($2,13,8); if ($2 >= dstart && $2 < dend) print }' | awk '$0 !~ /127\\.0\\.0\\.1|bot\\.|bot\\/|dotbot|crawler/ {print $2}' | sort -u | wc -l` works great for counting lines. But if I wish to remove the wc -l part to get an overview of how much the same ip requested I still need to use the extras"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T18:38:08.643",
"Id": "460799",
"Score": "1",
"body": "Thanks for prodding me! Posted a separate answer now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T18:42:44.400",
"Id": "460800",
"Score": "0",
"body": "Actually the `$0 !~ ` can be condensed to just `!`."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T14:03:13.890",
"Id": "235419",
"ParentId": "235416",
"Score": "7"
}
},
{
"body": "<p>Here's a refactoring which condenses much of the logic after the <code>zgrep</code> into a single Awk script.</p>\n\n<ul>\n<li>Prefer modern <code>$(command substitution)</code> over obsolescent <code>`command substitution`</code>syntax. But the <code>date</code> command substitutions don't really make sense here. Just pass in the dates as literal strings, like <code>dstart=\"20190109T00:00:00\"</code>.</li>\n<li>Two Awk processes can often be merged. If you have <code>awk -F : '{print $2}' | awk -F = '{print $1}'</code> you can simply use <code>awk -F : '{ split($2, x, /=/); print x[1] }'</code></li>\n<li>I refactored the <code>bot\\.|bot\\/</code> fragment in the regex to <code>bot[.\\/]</code>.</li>\n<li><code>uniq -c</code> can be replaced with a simple Awk associative array of counts. This does away with the first <code>sort</code>.</li>\n<li>If you only care about the number of unique IP addresses, there is no need for <code>sort -n</code>, and vice versa. I'm guessing you want either, so have not attempted to replace those parts.</li>\n<li>And of course, don't introduce syntax errors when splitting the script over multiple lines. A pipe <code>|</code> at end of line naturally splits the script, while a newline followed by a pipe is an error.</li>\n</ul>\n\n<pre class=\"lang-sh prettyprint-override\"><code>zgrep '\"GET /my/path/to/page.html' other_vhosts_access* |\nawk -F'[][]' \\\n -v dstart=\"20191209T00:00:00\" -v dend=\"20200109T00:00:00\" \\\n '{ $2 = substr($2,8,4) sprintf(\"%02d\",(\\\n match(\"JanFebMarAprMayJunJulAugSepOctNovDec\",\n substr($2,4,3))+2)/3) substr($2,1,2) \"T\" substr($2,13,8); \n if ($2 >= dstart && $2 < dend && \\\n $0 !~ /127\\.0\\.0\\.1|bot[.\\]/|dotbot|crawler/) {\n split($0, x, /[ \\t]+/)\n ip=x[2]\n ++p[ip] }\n }\n END { for (ip in p) printf \"%7i %s\\n\", p[ip], ip }' |\n# sort -n |\nwc -l\n</code></pre>\n\n<p>If you always want only the total, the end of the script can be replaced with</p>\n\n<pre><code> if (!p[ip]++) total++ }\n }\n END { print total }'\n</code></pre>\n\n<p>but if you sometimes want to see individual IP addresses, I would just keep the option to pipe to either <code>sort -n</code> or <code>wc -l</code>.</p>\n\n<p>Kudos for the rather compact date extraction logic. Of course, if Apache didn't default to a horrible \"human readable\" date format, this would not be necessary; but I guess we are stuck with it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T18:20:30.997",
"Id": "235432",
"ParentId": "235416",
"Score": "5"
}
},
{
"body": "<h3>Drop the unnecessary time part</h3>\n\n<p>The time part of the date doesn't play a role in the filtering.\nYou could drop it and the script will be simpler.</p>\n\n<h3>Use more variables</h3>\n\n<p>I find this line a bit difficult to read for multiple reasons:</p>\n\n<blockquote>\n<pre><code>'{ $2 = substr($2,8,4)sprintf(\"%02d\",(match(\"JanFebMarAprMayJunJulAugSepOctNovDec\",substr($2,4,3))+2)/3)substr($2,1,2)\"T\"substr($2,13,8); \n</code></pre>\n</blockquote>\n\n<p>First of all, I don't see a good reason to overwrite the original value of the field variable <code>$2</code>. It would be natural to store the computed date string in a variable called <code>date</code>.</p>\n\n<p>Secondly, the elements of the formatting logic are hard to read, and it would be easy to fix by assigning them to variables like <code>year</code>, <code>month</code>, <code>day</code>.</p>\n\n<p>Finally, a space between the concatenated elements such as <code>substr(...)sprintf(...)</code> would be really welcome by human readers.</p>\n\n<h3>Use <code>$(...)</code> instead of <code>`...`</code></h3>\n\n<p>There's really no reason to use the archaic and potentially troublesome <code>`...`</code> syntax.</p>\n\n<h3>Order terms in a condition by value</h3>\n\n<p>Instead of this:</p>\n\n<blockquote>\n<pre><code>if ($2 >= dstart && $2 < dend) ...\n</code></pre>\n</blockquote>\n\n<p>Consider this:</p>\n\n<pre><code>if (dstart <= $2 && $2 < dend) ...\n</code></pre>\n\n<p>When the values increase from left to right, the meaning becomes natural, intuitive.</p>\n\n<h3>Don't repeat yourself</h3>\n\n<p>Instead of typing <code>+%Y%m%dT%0H:%0M:%0S</code> twice, it would be better to write it once and store it in a variable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T17:34:26.663",
"Id": "235475",
"ParentId": "235416",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "235432",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T13:01:41.443",
"Id": "235416",
"Score": "6",
"Tags": [
"bash",
"awk"
],
"Title": "Count unique IP address in a date range from Apache log"
}
|
235416
|
<p>So here I wanted to make a system that registered a person's account. It remembers the person's email, account, first and last names, by writing to a file. You can login to that account by typing the email and password according to that email and then you would get a hello message, saying your first and last name that you used to register your account with.</p>
<pre><code>data_text = []
first_names = []
last_names = []
emails = []
passwords = []
def user_choice():
print('Hello user, create an account or login to an existing one.')
choice = input('Insert "1" if you wish to create an account or "2" if you wish to login: ')
print('\r')
if choice == '1':
create_account()
user_choice()
else:
login_account()
user_choice()
def register_info():
with open('Login_Data.txt', 'r') as login_data:
global data_text, first_names, last_names, emails, passwords
data_text = login_data.readlines()
for i in data_text:
data_text[data_text.index(i)] = i.strip()
emails = (data_text[2::4])
def create_account():
with open('Login_Data.txt', 'a') as login_data:
first_name = input('First name: ')
last_name = input('Last name: ')
email = input('Insert your Email adress: ')
while email in emails:
print('That email is already registered')
email = input('Insert another Email adress: ')
password = input('Create a password: ')
passwordc = input('Confirm your password: ')
info = [first_name, last_name, email, password]
while passwordc != password:
print('The passwords do not match.')
passwordc = input('Reinsert your password: ')
for i in info:
login_data.write(i)
login_data.write('\n')
print('Nice! Your account was registered.')
print('\r')
register_info()
def login_account():
register_info()
with open('Login_Data.txt', 'r'):
login_email = input('Email: ')
while login_email not in emails:
print('Invalid Email')
login_email = input('Reinsert your Email: ')
login_password = input('Password: ')
while login_password != data_text[data_text.index(login_email) + 1]:
print('Invalid password')
login_password = input('Reinsert your password: ')
print('Hello {} {}, welcome back!'.format(data_text[data_text.index(login_email) - 2], data_text[data_text.index(login_email) - 1]))
print('\r')
user_choice()
</code></pre>
|
[] |
[
{
"body": "<p><sub>Conversion of a comment to an answer.</sub></p>\n\n<blockquote>\n <p>Definitely avoid the recursion in <code>user_choice</code>. It will run out of stack if you keep exercising it for long enough. A simple <code>while True:</code> around the rest of the function body should fix it (obviously take out the calls where it calls itself).<br>\n - <a href=\"https://codereview.stackexchange.com/users/63322/tripleee\">tripleee</a></p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T00:32:48.440",
"Id": "235446",
"ParentId": "235418",
"Score": "1"
}
},
{
"body": "<ul>\n<li><code>user_choice</code> is your <em>main</em> loop, and so it would be better described as <code>main</code>. Whilst fairly undescriptive on what it does you can add a docstring to add information on what it performs.</li>\n<li>It is more idiomatic to use loops in Python rather than recursion. This is partly due to the recursion limit, and partially that the iterator pattern has a lot of support in Python.</li>\n<li>I've rarely seen <code>'\\r'</code> in Python. I don't see why you would need it and so have just removed them.</li>\n<li>I like the way that you got a users email. The use of a while loop here is pretty clean.</li>\n<li>I would change the prompted text when getting an email as it's different to the rest of the prompts.</li>\n<li>I would DRY your do while loop. There's not really a point to having two different <code>input</code> prompts with the above suggestion.</li>\n<li><p>Recently I was creating an account using <code>passwd</code> and multiple times I kept messing up <em>the first</em> password entry. It was rather vexing as I knew I messed up and I just had to hope I pressed backspace the correct amount of times to fix my mess up. Unfortunately I wasn't skilled enough to fix my mistake.</p>\n\n<p>However with your solution I would have to quit out of your entire program, removing the data I have already to fix my mistake. You should instead get again the password and the confirmation.</p></li>\n<li>There is no point in opening <code>login_data</code> until the user input has been confirmed to be correct. You should try to keep <code>with</code> statements as small as necessary.</li>\n<li>I would prefer to build a dictionary or an abstract datatype for the user information.</li>\n<li>You can remove one of your <code>login_data.write</code>s by passing <code>i + '\\n'</code>.</li>\n<li>\"Login_Data.txt\" seems ok, but it's not great. You can use JSON via <code>import json</code> and make a much easier and standard file type to work with.</li>\n<li><p>Your interactions with your globals seem really poor. If you want a global, than I suggest you only have one. This is easy when using dictionaries.</p>\n\n<p>I would also suggest changing your code to have <em>no globals</em>.</p></li>\n<li>I would change <code>login_account</code> to align with the above, changed do-while loops, no globals and using JSON.</li>\n<li>Since we are using JSON we can easily change the format to display the first and last name easier.</li>\n<li>Your solution is in no way safe, it's prone to over the shoulder attacks by not using <a href=\"https://docs.python.org/3/library/getpass.html\" rel=\"nofollow noreferrer\"><code>getpass</code></a> and you're storing passwords in plain-text. This is not safe. Do not use this for anything more than a toy project that will only ever have you entering a password unique to this toy.</li>\n</ul>\n\n<pre><code>import json\n\n\ndef main():\n \"\"\"Create an account or log in.\"\"\"\n while True:\n print('Hello user, create an account or login to an existing one.')\n choice = input('Insert \"1\" if you wish to create an account or \"2\" if you wish to login: ')\n print()\n if choice == '1':\n create_account()\n else:\n login_account()\n\n\ndef input_user_email(emails):\n \"\"\"Get an unowned email.\"\"\"\n while True:\n email = input('Email: ')\n if email not in emails:\n return email\n print('That email is already registered.')\n\n\ndef input_user_password():\n \"\"\"Get a user's email.\"\"\"\n while True:\n password = input('Password: ')\n confirmation = input('Confirm password: ')\n if password == confirmation:\n return password\n print('The passwords do not match.')\n\n\ndef get_user_information(emails):\n \"\"\"Get a user's information.\"\"\"\n return {\n 'first_name': input('First Name: '),\n 'last_name': input('Last Name: '),\n 'email': input_user_email(emails),\n 'password': input_user_password(),\n }\n\n\ndef create_account():\n \"\"\"Create user account.\"\"\"\n with open('login_data.json', 'w+') as f:\n users = json.load(f)\n emails = {user['email'] for user in users}\n user = get_user_information(emails)\n users.append(user)\n json.dump(users, f)\n print('Nice! Your account was registered.\\n')\n\n\ndef login_account():\n \"\"\"Log into a user account.\"\"\"\n with open('login_data.json') as f:\n users = json.load(f)\n by_email = {user['email']: user for user in users}\n\n while True:\n email = input('Email: ')\n if email in by_email:\n user = by_email[email]\n break\n print('Invalid Email')\n\n while True:\n password = input('Password: ')\n if password == user['password']:\n break\n print('Invalid password')\n\n print('Hello {0.first_name} {0.last_name}, welcome back!\\n'.format(user))\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T15:24:04.927",
"Id": "460909",
"Score": "0",
"body": "Thanks for all your suggestions man, about the '\\r' thing, I didn't know how to separate the data in different lines by using '.append'. I'll see if I can learn about encrypting text and JSON, thanks for mentioning that too."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T01:29:58.940",
"Id": "235450",
"ParentId": "235418",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235450",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T13:41:54.923",
"Id": "235418",
"Score": "2",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Login and account system"
}
|
235418
|
<p>I saw an article on <a href="https://www.geeksforgeeks.org/readwrite-class-objects-fromto-file-c/" rel="nofollow noreferrer">how to read/write class objects from/to file in C++</a>. The example there declared an object inside a member function and wrote the object into a file using <code>ostream::write()</code> method.</p>
<p>Now I wanted to understand the <code>ostream::write</code> method. So, I rewrote the code as below:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <fstream>
class Contestant {
public:
std::string Name;
int Age, Ratings;
int input();
int output_highest_rated();
};
int Contestant::input() {
std::ofstream file_obj;
file_obj.open("Input.txt", std::ios::app);
std::string str = "Micheal";
int age = 18, ratings = 2500;
Name = str;
Age = age;
Ratings = ratings;
file_obj.write((char*)this, sizeof(this));
str = "Terry";
age = 21;
ratings = 3200;
Name = str;
Age = age;
Ratings = ratings;
file_obj.write((char*)this, sizeof(this));
return 0;
}
int Contestant::output_highest_rated() {
std::ifstream file_obj;
file_obj.open("Input.txt", std::ios::in);
file_obj.read((char*)this, sizeof(this));
int max = 0;
std::string Highest_rated;
while (!file_obj.eof()) {
if (this->Ratings > max) {
max = this->Ratings;
Highest_rated = this->Name;
}
file_obj.read((char*)this, sizeof(this));
}
std::cout << Highest_rated;
return 0;
}
int main() {
Contestant object;
object.input();
object.output_highest_rated();
return 0;
}
</code></pre>
<p>What I did is that I replaced the object with the <code>this</code> identifier.</p>
<p>The code compiles without any error but I have very little understanding of the <code>this</code> identifier so please correct me if I've done anything wrong. And if I've posted on a wrong site, please help me migrate. Thanks.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T16:00:01.827",
"Id": "460773",
"Score": "0",
"body": "I've now followed the link and I see that you've just copied somebody else's code and posted it for review. That's specifically disallowed, [for several reasons](https://codereview.meta.stackexchange.com/questions/1294/why-is-only-my-own-written-code-on-topic). That said, that's a very poor approach, and won't even work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T16:05:47.663",
"Id": "460775",
"Score": "0",
"body": "I'm sorry. Perhaps I should review the rules. But can I modify someone's code and ask here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T16:07:51.893",
"Id": "460776",
"Score": "0",
"body": "What, exactly, did you change?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T16:11:44.820",
"Id": "460777",
"Score": "0",
"body": "I'm sorry. I messed up again. However, I edited the post to clarify what I changed."
}
] |
[
{
"body": "<p>It's worth writing functions that accept a <code>std::istream</code> or <code>std::ostream</code> for \nreading and writing (respectively), rather than hard-coding a file name. This makes for easier testing, as we can write to a <code>std::stringstream</code> rather than assuming we're able to write to <code>Input.txt</code> in the current working directory.</p>\n\n<p>It's also better for your production code, as we can separate the file handling from the I/O, and perhaps store many contestants' data in a single file.</p>\n\n<p>The output version should not modify <code>Contestant</code>, so declare it <code>const</code>.</p>\n\n<p>We should call the functions <code>operator>></code> and <code>operator<<</code>, so they can be used like the other streaming operators:</p>\n\n<pre><code>#include <iosfwd>\nstd::istream& operator>>(std::istream&, Contestant&);\nstd::ostream& operator<<(std::ostream&, const Contestant&);\n</code></pre>\n\n<hr>\n\n<p>Now to the meat of the review. There are several serious problems here:</p>\n\n<blockquote>\n<pre><code>file_obj.write((char*)this, sizeof(this));\n</code></pre>\n</blockquote>\n\n<ul>\n<li><p>The first is that <code>this</code> is a <code>Contestant*</code>, i.e. a pointer. So <code>sizeof this</code> evaluates to the size of the pointer, not to the size of a <code>Contestant</code>. You probably meant to write <code>sizeof *this</code>.</p></li>\n<li><p>The second big problem is that <code>std::string</code> objects are not <em>trivially copyable</em> - simply writing their memory representation isn't going to work. An obvious reason that it couldn't work is that strings generally need to be able to allocation additional memory when their contents grow; that memory is external to the object, and referenced by a pointer.</p></li>\n<li><p>The third issue is that types such as <code>int</code> are represented differently on different platforms (they may have different size and endianness, and represent negative values differently). So we should always convert to a neutral representation for interchange (remember that we might be reading with a newer version of the program, on the same machine). A human-readable form is usually best.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T15:57:42.477",
"Id": "235423",
"ParentId": "235422",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "235423",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T15:34:16.710",
"Id": "235422",
"Score": "-4",
"Tags": [
"c++",
"file-system"
],
"Title": "Writing an object to a file; Is this approach correct?"
}
|
235422
|
<p>We want to provide a simple Redis pub/sub alternative in memory for <a href="https://github.com/ICIJ/datashare" rel="nofollow noreferrer">our software</a>. So we implemented this :</p>
<pre><code>public class MemoryDataBus implements DataBus {
private final Map<Consumer<Message>, MessageListener> subscribers = new ConcurrentHashMap<>();
@Override
public void publish(final Channel channel, final Message message) {
Message nonNullMessage = requireNonNull(message, "cannot publish a null message");
subscribers.values().stream().filter(l -> l.hasSubscribedTo(channel)).forEach(l -> l.accept(nonNullMessage));
}
@Override
public void subscribe(final Consumer<Message> subscriber, final Channel... channels) throws InterruptedException {
MessageListener listener = new MessageListener(subscriber, channels);
subscribers.put(subscriber, listener);
listener.loopUntilShutdown();
}
@Override
public void unsubscribe(Consumer<Message> subscriber) {
ofNullable(subscribers.remove(subscriber)).ifPresent(l -> {
l.accept(new ShutdownMessage());
});
}
private static class MessageListener implements Consumer<Message> {
private final Consumer<Message> subscriber;
private final LinkedHashSet<Channel> channels;
final AtomicReference<Message> message = new AtomicReference<>();
public MessageListener(Consumer<Message> subscriber, Channel... channels) {
this.subscriber = subscriber;
this.channels = asSet(channels);
}
boolean hasSubscribedTo(Channel channel) {
return channels.contains(channel);
}
@Override
public void accept(Message message) {
subscriber.accept(message);
synchronized (this.message) {
this.message.set(message);
this.message.notify();
}
}
boolean shutdownAsked() {
Message message = this.message.get();
return message != null && message.type == Message.Type.SHUTDOWN;
}
void loopUntilShutdown() throws InterruptedException {
synchronized (message) {
while (!shutdownAsked()) {
message.wait();
}
}
}
}
}
</code></pre>
<p>I've removed unnecessary code that brings some noise (logs, couters) the source code <a href="https://github.com/ICIJ/datashare-api/blob/master/src/main/java/org/icij/datashare/com/MemoryDataBus.java" rel="nofollow noreferrer">is here</a>.</p>
<p>Our unit tests are green, and manual testing shows no regression compared to redis. But as we also know how difficult it is to make a correct thread safe implementation we want to verify with threading experts :</p>
<ul>
<li>the correctness of it (for example the value returned by shutdownAsked)</li>
<li>if the contention could be improved</li>
<li>if there could be a better implementation of it</li>
</ul>
<p>PS : must add that the question has been originally posted <a href="https://stackoverflow.com/questions/59681774/is-this-java-small-pubsub-memory-implementation-correct-and-effective">on SO</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T18:04:32.123",
"Id": "460792",
"Score": "0",
"body": "_\"must add that the question has been originally posted on SO.\"_ Please delete it there then. Cross posting is generally frowned upon."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T20:59:11.517",
"Id": "460811",
"Score": "1",
"body": "Well I see no Javadoc, so we have no idea how to call this or work with it in a thread safe manner. To illustrate a bit further, look at the Javadoc for [JFrame](https://docs.oracle.com/javase/9/docs/api/javax/swing/JFrame.html), right there it says `Warning: Swing is not thread safe. For more information see Swing's Threading Policy.` So that's it, thread safety is \"it ain't\" and they have a published policy how to interact with it. So, what's your policy how a caller will interact with this code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T23:14:29.077",
"Id": "460830",
"Score": "0",
"body": "@πάνταῥεῖ a kind user has discussed and provide useful information about this code on SO. I can't delete this information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T23:15:04.947",
"Id": "460832",
"Score": "0",
"body": "@markspace I even removed portions of code because my need here is thread correctness, not how I could add javadoc or comments"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T12:25:23.180",
"Id": "461102",
"Score": "0",
"body": "I ended up with a more generic implementation without dependencies and with a main to show how to use it @markspace see [this gist](https://gist.github.com/bamthomas/069f563b2d5216ee9ee016d3f8443d8b)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-18T20:21:33.053",
"Id": "461744",
"Score": "0",
"body": "In the given architecture the stream operation could benefit from `.unordered().parallel()`. However, even with parallel, the operation if far too expensive. Would it be possible to make something like `Channel::getAllSubscribers` ?"
}
] |
[
{
"body": "<p>Assuming <code>requireNonNull(...)</code> is <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Objects.html#requireNonNull(T,java.lang.String)\" rel=\"nofollow noreferrer\"><code>java.util.Objects.requireNonNull(...)</code></a> which throws an exception if <code>null</code>, then there is no need to have a separate local variable for the return value.</p>\n<p>Assuming <code>ofNullable(...)</code> is <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Optional.html#ofNullable(T)\" rel=\"nofollow noreferrer\"><code>java.util.Optional.ofNullable(...)</code></a>, then I would recommend removing the usage here because the code can be simplified:</p>\n<pre class=\"lang-java prettyprint-override\"><code>// ofNullable(...).ifPresent(l -> ...);\n// Simplified:\nMyClass result = ...\nif (result != null) {\n ...\n}\n</code></pre>\n<p><s>It looks like your locking in <code>MessageListener</code> will cause a deadlock:</s></p>\n<ol>\n<li><s><code>MemoryDataBus.subscribe(...)</code> calls <code>loopUntilShutdown</code> which synchronizes on <code>message</code></s></li>\n<li><s><code>MemoryDataBus.publish(...)</code> calls <code>accept</code> which has to wait because lock on <code>message</code> is still held, preventing it from updating <code>message</code></s></li>\n</ol>\n<p>Edit: No deadlock occurs because <code>Object.wait()</code> is used which releases ownership of the monitor (here field <code>message</code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-28T08:32:24.987",
"Id": "490210",
"Score": "0",
"body": "How does `MemoryDataBus.subscribe(...)` call `accept` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T20:16:45.163",
"Id": "490440",
"Score": "0",
"body": "@BrunoThomas, sorry that was a typo, I meant \"`MemoryDataBus.publish(...)` calls `accept`\". I have corrected it now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-02T10:16:41.067",
"Id": "490587",
"Score": "0",
"body": "hmm. thank you for your answer. I think it actually works because it is the same thread (for each message consumer), that is entering the two synchronized blocks. But maybe you have a use case in mind that I don't see. Could you write a test that shows the scenario (for ex like I did here https://github.com/ICIJ/datashare-api/blob/master/src/test/java/org/icij/datashare/com/MemoryDataBusTest.java) ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-05T21:09:08.940",
"Id": "490971",
"Score": "0",
"body": "@BrunoThomas, thank you for providing the code. My previous statement was wrong, I completely missed that `Object.wait()` releases the monitor, so no deadlock can occur. I am very sorry for the confusion my statement caused."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-27T22:40:59.383",
"Id": "249934",
"ParentId": "235427",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T16:28:12.523",
"Id": "235427",
"Score": "6",
"Tags": [
"java",
"multithreading"
],
"Title": "Is this Java small pubsub memory implementation correct and effective?"
}
|
235427
|
<p>I have the following class. </p>
<p>The aim is to have a few methods that deal with the type of the gift, the dwarf who is packing the gifts and the time he will take. And finally, the reindeer, which is supposed to do the work.</p>
<pre><code>class kdo_pack():
def __init__(self, maxsledge = 12, remainingplace=0):
self.maxsledge = maxsledge
self.remainingplace = remainingplace
self.giftlist = []
def gift_type(self,size_gift):
if size_gift == 1:
return "half second"
elif size_gift == 2:
return "one second"
elif size_gift == 5:
return "2 seconds"
def Dwarf(self):
while self.remainingplace < self.maxsledge:
self.size_gift = int(input("type the size, 1 (for 1kg),2 (for 2kg) or 5 (for 5 kg) \n"))
temps = self.gift_type(self.size_gift)
print('It will take me ',temps, ' because the size of the gift is {} kg'.format(self.size_gift))
self.remainingplace += self.size_gift
#return self.remainingplace
self.giftlist.append(self.size_gift)
#print(self.remainingplace)
#print(self.giftlist)
def Reindeer(self):
print("list of gift is the following : ",self.giftlist)
self.printcounter = len(self.giftlist)
#print(self.printcounter)
#print(len(self.giftlist))
while self.printcounter > 0:
if self.printcounter %5 == 0:
print(self.printcounter)
print("I stop, give me reindeer milk !")
break
else:
self.giftlist.remove(self.giftlist[0])
self.printcounter-=1
print("there are only {} gifts to deliver".format(self.printcounter))
vari_xmas = kdo_pack()
vari_xmas.Dwarf()
vari_xmas.Reindeer()
</code></pre>
<p>Code is working fine. However, I'm bit bugged by a few things:</p>
<ul>
<li><p>I'm using often a <code>while</code> loop for two of the methods. Although it is doing the job, it doesn't feel pythonic.</p></li>
<li><p>There is this <code>if self.printcounter %5 == 0:</code> in the method <code>Reindeer</code>. The aim is to mimic the following</p>
<blockquote>
<p>One time over 5, when the reindeer is asked to move, it refuses because it want reindeer milk… The only way is to ask it again and it will go.</p>
</blockquote></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T18:02:33.683",
"Id": "460791",
"Score": "2",
"body": "This might seem like a silly question, but what is it you want this code to do? It doesn't feel like it should be a class at all, but rather a function with nested helper functions -- it's not representing an object, it's representing a process."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T18:08:18.737",
"Id": "460793",
"Score": "0",
"body": "hi @SamStafford I took it from a kata. There is no guideline if I should use a class or function with nested helper functions. I use class because it seems coherent, at least to me. But if you have another way to do that, I'm all ears. Tbh, it is often difficult to say what should be the norm and what is not as there are no real guidelines (I could not find any in this situation). I end up often writing something and some ppl say \"well it is not the norm!\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T06:17:51.750",
"Id": "460885",
"Score": "0",
"body": "omg ... why the downvote ... T_T"
}
] |
[
{
"body": "<p>Here's a simplified version of this code:</p>\n\n<pre><code>from typing import Dict, List\n\ndef kdo_pack():\n gifts: List[int] = []\n gift_time: Dict[int, str] = {\n 1: \"half second\",\n 2: \"one second\",\n 5: \"2 seconds\",\n }\n sled_capacity = 12\n\n # Pack the gifts onto the sled!\n while sum(gifts) < sled_capacity:\n try:\n gift = int(input(\n \"type the size, 1 (for 1kg),2 (for 2kg) or 5 (for 5 kg) \\n\"\n ))\n print(\n 'It will take me {} because the size of the gift is {} kg'\n .format(gift_time[gift], gift)\n )\n except (KeyError, ValueError):\n break\n gifts.append(gift)\n\n # Deliver the gifts!\n print(\"list of gift is the following : \", gifts)\n while gifts:\n if len(gifts) % 5 == 0:\n print(len(gifts))\n print(\"I stop, give me reindeer milk !\")\n break\n gifts.pop()\n print(\"there are only {} gifts to deliver\".format(len(gifts)))\n\nkdo_pack()\n</code></pre>\n\n<p>It's not completely clear to me how the class is meant to be used, but in the context of the script you've given I don't think it needs to be a class at all; you're just doing a fixed sequence of steps and there's no result other than what gets printed to the console.</p>\n\n<p>Since the program would halt prematurely if the user inputted an invalid value, I modified it to break and move on to the next step instead since that makes it easier to test without having to fill the entire sled. Beyond that, I'm not sure what else to suggest since I'm not sure what the original intent was, but hopefully seeing the simplified code gets you thinking about ways to streamline your future efforts -- the rule of thumb is not to write code that you don't need to. :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T21:21:38.063",
"Id": "235436",
"ParentId": "235429",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235436",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T17:28:12.657",
"Id": "235429",
"Score": "-4",
"Tags": [
"python",
"python-3.x"
],
"Title": "Santa Claus, its dwarf and its reindeer"
}
|
235429
|
<p>I have the following recursive function to compute the continued fraction:</p>
<p><span class="math-container">$$s_i = \frac{a_{i}}{b_{i} + s_{i+1}}$$</span></p>
<p>The relative error is defined as:</p>
<p><span class="math-container">$$\text{Delta} = \frac{s_n - s_{n-1}}{s_{n}}$$</span></p>
<p>Here is the implementation in Python, of Lentz's method for computing continued fractions:</p>
<pre><code>import numpy as np
def n_continued_fraction(a, b, err, i_min=3):
f = lambda i : a(i)
g = lambda i : b(i)
d = lambda i : 1./g(0) if i == 0 else 1./(g(i) + f(i) * d(i-1))
h = lambda i : 0 if i == -1 else f(0)/g(0) if i == 0 else (h(i-1) * g(i) + h(i-2) * d(i-1) * f(i)) * d(i)
delta_h = lambda i : h(i) - h(i-1)
i_final = i_min
while np.abs(delta_h(i_final)) > err * np.abs(h(i_final)):
i_final += 1
return h(i_final)
</code></pre>
<p>and you can test it with e.g.</p>
<pre><code>a = lambda i : (i+1.)
b = lambda i : (i+5.)
n_continued_fraction(a, b, 1.e-16)
</code></pre>
<p>Is there a better method to do it? Am I doing anything wrong?</p>
|
[] |
[
{
"body": "<p>Since <code>lambda</code> expressions are hard to add types and decorators to, I'd start off by writing it like this:</p>\n\n<pre><code>import numpy as np\nfrom typing import Callable\n\ndef n_continued_fraction(\n a: Callable[[float], float], \n b: Callable[[float], float], \n err: float, \n i_min: float = 3.0\n) -> float:\n\n def d(i: float) -> float:\n if i == 0:\n return 1.0 / b(0)\n return 1.0 / (b(i) + a(i) * d(i - 1))\n\n def h(i: float) -> float:\n if i == -1:\n return 0\n if i == 0:\n return a(0) / b(0)\n return (h(i - 1) * b(i) + h(i - 2) * d(i - 1) * a(i)) * d(i)\n\n def delta_h(i: float) -> float:\n return h(i) - h(i - 1)\n\n i = i_min\n while np.abs(delta_h(i)) > err * np.abs(h(i)):\n i += 1\n return h(i)\n</code></pre>\n\n<p>In terms of performance, note that Python doesn't do tail recursion optimization, so if the stack gets deep enough the script will exit.</p>\n\n<p>However! Defining functions with <code>def</code> opens up the possibility of using the power of decorators to memoize those inner functions, which might help you get around the recursion limitations; I'll leave experimenting with that as an exercise for the reader. :) <a href=\"https://www.geeksforgeeks.org/memoization-using-decorators-in-python/\" rel=\"nofollow noreferrer\">https://www.geeksforgeeks.org/memoization-using-decorators-in-python/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T22:32:17.443",
"Id": "460817",
"Score": "0",
"body": "How's this better than the OPs code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T22:34:02.323",
"Id": "460819",
"Score": "0",
"body": "https://i.imgur.com/bJQPWcy.png"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T22:35:14.943",
"Id": "460821",
"Score": "1",
"body": "You're so funny. I can't contain my laughter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T22:41:39.027",
"Id": "460824",
"Score": "0",
"body": "How \"deep\" does the stack need to get before it exits? Is this completely resolved using separate functions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T00:12:29.147",
"Id": "460842",
"Score": "0",
"body": "It's somewhere on the order of thousands. Using separate functions doesn't help if one calls the other before returning; you can think of stack depth as \"how many function calls are still waiting to return\", total across the program. Memoization can potentially help by letting some of those calls return earlier than they would have otherwise."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T22:28:17.177",
"Id": "235438",
"ParentId": "235437",
"Score": "0"
}
},
{
"body": "<p>Nice code, it does what it should and it is short. But it can be improved :)</p>\n\n<hr>\n\n<p>General python tips:</p>\n\n<ul>\n<li>Use type annotation. You can look at the type annotation of <code>Sam Stafford</code> in the previous answer, it will make your code more readable and will prevent bugs.</li>\n<li>Remove redundant imports. Is <code>numpy</code> really needed here? You can use a simple <code>abs</code>.</li>\n<li>Don't use lambda functions. According to <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> <code>\"do not assign lambda expression, use a def\"</code>, there are several reasons why, mostly due to readability.</li>\n</ul>\n\n<hr>\n\n<p>Optimisation tips:<br>\nNote these tips contradict each other. Choose one and use it but you cannot use both.</p>\n\n<ul>\n<li>If <code>N</code> is the number of elements until convergence, and <code>a</code> and <code>b</code> is the calculation time of each function (Assuming equal for every <code>x</code>) The time complexity now is <code>O(N ^ 2 * a * b)</code>, for each <code>i</code> you calculate the entire series over and over.<br>\nIf you will use <a href=\"https://en.wikipedia.org/wiki/Exponential_search\" rel=\"nofollow noreferrer\">exponential search</a> you can reduce the complexity to <code>O(N * log N * a * b)</code>. Which will be much much faster!</li>\n<li>Readability vs. Runtime. If the readability is important to you you can ignore this tip. You can replace the recursion with a <a href=\"https://en.wikipedia.org/wiki/Dynamic_programming\" rel=\"nofollow noreferrer\"><code>dynamic programing</code></a> approach, this will remove the recursion and the iteration over <code>i</code>, the time complexity will be <code>O(N * a * b)</code> but you will need to rewrite a lot of the code.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T15:16:38.180",
"Id": "461004",
"Score": "0",
"body": "Thanks a lot. Can I get a hand with the second tip, i.e., replace the recursion with dynamic programming?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T18:54:11.143",
"Id": "461148",
"Score": "0",
"body": "Well I would like to help you but you will need to answer `Peilonrayz` question in the comments first. @user216427"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T22:36:37.150",
"Id": "461195",
"Score": "0",
"body": "Sure, I've tried to answer them as best as I could."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T13:22:51.443",
"Id": "461268",
"Score": "0",
"body": "This function will be used a few hundred thousand times, so I am interested in achieving the fastest performance possible, even if I have to sacrifice readability."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T16:39:00.173",
"Id": "461285",
"Score": "0",
"body": "I'm interested in how you'd get exponential search to work with recursive sequence with \\$O(n\\log{n})\\$ time. I don't know why you're saying DP is hard to read. [It's fairly simple, and as readable as the OP's](https://gist.github.com/Peilonrayz/2e7084149abf35c6be7b1038b3c9aeb2)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T12:02:18.613",
"Id": "235468",
"ParentId": "235437",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T22:15:44.073",
"Id": "235437",
"Score": "2",
"Tags": [
"python",
"recursion"
],
"Title": "Continued fraction with relative precision in Python"
}
|
235437
|
<p>this is my first post to Code Review, so please bare with me.</p>
<p>I just finished writing a simple Snake clone in C++ with the goal of having an actual design this time and not just winging it. So I made a class diagram of the game and wrote all the code, and it works fine, but there are some areas where I feel like I could have done better. For example, there are some hard coded elements which I wasn't able to elegantly remove, and there's one place where I use inheritance, but then I also have an enum to figure out which child a message is coming from when I would prefer not to have to care at all what type the child is.</p>
<p>Anyway, here's the class diagram:</p>
<p><a href="https://i.stack.imgur.com/ekJht.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ekJht.png" alt="class diagram"></a></p>
<p>Engine is a simple engine I wrote to display 2d graphics easily, I only use it for rendering and some helper classes like v2di which is a 2d integer vector for storing positional information</p>
<hr>
<p>Here's the game class which is responsible for starting and running the game. </p>
<p><code>OnCreate()</code> is called once on startup, </p>
<p><code>OnUpdate()</code> and <code>OnRender()</code> are called once per frame and should contain the game loop, </p>
<p><code>OnDestroy()</code> is called when the inner game loop is exiting and the program is about to quit:</p>
<pre class="lang-cpp prettyprint-override"><code>///////////////// .h
class SnakeGame : public rge::DXGraphicsEngine {
public:
SnakeGame();
bool OnCreate();
bool OnUpdate();
bool OnRender();
void OnDestroy();
protected:
Snake snake;
FieldGrid field;
int score;
bool gameOver;
int updateFreq;
int updateCounter;
};
//////////////////////// .cpp
SnakeGame::SnakeGame() : DXGraphicsEngine(), field(10, 10), snake(3, rge::v2di(3, 1), Direction::RIGHT), score(0), gameOver(false), updateFreq(10), updateCounter(0){
}
bool SnakeGame::OnCreate() {
field.AddSnake(snake.GetBody());
field.GenerateFood();
return true;
}
bool SnakeGame::OnUpdate() {
//check user input
if(GetKey(rge::W).pressed) {
snake.SetDirection(Direction::UP);
}
if(GetKey(rge::S).pressed) {
snake.SetDirection(Direction::DOWN);
}
if(GetKey(rge::A).pressed) {
snake.SetDirection(Direction::LEFT);
}
if(GetKey(rge::D).pressed) {
snake.SetDirection(Direction::RIGHT);
}
updateCounter++;
if(!gameOver && updateCounter >= updateFreq) {
updateCounter = 0;
//clear snake body from field
field.ClearSnake(snake.GetBody());
//move
snake.MoveSnake();
//add snake body to field
field.AddSnake(snake.GetBody());
//testcollision
CollisionMessage cm = field.CheckCollision(snake.GetHead());
gameOver = cm.gameOver;
score += cm.scoreChange ? snake.GetLength() * 10 : 0;
if(cm.tileType == TileType::Food) {
field.GenerateFood();
snake.ExtendSnake();
}
}
return true;
}
bool SnakeGame::OnRender() {
std::cout << score << std::endl;
field.Draw(&m_colorBuffer, 100, 20, 10);
snake.DrawHead(&m_colorBuffer, 100, 20, 10);
return true;
}
</code></pre>
<p>Next up is the <code>Snake</code> class that moves and extends the snake. There's also an enum for the <code>Direction</code> the snake can move in:</p>
<pre class="lang-cpp prettyprint-override"><code>///////////// .h
enum class Direction {
UP, DOWN, LEFT, RIGHT
};
class Snake {
public:
Snake();
Snake(int length, rge::v2di position, Direction direction);
rge::v2di GetHead() { return head; }
std::vector<rge::v2di> GetBody() { return body; }
void MoveSnake();
void ExtendSnake();
Direction GetDirection() { return direction; }
void SetDirection(Direction direction);
int GetLength() { return body.size() + 1; }
void DrawHead(rge::Buffer* buffer, int x, int y, int size);
protected:
std::vector<rge::v2di> body;
rge::v2di head;
Direction direction;
Direction oldDirection;
};
////////////// .cpp
Snake::Snake(): head(rge::v2di(0, 0)), direction(Direction::UP), oldDirection(Direction::UP), body(std::vector<rge::v2di>()){
body.push_back(rge::v2di(head.x, head.y + 1));
}
Snake::Snake(int length, rge::v2di position, Direction direction) : head(position), direction(direction), oldDirection(direction), body(std::vector<rge::v2di>()) {
for(int i = 0; i < length-1; ++i) {
rge::v2di bodyTile;
switch(direction) {
case Direction::UP:{
bodyTile.x = head.x;
bodyTile.y = head.y + (i + 1);
break;
}
case Direction::DOWN:{
bodyTile.x = head.x;
bodyTile.y = head.y - (i + 1);
break;
}
case Direction::LEFT: {
bodyTile.y = head.y;
bodyTile.x = head.x + (i + 1);
break;
}
case Direction::RIGHT: {
bodyTile.y = head.y;
bodyTile.x = head.x - (i + 1);
break;
}
}
body.push_back(bodyTile);
}
}
void Snake::MoveSnake() {
oldDirection = direction;
for(int i = body.size()-1; i > 0; --i) {
body[i] = body[i - 1];
}
body[0] = head;
switch(direction) {
case Direction::UP: {
head.y--;
break;
}
case Direction::DOWN: {
head.y++;
break;
}
case Direction::LEFT: {
head.x--;
break;
}
case Direction::RIGHT: {
head.x++;
break;
}
}
}
void Snake::ExtendSnake() {
body.push_back(body[body.size() - 1]);
}
void Snake::SetDirection(Direction direction) {
switch(this->oldDirection) {
case Direction::UP:
case Direction::DOWN: {
if(direction != Direction::UP && direction != Direction::DOWN) {
this->direction = direction;
}
break;
}
case Direction::LEFT:
case Direction::RIGHT: {
if(direction != Direction::LEFT && direction != Direction::RIGHT) {
this->direction = direction;
}
break;
}
}
}
void Snake::DrawHead(rge::Buffer* buffer, int x, int y, int size) {
rge::Color c(100, 100, 200);
buffer->DrawRegion(x + head.x * size, y + head.y * size, x + head.x * size + size, y + head.y * size + size, c.GetHex());
}
</code></pre>
<p>Then there's the <code>FieldGrid</code> class responsible for collision detection, food generation and storing the state of the map:</p>
<pre class="lang-cpp prettyprint-override"><code>//////////// .h
class FieldGrid {
public:
FieldGrid();
FieldGrid(int width, int height);
~FieldGrid();
void GenerateFood();
CollisionMessage CheckCollision(rge::v2di head);
void ClearSnake(std::vector<rge::v2di> body);
void AddSnake(std::vector<rge::v2di> body);
void Draw(rge::Buffer* buffer, int x, int y, int size);
protected:
std::vector<std::vector<Tile*>> field;
int width;
int height;
};
//////////// .cpp
FieldGrid::FieldGrid() : width(10), height(10), field(std::vector<std::vector<Tile*>>()) {
for(int i = 0; i < width; ++i) {
field.push_back(std::vector<Tile*>());
for(int j = 0; j < height; ++j) {
field[i].push_back(new EmptyTile());
}
}
}
FieldGrid::FieldGrid(int width, int height): width(width), height(height), field(std::vector<std::vector<Tile*>>()) {
for(int i = 0; i < width; ++i) {
field.push_back(std::vector<Tile*>());
for(int j = 0; j < height; ++j) {
field[i].push_back(new EmptyTile());
}
}
}
FieldGrid::~FieldGrid() {
for(int i = 0; i < field.size(); ++i) {
for(int j = 0; j < field[i].size(); ++j) {
delete field[i][j];
}
field[i].clear();
}
field.clear();
}
void FieldGrid::GenerateFood() {
int x = rand() % width;
int y = rand() % height;
while(!field[x][y]->IsFree()) {
x = rand() % width;
y = rand() % height;
}
delete field[x][y];
field[x][y] = new FoodTile();
}
CollisionMessage FieldGrid::CheckCollision(rge::v2di head) {
if(head.x < 0 || head.x >= width || head.y < 0 || head.y >= height) {
CollisionMessage cm;
cm.scoreChange = false;
cm.gameOver = true;
return cm;
}
return field[head.x][head.y]->OnCollide();
}
void FieldGrid::ClearSnake(std::vector<rge::v2di> body) {
for(int i = 0; i < body.size(); ++i) {
delete field[body[i].x][body[i].y];
field[body[i].x][body[i].y] = new EmptyTile();
}
}
void FieldGrid::AddSnake(std::vector<rge::v2di> body) {
for(int i = 0; i < body.size(); ++i) {
delete field[body[i].x][body[i].y];
field[body[i].x][body[i].y] = new SnakeTile();
}
}
void FieldGrid::Draw(rge::Buffer* buffer, int x, int y, int size) {
for(int xi = 0; xi < width; ++xi) {
for(int yi = 0; yi < height; ++yi) {
int xp = x + xi * size;
int yp = y + yi * size;
field[xi][yi]->Draw(buffer, xp, yp, size);
}
}
}
</code></pre>
<p><code>Tile</code> class used in <code>FieldGrid</code>:</p>
<pre class="lang-cpp prettyprint-override"><code>class Tile {
public:
virtual CollisionMessage OnCollide() = 0;
virtual bool IsFree() = 0;
void Draw(rge::Buffer* buffer, int x, int y, int size) {
buffer->DrawRegion(x, y, x + size, y + size, color.GetHex());
}
protected:
rge::Color color;
};
class EmptyTile : public Tile {
public:
EmptyTile() {
this->color = rge::Color(50, 50, 50);
}
CollisionMessage OnCollide() {
CollisionMessage cm;
cm.scoreChange = false;
cm.gameOver = false;
cm.tileType = TileType::Empty;
return cm;
}
bool IsFree() { return true; }
};
class FoodTile : public Tile {
public:
FoodTile() {
this->color = rge::Color(50, 200, 70);
}
CollisionMessage OnCollide() {
CollisionMessage cm;
cm.scoreChange = true;
cm.gameOver = false;
cm.tileType = TileType::Food;
return cm;
}
bool IsFree() { return false; }
};
class SnakeTile : public Tile {
public:
SnakeTile() {
this->color = rge::Color(120, 130, 250);
}
CollisionMessage OnCollide() {
CollisionMessage cm;
cm.scoreChange = false;
cm.gameOver = true;
cm.tileType = TileType::Snake;
return cm;
}
bool IsFree() { return false; }
};
</code></pre>
<p>Finally here's the <code>CollisionMessage</code> class used to send messages to the game when the snake head collides with any <code>Tile</code>:</p>
<pre class="lang-cpp prettyprint-override"><code>enum class TileType {
Empty,
Snake,
Food
};
class CollisionMessage {
public:
bool scoreChange;
bool gameOver;
TileType tileType;
};
</code></pre>
<p>I omitted all the includes and the main method, as they aren't relevant to the design and would just take up extra space.</p>
<hr>
<p>I appreciate the time you take to read through all my code and would really like to hear what you think about my code and the overall design I chose.</p>
<hr>
<p>EDIT:</p>
<p>I've received some helpful feedback so far to the code and how I could improve some areas of my c++ knowledge, but I haven't received much feedback on the primary reason for this post, which was to get feedback on the overall design. In this project I tried to adhere to the SOLID principles of OOP, but I find that to be a difficult task and would like some pointers as to how I could improve the overall design.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T01:49:07.220",
"Id": "460870",
"Score": "0",
"body": "1st impression is good. It would be much easier if you created a gist or a github with the actual filles. For something this size, I want to compile it on my own machine in my own IDE, because I find it easier to understand that way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T02:11:50.030",
"Id": "460874",
"Score": "0",
"body": "@OliverSchonrock I do have this on github, but there's a lot of other stuff in the same repository, so it might be a little confusing. https://github.com/Renge-Games/Renge-Engine/tree/dev"
}
] |
[
{
"body": "<p>The posted code looks pretty good. </p>\n\n<p>Constants: You declare a lot of inline literals. It will be hard to alter things like snake colors.</p>\n\n<hr>\n\n<p>Virtual destructors: it functionally works, but it's generally good practice to make your base class destructors virtual. It doesn't make your objects bigger since they already have a vtable.</p>\n\n<hr>\n\n<p>Use the <code>override</code> keyword when appropriate.</p>\n\n<hr>\n\n<p>But actually, why are tiles virtual? It appears that they could be structs that only store a type enum. Consider that currently all the empty tiles store a color, but all their colors will always be the same. You could have a small configuration table that associates tile types with color or behavior. </p>\n\n<hr>\n\n<p>Consider making the collision message be a <code>std::optional</code> result. Then you can communicate a non-collision semantically. Also consider making it a struct since it has public fields.</p>\n\n<hr>\n\n<p>Prefer smart pointers instead of adding a bunch of raw pointers to the vector. But actually, try avoiding needing big collections of polymorphic objects.</p>\n\n<hr>\n\n<p><code>MoveSnake</code>: Perhaps use a <code>std::deque</code> so you can push_front. Or use iterators to move the items. Or store the snake backwards in the vector to avoid needing to move all the memory. Or just insert a head at the beginning because the vector is always likely to be small and a memcpy to move the rest isn't a big deal.</p>\n\n<hr>\n\n<p>Try splitting out rendering logic from your objects. For example, instead of looping over tiles and calling their draw method, try making the method that does the looping also do the drawing. Later, you could batch up similar tiles to render faster.</p>\n\n<hr>\n\n<p><code>SnakeGame::OnRender</code>: Do you really want to cout every time you render? How does the body get rendered?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T16:19:26.087",
"Id": "460914",
"Score": "0",
"body": "Thanks for the response! The constants were one of my big issues writing this. I don't know how to fix that problem. I made the tiles virtual so I wouldn't need a big switch statement, and because I was trying to satisfy the open closed principle, but I see that I failed at that to an extent, because I have an enum to find the tile type and there's some other conditional stuff going on outside the scope of the the tiles. The body is drawn in FieldGrid with the snake tiles."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T02:33:00.617",
"Id": "235456",
"ParentId": "235439",
"Score": "2"
}
},
{
"body": "<p>Member variables are initialized by constructors <em>in the order they are declared</em>, not the order that are listed in the <em>mem-initializer-list</em> for a constructor. This can lead to unexpected results. Many compilers will issue a warning for this if you set the warning level higher (which you should be routinely doing, typically with <code>/W4</code> or <code>-w4</code>). For <code>Snake</code>, the members will be initialized in this order: <code>body</code>, <code>head</code>, <code>direction</code>, <code>oldDirection</code>. This is the order they should be listed in the constructor.</p>\n\n<p>Some of your initializers (<code>DXGraphicsEngine()</code>, <code>body(std::vector<rge::v2di>())</code>) aren't doing anything that doesn't happen by default and should be omitted.</p>\n\n<p>The <code>switch</code> statement in some functions like the second <code>Snake</code> constructor and in <code>Snake::MoveSnake</code> have unnecessary braces in the case statements. For readability, the <code>case</code> labels are often indented.</p>\n\n<p>The body for <code>Snake::ExtendSnake</code> can be rewritten as <code>body.emplace_back(body.back());</code></p>\n\n<p>There are places where you use <code>this-></code> to access member variables where it is unnecessary. Where it is necessary (like <code>Snake::SetDirection</code>), you should rename the local variable to something that does not shadow a member variable. For <code>SetDirection</code>, you can use <code>Snake::SetDirection(Direction dir)</code>. Elsewhere, you're assigning to <code>this->color =</code>, which can just be <code>color =</code>. Or place the initializer in the mem-iniitializer-list (<code>SnakeTile(): color(120, 130, 250) { }</code>).</p>\n\n<p>Rather than using <code>vector<Tile *></code>, look into using a <a href=\"https://en.cppreference.com/w/cpp/memory\" rel=\"nofollow noreferrer\">smart pointer</a> (like <code>shared_ptr</code> or <code>unique_ptr</code>) so you don't have to do all that manual memory management.</p>\n\n<p>The <code>FieldGrid</code> constructors can start off with <code>field.resize(width)</code> to avoid growing the array in the <code>i</code> loop. This could also be accomplished with the <em>mem-initializer-list</em>, but you'd have to be careful about specifying the list sine the <code>width</code> member will be initialized <em>after</em> <code>field</code>.</p>\n\n<p>Consider using some of the standard C++ <a href=\"https://en.cppreference.com/w/cpp/numeric/random\" rel=\"nofollow noreferrer\">random library</a> classes rather than using <code>rand</code>.</p>\n\n<p>Some functions can take parameters by <code>const &</code> to avoid making copies of the parameters. <code>FieldGrid::ClearSnake(const std::vector<rge::v2di> &body)</code>. Also, you can use range-based for loops:</p>\n\n<pre><code>for (const auto &b: body) {\n delete field[b.x][b.y];\n field[b.x][b.y] = new EmptyTile();\n}\n</code></pre>\n\n<p>In your classes derived from <code>Tile</code> you should use the <code>override</code> keyword when overriding virtual members from a base class. This will result in a compilation error if you make a mistake in the function signature or change something.</p>\n\n<pre><code>CollisionMessage OnCollide() override {\n}\nbool IsFree() override { return true; }\n</code></pre>\n\n<p>In addition, <code>IsFree</code> can be <code>const</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T15:50:55.983",
"Id": "460913",
"Score": "0",
"body": "Thanks for your suggestions, i had no idea the member variables weren't initialized in the order they appear in the constructor. Same with the default constructor for DXGraphicsEngine() I thought it was necessary to add the constructor of the base class in the constructor for the child class. The braces in the switch statement I usually have there so I don't run into any issues when I declare a variable like \"i\" or something in each case statement. How about the design of my project? Is there some OOP principle I violated or something I could improve there?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T03:42:54.207",
"Id": "235458",
"ParentId": "235439",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235458",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T23:18:25.393",
"Id": "235439",
"Score": "5",
"Tags": [
"c++"
],
"Title": "Simple Snake Game in C++"
}
|
235439
|
<p>I am trying to solve this question:</p>
<blockquote>
<p>In a block storage system, new data is written in blocks. We are going
to represent the flash memory as one sequential array. We have a list
of block writes coming in the form of arrays of size 2: writes[i] =
[first_block_written, last_block_written].</p>
<p>Each block has a rewrite limit. If rewrites on a block reach a certain
specified threshold we should run a special diagnostic.</p>
<p>Given <strong>blockCount</strong> (an integer representing the total number of blocks),
<strong>writes</strong> (the list of block-write arrays of size 2), and <strong>threshold</strong>, your
task is to return the list of disjoint block segments, each consisting
of blocks that have reached the rewrite threshold. The list of block
segments should be sorted in increasing order by their left ends.</p>
<p>Example</p>
<p>For blockCount = 10, writes = [[0, 4], [3, 5], [2, 6]], and threshold
= 2, the output should be blockStorageRewrites(blockCount, writes, threshold) = [[2, 5]].</p>
<ul>
<li>After the first write, the blocks 0, 1, 2, 3 and 4 were written in
once</li>
<li><p>After the second write, the blocks 0, 1, 2 and 5 were written in
once, and the blocks 3 and 4 reached the rewrite threshold; </p></li>
<li><p>After the final write, the blocks 2 and 5 reached the rewrite threshold as well,
so the blocks that should be diagnosed are 2, 3, 4 and 5. Blocks 2, 3,
4 and 5 form one consequent segment [2, 5]. For blockCount = 10,
writes = [[0, 4], [3, 5], [2, 6]], and threshold = 3, the output
should be blockStorageRewrites(blockCount, writes, threshold) = [[3,
4]];</p></li>
</ul>
<p>For blockCount = 10, writes = [[3, 4], [0, 1], [6, 6]], and threshold
= 1, the output should be blockStorageRewrites(blockCount, writes, threshold) = [[0, 1], [3, 4], [6, 6]].</p>
</blockquote>
<p>I have come up with a correct naive solution here but it's too slow to pass the test cases:</p>
<pre><code>def blockStorageRewrites(blockCount, writes, threshold):
a = defaultdict(int)
for (l, r) in writes:
for i in range(l, r+1):
a[i] += 1
start = None
res = []
for i in range(0, blockCount+1):
if a[i] >=threshold:
if start is None:
start = i
elif a[i] < threshold and start is not None:
res.append([start, i-1])
start = None
return res
</code></pre>
<p>How do I optimize it to run faster?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T05:03:23.620",
"Id": "460883",
"Score": "1",
"body": "The very wording of the problem statement may suggest use of [segment trees](https://en.m.wikipedia.org/wiki/Segment_tree)."
}
] |
[
{
"body": "<p>You can get an immediate speed-up by ditching the <code>defaultdict(int)</code>, and using a <code>bytearray(blockCount+1)</code> instead. Both have roughly <span class=\"math-container\">\\$O(1)\\$</span> lookup time, but the latter has a much smaller constant factor. In the former, each <code>key</code> must be hashed, then binned, then a linear search through the bin is required to find the correct <code>key</code> entry, if it exists, and creating it if it does not. In the latter, the <code>key</code> is a direct index to the required memory.</p>\n\n<p>This demonstrates a better than 3x improvement of <code>bytearray</code> over <code>defaultdict</code>:</p>\n\n<pre><code>>>> from collections import defaultdict\n>>> from timeit import timeit\n>>> def original():\n d = defaultdict(int)\n for i in range(1000000):\n d[i] += 1\n\n\n>>> def using_bytearray():\n b = bytearray(1000000)\n for i in range(1000000):\n b[i] += 1\n\n\n>>> timeit(original, number=100)\n25.083420443999984\n>>> timeit(using_bytearray, number=100)\n7.779039941000008\n</code></pre>\n\n<p>Not only is the <code>bytearray</code> faster, it is also more memory efficient. The <code>bytearray</code> uses just 57 bytes of overhead to store an array of 1 million bytes. In contrast, the <code>defaultdict</code> weighs in at over 40x more memory ...</p>\n\n<pre><code>>>> sys.getsizeof(b)\n1000057\n>>> sys.getsizeof(d)\n41943144\n</code></pre>\n\n<p>... but the real kicker is that is just the size of the dictionary's binning structures. It excludes the size of all of the keys and values stored in the dictionary; those are harder to total as many small integers are interned and don't use additional storage allocation, and duplicate values may point to the same object.</p>\n\n<p><strong>Note</strong>: If <code>threshold</code> can exceed 255, you’d need to use <code>array.array</code> instead, with the appropriate type code for the largest rewrite count you’ll experience.</p>\n\n<hr>\n\n<p>Of course, this is still the wrong approach. With <code>writes = [[0, 999999], [1, 1000000]]</code>, it should be obvious that block 0 is written once, blocks 1 through 999999 are written twice, and block 1000000 is written once. There is no need to loop through the million indices; we just need to consider the end-points of each range.</p>\n\n<p>So just store the starting & ending points, and the number of times each has been seen. With a sorted array of indices of where the transitions occur, you should be able to iterate over these transition points, and construct your diagnostic list.</p>\n\n<p>Implementation left to student.</p>\n\n<p>Bonus: it is possible use one simple <code>Dict[int,int]</code> structure to store both starting and ending counts, if you think about it the right way.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T01:47:11.323",
"Id": "460868",
"Score": "0",
"body": "\"You can get an immediate speed-up by ...\" This seems to be pure conjecture. Python is a strange beast, and many of my assumptions, that are theorized like yours, have been wrong. Would you be willing to provide a timed plot to show that your statement is true? If, for some bizarre reason, `bytearray` were implemented in or partially in Python I can see both theoretically and logistically that a dictionary could be faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T02:01:33.477",
"Id": "460873",
"Score": "0",
"body": "@Peilonrayz As you wish."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T02:58:43.323",
"Id": "460876",
"Score": "0",
"body": "Thanks. Your timed tests are testing the performance of something different. Oh well, it's somewhat similar."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T01:35:22.977",
"Id": "235452",
"ParentId": "235440",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T23:24:39.953",
"Id": "235440",
"Score": "3",
"Tags": [
"python",
"algorithm",
"python-3.x",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Flash Memory block write counting & thresholding"
}
|
235440
|
<p>For a code challenge I thought it'd be useful to have a helper function to group positives and negatives into their own sub arrays while maintaining the ordering of the original array. I'm sure there's a better way to do this but wanted to take a crack at it before researching. </p>
<p>This idea came to mind, to track the state of the numbers, either positive or negative, and group them according to state. This is just MVP and I didn't account for 0.</p>
<p>Despite being verbose, does the code make sense> Do you have recommendations for improvement?</p>
<p>(<a href="https://typescript-play.js.org/#code/FAehGMHsFsAcEMBOBTABAFwO6VQOwK7QBGyiAzqmevOssAGb67joCWkueyA5gIK4ATAAqQyAYRgIUACgLReALjyESiADTLoAISVzVASlQBvYKjOpW9VLMK9UAPlQAGVADJXmrQ+eGT5-6hgqJjIAOQANuGo4PCRqACMqJD4iKiwoqxsAG5oVDR0AeYo6Cmc8QDcpuYAvlVmyOFkaJbWcnYAPM5uHnJenU6+dQFBIRFRMXEAtInJqbg8NKw5lNS0Q-7FpajTQ7X+DU3G6+ZB9LGHrBQtWDh6pBRIaLiQ6BgAFrnw0LmrBYWom0QnDOjWQlX8tVqoBAZFYcHCAE8AcgSkD3j98kkrPBKKxcNxwk8VKQGEwWOxONwUQBlX6tQioXTExCDfwtGzQbwDPz-QFlcE1IYHZpWDmofqs3korbTAVmSHARWMZhsDhcPiCERkXiIRDSJCIJnEUgAbQAupKzEFZqh6HjYsjUbghlBcFQkvh0LBPUbVObzagALyoc2VIZgTAfFDBMJxN6QcICTSqCiQKzoD6UL4Y2gaTJjVAkVDIAAe4HC+FhOQ0yEyUbSog0kDmPAAdOGQDHovBOAJkGd8OFXpkMDgM2gcogkXbyK87oghoTXrQ4AB9MjZgDSeKTwZNBpNTjNZrD-iC3EQ8CI6JWmMQrG4b1e8Ew8ARGkeXbyiDY+OCdYbVMW24AB+RcUWiFIUFwdBaUxYMqVg359V1Q8LVPcx6GbawlwsINnHKPDOgNVtCXxDNCNYABqKjLWGTtwA+cAAGt3hoPDLlQbhaG2RxEjIHAQm7TgN3oBokUY5AWNQA9WGmM1jjMdlWAcYN4kGRT6OuTNwCg5AYOTUhokkR4k3QMdM3CeB3XnGTo2eZdMw3b5b1zdFOAzdjvh7ChxxWFB4FYtMZK4pZ9Nc5pU0nTS2VFeYNWEUQJDgR4UMQE1WDND9UJUyYEgtINA2DEEmg0-5yrAC8rxveZMAi9tyvK3TdX0pD4K4mlkNk9DFUa-4wG9Mg3hq5lU3TJzswitjXlGZZ4HAXToEHfIkwE20kA0cckRIcIOG4UdEPrHsk1GOIUCaV4bRXWBUHjRMjJi-qQHMmSFpgSABExG1aqm4L5zIR7CmSL1PVbQa3mka71y3Hd9DlPrzCh5zkG3QR8NDXqEbPEBwZvZroLnZkAQfJ8ZNfd8LGHXzMxnGyieC77kDqvJaFbd5OMgWBSEWNVONhaBWHCVgkFHW7IDqoS+wHIdkCTWZAfojBkDXZHUaTA032Jx9Lvoca0CIdjpBILDoz8k3UF2zn9DZlpJY4UJXlxkdnjq-M4m4HABbIWF8QarHEeV2Boe+NWwcrCHurhhWoSxoI-Px1rDNSDm9azFyWbQayPVSBODKoALmM2qN+2bNAhNfAyXrxct8D7SmLE4G15sW5bVVwNmFfZeL+ES8QTJkbrsvS3L8sMIrg1ztraF8f3zAV-wkZhwQw6GtKMp6rG9n+Lf5Q7dmKEk6TgdhOvgrN7DLZuzizftKJcYZlJXpbqzaCTf7Ww-iwrDt3AHaf97Po8T8lZd0GcsRJzIBoPeW0CxFlLDXPsSYiBIhtLAFAWR2CVgtpAbgrBwDWB9uANAfkwECEgMgMgv9XiMR7FSGS3B4B4gbjec2l99BDHZIvEOsMeRA09N6dAK8IZcJRrDeGO9HRbGBgIwiwAoTd01KIHUeoTTxDUAAJjUJMAALBotQABWLRAA2LRABmNQ5jJgmIABxqAAJzoSAA" rel="nofollow noreferrer">code playground</a>)</p>
<pre><code>//compare two numbers state
function negAndPosCompare(numA: number, numB: number) {
if (numA > 0 && numB > 0) {
// we'll call 1 our positive state
return 1;
}
else if (numA < 0 && numB < 0) {
// we'll call -1 our negative state
return -1
}
else {
// false is if two numbers are not the same state
return false;
}
}
//simply return the state of a single number
function getState (num : number) {
if (num > 0){
return 1;
}
else if (num < 0) {
return -1;
}
}
function subArray_pos_and_neg(arr: number[]) {
// our final return
const output: number[][] = [];
//where we'll hold numbers of the same state, it'll be exclusive, either pos, or neg.
// we can default it to the very first number. It's a temp because we'll keep recycling it whenever state changes.
let temp_sameKind = [arr[0]];
// grab the state right away, are we starting with pos or neg?
let currentState = getState(arr[0]);
for (let i = 0; i < arr.length; i++) {
// check that i is gte -> 1 so we can safely check arr[i-1]
if (i >= 1) {
//if the current number compared to the last number are not the same state, then that means the streak of a given state is over
if (negAndPosCompare(arr[i], arr[i - 1]) === false) {
//grab the new state.
currentState = getState(arr[i]);
//push the numbers of the same state that we've accumulated so far, they belong together and we'll reset our temp holder
//to accomodate our new state of numbers
output.push(temp_sameKind);
temp_sameKind = [];
//push the current number right away, it is the first number of our new state. this operation is similiar to how we defaulted our
// temp_sameKind array right off the bat (before the for loop). if we don't push it now it'll go missing.
temp_sameKind.push(arr[i]);
}
// the current number is of the same state as our current streak, therefore we want to include it in our accumulation.
if (negAndPosCompare(arr[i], arr[i - 1]) === currentState) {
temp_sameKind.push(arr[i]);
}
}
}
// this check outside of the for loop is the final push of our accumulated numbers... if we don't accomodate the last state of numbers,
// they'll be excluded by our previous logic (since the state doesn't change again in the for loop)
if (temp_sameKind){
output.push(temp_sameKind);
}
return output;
}
subArray_pos_and_neg([1,2,-4,2,5,-6,-3,3,-6,8,9]); //?
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T20:56:01.533",
"Id": "460837",
"Score": "0",
"body": "Thank you i will post it there"
}
] |
[
{
"body": "<p>I think your code is great, but it is indeed way too verbose. It makes sense, but I got to admit, it took me some time. To me longer code isn't necessarily easier to understand. For instance your if/else really confused me at first.</p>\n\n<p>Personally, I think you could have improved your code by making much shorter. Here's what I came up with :</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function createSubArr(A) {\r\n let output = [];\r\n for(let i = 0; i < A.length; i++) {\r\n let subArr = [A[i]];\r\n while(A[i] > 0 === A[i + 1] > 0) {\r\n subArr.push(A[i + 1]);\r\n i++;\r\n }\r\n output.push(subArr);\r\n }\r\n return output;\r\n}\r\n\r\nconsole.log(createSubArr([-1, -2, -3, 1, -1, -2, 2, 3, 4, -9, 5, 6, 7]))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T21:13:36.263",
"Id": "460838",
"Score": "1",
"body": "Great, thank you! This short code is really nice, it'll take some going over it for me to get the feel and click of it.\n\nAs i'm writing the code the verbose way makes more sense but more and more i want to move towards this short style."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T21:29:09.600",
"Id": "460839",
"Score": "1",
"body": "I stepped through your code with the debugger to help understand it, and i'll rewrite it for the practice...\n\nIt's really great, just the sort of thing i was looking for, thanks again! \n\nI really like how you have a while loop inside your for loop that also can also increment i when appropriate, i hadn't seen or thought of that before, really useful!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T08:12:03.663",
"Id": "460892",
"Score": "0",
"body": "your while needs to check for bounds (`i + 1 < A.length`)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T08:12:55.187",
"Id": "460893",
"Score": "0",
"body": "also, `output` and `subArr` should be `const` as they are never re-assigned"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T08:16:08.407",
"Id": "460894",
"Score": "0",
"body": "actually this answer would deserve a code review of its own: I would argue that the inner while is not necessary and possibly confusing, as it adds a place where `i` is incremented, whereas keeping track of the sign of the previous value might be clearer. I find Nate's answer much easier to read"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T21:00:23.153",
"Id": "235443",
"ParentId": "235441",
"Score": "5"
}
},
{
"body": "<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 returnNegatives = arr => arr.filter(n => n < 0)\nconst returnPositives = arr => arr.filter(n => n >= 0)\n\nconst mixedArray = [1, 2, -4, 2, 5, -6, -3, 3, -6, 8, 9, 0]\n\nconsole.log('The negatives', returnNegatives(mixedArray))\nconsole.log('The positives', returnPositives(mixedArray))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><strong>Edit:</strong> Think I misunderstood what you wanted with the above, updated version:</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 isPositive = n => n >= 0\nconst mixedArray = [1, 2, -4, 2, 5, -6, -3, 3, -6, 8, 9, 0]\n\nconst groupByType = arr => {\n let prev = isPositive(arr[0]), result = [], subArray = []\n arr.forEach(n => {\n if (isPositive(n) === prev) subArray.push(n)\n else {\n result.push(subArray)\n subArray = [n]\n }\n prev = isPositive(n)\n })\n result.push(subArray)\n return result\n}\n\nconsole.log(groupByType(mixedArray))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T03:11:07.570",
"Id": "460877",
"Score": "0",
"body": "You failed to catch the flaw: There is a positive 0 and a negative 0, yet your code puts them both in the positives :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T05:34:06.490",
"Id": "460884",
"Score": "0",
"body": "Nate, yes your second code is what i was asking about, very neat and clean, Thanks!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T00:45:13.437",
"Id": "235447",
"ParentId": "235441",
"Score": "3"
}
},
{
"body": "<p>You could check the sign of the item and the predecessor and if unequal take a new array as group.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function createSubArr(array) {\n let result = [], group;\n for (let i = 0; i < array.length; i++) {\n if (Math.sign(array[i - 1]) !== Math.sign(array[i])) result.push(group = []);\n group.push(array[i]);\n }\n return result;\n}\n\nconsole.log(createSubArr([-1, -2, -3, 1, -1, -2, 2, 3, 4, -9, 5, 6, 7]))</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T23:57:52.753",
"Id": "461202",
"Score": "0",
"body": "Great answer, thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-16T19:36:57.383",
"Id": "461582",
"Score": "0",
"body": "<3 this code, very succinct"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T19:13:19.787",
"Id": "235479",
"ParentId": "235441",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-10T20:40:25.913",
"Id": "235441",
"Score": "3",
"Tags": [
"javascript",
"typescript"
],
"Title": "Maintain the ordering of the original array, but group either negative or positive numbers into sub arrays"
}
|
235441
|
<p>For a basic program I am writing to help learn, I am at the step where I should be cleaning up the messy code and trying to condense my "main" to 5-20 lines by recalling other methods that repeat themselves. I simplified one section perfectly where the user enters their score and the score is recalled from another method, but now I can't quite figure out how to go from here for another section.</p>
<p>This is a program I made for a golfer entering his score into a computer to calculate his single round handicap. The code prompts the user for his/her name, what color tees were played, and the score for those tees. It will then output the handicap differential for the round.</p>
<pre class="lang-none prettyprint-override"><code>Welcome to Medford Village CC Single Round Handicap Calculator!
Please type your Name: Sam
Thank you Sam. Did you play the White, Blue or Black tees?
Tees Played: white
Please enter your white tee round score: 89
Sam, Your Handicap Differential for this round is: 16.64. This rounds to 16.6!
Thank you, Goodbye!
</code></pre>
<p><strong>ISSUE</strong> - I know to look for repetitive sections of code which means they can probably be simplified to another method to be recalled. I ask the user to enter which color tees they played from. So I have a <code>while</code> loop and different sections of if's within them for depending on which color tee the played. If they don't enter a correct color tee, it loops back and asks again. My issue is that each color tee has its own "final" data for course rating and course slope, and this makes the calculation differ. If anyone has any insight on how to clean up the individual <code>if</code> statements, without getting too complicated, I would really appreciate it. The code runs exactly how I want it to with the code below, I am just looking to simplify it.</p>
<pre><code>public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
final short blackTeeSlope = 146;
final float blackTeeRating = 74.6F;
final short blueTeeSlope = 139;
final float blueTeeRating = 72.4F;
final short whiteTeeSlope = 129;
final float whiteTeeRating = 70.0F;
final short goldTeeSlope = 133;
final float goldTeeRating = 71.3F;
String input = "";
System.out.println("Welcome to Medford Village CC Single Round Handicap Calculator!");
System.out.print("Please type your Name: ");
String name = scanner.nextLine().trim();
System.out.println("Thank you " + name + ". Did you play the White, Blue or Black tees?");
while (true) {
System.out.print("Tees Played: ");
String teesPlayed = scanner.nextLine().trim().toLowerCase();
if (teesPlayed.equals("black")) {
short userScore = (short)readNumber("Please enter your black tee round score: ", 55, 300);
double handicapDifferential = (userScore - blackTeeRating) * 113 / blackTeeSlope;
double rounded = Math.round(handicapDifferential * 10.0) / 10.0;
String formattedDifferential = String.format("%.02f", handicapDifferential);
System.out.println();
System.out.println(name + ", Your Handicap Differential for this round is: " + formattedDifferential + ". This rounds to " + rounded + "!");
break;
}
if (teesPlayed.equals("blue")) {
short userScore = (short)readNumber("Please enter your blue tee round score: ", 55, 300);
double handicapDifferential = (userScore - blueTeeRating) * 113 / blueTeeSlope;
double rounded = Math.round(handicapDifferential * 10.0) / 10.0;
String formattedDifferential = String.format("%.02f", handicapDifferential);
System.out.println();
System.out.println(name + ", Your Handicap Differential for this round is: " + formattedDifferential + ". This rounds to " + rounded + "!");
break;
}
if (teesPlayed.equals("white")) {
short userScore = (short)readNumber("Please enter your white tee round score: ", 55, 300);
double handicapDifferential = (userScore - whiteTeeRating) * 113 / whiteTeeSlope;
double rounded = Math.round(handicapDifferential * 10.0) / 10.0;
String formattedDifferential = String.format("%.02f", handicapDifferential);
System.out.println();
System.out.println(name + ", Your Handicap Differential for this round is: " + formattedDifferential + ". This rounds to " + rounded + "!");
break;
}
if (teesPlayed.equals("gold")) {
short userScore = (short)readNumber("Please enter your gold tee round score: ", 55, 300);
double handicapDifferential = (userScore - goldTeeRating) * 113 / goldTeeSlope;
double rounded = Math.round(handicapDifferential * 10.0) / 10.0;
String formattedDifferential = String.format("%.02f", handicapDifferential);
System.out.println();
System.out.println(name + ", Your Handicap Differential for this round is: " + formattedDifferential + ". This rounds to " + rounded + "!");
break;
}
System.out.println("Please Enter Black, Blue, Gold or White.");
}
System.out.println();
System.out.println("Thank you, Goodbye!");
}
public static double readNumber (String prompt, int min, int max){
Scanner scanner = new Scanner(System.in);
short value;
while (true){
System.out.print(prompt);
value = scanner.nextShort();
if (value >=min && value <=max)
break;
System.out.println("Please enter an amount between " + min +" and " + max + ".");
}
return value;
}
</code></pre>
|
[] |
[
{
"body": "<p>I have some suggestions for your code.</p>\n\n<p>1) The <code>input</code> variable is unused.</p>\n\n<p>2) Since the tees variables are hard-coded and have two values, I suggest that you use an <code>Enum</code> to hold the values. It will make the code easier to read and remove the variables from the method.</p>\n\n<p><strong>Tees.java</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public enum Tees {\n BLACK(146, 74.6F),\n BLUE(139, 72.4F),\n WHITE(129, 70.0F),\n GOLD(133, 71.3F);\n\n private final int slope;\n private final float rating;\n\n Tees(int slope, float rating) {\n this.slope = slope;\n this.rating = rating;\n }\n\n public int getSlope() {\n return slope;\n }\n\n public float getRating() {\n return rating;\n }\n}\n\n</code></pre>\n\n<p><strong>Main.java</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>\n//[...]\ndouble handicapDifferential = (userScore - Tees.BLACK.getRating()) * 113 / Tees.BLACK.getSlope();\n//[...]\n\n</code></pre>\n\n<p>3) Since there are multiple instances of <code>java.util.Scanner</code>, I suggest that you create a constant for it; so you can use it everywhere.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> public static final Scanner SCANNER = new Scanner(System.in);\n</code></pre>\n\n<p>4) For the method <code>readNumber</code>, I suggest that you rename it to <code>readAnswersAsNumber</code>; since this method to more than read. </p>\n\n<p>5) In the same idea of the method <code>readNumber</code>, I suggest that you make a new method to read <code>java.lang.String</code> answers. This will save 2 lines per questions / answers.</p>\n\n<p><strong>Before</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>System.out.print(\"Please type your Name: \");\nString name = SCANNER.nextLine().trim();\n</code></pre>\n\n<p><strong>After</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n //[...]\n String name = readAnswersAsString(\"Please type your Name: \");\n //[...]\n}\n\nprivate static String readAnswersAsString(String question) {\n System.out.print(question);\n return SCANNER.nextLine().trim();\n}\n</code></pre>\n\n<p>6) Instead of concatenating a string in the <code>java.io.PrintStream#println</code>, you can use the <code>java.io.PrintStream#printf</code> and use the java string templates. But, the only downside, it has the same effect as the <code>java.io.PrintStream#print</code> method, it doesn't add a new line, so you have to add it to the template ('\\n' or '%n').</p>\n\n<p>'\\n' vs '%n' on <a href=\"https://stackoverflow.com/questions/1883345/whats-up-with-javas-n-in-printf/\">stackoverflow</a></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>System.out.printf(\"Thank you %s. Did you play the White, Blue or Black tees?%n\", name);\n</code></pre>\n\n<p>7) When checking the color of the tees, since we used an <code>Enum</code> earlier, we can use it instead of the string.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>String teesPlayed = readAnswersAsString(\"Tees Played: \").toUpperCase();\n\nif(Tees.BLACK.name().equals(teesPlayed)) {\n //[...]\n}\n</code></pre>\n\n<p>8) Instead of using only <code>if</code>, I suggest that you use the <code>if-else-if</code>, since there's only one color each time.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>\nif (Tees.BLACK.name().equals(teesPlayed)) {\n //[...]\n} else if(Tees.BLUE.name().equals(teesPlayed)) {\n //[...]\n}\n\n</code></pre>\n\n<p>9) Since the score logic is similar in all colors, I suggest that you extract it in a method.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n if (Tees.BLACK.name().equals(teesPlayed)) {\n handleScore(name, \"Please enter your black tee round score: \", Tees.BLACK);\n break;\n } else if (Tees.BLUE.name().equals(teesPlayed)) {\n handleScore(name, \"Please enter your blue tee round score: \", Tees.BLUE);\n break;\n } else if (Tees.WHITE.name().equals(teesPlayed)) {\n handleScore(name, \"Please enter your white tee round score: \", Tees.WHITE);\n break;\n } else if (Tees.GOLD.name().equals(\"gold\")) {\n handleScore(name, \"Please enter your gold tee round score: \", Tees.GOLD);\n break;\n }\n}\n\nprivate static void handleScore(String name, String question, Tees tees) {\n short userScore = (short) readAnswersAsNumber(question, 55, 300);\n\n double handicapDifferential = (userScore - tees.getRating()) * 113 / tees.getSlope();\n double rounded = Math.round(handicapDifferential * 10.0) / 10.0;\n\n System.out.printf(\"%n%s, Your Handicap Differential for this round is: %.02f. This rounds to %.2f!\", name, handicapDifferential, rounded);\n}\n</code></pre>\n\n<h2>Refactored code</h2>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static final Scanner SCANNER = new Scanner(System.in);\n\npublic static void main(String[] args) {\n System.out.println(\"Welcome to Medford Village CC Single Round Handicap Calculator!\");\n String name = readAnswersAsString(\"Please type your Name: \");\n System.out.printf(\"Thank you %s. Did you play the White, Blue or Black tees?%n\", name);\n\n while (true) {\n String teesPlayed = readAnswersAsString(\"Tees Played: \").toUpperCase();\n\n if (Tees.BLACK.name().equals(teesPlayed)) {\n handleScore(name, \"Please enter your black tee round score: \", Tees.BLACK);\n break;\n } else if (Tees.BLUE.name().equals(teesPlayed)) {\n handleScore(name, \"Please enter your blue tee round score: \", Tees.BLUE);\n break;\n } else if (Tees.WHITE.name().equals(teesPlayed)) {\n handleScore(name, \"Please enter your white tee round score: \", Tees.WHITE);\n break;\n } else if (Tees.GOLD.name().equals(teesPlayed)) {\n handleScore(name, \"Please enter your gold tee round score: \", Tees.GOLD);\n break;\n }\n\n System.out.println(\"Please Enter Black, Blue, Gold or White.\");\n }\n\n System.out.println();\n System.out.println(\"Thank you, Goodbye!\");\n}\n\nprivate static void handleScore(String name, String question, Tees tees) {\n short userScore = (short) readAnswersAsNumber(question, 55, 300);\n\n double handicapDifferential = (userScore - tees.getRating()) * 113 / tees.getSlope();\n double rounded = Math.round(handicapDifferential * 10.0) / 10.0;\n\n System.out.printf(\"%n%s, Your Handicap Differential for this round is: %.02f. This rounds to %.2f!\", name, handicapDifferential, rounded);\n}\n\nprivate static String readAnswersAsString(String question) {\n System.out.print(question);\n return SCANNER.nextLine().trim();\n}\n\npublic static double readAnswersAsNumber(String prompt, int min, int max) {\n short value;\n while (true) {\n System.out.print(prompt);\n value = SCANNER.nextShort();\n if (value >= min && value <= max)\n break;\n System.out.println(\"Please enter an amount between \" + min + \" and \" + max + \".\");\n }\n return value;\n}\n</code></pre>\n\n<hr>\n\n<h2>Edit - Method to fetch the tee color directly</h2>\n\n<p>I suggest that you create a method that return directly the <code>Tees</code> enum.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static Tees readTeeColor() {\n while (true) {\n String teeColor = readAnswersAsString(\"Tees Played: \").toUpperCase();\n\n try {\n return Tees.valueOf(teeColor);\n } catch (IllegalArgumentException ex) {\n System.out.println(\"Please Enter Black, Blue, Gold or White.\");\n }\n }\n}\n</code></pre>\n\n<p>With this modification, you need to change the condition and remove the while loop, since the <code>readTeeColor</code> will now handle the invalid choice by looping indefinitely.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>System.out.printf(\"Thank you %s. Did you play the White, Blue or Black tees?%n\", name);\n\nTees teesPlayed = readTeeColor();\n\nif (Tees.BLACK.equals(teesPlayed)) {\n handleScore(name, Tees.BLACK);\n} else if (Tees.BLUE.equals(teesPlayed)) {\n handleScore(name, Tees.BLUE);\n} else if (Tees.WHITE.equals(teesPlayed)) {\n handleScore(name, Tees.WHITE);\n} else if (Tees.GOLD.equals(teesPlayed)) {\n handleScore(name, Tees.GOLD);\n}\n\nSystem.out.println();\n</code></pre>\n\n<hr>\n\n<h2>Edit - Code clean-up</h2>\n\n<p>Has @roland-illig suggested in the comment, you can remove the similar message very easily.</p>\n\n<p>1) Remove the parameter <code>question</code> of the method <code>handleScore</code>.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static void handleScore(String name, Tees tees) {\n //[...]\n}\n</code></pre>\n\n<p>2) Use the template in the method <code>handleScore</code>.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static void handleScore(String name, Tees tees) {\n //[...]\n short userScore = (short) readAnswersAsNumber(String.format(\"Please enter your %s tee round score: \", tees.name().toLowerCase()), 55, 300);\n //[...]\n}\n</code></pre>\n\n<p>3) Since the <code>handleScore</code> is now generic, you don’t need the <code>if-else</code> checks anymore.</p>\n\n<p><strong>Redacted Code</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static final Scanner SCANNER = new Scanner(System.in);\n\npublic static void main(String[] args) {\n System.out.println(\"Welcome to Medford Village CC Single Round Handicap Calculator!\");\n String name = readAnswersAsString(\"Please type your Name: \");\n System.out.printf(\"Thank you %s. Did you play the White, Blue or Black tees?%n\", name);\n\n handleScore(name, readTeeColor());\n\n System.out.println();\n System.out.println(\"Thank you, Goodbye!\");\n}\n\nprivate static void handleScore(String name, Tees tees) {\n short userScore = (short) readAnswersAsNumber(String.format(\"Please enter your %s tee round score: \", tees.name().toLowerCase()), 55, 300);\n\n double handicapDifferential = (userScore - tees.getRating()) * 113 / tees.getSlope();\n double rounded = Math.round(handicapDifferential * 10.0) / 10.0;\n\n System.out.printf(\"%n%s, Your Handicap Differential for this round is: %.02f. This rounds to %.2f!\", name, handicapDifferential, rounded);\n}\n\n\nprivate static Tees readTeeColor() {\n while (true) {\n String teeColor = readAnswersAsString(\"Tees Played: \").toUpperCase();\n\n try {\n return Tees.valueOf(teeColor);\n } catch (IllegalArgumentException ex) {\n System.out.println(\"Please Enter Black, Blue, Gold or White.\");\n }\n }\n}\n\nprivate static String readAnswersAsString(String question) {\n System.out.print(question);\n return SCANNER.nextLine().trim();\n}\n\npublic static double readAnswersAsNumber(String prompt, int min, int max) {\n short value;\n while (true) {\n System.out.print(prompt);\n value = SCANNER.nextShort();\n if (value >= min && value <= max)\n break;\n System.out.println(\"Please enter an amount between \" + min + \" and \" + max + \".\");\n }\n return value;\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T08:58:08.447",
"Id": "460974",
"Score": "1",
"body": "To make this answer perfect, you could describe how to get rid of the 4 very similar string literals that are passed to `handleScore`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T10:22:58.037",
"Id": "460980",
"Score": "0",
"body": "I don't find enum to be a good solution for managing the tee information. The tees are likely to be data that changes, so hard coding them makes maintenance difficult. I would define them as a data structure that is populated at run time. This also prevents you from hard coding the tees to other methods forcing you to write more modular code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T17:36:07.197",
"Id": "461021",
"Score": "0",
"body": "@roland-illig Done, added in the `Edit - Code clean-up` section, thanks!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T02:47:00.233",
"Id": "235457",
"ParentId": "235448",
"Score": "5"
}
},
{
"body": "<p>There is already a good answer from @Doi9t. I was too slow to publish mine but can still be useful.</p>\n\n<hr>\n\n<p><em>\"My issue is that each color tee has its own \"final\" data for course rating and course slope, and this makes the calculation differ\"</em>. Okay, do you know the the <em>strategy</em> pattern ?</p>\n\n<blockquote>\n <p>In computer programming, the strategy pattern is a behavioral software design pattern that enables selecting an algorithm at runtime. [..]\n Strategy lets the algorithm vary independently from clients that use it [..] Deferring the decision about which algorithm to use until runtime allows the calling code to be more flexible and reusable.</p>\n \n <p>-- <a href=\"https://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Strategy_pattern</a></p>\n</blockquote>\n\n<p>However, from what I see, the calculation is always the same, it differ only on the rating and slope. So this is not really a <em>strategy</em> because there is no different algorithm. But this concept of <em>color</em> is still important. There is no interest to create one abstraction when only the values are different, so let's create one <code>Color(rating, slope)</code> class for it. By doing that you will remove the almost duplicated constants, at this time you can create one enumeration for that[1].</p>\n\n<p>The computed handicap is also an important concept, why not extracting one class for that. This will also remove a lot of duplication. And since, the handicap require a tee color to be computed you can create on <em>factory method</em> on the color:</p>\n\n<pre><code>enum Colors implements Color {\n BLACK(146, 74.6f),\n BLUE(139, 72.4f),\n WHITE(129, 70.0f),\n GOLD(133, 71.3f);\n\n private final short slope;\n private final float rating;\n\n Colors(short slope, float rating) {\n this.rating = rating;\n this.slope = slope;\n }\n\n HandicapDifferential handicap(short score) {\n return new HandicapDifferential(score, rating, slope);\n }\n}\n</code></pre>\n\n<p>Now you have a model that can be tested. But there is still some duplication in the presentation. You can still create one <em>decorator</em> class on <code>Scanner</code> with a couple of method tailored to your needs:</p>\n\n<pre><code>class ConsoleView {\n private final Scanner scanner;\n Presentation(InputStream in) {\n this.scanner = new Scanner(in);\n }\n\n String getName() {\n System.out.print(\"Please type your Name: \"); \n return scanner.nextLine().trim();\n }\n\n String getTeeColor() // ...\n\n short getScore() // ...\n\n void print(HandicapDifferential handicap) // ...\n\n}\n</code></pre>\n\n<p>So you have some classes for the model and one for handling interactions with the user. You just miss one to coordinate both. This is what your <code>main</code> method will do. But most of the time, mainly for testing, you may want to move that \"flow\" to one instance instead of the <code>main</code> method. </p>\n\n<pre><code>class SingleRoundHandicapCalculator {\n\n public static void main(String[] args) {\n new SingleRoundHandicapCalculator(new ConsoleView(System.in))\n .run();\n }\n\n // ~ ----------------------------------------------------------------- ~ //\n\n private final ConsoleView view;\n\n SingleRoundHandicapCalculator(final ConsoleView view) {\n this.view = view;\n }\n\n void run() {\n view.greet();\n String color = view.getColor();\n short score = view.getScore();\n\n HandicapDifferential handicap = Color.valueOf(color.toUpperCase()).handicap(score);\n view.show(handicap);\n }\n}\n</code></pre>\n\n<p>As you can see the \"name\" is removed. This is the power of this kind of code, where you can hide some presentation requirement into the view itself.</p>\n\n<p>[1] An enumeration is the ideal candidate to group a set of identical \"classes\" where only the attributes vary. To have a more flexible model you can create one interface to represents the tee color so that you can \"generate\" them at runtime later from any datasource if needed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T08:22:45.293",
"Id": "235638",
"ParentId": "235448",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T01:00:58.873",
"Id": "235448",
"Score": "5",
"Tags": [
"java",
"beginner"
],
"Title": "Single round handicap calculator for golfers"
}
|
235448
|
<p>This is a follow up to <a href="https://codereview.stackexchange.com/q/235164/197645">this question</a></p>
<p><strong>Objective:</strong></p>
<p>Manage what happens when users interact with Excel Tables (ListObjects)</p>
<hr>
<p><strong>Code incorporates:</strong></p>
<ul>
<li>Greedo's <a href="https://codereview.stackexchange.com/a/235295/197645">answer suggestions</a>:
<ul>
<li>Listen to an encapsulated <code>ListObject</code></li>
<li>Gather useful data to pass to the event raised when the <code>ListObject</code> was changed</li>
<li>Raise events according to the user interaction</li>
</ul></li>
<li>Mathieu's help on this <a href="https://stackoverflow.com/a/59654817/1521579">question</a></li>
</ul>
<hr>
<p><strong>Remarks:</strong></p>
<p>I combined Matt's solution but ended up with another class (<code>Tables</code>) to store the instances of each <code>Table</code> created so this could manage multiple tables in a <code>Sheet</code>, so I'm not sure if this part could be simplificated.</p>
<hr>
<p><strong>Questions:</strong></p>
<ol>
<li>Could this be simplified in a single class?</li>
<li>Is the <code>SheetTable</code> class required?</li>
<li>Is there a way to unit test these classes? is there a benefit to do it? if someone can give me an example, would appreciate it. (I'm trying to learn that topic)</li>
<li>Any suggestion to improve it is welcome</li>
</ol>
<p><strong>Sample file:</strong></p>
<p>You can download the file with code from <a href="https://1drv.ms/x/s!ArAKssDW3T7wnL1RboFR2aIc3gq9Sg?e=1Idez9" rel="nofollow noreferrer">this link</a> (read-only)</p>
<hr>
<p><strong>File structure:</strong></p>
<p><a href="https://i.stack.imgur.com/w2JWn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/w2JWn.png" alt="Code tree"></a></p>
<p><strong>Code:</strong></p>
<p>Sheet: <code>Sheet1</code></p>
<pre><code>Option Explicit
Private sheetTables As ITables
Private Sub Worksheet_Activate()
Set sheetTables = Tables.Create(Me)
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
sheetTables.AddTables
End Sub
Private Sub Worksheet_Deactivate()
Set sheetTables = Nothing
End Sub
</code></pre>
<p>Class: <code>ITable</code></p>
<pre><code>Option Explicit
Public Property Get SourceTable() As ListObject
End Property
</code></pre>
<p>Class: <code>Table</code></p>
<pre><code>'@Folder("VBAProject")
'@PredeclaredId
Option Explicit
Private WithEvents TableSheet As Excel.Worksheet
Private Type TTable
SourceTable As ListObject
LastRowCount As Long
LastColumnCount As Long
End Type
Private this As TTable
Public Event Changed(ByVal cell As Range)
Public Event AddedNewRow(ByVal newRow As ListRow)
Public Event AddedNewColumn(ByVal newColumn As ListColumn)
Implements ITable
Public Function Create(ByVal Source As ListObject) As ITable
With New Table
Set .SourceTable = Source
Set Create = .Self
End With
End Function
Public Property Get Self() As Table
Set Self = Me
End Property
Public Property Get SourceTable() As ListObject
Set SourceTable = this.SourceTable
End Property
Public Property Set SourceTable(ByVal Value As ListObject)
ThrowIfSet this.SourceTable
ThrowIfNothing Value
Set TableSheet = Value.Parent
Set this.SourceTable = Value
Resize
End Property
Friend Sub OnChanged(ByVal Target As Range)
RaiseEvent Changed(Target)
End Sub
Friend Sub OnAddedNewRow(ByVal newRow As ListRow)
RaiseEvent AddedNewRow(newRow)
End Sub
Friend Sub OnAddedNewColumn(ByVal newColumn As ListColumn)
RaiseEvent AddedNewColumn(newColumn)
End Sub
Private Sub ThrowIfNothing(ByVal Target As Object)
If Target Is Nothing Then Err.Raise 5, TypeName(Me), "Argument cannot be a null reference."
End Sub
Private Sub ThrowIfSet(ByVal Target As Object)
If Not Target Is Nothing Then Err.Raise 5, TypeName(Me), "This reference is already set."
End Sub
Private Sub Resize()
With this.SourceTable
this.LastRowCount = .ListRows.Count
this.LastColumnCount = .ListColumns.Count
End With
End Sub
Private Sub TableSheet_Change(ByVal Target As Range)
' Used intersect to catch only the databodyrange, otherwise this could be Target.ListObject is SourceTable
If Intersect(Target, SourceTable.DataBodyRange) Is Nothing Then Exit Sub
Select Case True
Case this.SourceTable.DataBodyRange.Columns.Count > this.LastColumnCount
OnAddedNewColumn SourceTable.ListColumns(GetCellColumn(this.SourceTable, Target))
Case this.SourceTable.DataBodyRange.Rows.Count > this.LastRowCount
OnAddedNewRow SourceTable.ListRows(GetCellRow(this.SourceTable, Target))
Case Else
OnChanged Target
End Select
Resize
End Sub
Private Property Get ITable_SourceTable() As ListObject
Set ITable_SourceTable = this.SourceTable
End Property
Private Function GetCellRow(ByVal evalTable As ListObject, ByVal EvalCell As Range) As Long
If Intersect(EvalCell, evalTable.DataBodyRange) Is Nothing Then Exit Function
GetCellRow = EvalCell.Row - evalTable.HeaderRowRange.Row
End Function
Private Function GetCellColumn(ByVal evalTable As ListObject, ByVal EvalCell As Range) As Long
If Intersect(EvalCell, evalTable.DataBodyRange) Is Nothing Then Exit Function
GetCellColumn = EvalCell.Column - evalTable.HeaderRowRange.Column + 1
End Function
</code></pre>
<p>Class: <code>ITables</code></p>
<pre><code>Option Explicit
Public Sub AddTables()
End Sub
Public Function Create(ByVal SourceSheet As Worksheet) As Tables
End Function
</code></pre>
<p>Class: <code>Tables</code></p>
<pre><code>'@Folder("VBAProject")
Option Explicit
'@PredeclaredId
Private WithEvents MyTable As Table
Private Type TTables
Sheet As Worksheet
sheetTables As Collection
Counter As Long
End Type
Private this As TTables
Implements ITables
Public Property Get sheetTables() As Collection
Set sheetTables = this.sheetTables
End Property
Friend Property Set sheetTables(ByVal Value As Collection)
Set this.sheetTables = Value
End Property
Public Property Get Sheet() As Worksheet
Set Sheet = this.Sheet
End Property
Friend Property Set Sheet(ByVal Value As Worksheet)
Set this.Sheet = Value
End Property
Public Property Get Counter() As Long
Counter = this.Counter
End Property
Friend Property Let Counter(ByVal Value As Long)
this.Counter = Value
End Property
Public Property Get Self() As Tables
Set Self = Me
End Property
Public Sub AddTables()
Select Case True
Case Counter = 0 Or Counter > Sheet.ListObjects.Count
AddAllTablesInSheet
Case Sheet.ListObjects.Count > Counter
AddNewTable Sheet.ListObjects(Sheet.ListObjects.Count)
End Select
Counter = Sheet.ListObjects.Count
End Sub
Private Sub AddAllTablesInSheet()
Dim evalTable As ListObject
Set sheetTables = New Collection
For Each evalTable In Sheet.ListObjects
AddNewTable evalTable
Next evalTable
End Sub
Private Sub AddNewTable(ByVal evalTable As ListObject)
Dim NewSheetTable As SheetTable
Set NewSheetTable = New SheetTable
Set NewSheetTable.TableEvents = Table.Create(evalTable)
sheetTables.Add Item:=NewSheetTable, Key:=evalTable.Name
End Sub
Public Function Create(ByVal SourceSheet As Worksheet) As ITables
With New Tables
Set .Sheet = SourceSheet
Set Create = .Self
.AddTables
End With
End Function
Private Sub MyTable_AddedNewColumn(ByVal newColumn As ListColumn)
MsgBox "Added new column " & newColumn.Range.Column
End Sub
Private Sub MyTable_AddedNewRow(ByVal newRow As ListRow)
MsgBox "Added new row " & newRow.Range.Row
End Sub
Private Sub MyTable_Changed(ByVal cell As Range)
MsgBox "Changed " & cell.Address
End Sub
Private Sub ITables_AddTables()
AddTables
End Sub
Private Function ITables_Create(ByVal SourceSheet As Worksheet) As Tables
Set ITables_Create = Create(SourceSheet)
End Function
</code></pre>
<p>Class: <code>SheetTable</code></p>
<pre><code>'@Folder("VBAProject")
'@PredeclaredId
Option Explicit
Private WithEvents MyTable As Table
Public Property Get TableEvents() As Table
Set TableEvents = MyTable
End Property
Public Property Set TableEvents(ByVal Value As Table)
Set MyTable = Value
End Property
Private Sub MyTable_AddedNewColumn(ByVal newColumn As ListColumn)
MsgBox "Added new table column in sheet column " & newColumn.Range.Column
End Sub
Private Sub MyTable_AddedNewRow(ByVal newRow As ListRow)
MsgBox "Added new table row in sheet row " & newRow.Range.Row
End Sub
Private Sub MyTable_Changed(ByVal cell As Range)
MsgBox "Changed " & cell.Address & " which belongs to the table: " & cell.ListObject.Name
End Sub
</code></pre>
<blockquote>
<p>Code has annotations from <a href="http://rubberduckvba.com/" rel="nofollow noreferrer">Rubberduck add-in</a></p>
</blockquote>
<p><strong>Notes:</strong></p>
<ul>
<li>As Sheet's Activate event is not fired on Workbook Open (<a href="https://www.google.com.co/url?sa=t&rct=j&q=&esrc=s&source=web&cd=5&cad=rja&uact=8&ved=2ahUKEwi57JWSq_rmAhWJjlkKHfEnDMkQFjAEegQIAxAB&url=https%3A%2F%2Fpixcels.nl%2Fevents-in-workbooks%2F&usg=AOvVaw0VFqe2WhShVuPapYjRpNrz" rel="nofollow noreferrer">read this</a>) you'd have to manage that situation or manually activate the sheet holding the tables.</li>
</ul>
|
[] |
[
{
"body": "<p>I find relying on <code>Sheet.Activate</code> / <code>Sheet.Deactivate</code> to set/unset the <code>sheetTables</code> reference is rather frail, error-prone (miss an <code>Activate</code> event for whatever reason (<code>Application.EnableEvents</code> being toggled off, for example), and just like that the <code>Change</code> handler starts throwing error 91), and doesn't really make much sense: the table exists on <code>Sheet1</code> as long as <code>Sheet1</code> does, no?</p>\n\n<blockquote>\n<pre><code>Private Sub Worksheet_Change(ByVal Target As Range)\n sheetTables.AddTables\nEnd Sub\n</code></pre>\n</blockquote>\n\n<p>In that case, then why do we need to re-create the wrapper every single time any cell is modified on that sheet? This method should run <em>once</em>, for the entire lifetime of the worksheet: I'd do that in a <code>Workbook.Open</code> handler.</p>\n\n<p>When present, a factory method should be the first member listed, followed by the public members of the class' default interface.</p>\n\n<blockquote>\n<pre><code>Public Function Create(ByVal SourceSheet As Worksheet) As ITables\n With New Tables\n Set .Sheet = SourceSheet\n Set Create = .Self\n .AddTables\n End With\nEnd Function\n</code></pre>\n</blockquote>\n\n<p>You wouldn't bury a C# class constructor at the bottom of the class; don't bury a VBA factory method at the bottom of the class... or worse, somewhere in the middle of it.</p>\n\n<p>Note that the <code>.AddTables</code> member call is made against the <code>Tables</code> interface. <code>ITables</code> is weird:</p>\n\n<blockquote>\n<pre><code>Option Explicit\n\nPublic Sub AddTables()\nEnd Sub\n\nPublic Function Create(ByVal SourceSheet As Worksheet) As Tables\nEnd Function\n</code></pre>\n</blockquote>\n\n<p>Class modules that are intended to be used as abstract interfaces should have an <code>@Interface</code> annotation; Rubberduck's static code analysis will then treat it as such, whether or not the interfacec is actually implemented anywhere.</p>\n\n<p>But the weird thing with this interface, is that it's exposing the factory method, which is normally invoked off the default instance of the concrete type... like you do here:</p>\n\n<blockquote>\n<pre><code>Private Sub Worksheet_Activate()\n Set sheetTables = Tables.Create(Me)\nEnd Sub\n</code></pre>\n</blockquote>\n\n<p>A factory method on an abstract interface would be legit if we were looking at an <em>Abstract Factory</em> - but that's not what we have here, this factory method is yielding the concrete type (<code>Tables</code>) ...and yet the actual factory method you're using <em>does</em> yield the <code>ITables</code> abstraction.</p>\n\n<p><code>AddTables</code> doesn't belong on that interface either: it's an implementation detail of the <code>Create</code> factory method, which itself belongs on the concrete type - none of the members of <code>ITables</code> belong on <code>ITables</code>.</p>\n\n<p>These would all feel right at home on that interface though:</p>\n\n<pre><code>Public Property Get sheetTables() As Collection\nEnd Property\n\nPublic Property Get Sheet() As Worksheet\nEnd Property\n\nPublic Property Get Counter() As Long\nEnd Property\n</code></pre>\n\n<p>...with a reservation for <code>sheetTables As Collection</code>: exposing a <code>Collection</code> means the client code is able to <code>.Add</code> and <code>.Remove</code> items, and you certainly don't want to allow that. Consider exposing it as an indexed property instead:</p>\n\n<pre><code>Public Property Get SheetTable(ByVal index As Variant) As ITable\nEnd Property\n</code></pre>\n\n<p>Now given a name or index, retrieve the <code>ITable</code> item and return it. Also consider exposing a <code>NewEnum</code> member (and yield <code>sheetTables.[_NewEnum]</code>) with an <code>@Enumerator</code> annotation (sync attributes through Rubberduck inspections), and then the client code will be able to iterate the items in this custom collection class, with an idiomatic <code>For Each</code> loop. The name <code>Tables</code>, pluralized, strongly suggests that it's a collection of tables.</p>\n\n<p>Or you could introduce some <code>ReadOnlyCollection</code> class with a <code>Create</code> method that takes a <code>ParamArray</code> argument, with logic to initialize the encapsulated collection with the specified items (could be an array or collection - I'll leave the implementation up to the reader), and then there'd be no problem exposing such a read-only collection that can only be iterated.</p>\n\n<p>Exposing the encapsulated <code>Collection</code> itself, breaks encapsulation.</p>\n\n<p>Not sure what the purpose of this <code>eval</code>/<code>Eval</code> prefix is:</p>\n\n<blockquote>\n<pre><code>Private Function GetCellRow(ByVal evalTable As ListObject, ByVal EvalCell As Range) As Long\n If Intersect(EvalCell, evalTable.DataBodyRange) Is Nothing Then Exit Function\n\n GetCellRow = EvalCell.Row - evalTable.HeaderRowRange.Row\nEnd Function\n\nPrivate Function GetCellColumn(ByVal evalTable As ListObject, ByVal EvalCell As Range) As Long\n If Intersect(EvalCell, evalTable.DataBodyRange) Is Nothing Then Exit Function\n\n GetCellColumn = EvalCell.Column - evalTable.HeaderRowRange.Column + 1\nEnd Function\n</code></pre>\n</blockquote>\n\n<p>The objective clearly isn't related to preserving the <code>camelCase</code> or <code>PascalCase</code> of parameter names, so I'm left baffled as to why it's not just <code>table</code> and <code>cell</code>. Actually, since these members belong to <code>Table</code> which is wrappping a <code>ListObject</code>, ...I think the <code>ListObject</code> parameters should be removed - if these functions really belong in that class, then they should be working off the <code>this.SourceTable</code> instance field.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T18:35:14.000",
"Id": "461144",
"Score": "1",
"body": "Hi Mathieu. answering your question: `why do we need to re-create the wrapper every single time any cell is modified on that sheet?` I need it to handle new tables added (or removed) to the same sheet. I couldn't find another way to know they were added but to use the sheet's change event."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T18:57:21.167",
"Id": "461150",
"Score": "0",
"body": "Ah, yeah that makes more sense now. Was under the impression that all tables existed on their respective sheet at compile-time!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T17:48:12.630",
"Id": "235569",
"ParentId": "235449",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "235569",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T01:09:36.100",
"Id": "235449",
"Score": "3",
"Tags": [
"object-oriented",
"vba",
"excel",
"rubberduck"
],
"Title": "Managing Excel Tables (ListObjects) with OOP Approach (Follow up)"
}
|
235449
|
<p>As a small exercise in Python, I created an Assembler for the rather simple Brookshear Machine (see f.e. <a href="https://brookshear.jfagerberg.me/#" rel="noreferrer">Brookshear Machine</a>, please note, however, that the instruction set differs from mine).
The instruction set used by this implementation is based on a task from a friend's Computer Science course. He showed me another online emulator <a href="http://joeledstrom.github.io/brookshear-emu/#12ff4004a103c000" rel="noreferrer">here</a> which is compatible to the machine code generated by this assembler.</p>
<p>I'm open to any suggestions for improvement but do not have any specific question
at hand because I'm quite satisfied how the module looks for the moment.</p>
<p>While typing, I realised I'd like to know if there's a better way to handle DEBUG messages in the code, so that I can quickly enable/disable all of them.</p>
<pre class="lang-py prettyprint-override"><code>'''Assembler for the Brookshear machine.
This is a module for assembling assembler code compatible to the Brookshear
Machine.
'''
from enum import Enum
from typing import List, Tuple
class OpType(Enum):
'''The type of the operand's parameter
The value of every enumeration's item is it's maximum allowed value.
'''
ZER = 0x0 # Zero (0)
REG = 0xF # Register address
NIB = 0xF # Non-restricted Nibble (4 bit)
ADR = 0xFF # Address
class Op(Enum):
'''All the available operands in this Brookshear machine model.
Every element of the enumeration is a single operand in this Brookshear
machine and consists of a tuple with the following elements:
1. The OpCode in machine code
2. The OpTypes of the input parameters
3. The order of the output parameters.
'''
# Mnemonic Opcode Input-Types output order
LOAD = (1, [OpType.REG, OpType.ADR], [0, 1])
LOADI = (2, [OpType.REG, OpType.ADR], [0, 1])
STORE = (3, [OpType.ADR, OpType.REG], [1, 0])
MOVE = (4, [OpType.REG, OpType.REG], [OpType.ZER, 1, 0])
ADD = (5, [OpType.REG, OpType.REG, OpType.REG], [0, 1, 2])
ADD_FLOAT = (6, [OpType.REG, OpType.REG, OpType.REG], [0, 1, 2])
OR = (7, [OpType.REG, OpType.REG, OpType.REG], [0, 1, 2])
AND = (8, [OpType.REG, OpType.REG, OpType.REG], [0, 1, 2])
XOR = (9, [OpType.REG, OpType.REG, OpType.REG], [0, 1, 2])
ROTATE_RIGHT= (0xA, [OpType.REG, OpType.NIB], [0, OpType.ZER, 1])
JUMP = (0xB, [OpType.ADR, OpType.REG], [1, 0])
HALT = (0xC, [], [OpType.ZER, OpType.ZER, OpType.ZER])
class Assembler:
'''Assembler for given Brookshear machine model.'''
commentSymb = ";"
delimSymb = ","
def __init__(self, code: str):
self.code = code
self.output = None
def get_last_translation(self) -> str:
'''Return the most recently translated program.
If no program was created yet, return null.
'''
return self.output
def translate(self) -> str:
'''Translates the Brookshear Assembly Code to Brookshear Machine code.'''
self.output = ""
for num, line in enumerate(self.code.split("\n"), 1):
print(f"[DEBUG] Processing: #{line}#")
line = self.__preprocess_line(line)
# If the line is empty, skip further processing.
if len(line) == 0:
continue
decoded_line = self.__decode_instr(line)
if not decoded_line[0]:
# There was an error decoding the instruction... Display error
# and add notice to output
print(f"[ERROR] ({num}): {decoded_line[1]}")
self.output += "[ERR]"
else:
# The assembling of the instruction was successful. Add it to
# the output.
print(f"[DEBUG] {decoded_line[1]}")
self.output += decoded_line[1]
return self.output
def __preprocess_line(self, line: str) -> str:
'''Preprocess a line from the given input.
Strip any leading/trailing whitespace, remove any comments and convert
all characters to uppercase.
'''
return line.strip().split(Assembler.commentSymb)[0].upper()
def __decode_instr(self, line: str) -> Tuple[bool,str]:
'''Decode a single instruction.
As a first step, a line from the source file is scanned for a known Op-
Code and handled accordingly.
Return a tuple whose first element is 'False' if any error occured.
'''
print(f"[DEBUG] Decode: #{line}#")
# A String representation of all available Ops
op_list = [name for name, member in Op.__members__.items()]
# HALT Operation needs no space after it
if line.startswith("HALT"):
return self.__validate_instr(Op.HALT, line)
elif len(line.split(" ")) <= 1\
or line.split(" ")[0].replace("-","_") not in op_list:
return (False, f"No valid instruction found! - "\
f"len={len(line.split(' '))}, instr={line.split(' ')[0]}")
else:
op = line.split(" ")[0].replace("-","_")
return self.__validate_instr(Op[op], line)
def __validate_instr(self, op: Op, instr: str) -> Tuple[bool,str]:
'''Validate a single decoded instruction.
Return a tuple whose first element is 'False' if any error occured.
'''
print(f"[DEBUG] Validate: <{op}> #{instr}#")
# Remove Assembler-OpCode and whitespace
instr = instr[len(op.name) + 1:].strip()
expected_no_of_ops = len(op.value[1])
# Compare length of expected operand list and actual operand list
if expected_no_of_ops > 0 and\
expected_no_of_ops != len(instr.split(Assembler.delimSymb)):
return (False, f"Invalid number of operands for Instr. {op.name}:"\
f" Expected: {expected_no_of_ops}"\
f" Got: {len(instr.split(Assembler.delimSymb))}")
try:
operands = None
if expected_no_of_ops > 0:
operands = [int(x.strip(), 16) for x in instr.split(",")]
# Check if operands are in valid value range
for limitation, operand in zip(op.value[1], operands):
if operand > limitation.value:
return (False, f"Invalid operand (value exceeds range): "\
f"{operand}")
# Every validation check was passed. Return successfully
return (True, self.__encode_instr(op, operands))
except ValueError as ve:
return (False, f"Invalid argument value: {str(ve).split(': ')[-1]}")
def __encode_instr(self, op: Op, operands: List[int]) -> str:
'''Encode/Assemble a single validated instruction.
Return a String consisting of the assembled instruction.
'''
print(f"[DEBUG] Encode: <{op}> #{operands}#")
machine_code = format(op.value[0], "x")
# Handle the output order of the assembler instructions
for output in op.value[2]:
if output == OpType.ZER:
machine_code += "0"
else:
# add the operand with formatting based on its type
if op.value[1][output] == OpType.ADR:
machine_code += format(operands[output], "02x")
else:
machine_code += format(operands[output], "x")
return machine_code
if __name__ == '__main__':
with open("debug.bin", "r") as f:
ass = Assembler(f.read())
print("Translate: " + ass.translate())
print("URL:")
print("http://joeledstrom.github.io/brookshear-emu/#" + ass.get_last_translation())
#print("Get Translate: " + ass.get_last_translation())
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T01:31:40.670",
"Id": "461072",
"Score": "0",
"body": "_The instruction set used by this implementation is based on a task from a friend's Computer Science course._ Do you happen to have a way of sharing that task? I would love to give this a try myself. That code currently isn't runnable, eh."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T05:38:30.153",
"Id": "461228",
"Score": "0",
"body": "@AMC I‘ve uploaded the code to GitHub. The instruction set can be found in the ReadMe: https://github.com/DerReparator/Assembler-for-Brookshear-Machine A compatible machine can be found at the link in my question above."
}
] |
[
{
"body": "<p>Overall, looks very good and clean to me too, especially from a first poster. A few minor things:</p>\n\n<p>PEP 8 prefers triple double quotes for docstrings. I don't particularly care but it's in the contract to point such things out. And, in general, it's a courtesy to reviewers to get your IDE/linter to fix such things before posting. </p>\n\n<p>There are a few debateable comparisons to 0. I'm not sure that I greatly prefer \"if expected_no_of_ops\" to \"if expected_no_of_ops > 0\". However, \"if not line\" is definitely more idiomatic than \"if len(line) == 0:\"</p>\n\n<p>Finally, I marginally prefer passing a stream rather than a string to Assembler:</p>\n\n<pre><code> ass = Assembler(f.read()) \n ... \n for num, line in enumerate(self.code.split(\"\\n\"), 1):\n</code></pre>\n\n<p>would be easier as:</p>\n\n<pre><code> ass = Assembler(f) \n ... \n for num, line in enumerate(self.code_stream, 1):\n</code></pre>\n\n<p>You can always use StringIO to go from string to stream (e.g. for testing)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T11:25:04.413",
"Id": "460900",
"Score": "0",
"body": "Your suggestion regarding the usage of a _stream_ sounds very good. Thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T10:57:21.447",
"Id": "235467",
"ParentId": "235451",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "235467",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T01:33:43.690",
"Id": "235451",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"assembly"
],
"Title": "Assembler for Brookshear Machine"
}
|
235451
|
<p><strong>Objective:</strong></p>
<p>Simulate <code>namespaces</code> in VBA and access functions like if you had a <code>Framework</code> setup or at least that was what I understood...</p>
<hr>
<p><strong>Background:</strong></p>
<p>I was inspired by this piece of code: <code>Framework.Strings.StartsWith</code> in <a href="https://codereview.stackexchange.com/q/63004/197645">this post</a></p>
<hr>
<p><strong>Questions:</strong></p>
<ol>
<li>As I'm basically coding against the predeclared instance, is there a risk of a memory leak?</li>
<li>I see benefits while coding and accessing the functions, do you see downsides?</li>
</ol>
<hr>
<p><strong>Code / File structure:</strong></p>
<p><a href="https://i.stack.imgur.com/NGOTG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NGOTG.png" alt="Implementation"></a></p>
<hr>
<p><strong>Code:</strong></p>
<p>Class: <code>Framework</code> (simplified version)</p>
<pre><code>'@Version(1)
'@Folder("Framework")
Option Explicit
'@PredeclaredId
' Copywrite (C) 2019 Ricardo Diaz
' This file is distributed under the GPL-3.0 license
' Obtain a copy of the GPL-3.0 license <http://opensource.org/licenses/GPL-3.0>
Private Type TFramework
Collection As CollectionUtilities
End Type
Private this As TFramework
Public Property Get Collection() As CollectionUtilities
Set Collection = this.Collection
End Property
Public Property Set Collection(ByVal Value As CollectionUtilities)
Set this.Collection = Value
End Property
Private Sub Class_Initialize()
Set Collection = New CollectionUtilities
End Sub
</code></pre>
<p>Class: <code>CollectionUtilities</code></p>
<pre><code>'@Version(1)
'@Folder("Framework.Utilities")
Option Explicit
'@PredeclaredId
'Credits: https://jkp-ads.com/Articles/buildexceladdin02.asp
'@Ignore ProcedureNotUsed
Public Function IsIn(ByVal Collection As Variant, ByVal Name As String) As Boolean
'-------------------------------------------------------------------------
' Procedure : IsIn Created by Jan Karel Pieterse
' Company : JKP Application Development Services (c) 2005
' Author : Jan Karel Pieterse
' Created : 28-12-2005
' Purpose : Determines if object is in collection
'-------------------------------------------------------------------------
Dim newObject As Object
Set newObject = Collection(Name)
IsIn = (newObject Is Nothing)
If IsIn = False Then
Set newObject = Collection(Application.WorksheetFunction.Substitute(Name, "'", vbNullString))
IsIn = (newObject Is Nothing)
End If
End Function
'@Ignore ProcedureNotUsed
Public Sub ClearCollection(ByRef Container As Collection)
Dim counter As Long
For counter = 1 To Container.Count
Container.Remove counter
Next
End Sub
'@Ignore ProcedureNotUsed
Public Function HasItem(ByVal Container As Collection, ByVal ItemKeyOrNum As Variant) As Boolean
Dim temp As Variant
On Error Resume Next
temp = IsObject(Container.Item(ItemKeyOrNum))
On Error GoTo 0
HasItem = Not IsEmpty(temp)
End Function
'@Ignore ProcedureNotUsed
Public Function ArrayToCollection(ByVal evalArray As Variant) As Collection
' Credits: https://stackoverflow.com/a/12258926/1521579
Dim tempCollection As Collection
Dim Item As Variant
Set tempCollection = New Collection
For Each Item In evalArray
tempCollection.Add Item
Next Item
Set ArrayToCollection = tempCollection
End Function
'@Ignore ProcedureNotUsed
Public Sub AddArrayItemsToCollection(ByVal evalCollection As Collection, ByVal evalArray As Variant)
Dim Item As Variant
For Each Item In evalArray
evalCollection.Add Item
Next Item
End Sub
'@Ignore ProcedureNotUsed
Public Sub DebugCollectionValues(ByVal evalCol As Collection)
Dim counter As Long
For counter = 1 To evalCol.Count
Debug.Print evalCol(counter).Name, evalCol(counter).Value
Next counter
End Sub
'@Ignore ProcedureNotUsed
Public Function TableRowToCollection(ByVal sourceCell As Range) As Collection
Dim EvalCell As Range
Dim evalTable As ListObject
Dim evalListRow As ListRow
Dim evalCollection As Collection
Dim evalRow As Long
Set evalTable = sourceCell.ListObject
evalRow = sourceCell.Row - evalTable.HeaderRowRange.Row
Set evalListRow = evalTable.ListRows(evalRow)
Set evalCollection = New Collection
For Each EvalCell In evalListRow.Range.Cells
evalCollection.Add EvalCell.Value2, evalTable.HeaderRowRange.Cells(EvalCell.Column - evalTable.HeaderRowRange.Column + 1).Value2
Next EvalCell
Set TableRowToCollection = evalCollection
End Function
</code></pre>
<p>And call it like this:</p>
<p><a href="https://i.stack.imgur.com/p4iu6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/p4iu6.png" alt="How to call the framework utilities"></a></p>
<blockquote>
<p>Code has annotations from <a href="http://rubberduckvba.com/" rel="nofollow noreferrer">Rubberduck add-in</a></p>
</blockquote>
|
[] |
[
{
"body": "<p>It's tradeoffs. On one hand you get useful static methods in a toolbox, functions that don't accidentally show up in Excel's IntelliSense in the formula bar. On the other hand, you could get the very same out of a standard module with <code>Option Private Module</code> specified, minus the possibility of client code mistakenly attempting to create a <code>New</code> instance of the class... and since class modules are either <code>Private</code> or <code>PublicNotCreatable</code>, the best way to implement this <code>Framework</code> namespace would be to have an Excel add-in VBA project named <code>Framework</code>, exposing these predeclared instances to whoever wants to consume its members. The cost for using classes is a <code>LongPtr</code> per instance - the actual size of that pointer depends on the bitness of the host application... and it's negligible.</p>\n\n<p>The main difference between a class and a standard module is that you can pass an object reference to a procedure, but you can't pass a module; you can't declare a variable <code>As</code> that module \"type\", <code>New</code> it up (in the same VBA project, accidentally or not), or make it handle events or implement interfaces.</p>\n\n<p>I think <em>framework</em>-level static/shared functions, in VBA, feel right at home in a standard module.</p>\n\n<p>So you would reference the <code>Framework</code> add-in project, and then you'd do <code>?Framework.Collections.HasItem(items, item)</code>, and <code>?Collections.HasItem(items, item)</code> would also be legal, and yes, <code>?HasItem(items, item)</code> would be as well! ...unless the identifier is shadowed by a public member with the same name in a higher-priority referenced library, or in the referencing VBA project itself.</p>\n\n<p>You would use classes in a <code>Framework</code> add-in to encapsulate some state - you could have a <code>ProgressIndicator</code> class exposed, for example, that registers a worker method that never needs to know anything about any <code>ProgressIndicatorForm</code>, and even less about any <code>MSForms.Label</code> control's <code>Width</code>. You'd have a <code>StringBuilder</code> class, a <code>FileWriter</code> class, a <code>SqlCommand</code> class - you want classes that represent & encapsulate some data and implement some behavior, and modules that group related procedures together... but why not have a custom collection class (some <code>List</code> perhaps) that exposes all the things you ever dreamed a <code>Collection</code> could do, instead of a <code>CollectionUtilities</code> class/module?</p>\n\n<p>Maybe it's just the \"utilities\" name ringing a \"bag of whatever\" ring to it, but having <code>Utilities</code> in the name of every module feels like redundant suffixing, I find.</p>\n\n<p>You want an <code>@IgnoreModule ProcedureNotUsed</code> annotation at module level here, rather than having an annotation on every individual member - that way it's much easier to toggle it back on if you choose to leave that code as a bunch of modules to import in every new project (rather than an Excel add-in you'd reference): these Rubberduck inspection results are telling you which members can be removed from this particular project; no need to bloat up a project you're distributing with a whole framework!</p>\n\n<p>It's not clear what the difference is between <code>IsIn</code> and <code>HasItem</code> functions - both feel like just slightly different solutions to the same problem (although I suspect you removed an <code>On Error Resume Next</code> from JKP's code, since that function can't return <code>False</code> without throwing error 9), and that makes a confusing API. I'd keep <code>HasItem</code> but swap the <code>IsObject</code> check for an <code>Err.Number = 0</code> check.</p>\n\n<p>Variables could be declared closer to where they're used in a few places, especially in <code>TableRowToCollection</code>.</p>\n\n<p>Since this is a framework, there's an opportunity for every public member to have a short <code>@Description</code> annotation comment, and for modules to have a <code>@ModuleDescription</code>.</p>\n\n<p>Side note, it's \"copyright\", ...and this Q&A post is licensed under CC-BY-SA as per Stack Exchange terms of service ;-) </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T14:06:58.763",
"Id": "460905",
"Score": "0",
"body": "Thank you Mathieu! I have more clarity about the pros, cons and alternatives. Also good suggestions to implement along my solution. and about the copyright...just blushed ;("
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T21:09:03.193",
"Id": "460936",
"Score": "1",
"body": "I did this...`although I suspect you removed an On Error Resume Next` you saved me like 2 hours of debugging!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T21:23:45.220",
"Id": "460937",
"Score": "0",
"body": "@RicardoDiaz if there was a OERN without a OEG0, there should have been a result for [UnhandledOnErrorResumeNext](http://rubberduckvba.com/Inspections/Details/UnhandledOnErrorResumeNext) - with a [RestoreErrorHandling](http://rubberduckvba.com/Inspections/QuickFixInfo/RestoreErrorHandling) quickfix offered ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T21:30:27.443",
"Id": "460939",
"Score": "0",
"body": "Yes, that I catched with the help of Rubberduck, but the problem was that I added OEG0 before err.number was evaluated, so it always returned 0. Thank you!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T04:14:35.417",
"Id": "235460",
"ParentId": "235453",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235460",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T01:56:05.627",
"Id": "235453",
"Score": "1",
"Tags": [
"object-oriented",
"vba",
"excel"
],
"Title": "VBA Class instance to simulate a framework"
}
|
235453
|
<p><strong>Objective:</strong></p>
<p>Have a single point of entrance to initialize a class that holds instances of "sub" <code>classes</code></p>
<hr>
<p><strong>Background:</strong></p>
<ul>
<li>I read about inheritance in VBA (or as close as you will) in <a href="https://exceldevelopmentplatform.blogspot.com/2018/09/vba-inheritance-or-as-close-as-you-will.html" rel="nofollow noreferrer">this post</a> and it occurred to me that you could have a hierarchy of classes/objects so accessing them while coding would be easier</li>
<li>Thought about how to initialize the "base" class in order to recover from code crashes in <a href="https://stackoverflow.com/a/4196960/1521579">this post</a></li>
<li>Read about Lazy object / weak reference in <a href="https://rubberduckvba.wordpress.com/2018/09/11/lazy-object-weak-reference/" rel="nofollow noreferrer">this post</a> and got worried about this could be happening in my project</li>
</ul>
<hr>
<p><strong>Questions:</strong></p>
<ol>
<li>Is this a source of a memory leak risk? (see my post about the idea of a framework <a href="https://codereview.stackexchange.com/q/235453/197645">here</a> where I'm asking from a different perspective because in this case I am creating a new instance of the base class inside the function)</li>
<li>The idea of a single point of entrance to initialize the class is "compatible" / recommeded with the whole classes hierarchy approach?</li>
</ol>
<hr>
<p><strong>Code / File structure:</strong></p>
<p><a href="https://i.stack.imgur.com/7CyrJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7CyrJ.png" alt="Code file structure"></a></p>
<hr>
<p><strong>Code components:</strong></p>
<p>Module: <code>AppMacros</code></p>
<p>Description: This is the function that I call to access the classes in the whole application.</p>
<pre><code>'@Version(1)
'@Folder("App")
Option Explicit
Private Const ModuleName As String = "AppMacros"
Public Function AppWorkbook() As App
On Error GoTo CleanFail
Static newApp As App
If newApp Is Nothing Then
Set newApp = App.Create
LogManager.Register TableLogger.Create("AppInfoLogger", PerfLevel, "TablaRegistroApp")
newApp.SecurityManager.RestoreSheetsProtection
newApp.SecurityManager.RestoreWorkbookProtection
End If
Set AppWorkbook = newApp
CleanExit:
Exit Function
CleanFail:
ErrorHandler.DisplayMessage ModuleName, "InitAppWorkbook", Err.Number, Err.Description, , True
If Not DebugMode Then Resume CleanExit Else: Stop: Resume
End Function
</code></pre>
<p>I call it like this:</p>
<p><a href="https://i.stack.imgur.com/sKuOc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sKuOc.png" alt="How to call the point of entrance function"></a></p>
<p>And call a function from one of the sub classes:</p>
<p><a href="https://i.stack.imgur.com/WslDh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WslDh.png" alt="Call a function from one of the sub classes"></a></p>
<p>Class: <code>App</code></p>
<pre><code>'@Version(1)
'@Folder("App")
Option Explicit
'@PredeclaredId
' Copywrite (C) 2019 Ricardo Diaz
' This file is distributed under the GPL-3.0 license
' Obtain a copy of the GPL-3.0 license <http://opensource.org/licenses/GPL-3.0>
Private Type TApp
DateUpdated As Date
AutomationManager As AutomationManager
ConfigManager As ConfigManager
DisplayManager As DisplayManager
ExternalDataManager As ExternalDataManager
ErrorHandler As ErrorHandler
NavigationManager As NavigationManager
OptionsManager As OptionsManager
ParamManager As ParamManager
PerfManager As PerfManager
RoadMapManager As RoadMapManager
SecurityManager As SecurityManager
SettingsManager As DefaultsManager
StartManager As StartManager
StateManager As StateManager
TaskManager As TaskManager
VersionManager As VersionManager
End Type
Private this As TApp
Public Property Get DateUpdated() As Date
DateUpdated = this.DateUpdated
End Property
Public Property Let DateUpdated(ByVal vNewValue As Date)
this.DateUpdated = vNewValue
End Property
Public Property Get Self() As App
Set Self = Me
End Property
Public Property Get AutomationManager() As AutomationManager
Set AutomationManager = this.AutomationManager
End Property
Friend Property Set AutomationManager(ByVal Value As AutomationManager)
Set this.AutomationManager = Value
End Property
Public Property Get ConfigManager() As ConfigManager
Set ConfigManager = this.ConfigManager
End Property
Friend Property Set ConfigManager(ByVal Value As ConfigManager)
Set this.ConfigManager = Value
End Property
Public Property Get DisplayManager() As DisplayManager
Set DisplayManager = this.DisplayManager
End Property
Friend Property Set DisplayManager(ByVal Value As DisplayManager)
Set this.DisplayManager = Value
End Property
Public Property Get ErrorHandler() As ErrorHandler
Set ErrorHandler = this.ErrorHandler
End Property
Friend Property Set ErrorHandler(ByVal Value As ErrorHandler)
Set this.ErrorHandler = Value
End Property
Public Property Get ExternalDataManager() As ExternalDataManager
Set ExternalDataManager = this.ExternalDataManager
End Property
Friend Property Set ExternalDataManager(ByVal Value As ExternalDataManager)
Set this.ExternalDataManager = Value
End Property
Public Property Get NavigationManager() As NavigationManager
Set NavigationManager = this.NavigationManager
End Property
Friend Property Set NavigationManager(ByVal Value As NavigationManager)
Set this.NavigationManager = Value
End Property
Public Property Get OptionsManager() As OptionsManager
Set OptionsManager = this.OptionsManager
End Property
Friend Property Set OptionsManager(ByVal Value As OptionsManager)
Set this.OptionsManager = Value
End Property
Public Property Get ParamManager() As ParamManager
Set ParamManager = this.ParamManager
End Property
Friend Property Set ParamManager(ByVal Value As ParamManager)
Set this.ParamManager = Value
End Property
Public Property Get PerfManager() As PerfManager
Set PerfManager = this.PerfManager
End Property
Friend Property Set PerfManager(ByVal Value As PerfManager)
Set this.PerfManager = Value
End Property
Public Property Get RoadMapManager() As RoadMapManager
Set RoadMapManager = this.RoadMapManager
End Property
Friend Property Set RoadMapManager(ByVal Value As RoadMapManager)
Set this.RoadMapManager = Value
End Property
Public Property Get SecurityManager() As SecurityManager
Set SecurityManager = this.SecurityManager
End Property
Friend Property Set SecurityManager(ByVal Value As SecurityManager)
Set this.SecurityManager = Value
End Property
Public Property Get SettingsManager() As DefaultsManager
Set SettingsManager = this.SettingsManager
End Property
Friend Property Set SettingsManager(ByVal Value As DefaultsManager)
Set this.SettingsManager = Value
End Property
Public Property Get StartManager() As StartManager
Set StartManager = this.StartManager
End Property
Friend Property Set StartManager(ByVal Value As StartManager)
Set this.StartManager = Value
End Property
Public Property Get StateManager() As StateManager
Set StateManager = this.StateManager
End Property
Friend Property Set StateManager(ByVal Value As StateManager)
Set this.StateManager = Value
End Property
Public Property Get TaskManager() As TaskManager
Set TaskManager = this.TaskManager
End Property
Friend Property Set TaskManager(ByVal Value As TaskManager)
Set this.TaskManager = Value
End Property
Public Property Get VersionManager() As VersionManager
Set VersionManager = this.VersionManager
End Property
Friend Property Set VersionManager(ByVal Value As VersionManager)
Set this.VersionManager = Value
End Property
'@Ignore FunctionReturnValueNotUsed
Public Function Create() As App
With New App
Set .AutomationManager = New AutomationManager
Set .ConfigManager = New ConfigManager
Set .DisplayManager = New DisplayManager
Set .ErrorHandler = New ErrorHandler
Set .ExternalDataManager = New ExternalDataManager
Set .NavigationManager = New NavigationManager
Set .OptionsManager = New OptionsManager
Set .ParamManager = New ParamManager
Set .PerfManager = New PerfManager
Set .RoadMapManager = New RoadMapManager
Set .SecurityManager = New SecurityManager
Set .SettingsManager = New DefaultsManager
Set .StartManager = New StartManager
Set .StateManager = New StateManager
Set .TaskManager = New TaskManager
Set .VersionManager = New VersionManager
.VersionManager.Create
Set Create = .Self
End With
End Function
</code></pre>
<p>Class (sub-class): <code>ExternalDataManager</code></p>
<pre><code>'@Version(2 )
'@Folder("App.ExternalData")
Option Explicit
'@PredeclaredId
' Copywrite (C) 2019 Ricardo Diaz
' This file is distributed under the GPL-3.0 license
' Obtain a copy of the GPL-3.0 license <http://opensource.org/licenses/GPL-3.0>
'
' Private Members
' ---------------
'
'
' Public Members
' --------------
'
'
' Private Methods
' ---------------
'
Private Function DoesQueryExist(ByVal QueryName As String) As Boolean
' Helper function to check if a query with the given name already exists
Dim evalQuery As WorkbookQuery
If (ThisWorkbook.Queries.Count = 0) Then
DoesQueryExist = False
Exit Function
End If
For Each evalQuery In ThisWorkbook.Queries
If (evalQuery.Name = QueryName) Then
DoesQueryExist = True
Exit Function
End If
Next
DoesQueryExist = False
End Function
Private Sub RefreshQueryWaitUntilFinish(ByVal currentConnection As WorkbookConnection)
Dim backgroundRefresh As Boolean
With currentConnection.OLEDBConnection
backgroundRefresh = .BackgroundQuery
.BackgroundQuery = False
.Refresh
.BackgroundQuery = backgroundRefresh
End With
End Sub
Private Sub LoadToWorksheetOnly(ByVal query As WorkbookQuery, ByVal loadSheet As Worksheet)
' The usual VBA code to create ListObject with a Query Table
' The interface is not new, but looks how simple is the connection string of Power Query:
' "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=" & query.Name
With loadSheet.ListObjects.Add(SourceType:=0, source:= _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=" & query.Name _
, destination:=Range("$A$1")).queryTable
.CommandType = xlCmdDefault
.CommandText = Array("SELECT * FROM [" & query.Name & "]")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = False
.Refresh BackgroundQuery:=False
End With
End Sub
Private Sub LoadToWorksheetAndModel(ByVal query As WorkbookQuery, ByVal currentSheet As Worksheet)
' Let's load the query to the Data Model
LoadToDataModel query
' Now we can load the data to the worksheet
With currentSheet.ListObjects.Add(SourceType:=4, source:=ActiveWorkbook. _
Connections("Query - " & query.Name), destination:=Range("$A$1")).TableObject
.RowNumbers = False
.PreserveFormatting = True
.PreserveColumnInfo = False
.AdjustColumnWidth = True
.RefreshStyle = 1
.ListObject.DisplayName = Replace(query.Name, " ", "_") & "_ListObject"
.Refresh
End With
End Sub
Private Sub LoadToDataModel(ByVal query As WorkbookQuery)
' This code loads the query to the Data Model
ThisWorkbook.Connections.Add2 "Query - " & query.Name, _
"Connection to the '" & query.Name & "' query in the workbook.", _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=" & query.Name _
, """" & query.Name & """", 6, True, False
End Sub
'@Ignore ProcedureNotUsed
Private Sub ReplaceStringInWorkBook(ByVal SearchFor As String, ByVal ReplaceWith As String)
Dim evalQuery As WorkbookQuery
For Each evalQuery In ThisWorkbook.Queries
ReplaceStringInQuery evalQuery.Name, SearchFor, ReplaceWith
Next evalQuery
End Sub
Private Sub ReplaceStringInQuery(ByVal QueryName As String, ByVal SearchFor As String, ByVal ReplaceWith As String)
Dim queryFormula As String
Dim queryResult As String
If DoesQueryExist(QueryName) = False Then Exit Sub
queryFormula = ThisWorkbook.Queries(QueryName).Formula
queryResult = Replace(queryFormula, SearchFor, ReplaceWith)
ThisWorkbook.Queries(QueryName).Formula = queryResult
End Sub
'@Ignore ProcedureNotUsed, AssignedByValParameter
Public Sub TransferQueries(Optional ByVal FromWorkbook As Workbook, Optional ByVal ToWorkbook As Workbook, Optional ByVal overwrite As Boolean = False)
Dim sourceQuery As WorkbookQuery
If FromWorkbook Is Nothing Then Set FromWorkbook = Application.ThisWorkbook
If ToWorkbook Is Nothing Then Set ToWorkbook = Application.ActiveWorkbook
If FromWorkbook.fullName = ToWorkbook.fullName Then Exit Sub
For Each sourceQuery In FromWorkbook.Queries
If QueryExists(sourceQuery.Name, ToWorkbook) Then
If overwrite Then
ToWorkbook.Queries(sourceQuery.Name).Delete
ToWorkbook.Queries.Add sourceQuery.Name, sourceQuery.Formula, sourceQuery.Description
End If
Else
ToWorkbook.Queries.Add sourceQuery.Name, sourceQuery.Formula, sourceQuery.Description
End If
Next
End Sub
' check if a given query exists in the given workbook
'@Ignore ProcedureNotUsed, AssignedByValParameter
Private Function QueryExists(ByVal EvalQueryName As String, Optional ByVal evalWorkbook As Workbook) As Boolean
If evalWorkbook Is Nothing Then Set evalWorkbook = Application.ActiveWorkbook
On Error Resume Next
QueryExists = CBool(Len(evalWorkbook.Queries(EvalQueryName).Name))
On Error GoTo 0
End Function
'
'
' Constructors
' ------------
'
'
' Class
' -----
'
' Private Sub Class_Initialize() : End Sub
'
' Enumerator
' Public Property Get NewEnum() As IUnknown : Attribute NewEnum.VB_UserMemId = -4 : Set NewEnum = pCollec.[_NewEnum] : End Property
'
' Public Methods
' --------------
'
Public Sub DisplayQueriesPane(ByVal Show As Boolean)
Application.CommandBars("Queries and Connections").visible = Show
Application.CommandBars("Queries and Connections").Width = 300
End Sub
'@Ignore ProcedureNotUsed
Public Sub ToggleQueriesPane()
Application.CommandBars("Queries and Connections").visible = _
Not (Application.CommandBars("Queries and Connections").visible)
Application.CommandBars("Queries and Connections").Width = 300
End Sub
Public Sub UpdateAll()
AppWorkbook.StateManager.DisplayStatusBarMessage True, , "(Actualizando todas las conexiones de datos)"
ThisWorkbook.RefreshAll
AppWorkbook.StateManager.DisplayStatusBarMessage True, , "(Actualización de todas las conexiones de datos finalizada)"
End Sub
Public Sub UpdateDataModel()
AppWorkbook.StateManager.DisplayStatusBarMessage True, , "(Inicializando modelo de datos)"
ThisWorkbook.Model.Initialize
AppWorkbook.StateManager.DisplayStatusBarMessage True, , "(Modelo de datos inicializado, actualizando)"
ThisWorkbook.Model.Refresh
AppWorkbook.StateManager.DisplayStatusBarMessage True, , "(Actualización del modelo de datos finalizada)"
End Sub
Public Sub Update(Optional ByVal QueryName As String)
Dim currentConnection As WorkbookConnection
For Each currentConnection In ThisWorkbook.Connections
Select Case QueryName <> vbNullString
Case True
If InStr(currentConnection.Name, QueryName) > 0 Then RefreshQueryWaitUntilFinish currentConnection
Case False
RefreshQueryWaitUntilFinish currentConnection
End Select
Next currentConnection
End Sub
'Refresh particular PowerPivot table
'@Ignore ProcedureNotUsed
Public Sub UpdatedPowerPivotTable(ByVal QueryName As String)
ThisWorkbook.Model.Initialize
ThisWorkbook.Connections(QueryName).Refresh
End Sub
' Credits from here under: https://gallery.technet.microsoft.com/office/VBA-to-automate-Power-956a52d1
' Adapted by Ricardo Diaz
Public Sub DeleteQuery(ByVal QueryName As String)
Dim evalQuery As WorkbookQuery
' We get from the first worksheets all the data in order to know which query to delete, including its worksheet, connection and Data Model is needed
Dim evalConnection As WorkbookConnection
Dim connectionString As String
For Each evalConnection In ThisWorkbook.Connections
If Not evalConnection.InModel Then
' This is not a Data Model conenction. We created this connection without the "Power Query - " prefix, to determine if we should delete it, let's check the connection string
If Not IsNull(evalConnection.OLEDBConnection) Then
' This is a OLEDB Connection. Good chance it is our connection. Let's check the connection string
connectionString = evalConnection.OLEDBConnection.Connection
Dim prefix As String
prefix = "Provider=Microsoft.Mashup.OleDb.1;"
If (Left$(connectionString, Len(prefix)) = prefix) And (0 < InStr(connectionString, "Location=" & QueryName)) Then
' This is our connection
' It starts with "Provider=Microsoft.Mashup.OleDb.1;" and contains "Location=" with our query name. This is our connection.
evalConnection.Delete
End If
End If
ElseIf (InStr(1, evalConnection.Name, "Query - " & QueryName)) Then
' We created this connection with "Power Query - " prefix, so we can this connection
evalConnection.Delete
End If
Next
If DoesQueryExist(QueryName) Then
' Deleting the query
Set evalQuery = ThisWorkbook.Queries(QueryName)
evalQuery.Delete
End If
End Sub
' In parameters if not used "" rather vbNullString adding the query raises an error
'@Ignore ProcedureNotUsed, EmptyStringLiteral
Public Sub CreateQuery(ByVal QueryName As String, ByVal codeM As String, Optional ByVal shouldLoadToDataModel As Boolean = False, Optional ByVal shouldLoadToWorksheet As Boolean = False, Optional ByVal queryDescription As String = "")
Dim evalQuery As WorkbookQuery
Dim currentSheet As Worksheet
If DoesQueryExist(QueryName) Then
DeleteQuery QueryName
End If
' The new interface to create a new Power Query query. It gets as an input the query name, codeM formula and description (if description is empty, th
Set evalQuery = ThisWorkbook.Queries.Add(QueryName, codeM, queryDescription)
If shouldLoadToWorksheet Then
' We add a new worksheet with the same name as the Power Query query
Set currentSheet = ThisWorkbook.Sheets.Add(After:=ActiveSheet)
currentSheet.Name = QueryName
If Not shouldLoadToDataModel Then
' Let's load to worksheet only
LoadToWorksheetOnly evalQuery, currentSheet
Else
' Let's load to worksheet and Data Model
LoadToWorksheetAndModel evalQuery, currentSheet
End If
ElseIf shouldLoadToDataModel Then
' No need to load to worksheet, only Data Model
LoadToDataModel evalQuery
End If
End Sub
Public Sub CreateNameParameterQueriesFromRange(ByVal EvalRange As Range)
Dim EvalCell As Range
For Each EvalCell In EvalRange.Cells
CreateNameParameterQueryFromCell EvalCell
Next EvalCell
End Sub
Public Sub CreateNameParameterQueryFromCell(ByVal CurrentCell As Range)
If Framework.Name.DoesNameExists(CurrentCell) = False Then Exit Sub
Dim QueryName As String
Dim baseCode As String
Dim wrapCode As String
Dim cellStyleType As Long
QueryName = CurrentCell.Name.Name
baseCode = "fnCargarParamExcel(""<cellName>"", <cellStyleType>) meta [IsParameterQuery=true, Type=""Number"", IsParameterQueryRequired=false]"
' Cells style types defined in Styles classes TODO: decouple class from constants
' 1 Text
' 2 Number
' 3 Date
Select Case True
Case InStr(LCase$(CurrentCell.style.Name), constStyleNameContainsDate)
cellStyleType = 3
Case InStr(LCase$(CurrentCell.style.Name), constStyleNameContainsYear), InStr(LCase$(CurrentCell.style.Name), constStyleNameContainsNumber), InStr(LCase$(CurrentCell.style.Name), constStyleNameContainsCurrency), InStr(LCase$(CurrentCell.style.Name), constStyleNameContainsMultiple), InStr(LCase$(CurrentCell.style.Name), constStyleNameContainsPercentage)
cellStyleType = 2
Case Else
cellStyleType = 1
End Select
'@Ignore AssignmentNotUsed
wrapCode = Replace(baseCode, "<cellName>", QueryName)
wrapCode = Replace(wrapCode, "<cellStyleType>", cellStyleType)
CreateQuery QueryName, wrapCode, False, False
End Sub
</code></pre>
<blockquote>
<p>Code has annotations from <a href="http://rubberduckvba.com/" rel="nofollow noreferrer">Rubberduck add-in</a></p>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T12:21:56.673",
"Id": "460902",
"Score": "2",
"body": "I'm not entirely sure what you want reviewed here; just your two questions, or the partial code you've posted? Regarding those questions in brief: 1) No there's no risk of memory leak here; VBA is a COM based language meaning it uses (strong) reference counting to keep objects alive. As long as the number of references to an object (variables pointing to it or `With` blocks) is non-zero, the object will hang around. The memory leak you're worried about here would be a circular reference, where a parent class holds a reference to a child class and the child holds a reference to the parent ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T12:33:58.217",
"Id": "460903",
"Score": "2",
"body": "... e.g `ExternalDataManager` has a reference to `App`. In that case, if you create a `New App` (+1 reference) then later it falls out of scope (-1 reference), the `App` object will not be destroyed since its child subclass still holds a reference to it, and the child won't be destroyed since the parent still holds a reference to it. You never pass `Me` to the subclasses so there should be no circular references. As for weak references, these are where you save a pointer and dereference it - not native VBA so you'd know if you were doing it! Q. 2) is more nuanced so I'll leave for reviewers"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T14:14:44.220",
"Id": "460907",
"Score": "1",
"body": "Thank you Greedo for your time and excellent explanations. I've noticed that sometimes I close Excel and the instance remains in the task manager. So maybe there is a class instance \"_alive_\" and I suspect that the circular reference may be happening. As the code is very extensive, don't know well how to debug it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T15:37:54.207",
"Id": "460912",
"Score": "1",
"body": "Hmmm, that strikes me as unusual. IIRC the VBA interpreter which is responsible for running code, managing memory etc is hosted by Excel, so Excel has permission to close it whenever it fancies (like hitting the square Stop button) - well behaved VBA code that doesn't do weird stuff with WinAPI should never prevent Excel closing, regardless of circular references. This sounds more like an issue with maybe Add Ins unloading or a `Workbook_BeforeClose` event. As for debugging, I'd recommend sprinkling `Debug.Print` in the `Class_Terminate` handlers to check things are being closed as expected."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T20:55:37.493",
"Id": "460930",
"Score": "0",
"body": "Awesome. Will follow your advice. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T23:25:49.430",
"Id": "461051",
"Score": "0",
"body": "About the circular references / memory leaks - Excel process not terminating properly is a hint. Have a UserForm designer opened in the VBE when you start running the code; the designer will close when execution starts, and ***should*** reopen again when execution ends. If it doesn't, then you have a memory leak, likely caused by some circular reference - and yes, that `WeakReference` stuff can help fix it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T18:17:04.430",
"Id": "461138",
"Score": "0",
"body": "@MathieuGuindon this is a great tip! thank you!"
}
] |
[
{
"body": "<blockquote>\n<pre><code>If Not DebugMode Then Resume CleanExit Else: Stop: Resume\n</code></pre>\n</blockquote>\n\n<p>Avoid using the <code>:</code> instruction separator in code. That's good for golfing up quick throw-away code in the <em>immediate pane</em>, not for production code.</p>\n\n<p>Statement syntax is fine when the <code>Then</code> part is a single statement - if it gets any more complex than that, block syntax should be used for clarity and maintainability (much easier to add statements in either conditional branch):</p>\n\n<pre><code>If Not DebugMode Then\n Resume CleanExit\nElse\n Stop\n Resume\nEnd If\n</code></pre>\n\n<p>It's not clear where <code>DebugMode</code> is defined, but it's clearly not a conditional compilation constant... which means the compiled code includes these debugging helpers. Not a big deal, but essentially the equivalent of shipping a release with the .pdb debug files.</p>\n\n<p>Consider defining <code>DebugMode</code> as a conditional compilation constant, and then the condition can be conditionally compiled, resulting in this code with <code>DebugMode=1</code>:</p>\n\n<pre><code> Stop\n Resume\n</code></pre>\n\n<p>...and this code with <code>DebugMode=0</code>:</p>\n\n<pre><code> Resume CleanExit\n</code></pre>\n\n<p>While the source code would look like this:</p>\n\n<pre><code>#If DebugMode = 0 Then\n Resume CleanExit\n#Else\n Stop\n Resume\n#End If\n</code></pre>\n\n<p>That way no opcodes will be generated for the dead code when <code>DebugMode</code> is toggled on or off, and no condition needs to be evaluated at run-time; static code analysis (Rubberduck) will not see the dead code either, so <a href=\"http://rubberduckvba.com/Inspections/Details/StopKeyword\" rel=\"noreferrer\">StopKeywordInspection</a> will only fire a result when <code>DebugMode = 1</code>, which can make a great heads-up that you're about to release code that includes instructions that were intended purely for debugging purposes.</p>\n\n<hr>\n\n<p>Avoid noisy banner comments - especially if they're just there to eat up screen estate:</p>\n\n<blockquote>\n<pre><code>'\n' Private Members\n' ---------------\n'\n\n'\n' Public Members\n' --------------\n'\n\n'\n' Private Methods\n' ---------------\n'\n</code></pre>\n</blockquote>\n\n<p>Group your members that way - and then the fact that private methods are private methods among other private methods will be self-evident; comments that plainly state the obvious, should be removed.</p>\n\n<blockquote>\n<pre><code>'@Version(1)\n'@Folder(\"App\")\n\nOption Explicit\n'@PredeclaredId\n</code></pre>\n</blockquote>\n\n<p>Consider grouping <em>all</em> module annotations together - either above or under <code>Option Explicit</code>... just not on <em>both</em> sides of it: the day [future] you (or a future maintainer) want(s) to add a <code>@ModuleDescription</code> annotation, if annotations are scattered everywhere then new annotations will just end up being added wherever they're added.</p>\n\n<pre><code>'@Folder(\"App\")\n'@PredeclaredId\nOption Explicit\n</code></pre>\n\n<p>If annotations are always consistently above <code>Option Explicit</code>, then the message to the maintainer is clear: we want annotations above <code>Option Explicit</code>, and a maintainer unfamiliar with the code would know to put any new ones where they belong.</p>\n\n<p>Note that <code>@Version</code> isn't a legal Rubberduck annotation, and very likely will never be one: version information (and copyright, authorship, license, diff history, etc.) does not belong in source code. It belongs in a source control repository. If your code isn't under source/version control, then what does a \"version\" mean anyway? I'd just remove it, it's a noisy comment that poses as a Rubberduck annotation, likely flagged by the <a href=\"http://rubberduckvba.com/Inspections/Details/IllegalAnnotation\" rel=\"noreferrer\">IllegalAnnotation</a> inspection.</p>\n\n<hr>\n\n<p><code>ReplaceStringInWorkBook</code> is iterating <code>ThisWorkbook.Queries</code>, which makes it very, very misleading. Since it's <code>Private</code>, I'm struggling to see what justifies <code>@IgnoreProcedureNotUsed</code> here - a private method with a misleading name that isn't invoked from anywhere, is dead code that needs to be removed.</p>\n\n<p>A <code>Public</code> procedure (wait why is it in the middle of a bunch of <code>Private</code> methods?) in a framework-type project might be legitimately unused, but the <code>AssignedByValParameter</code> is a real concern here:</p>\n\n<blockquote>\n<pre><code>'@Ignore ProcedureNotUsed, AssignedByValParameter\nPublic Sub TransferQueries(Optional ByVal FromWorkbook As Workbook, Optional ByVal ToWorkbook As Workbook, Optional ByVal overwrite As Boolean = False)\n</code></pre>\n</blockquote>\n\n<p>By assigning to the supplied parameter, the rest of the procedure loses the ability to tell what the supplied values were. Whether or not the rest of the procedure needs that knowledge makes no difference: the <code>Optional</code> parameters are suspicious and make the public API ambiguous and adds implicit behavior to the calling code... and implicit behavior in an API, while pretty common in the Excel object model, should be avoided like the plague in any modern piece of code. If you don't want to declare and assign local variables instead, consider making the parameters non-optional, and raising an error if <code>FromWorkbook</code> or <code>ToWorkbook</code> isn't specified. If you really need a method that does this with <code>ThisWorkbook</code>, consider exposing a <code>TransferQueriesFromThisWorkbook</code> method that makes it explicit, doesn't take a <code>FromWorkbook</code> argument, and simply passes <code>ThisWorkbook</code> as the first argument to <code>TransferQueries</code>.</p>\n\n<p>Note that <code>ThisWorkbook</code> is an identifier that refers to the host document's <code>ThisWorkbook</code> component, while <code>Application.ThisWorkbook</code> refers to the same, but then if you renamed <code>ThisWorkbook</code> to something else, the VBA project component would need to be updated, but <code>Application.ThisWorkbook</code> will always refer to the host document... except if you renamed <code>ThisWorkbook</code>, then <code>Application.ThisWorkbook</code> gets confusing - consider referring to the host workbook using the <code>ThisWorkbook</code> module identifier like you do for every single other module in your VBA project (and like you're doing everywhere else), because <code>Application.ThisWorkbook</code> is still going to be available through the <code>[_Global]</code> interface, which means renaming <code>ThisWorkbook</code> to <code>SomeWorkbook</code> will make <code>[Application.]ThisWorkbook</code> refer to <code>SomeWorkbook</code>, but as a member call against <code>Application</code>, won't get renamed by Rubberduck's <em>rename</em> refactoring.</p>\n\n<p>Consider ditching the \"Manager\" suffix - see <a href=\"https://blog.codinghorror.com/i-shall-call-it-somethingmanager/\" rel=\"noreferrer\">I Shall Call It... SomethingManager</a> on Jeff Atwood's <em>Coding Horror</em> blog for more information.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T18:41:32.893",
"Id": "461147",
"Score": "1",
"body": "I keep learning all the time. Thank you for these great reviews. Great reading about naming classes (in deed it's hard!)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T19:12:14.573",
"Id": "461157",
"Score": "0",
"body": "What's your opinion on the `Public Function AppWorkbook() As App`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T19:26:08.990",
"Id": "461158",
"Score": "0",
"body": "@RicardoDiaz If it's meant to be invoked often (for every access to its properties and encapsulated objects), then it shouldn't be a `Function` but a `Property Get` that merely returns an instance that lives as long as the host workbook does -- and I'd put the setup code in the `Workbook.Open` handler."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T19:27:02.667",
"Id": "461160",
"Score": "0",
"body": "Basically you want to avoid re-doing the construction work every time, especially if code can do `AppWorkbook.Something` and then `AppWorkbook.SomethingElse` right after."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T20:02:31.700",
"Id": "461162",
"Score": "0",
"body": "It's meant to hold the class initialized even if by any chance the code crashes. So if it loses state, it'd new it up again, and like that it'd be a \"single point of entry\" to call and initialize the class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T20:03:15.603",
"Id": "461163",
"Score": "0",
"body": "If I understand what you mean, would I need a class with a default instance and put there the property? Sorry if I'm not clear or I don't get what you mean. Bottom line is, what to do when the code crashes in an unhandled exception and you need that the the rest of the application keeps working? and the base of the application is a class... How do you recover from that? I had a sub to reinitialize the class, but then saw this function idea with an static variable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T20:04:14.283",
"Id": "461164",
"Score": "1",
"body": "If the code crashes with an unhandled error *in production*, you have a serious bug that you should be fixing instead of bending over backwards to keep the app running despite having serious issues :p I guess what I mean is, unhandled is unhandled, you don't know that the error is even recoverable - a hard crash is sometimes the best way to handle things."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T20:07:45.713",
"Id": "461165",
"Score": "1",
"body": "As for `Static` locals to hold instance state, IMO instance state should live at instance level. Besides \"static\" in VBA means something very different than it does in every single other programming language, so should be avoided ...but maybe that's just me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T09:27:13.600",
"Id": "461371",
"Score": "0",
"body": "Will take your advice Mathieu. Thabk you!"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T23:22:42.080",
"Id": "235532",
"ParentId": "235455",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "235532",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T02:31:20.637",
"Id": "235455",
"Score": "4",
"Tags": [
"object-oriented",
"vba",
"excel",
"rubberduck"
],
"Title": "Implementing a class hierarchy and instancing the base class in VBA"
}
|
235455
|
<p>We are given a vector of <code>std::pair<int, int></code>s, <code>start</code> int and <code>stop</code> int, and I need to extract the path out of it. </p>
<p>For instance:
given <code>start = 2</code>, <code>stop = 8</code> and list of <code>std::pair</code>s as <code>[(0, 5) (6,8), (5,6), (2,0)]</code>. I am ordering the vector into:
<code>[(2,0), (0,5), (5,6), (6,8)]</code>. Now I need to isolate the nodes to get the path as <code>[2,0,5,6,8]</code>. (i.e. <code>(2,0)</code> and <code>(0,5)</code> become <code>[2,0,5]</code> and so on).</p>
<p>I have the following code. It works but I feel that it is needlessly long. Any idea to make it more compact and "safe"?</p>
<pre><code>std::vector<int> get_pretty_path(const std::vector<std::pair<int,int>>& path_arcs, int s, int t){
std::vector<std::pair<int,int>> ordered_arcs;
assert(path_arcs.size() > 0);
int _s = s;
int _t = t;
bool l_flag= true;
std::vector<int> path;
while (l_flag) {
for(auto &arc: path_arcs){
if (arc.first == _s){
ordered_arcs.push_back(arc);
_s = arc.second;
if(arc.second == _t){
l_flag = false;
break;
}
}
}
}
if(ordered_arcs.size() == 1){
path.push_back(ordered_arcs.begin()->first);
path.push_back(ordered_arcs.begin()->second);
}
else if (ordered_arcs.size() == 2){
for (auto it = ordered_arcs.begin(); it != ordered_arcs.end()-1; ++it){
if (it->second == (it+1)->first){
path.push_back(it->first);
path.push_back(it->second);
}
if((it+1) == ordered_arcs.end()-1){
path.push_back((it+1)->second);
}
}
}
else{
for (auto it = ordered_arcs.begin(); it != ordered_arcs.end()-1; ++it){
if (it->second == (it+1)->first){
path.push_back(it->first);
}
if((it+1) == ordered_arcs.end()-1){
path.push_back((it+1)->first);
path.push_back((it+1)->second);
}
}
}
return path;
}
</code></pre>
<p>This function is called in the order of 10,000 times. I was wondering if it can be as fast as possible. The max length of <code>path_arcs</code> is around 7-8 but is is usually 4-5 or less.</p>
<p>Note that the paths are not weighted. There is only one path. I just need it to be ordered from <code>start</code> to <code>end</code>. Some more examples:</p>
<pre><code>input = [(2,0)] // given by the user
start = 2 // given by the user
stop = 0 // given by the user
output = [2,0] // This should be the output
input = [(1,4), (2,1)] // given by the user
start = 2 // given by the user
stop = 4 // given by the user
output = [2,1,4]
input = [(4,5),(7,4),(2,3),(5,2)] // given by the user
start = 7 // given by the user
stop = 3 // given by the user
output = [7,4,5,2,3]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T09:08:19.813",
"Id": "460896",
"Score": "2",
"body": "You should probably explain what the code is supposed to do. *... The path is [2,0,5,6,8].* Why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T12:14:09.050",
"Id": "460901",
"Score": "0",
"body": "Hello! The start is 2 and the end is 8. so we need to go through each of the arc in the list and get the path."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T14:12:49.427",
"Id": "460906",
"Score": "0",
"body": "The question is better now, but there are still some questions: if the arcs are edges in a (non-weighted?) graph, then which path do you want? Any path, or path with least amount of arcs? It would be great to have a runnable example (something we could paste in e.g. [wandbox.org](wandbox.org) to try out and play with it). Otherwise the question sounds good, just needs a bit more elaboration on the description."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T20:15:57.553",
"Id": "460927",
"Score": "0",
"body": "@Incomputable I added more info."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T22:30:26.763",
"Id": "460942",
"Score": "2",
"body": "_`(2,0)` and `(0,5)` become `[2,5]`_ - it should become `[2,0,5]`, shouldn't it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T22:57:07.023",
"Id": "460943",
"Score": "0",
"body": "@vnp. You are right"
}
] |
[
{
"body": "<p>The key is to create a mapping for the edges:</p>\n\n<pre><code>vector<int>\nget_pretty_path(const vector<pair<int,int>>& edges, int s, int t) {\n map<int,int> edgeMap = {begin(edges), end(edges)};\n vector<int> path;\n while (s != t) {\n path.push_back(s);\n s = edgeMap[s];\n }\n path.push_back(s);\n return path;\n}\nint main() {\n const vector<pair<int,int>> edges{{4, 5}, {7, 4}, {2, 3}, {5, 2}};\n const vector<int> path = get_pretty_path(edges, 7, 3);\n for (auto i : path) {\n cout << i << ' ';\n }\n cout << endl;\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>The code assumes <code>using namespace std;</code> which is sometimes frowned\nupon but which I think is fine for small examples. The code will bug\nout if you can't walk from <code>s</code> to <code>t</code> or if more than one edge starts\nat a given node index. If such situations can happen, you have to decide\nhow to best handle them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T07:09:40.107",
"Id": "460970",
"Score": "0",
"body": "Thanks! I just want to profile it against my implementation as this function is called lot of times."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-17T18:26:16.057",
"Id": "461660",
"Score": "0",
"body": "You should pass `edges` by *const* reference. But this is a clean solution. (I added some consts to your solution; feel free to flag my comment as \"no longer needed\")."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T03:51:47.030",
"Id": "235490",
"ParentId": "235461",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T05:33:36.273",
"Id": "235461",
"Score": "1",
"Tags": [
"c++"
],
"Title": "Getting a path from list of arcs in C++"
}
|
235461
|
<p>The case scenario:</p>
<p>A 2-D array is given:</p>
<pre><code>1 3 6 10 15
2 5 9 14 19
4 8 13 18 22
7 12 17 21 24
11 16 20 23 25
</code></pre>
<p>and its size <code>N</code> is given as 5.</p>
<p>The program should output it as </p>
<pre><code>1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
</code></pre>
<p>The code I wrote for this problem:</p>
<pre><code>#include <stdio.h>
void main()
{
int N = 5;
int pixel_array[5][5] = {
{1, 3, 6, 10, 15}, {2, 5, 9, 14, 19}, {4, 8, 13, 18, 22}, {7, 12, 17, 21, 24}, {11, 16, 20, 23, 25}
};
for (int row = 0; row < N; row++)
{
if (row < N - 1)
{
for (int temp_row = row, col = 0; temp_row >= 0; temp_row--, col++)
printf("%d ", pixel_array[temp_row][col]);
}
else
{
for (int col = 0; col < N; col++)
for (int temp_col = col, temp_row = N - 1; temp_col < N; temp_col++, temp_row--)
printf("%d ", pixel_array[temp_row][temp_col]);
}
}
}
</code></pre>
<p>The above code works fine and outputs the required result.</p>
<p>Some specific questions:</p>
<p>Since there are many <code>for</code> loops here -</p>
<ul>
<li>how can I decrease code length?</li>
<li>how can I improve the efficiency of this program?</li>
<li>Any other programming practices to be implemented?</li>
</ul>
<p>Any advice would help.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T07:02:04.653",
"Id": "460887",
"Score": "0",
"body": "Please remove the part with \"ascending order\". It Is irelevant And confusing because it only happens to produce ascending order in the specific case of input you provided (And some others but not for all inputs). The diagonal traversal Is the point here if i get it right..."
}
] |
[
{
"body": "<blockquote>\n <p>How can I decrease code length?</p>\n</blockquote>\n\n<p>You could split your big <code>for</code> loop into <code>2</code> smaller ones. The first one would print all diagonals up to the main one, and the other one the remaining ones. </p>\n\n<p>For instance, let's say there's a matrix like:</p>\n\n<pre><code>1 2 3\n4 5 6\n7 8 9\n</code></pre>\n\n<p>Then, your first loop would print <code>1 4 2 7 5 3</code> and the second one <code>8 6 9</code>. The code would look conciser and more readable too:</p>\n\n<pre><code>for (int i = 0; i < N; i++) {\n for (int j = 0; j <= i; j++) {\n printf(\"%d \", pixel_array[i - j][j]);\n }\n}\n\nfor (int j = 0; j < N - 1; j++) {\n for (int i = N - 1; i > j; i--) {\n printf(\"%d \", pixel_array[i][N - i + j]);\n }\n}\n</code></pre>\n\n<blockquote>\n <p>How can I improve the efficiency of this program?</p>\n</blockquote>\n\n<p>I don't think it's possible to make it more efficient than O(n²) as you have to go through all matrix elements to print them diagonally. So, the suggested solution is efficient enough.</p>\n\n<blockquote>\n <p>Any other programming practices to be implemented</p>\n</blockquote>\n\n<p>Rather than using an <code>int</code> type for defining a size of your array, you could use <code>uint32_t</code> (or <code>uint16_t</code> or <code>uint64_t</code> - it depends on your requirements). Your size cannot be negative, anyways. So, change <code>int N = 5;</code> to <code>const uint32_t N = 5</code>. </p>\n\n<p>Rename your <code>array</code> to <code>squareMatrix</code> because you're actually dealing with square matrices in your app. </p>\n\n<p>Also, create a method out of your algorithm block - but I'll leave it up to you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T13:24:56.787",
"Id": "461112",
"Score": "0",
"body": "`size_t` is the usual recommended type for object counts..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T19:56:28.087",
"Id": "235522",
"ParentId": "235462",
"Score": "4"
}
},
{
"body": "<p>Firstly, <code>main()</code> must return an <code>int</code>:</p>\n\n<pre><code>int main(void)\n</code></pre>\n\n<p>We can make the array initialization easier to read with judicious use of whitespace:</p>\n\n<pre><code>static const int N = 5;\nconst int pixel_array[5][5] =\n {\n {1, 3, 6, 10, 15},\n {2, 5, 9, 14, 19},\n {4, 8, 13, 18, 22},\n {7, 12, 17, 21, 24},\n {11, 16, 20, 23, 25}\n };\n</code></pre>\n\n<p>Instead of the <code>if</code>/<code>else</code> inside the loop, notice that the <code>else</code> is only taken on the last iteration, and move that out:</p>\n\n<blockquote>\n<pre><code>for (int row = 0; row < N; row++)\n{\n if (row < N - 1)\n {\n for (int temp_row = row, col = 0; temp_row >= 0; temp_row--, col++)\n printf(\"%d \", pixel_array[temp_row][col]);\n }\n else\n {\n for (int col = 0; col < N; col++)\n for (int temp_col = col, temp_row = N - 1; temp_col < N; temp_col++, temp_row--)\n printf(\"%d \", pixel_array[temp_row][temp_col]);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>becomes</p>\n\n<pre><code>for (int row = 0; row < N - 1; row++)\n{\n for (int temp_row = row, col = 0; temp_row >= 0; temp_row--, col++)\n printf(\"%d \", pixel_array[temp_row][col]);\n}\n\n/* row == N - 1 */\nfor (int col = 0; col < N; col++)\n for (int temp_col = col, temp_row = N - 1; temp_col < N; temp_col++, temp_row--)\n printf(\"%d \", pixel_array[temp_row][temp_col]);\n</code></pre>\n\n<p>We can move the printing of the main diagonal to the first loop, so that its condition is <code>row < N</code> and remove it from the second loop by starting <code>col</code> at <code>1</code>. Also observe that <code>temp_row</code> and <code>temp_col</code> can always be derived from <code>row</code> and <code>column</code>:</p>\n\n<pre><code>for (int row = 0; row < N; ++row) {\n for (int col = 0; col <= row; ++col) {\n printf(\"%d \", pixel_array[row-col][col]);\n }\n}\n\nfor (int col = 1; col < N; ++col) {\n for (int row = N - 1; row >= col; --row) {\n printf(\"%d \", pixel_array[row][col+N-1-row]);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T13:49:56.153",
"Id": "235558",
"ParentId": "235462",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T06:03:57.203",
"Id": "235462",
"Score": "8",
"Tags": [
"performance",
"beginner",
"c",
"array"
],
"Title": "Printing a 2-D array diagonally"
}
|
235462
|
<h1>The Application</h1>
<p>I have an application in testing that runs off of an MS SQL Server database. The app allows users to authenticate using Windows authentication (that is, using the Windows username the user is currently logged in with), but the need was discovered for the app to a have a built-in, independent method of authentication.</p>
<p>Rather than handle the delicate task of storing usernames and passwords in the database- and considering that the database is the thing that needs securing anyway, so keeping the credentials there would defeat the purpose- I came up with the following solution:</p>
<p>Use the built-in <a href="https://docs.microsoft.com/en-us/sql/relational-databases/security/authentication-access/create-a-database-user?view=sql-server-ver15" rel="nofollow noreferrer">users</a> functionality in SQL Server to store the users for my application.</p>
<h1>The Code</h1>
<p>To this end, I configured the database to be <a href="https://docs.microsoft.com/en-us/sql/relational-databases/databases/contained-databases?view=sql-server-ver15" rel="nofollow noreferrer">partially contained</a>, so database users can be used without having to link them to a server-level login.</p>
<p>I then created the following class:</p>
<pre><code>Imports System.Data.SqlClient
Public Module SqlServerAuthenticator
Public Sub CreateUser(cmd As SqlCommand, UserName As String, Password As String, UserRole As String)
UserName = QuoteUserName(cmd, UserName)
Password = QuotePassword(cmd, Password)
cmd.CommandText = $"CREATE USER {UserName} WITH PASSWORD = {Password}"
cmd.ExecuteNonQuery()
If Not UserRole.IsNullOrEmpty Then
cmd.CommandText = $"ALTER ROLE {UserRole} ADD MEMBER {UserName}"
cmd.ExecuteNonQuery()
End If
End Sub
Public Sub DropUser(cmd As SqlCommand, UserName As String)
UserName = QuoteUserName(cmd, UserName)
cmd.CommandText = $"DROP USER {UserName}"
cmd.ExecuteNonQuery()
End Sub
Public Sub RenameUser(cmd As SqlCommand, CurrentUserName As String, NewUserName As String)
CurrentUserName = QuoteUserName(cmd, CurrentUserName)
NewUserName = QuoteUserName(cmd, NewUserName)
cmd.CommandText = $"ALTER USER {CurrentUserName} WITH NAME = {NewUserName}"
cmd.ExecuteNonQuery()
End Sub
Public Sub SetUserPassword(cmd As SqlCommand, UserName As String, Password As String)
UserName = QuoteUserName(cmd, UserName)
Password = QuotePassword(cmd, Password)
cmd.CommandText = $"ALTER USER {UserName} WITH PASSWORD = {Password}"
cmd.ExecuteNonQuery()
End Sub
Public Function ValidateUserName(UserName As String) As Boolean
If UserName.IsNullOrWhileSpace Then Return False
If UserName.IndexOfAny(IllegalCharacters) > -1 Then Return False
If ReservedNames.Contains(UserName, StringComparer.OrdinalIgnoreCase) Then Return False
Return True
End Function
Private Function QuoteUserName(cmd As SqlCommand, UserName As String) As String
cmd.CommandText = "SELECT QUOTENAME(@UserName)"
Dim param = cmd.Parameters.AddWithValue("@UserName", UserName)
UserName = cmd.ExecuteScalar
cmd.Parameters.Remove(param)
Return UserName
End Function
Private Function QuotePassword(cmd As SqlCommand, Password As String) As String
cmd.CommandText = "SELECT QUOTENAME(@Password, '''')"
Dim param = cmd.Parameters.AddWithValue("@Password", Password)
Password = cmd.ExecuteScalar
cmd.Parameters.Remove(param)
Return Password
End Function
Public ReadOnly IllegalCharacters() As Char = "\/*%_^#@[](){};"
Public ReadOnly ReservedNames() As String = {"sa",
"public",
"sa",
"public",
"sysadmin",
"securityadmin",
"serveradmin",
"setupadmin",
"processadmin",
"diskadmin",
"dbcreator",
"bulkadmin",
"ADD",
"ALL",
"ALTER",
"AND",
"ANY",
"AS",
"ASC",
"AUTHORIZATION",
"BACKUP",
"BEGIN",
"BETWEEN",
"BREAK",
"BROWSE",
"BULK",
"BY",
"CASCADE",
"CASE",
"CHECK",
"CHECKPOINT",
"CLOSE",
"CLUSTERED",
"COALESCE",
"COLLATE",
"COLUMN",
"COMMIT",
"COMPUTE",
"CONSTRAINT",
"CONTAINS",
"CONTAINSTABLE",
"CONTINUE",
"CONVERT",
"CREATE",
"CROSS",
"CURRENT",
"CURRENT_DATE",
"CURRENT_TIME",
"CURRENT_TIMESTAMP",
"CURRENT_USER",
"CURSOR",
"DATABASE",
"DBCC",
"DEALLOCATE",
"DECLARE",
"DEFAULT",
"DELETE",
"DENY",
"DESC",
"DISK",
"DISTINCT",
"DISTRIBUTED",
"DOUBLE",
"DROP",
"DUMP",
"ELSE",
"END",
"ERRLVL",
"ESCAPE",
"EXCEPT",
"EXEC",
"EXECUTE",
"EXISTS",
"EXIT",
"EXTERNAL",
"FETCH",
"FILE",
"FILLFACTOR",
"FOR",
"FOREIGN",
"FREETEXT",
"FREETEXTTABLE",
"FROM",
"FULL",
"FUNCTION",
"GOTO",
"GRANT",
"GROUP",
"HAVING",
"HOLDLOCK",
"IDENTITY",
"IDENTITY_INSERT",
"IDENTITYCOL",
"IF",
"IN",
"INDEX",
"INNER",
"INSERT",
"INTERSECT",
"INTO",
"IS",
"JOIN",
"KEY",
"KILL",
"LEFT",
"LIKE",
"LINENO",
"LOAD",
"MERGE",
"NATIONAL",
"NOCHECK",
"NONCLUSTERED",
"NOT",
"NULL",
"NULLIF",
"OF",
"OFF",
"OFFSETS",
"ON",
"OPEN",
"OPENDATASOURCE",
"OPENQUERY",
"OPENROWSET",
"OPENXML",
"OPTION",
"OR",
"ORDER",
"OUTER",
"OVER",
"PERCENT",
"PIVOT",
"PLAN",
"PRECISION",
"PRIMARY",
"PRINT",
"PROC",
"PROCEDURE",
"PUBLIC",
"RAISERROR",
"READ",
"READTEXT",
"RECONFIGURE",
"REFERENCES",
"REPLICATION",
"RESTORE",
"RESTRICT",
"RETURN",
"REVERT",
"REVOKE",
"RIGHT",
"ROLLBACK",
"ROWCOUNT",
"ROWGUIDCOL",
"RULE",
"SAVE",
"SCHEMA",
"SECURITYAUDIT",
"SELECT",
"SEMANTICKEYPHRASETABLE",
"SEMANTICSIMILARITYDETAILSTABLE",
"SEMANTICSIMILARITYTABLE",
"SESSION_USER",
"SET",
"SETUSER",
"SHUTDOWN",
"SOME",
"STATISTICS",
"SYSTEM_USER",
"TABLE",
"TABLESAMPLE",
"TEXTSIZE",
"THEN",
"TO",
"TOP",
"TRAN",
"TRANSACTION",
"TRIGGER",
"TRUNCATE",
"TRY_CONVERT",
"TSEQUAL",
"UNION",
"UNIQUE",
"UNPIVOT",
"UPDATE",
"UPDATETEXT",
"USE",
"USER",
"VALUES",
"VARYING",
"VIEW",
"WAITFOR",
"WHEN",
"WHERE",
"WHILE",
"WITH",
"WITHIN GROUP",
"WRITETEXT",
"ABSOLUTE",
"ACTION",
"ADA",
"ALLOCATE",
"ARE",
"ASSERTION",
"AT",
"AVG",
"BIT",
"BIT_LENGTH",
"BOTH",
"CASCADED",
"CAST",
"CATALOG",
"CHAR",
"CHAR_LENGTH",
"CHARACTER",
"CHARACTER_LENGTH",
"COLLATION",
"CONNECT",
"CONNECTION",
"CONSTRAINTS",
"CORRESPONDING",
"COUNT",
"DATE",
"DAY",
"DEC",
"DECIMAL",
"DEFERRABLE",
"DEFERRED",
"DESCRIBE",
"DESCRIPTOR",
"DIAGNOSTICS",
"DISCONNECT",
"DOMAIN",
"END-EXEC",
"EXCEPTION",
"EXTRACT",
"FALSE",
"FIRST",
"FLOAT",
"FORTRAN",
"FOUND",
"GET",
"GLOBAL",
"GO",
"HOUR",
"IMMEDIATE",
"INCLUDE",
"INDICATOR",
"INITIALLY",
"INPUT",
"INSENSITIVE",
"INT",
"INTEGER",
"INTERVAL",
"ISOLATION",
"LANGUAGE",
"LAST",
"LEADING",
"LEVEL",
"LOCAL",
"LOWER",
"MATCH",
"MAX",
"MIN",
"MINUTE",
"MODULE",
"MONTH",
"NAMES",
"NATURAL",
"NCHAR",
"NEXT",
"NO",
"NONE",
"NUMERIC",
"OCTET_LENGTH",
"ONLY",
"OUTPUT",
"OVERLAPS",
"PAD",
"PARTIAL",
"PASCAL",
"POSITION",
"PREPARE",
"PRESERVE",
"PRIOR",
"PRIVILEGES",
"REAL",
"RELATIVE",
"ROWS",
"SCROLL",
"SECOND",
"SECTION",
"SESSION",
"SIZE",
"SMALLINT",
"SPACE",
"SQL",
"SQLCA",
"SQLCODE",
"SQLERROR",
"SQLSTATE",
"SQLWARNING",
"SUBSTRING",
"SUM",
"TEMPORARY",
"TIME",
"TIMESTAMP",
"TIMEZONE_HOUR",
"TIMEZONE_MINUTE",
"TRAILING",
"TRANSLATE",
"TRANSLATION",
"TRIM",
"TRUE",
"UNKNOWN",
"UPPER",
"USAGE",
"USING",
"VALUE",
"VARCHAR",
"WHENEVER",
"WORK",
"WRITE",
"YEAR",
"ZONE",
"ADMIN",
"AFTER",
"AGGREGATE",
"ALIAS",
"ARRAY",
"ASENSITIVE",
"ASYMMETRIC",
"ATOMIC",
"BEFORE",
"BINARY",
"BLOB",
"BOOLEAN",
"BREADTH",
"CALL",
"CALLED",
"CARDINALITY",
"CLASS",
"CLOB",
"COLLECT",
"COMPLETION",
"CONDITION",
"CONSTRUCTOR",
"CORR",
"COVAR_POP",
"COVAR_SAMP",
"CUBE",
"CUME_DIST",
"CURRENT_CATALOG",
"CURRENT_DEFAULT_TRANSFORM_GROUP",
"CURRENT_PATH",
"CURRENT_ROLE",
"CURRENT_SCHEMA",
"CURRENT_TRANSFORM_GROUP_FOR_TYPE",
"CYCLE",
"DATA",
"DEPTH",
"DEREF",
"DESTROY",
"DESTRUCTOR",
"DETERMINISTIC",
"DICTIONARY",
"DYNAMIC",
"EACH",
"ELEMENT",
"EQUALS",
"EVERY",
"FILTER",
"FREE",
"FULLTEXTTABLE",
"FUSION",
"GENERAL",
"GROUPING",
"HOLD",
"HOST",
"IGNORE",
"INITIALIZE",
"INOUT",
"INTERSECTION",
"ITERATE",
"LARGE",
"LATERAL",
"LESS",
"LIKE_REGEX",
"LIMIT",
"LN",
"LOCALTIME",
"LOCALTIMESTAMP",
"LOCATOR",
"MAP",
"MEMBER",
"METHOD",
"MOD",
"MODIFIES",
"MODIFY",
"MULTISET",
"NCLOB",
"NEW",
"NORMALIZE",
"OBJECT",
"OCCURRENCES_REGEX",
"OLD",
"OPERATION",
"ORDINALITY",
"OUT",
"OVERLAY",
"PARAMETER",
"PARAMETERS",
"PARTITION",
"PATH",
"POSTFIX",
"PREFIX",
"PREORDER",
"PERCENT_RANK",
"PERCENTILE_CONT",
"PERCENTILE_DISC",
"POSITION_REGEX",
"RANGE",
"READS",
"RECURSIVE",
"REF",
"REFERENCING",
"REGR_AVGX",
"REGR_AVGY",
"REGR_COUNT",
"REGR_INTERCEPT",
"REGR_R2",
"REGR_SLOPE",
"REGR_SXX",
"REGR_SXY",
"REGR_SYY",
"RELEASE",
"RESULT",
"RETURNS",
"ROLE",
"ROLLUP",
"ROUTINE",
"ROW",
"SAVEPOINT",
"SCOPE",
"SEARCH",
"SENSITIVE",
"SEQUENCE",
"SETS",
"SIMILAR",
"SPECIFIC",
"SPECIFICTYPE",
"SQLEXCEPTION",
"START",
"STATE",
"STATEMENT",
"STATIC",
"STDDEV_POP",
"STDDEV_SAMP",
"STRUCTURE",
"SUBMULTISET",
"SUBSTRING_REGEX",
"SYMMETRIC",
"SYSTEM",
"TERMINATE",
"THAN",
"TRANSLATE_REGEX",
"TREAT",
"UESCAPE",
"UNDER",
"UNNEST",
"VAR_POP",
"VAR_SAMP",
"VARIABLE",
"WIDTH_BUCKET",
"WITHOUT",
"WINDOW",
"WITHIN",
"XMLAGG",
"XMLATTRIBUTES",
"XMLBINARY",
"XMLCAST",
"XMLCOMMENT",
"XMLCONCAT",
"XMLDOCUMENT",
"XMLELEMENT",
"XMLEXISTS",
"XMLFOREST",
"XMLITERATE",
"XMLNAMESPACES",
"XMLPARSE",
"XMLPI",
"XMLQUERY",
"XMLSERIALIZE",
"XMLTABLE",
"XMLTEXT",
"XMLVALIDATE"}
End Module
</code></pre>
<p>The purpose of the class is to handle the actual creation, removal and changing of user accounts in the database.</p>
<p>Each of the main methods takes a blank <code>SqlCommand</code> with <code>Connection</code> (and potentially <code>Transaction</code>) already set by the calling code.</p>
<p>Before <code>CreateUser</code> or <code>RenameUser</code> is called, it is expected that the caller has already called <code>ValidateUserName</code> and has insured that no user by that name already exists.</p>
<p><code>IllegalCharacters</code> was filled with any special character I could think of that I wouldn't think would be sensibly used in a username. <code>ReservedNames</code> was built from the MSDN page on <a href="https://docs.microsoft.com/en-us/sql/t-sql/language-elements/reserved-keywords-transact-sql?view=sql-server-ver15" rel="nofollow noreferrer">Reserved Keywords</a> as well as <a href="https://dba.stackexchange.com/a/173148/184962">this answer</a> from a question on the dba stack exchange.</p>
<h1>What I'm Worrying About & What I'm Not</h1>
<p>The only way I could find to manage these users was by using dynamic SQL, so naturally I'm pretty concerned about SQL injection. I run each username and password through <code>QUOTENAME</code> to try and mitigate that, and I'm hoping that that, combined with <code>ValidateUserName</code> should be enough, but if anyone can think of a hole in this, let me know. Also, if anyone can tell me a way to do this without having to resort to dynamic SQL, I'm all ears.</p>
<p>I'm not particularly worried about the fact that I'm passing the passwords around in memory in plain text. The password for the currently logged in user (when not using Windows authentication) is stored as a <code>SecureString</code>, but since I need plain text passwords eventually to construct the dynamic SQL, I kept all of this component plain text. If anyone can tell me a way to create these users using <code>SecureString</code>, or using some other more-secure method, I'd be happy to hear it.</p>
<p>For this particular question, I'm also not overly-worried about the permissions that these users obviously need to have within the database itself in order to be able to create/drop/rename other users. I'll hear you out- particularly if you have a usable suggestion- but I'm not very concerned at the moment.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T19:29:51.827",
"Id": "462253",
"Score": "0",
"body": "This is doing it the hard way. Instead, create (one or more) Active Directory Groups, and give the groups permission to the database and database objects. Then, new users just have to be added to the group(s), and terminated users removed from the group(s). Typically, you could have a read-only AD group, an application admin group, maybe a power user group, but that's all dependent upon the roles within the app."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T00:58:00.787",
"Id": "462287",
"Score": "0",
"body": "@HardCode That assumes that you have an active directory to begin with. Plus it would require a separate interface for managing users outside of the application (the AD admin screen). That is unless I make a management interface inside the app, in which case it's the same as what I already have except instead of calling SQL to create/manage users I would be calling the Active Directory to do the same."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T15:47:32.020",
"Id": "462378",
"Score": "0",
"body": "Yes. You stated Windows logins, and of course user access would be managed by Active Directory. But you wouldn't need to add *user* domain accounts to SQL Server, only the static groups."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T17:19:54.050",
"Id": "462395",
"Score": "0",
"body": "@HardCode Right, I see what your saying. Normally I do manage SQL access by using an Active Directory with a group, and this app can do that. But there are some environments (poorly managed workgroups) where I can't take advantage of an AD. That's what the the code in this question is for: providing a method of authentication that doesn't reply on Windows."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T06:05:20.320",
"Id": "235463",
"Score": "3",
"Tags": [
".net",
"security",
"sql-server",
"authentication",
"vb.net"
],
"Title": "Creating SQL Server Database Users Dynamically from User Input"
}
|
235463
|
<p>First off, not the greatest with jQuery but know enough to get by. I have a custom script for our WordPress site that ties in with a main plugin we use. I have a JSFiddle that gives the gist of what it does as well as the staging site. My main goal right now is to improve upon the code. The main thing is trim the fat and reduce the wait for it to properly display the page.</p>
<p>This checks if one of the options are pre-checked first. If so, display the correct section and hide the rest. The second is when changing options to do the same but also uncheck any options that could have been selected under the "Stains" section.</p>
<pre><code>jQuery(function ($) {
// Create Variables
var stains = $(".stains-container");
var radio_buttons = $("input[name='tmcp_radio_0'], input.wood-class");
// Check if Oak is checked
var oak_checked = $(":radio[value^=Oak_], :radio[value*=Oak_], :radio[value^=Barnwood_]").is(":checked");
var $oakchecked = $("input.b-maple-stains, input.cherry-stains, input.qswo-stains, input.h-maple-stains, input.hickory-stains, input.walnut-stains");
var $oakactive = $(".b-maple-stains-div li, .cherry-stains-div li, .qswo-stains-div li, .h-maple-stains-div li, .hickory-stains-div li, .walnut-stains-div li");
var $oakactivehide = $(".b-maple-stains-div, .cherry-stains-div, .qswo-stains-div, .h-maple-stains-div, .hickory-stains-div, .walnut-stains-div");
// Check if B. Maple is checked
var bmaple_checked = $(":radio[value^=Brown], :radio[value^=Wormy]").is(":checked");
var $bmaplechecked = $("input.oak-stains, input.cherry-stains, input.qswo-stains, input.h-maple-stains, input.hickory-stains, input.walnut-stains");
var $bmapleactive = $(".oak-stains-div li, .cherry-stains-div li, .qswo-stains-div li, .h-maple-stains-div li, .hickory-stains-div li, .walnut-stains-div li");
var $bmapleactivehide = $(".oak-stains-div, .cherry-stains-div, .qswo-stains-div, .h-maple-stains-div, .hickory-stains-div, .walnut-stains-div");
// Check if Cherry is checked
var cherry_checked = $(":radio[value^=Cherry_], :radio[value*=Cherry_]").is(":checked");
var $cherrychecked = $("input.oak-stains, input.b-maple-stains, input.qswo-stains, input.h-maple-stains, input.hickory-stains, input.walnut-stains");
var $cherryactive = $(".oak-stains-div li, .b-maple-stains-div li, .qswo-stains-div li, .h-maple-stains-div li, .hickory-stains-div li, .walnut-stains-div li");
var $cherryactivehide = $(".oak-stains-div, .b-maple-stains-div, .qswo-stains-div, .h-maple-stains-div, .hickory-stains-div, .walnut-stains-div");
// Check if QSWO is checked
var qswo_checked = $(":radio[value^=Quartersawn]").is(":checked");
var $qswochecked = $("input.oak-stains, input.b-maple-stains, input.cherry-stains, input.h-maple-stains, input.hickory-stains, input.walnut-stains");
var $qswoactive = $(".oak-stains-div li, .b-maple-stains-div li, .cherry-stains-div li, .h-maple-stains-div li, .hickory-stains-div li, .walnut-stains-div li");
var $qswoactivehide = $(".oak-stains-div, .b-maple-stains-div, .cherry-stains-div, .h-maple-stains-div, .hickory-stains-div, .walnut-stains-div");
// Check if H. Maple is checked
var hmaple_checked = $(":radio[value^=Hard], :radio[value*=Hard]").is(":checked");
var $hmaplechecked = $("input.oak-stains, input.b-maple-stains, input.cherry-stains, input.qswo-stains, input.hickory-stains, input.walnut-stains");
var $hmapleactive = $(".oak-stains-div li, .b-maple-stains-div li, .cherry-stains-div li, .qswo-stains-div li, .hickory-stains-div li, .walnut-stains-div li");
var $hmapleactivehide = $(".oak-stains-div, .b-maple-stains-div, .qswo-stains-div, .cherry-stains-div, .hickory-stains-div, .walnut-stains-div");
// Check if Hickory is checked
var hickory_checked = $(":radio[value^=Hickory_], :radio[value*=Hickory_]").is(":checked");
var $hickorychecked = $("input.oak-stains, input.b-maple-stains, input.cherry-stains, input.qswo-stains, input.h-maple-stains, input.walnut-stains");
var $hickoryactive = $(".oak-stains-div li, .b-maple-stains-div li, .cherry-stains-div li, .qswo-stains-div li, .h-maple-stains-div li, .walnut-stains-div li");
var $hickoryactivehide = $(".oak-stains-div, .b-maple-stains-div, .qswo-stains-div, .h-maple-stains-div, .cherry-stains-div, .walnut-stains-div");
// Check if Walnut is checked
var walnut_checked = $(":radio[value^=Walnut_], :radio[value*=Walnut_]").is(":checked");
var $walnutchecked = $("input.oak-stains, input.b-maple-stains, input.cherry-stains, input.qswo-stains, input.h-maple-stains, input.hickory-stains");
var $walnutactive = $(".oak-stains-div li, .b-maple-stains-div li, .cherry-stains-div li, .qswo-stains-div li, .h-maple-stains-div li, .hickory-stains-div li");
var $walnutactivehide = $(".oak-stains-div, .b-maple-stains-div, .qswo-stains-div, .h-maple-stains-div, .cherry-stains-div, .hickory-stains-div");
// Hide stains unless a wood is chosen
if(oak_checked) {
$(".oak-stains-div").show();
$oakactivehide.hide();
$oakchecked.prop('checked', false);
$oakactive.removeClass( "tc-active" );
} else if(bmaple_checked) {
$(".b-maple-stains-div").show();
$bmapleactivehide.hide();
$bmaplechecked.prop('checked', false);
$bmapleactive.removeClass( "tc-active" );
} else if(cherry_checked) {
$(".cherry-stains-div").show();
$cherryactivehide.hide();
$cherrychecked.prop('checked', false);
$cherryactive.removeClass( "tc-active" );
} else if(qswo_checked) {
$(".qswo-stains-div").show();
$qswoactivehide.hide();
$qswochecked.prop('checked', false);
$qswoactive.removeClass( "tc-active" );
} else if(hmaple_checked) {
$(".h-maple-stains-div").show();
$hmapleactivehide.hide();
$hmaplechecked.prop('checked', false);
$hmapleactive.removeClass( "tc-active" );
} else if(hickory_checked) {
$(".hickory-stains-div").show();
$hickoryactivehide.hide();
$hickorychecked.prop('checked', false);
$hickoryactive.removeClass( "tc-active" );
} else if(walnut_checked) {
$(".walnut-stains-div").show();
$walnutactivehide.hide();
$walnutchecked.prop('checked', false);
$walnutactive.removeClass( "tc-active" );
} else if(radio_buttons.is(":not(:checked)")) {
$(".stains-container").hide();
}
// Check if Oak is selected or pre-selected
radio_buttons.on('change', function(e) {
var oakRegExp = /^Oak_\d$/;
var reclaimedOakRegExp = /^Reclaimed Oak_\d$/;
var barnwoodOakRegExp = /^Reclaimed Barnwood_\d$/;
var rstHckOakRegExp = /^Rustic Hickory Twigs and Oak_\d$/;
if (oakRegExp.test(e.target.value) || reclaimedOakRegExp.test(e.target.value) || barnwoodOakRegExp.test(e.target.value) || rstHckOakRegExp.test(e.target.value)) {
stains.show();
$(".oak-stains-div").show();
$oakchecked.prop('checked', false);
$oakactive.removeClass("tc-active");
} else {
$(".oak-stains-div").hide();
}
});
// Check if B. Maple is selected or pre-selected
radio_buttons.on('change', function(e) {
var brownMapleRegExp = /^Brown Maple_\d$/;
var wormyMapleRegExp = /^Wormy Maple_\d$/;
if (brownMapleRegExp.test(e.target.value) || wormyMapleRegExp.test(e.target.value)) {
stains.show();
$(".b-maple-stains-div").show();
$bmaplechecked.prop('checked', false);
$bmapleactive.removeClass("tc-active");
} else {
$(".b-maple-stains-div").hide();
}
});
// Check if Cherry is selected or pre-selected
radio_buttons.on('change', function(e) {
var cherryRegExp = /^Cherry_\d$/;
var rusticCherryRegExp = /^Rustic Cherry_\d$/;
var rusticHickoryCherryRegExp = /^Rustic Hickory Twigs and Cherry_\d$/;
if (cherryRegExp.test(e.target.value) || rusticCherryRegExp.test(e.target.value) || rusticHickoryCherryRegExp.test(e.target.value)) {
stains.show();
$(".cherry-stains-div").show();
$cherrychecked.prop('checked', false);
$cherryactive.removeClass( "tc-active" );
} else {
$(".cherry-stains-div").hide();
}
});
// Check if QSWO is selected or pre-selected
radio_buttons.on('change', function(e) {
var qswoRegExp = /^Quartersawn White Oak_\d$/;
if (qswoRegExp.test(e.target.value)) {
stains.show();
$(".qswo-stains-div").show();
$qswochecked.prop('checked', false);
$qswoactive.removeClass( "tc-active" );
} else {
$(".qswo-stains-div").hide();
}
});
// Check if Hard Maple is selected or pre-selected
radio_buttons.on('change', function(e) {
var hMapleRegExp = /^Hard Maple_\d$/;
var rusticHickoryhMapleRegExp = /^Rustic Hickory Twigs and Hard Maple_\d$/;
if (hMapleRegExp.test(e.target.value) || rusticHickoryhMapleRegExp.test(e.target.value)) {
stains.show();
$(".h-maple-stains-div").show();
$hmaplechecked.prop('checked', false);
$hmapleactive.removeClass( "tc-active" );
} else {
$(".h-maple-stains-div").hide();
}
});
// Check if Hickory is selected or pre-selected
radio_buttons.on('change', function(e) {
var hickoryRegExp = /^Hickory_\d$/;
var rusticHickoryTwigsHickoryRegExp = /^Rustic Hickory Twigs and Hickory_\d$/;
if (hickoryRegExp.test(e.target.value) || rusticHickoryTwigsHickoryRegExp.test(e.target.value)) {
stains.show();
$(".hickory-stains-div").show();
$hickorychecked.prop('checked', false);
$hickoryactive.removeClass( "tc-active" );
} else {
$(".hickory-stains-div").hide();
}
});
// Check if Walnut is selected or pre-selected
radio_buttons.on('change', function(e) {
var walnutRegExp = /^Walnut_\d$/;
var rusticWalnutRegExp = /^Rustic Walnut_\d$/;
if (walnutRegExp.test(e.target.value) || rusticWalnutRegExp.test(e.target.value)) {
stains.show();
$(".walnut-stains-div").show();
$walnutchecked.prop('checked', false);
$walnutactive.removeClass( "tc-active" );
} else {
$(".walnut-stains-div").hide();
}
});
});
</code></pre>
<p>The HTML is ripped off the staging site so it's very unreadable so it's best I just drop the JSFiddle link <a href="https://jsfiddle.net/amishdirect/h94c7rsw/" rel="nofollow noreferrer">here</a>. If anyone has any suggestions on trimming some fat I would so very much appreciate it. Or if you have any suggestions on reducing the page time (Waiting (TTFB)). I've tried to defer and/or async the JS and it doesn't seem to improve anything.</p>
<p><a href="https://amishdirectfurniture-staging.g3wenplb-liquidwebsites.com/shop/dining/table/trestle-table/abilene-dining-table/" rel="nofollow noreferrer">Staging site</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T07:13:32.120",
"Id": "460888",
"Score": "1",
"body": "If you have problems with ttfb then fe js Is not the core of it. Its on backend. Anyway try narrowing CSS selectors to only select under a Common ancestor which you already revealed. Dont lookup the entire document again And again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T21:24:27.347",
"Id": "460938",
"Score": "0",
"body": "Unfortunately since I have to work around the plugin and a lot of it is generated this is the best way for me to do it. I am trying to find a better work around for how it finds if a button is checked or not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T19:18:38.600",
"Id": "461034",
"Score": "1",
"body": "Two things would be very helpful: An explanation on what this script actually does and the HTML it works on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T22:34:30.387",
"Id": "461192",
"Score": "0",
"body": "I added a description. The staging site demonstrates the actual live set up. The JSFiddle just narrows down the exact portion I am trying to clean up."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T06:56:30.663",
"Id": "235464",
"Score": "3",
"Tags": [
"javascript",
"performance",
"jquery",
"dom"
],
"Title": "Displaying sections from pre-checked options"
}
|
235464
|
<p>I'm new to programming, I'd like you to check my work and criticize the hell out of me. What would you do differently?</p>
<p>FQDN: <a href="https://en.m.wikipedia.org/wiki/Fully_qualified_domain_name" rel="nofollow noreferrer">https://en.m.wikipedia.org/wiki/Fully_qualified_domain_name</a></p>
<ul>
<li>253 characters not including trailing dot</li>
<li>Label1.Label2.Label3.adomain.com</li>
<li>All labels must be between 1-63 characters</li>
<li>Cannot start or end with hyphen (-)</li>
<li>May contain only a-z, 0-9 and hyphens</li>
</ul>
<p>This just checks to make sure the hostname passed as an argument meets all standards. </p>
<pre><code>import re
def is_fqdn(hostname):
"""
:param hostname: string
:return: bool
"""
# Remove trailing dot
try: # Is this necessary?
if hostname[-1] == '.':
hostname = hostname[0:-1]
except IndexError:
return False
# Check total length of hostname < 253
if len(hostname) > 253:
return False
# Split hostname into list of DNS labels
hostname = hostname.split('.')
# Define pattern of DNS label
# Can begin and end with a number or letter only
# Can contain hyphens, a-z, A-Z, 0-9
# 1 - 63 chars allowed
fqdn = re.compile(r'^[a-z0-9]([a-z-0-9-]{0,61}[a-z0-9])?$', re.IGNORECASE)
# Check if length of each DNS label < 63
# Match DNS label to pattern
for label in hostname:
if len(label) > 63:
return False
if not fqdn.match(label):
return False
# Found no errors, returning True
return True
</code></pre>
<p>I declared the variable for the regex pattern after the 2 conditionals with return statements. My thought was, why store a variable that would be unused if the prior conditions were met?</p>
<p>Could the regex be written any better?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T16:54:55.753",
"Id": "460917",
"Score": "1",
"body": "Your code looks good so far. Have you already written some unit tests for it? Using [pytest](https://docs.pytest.org/en/latest/) this is really simple. This way you can check yourself whether the `try` block is really necessary. If you have unit tests, you should add them to your question. And if you don't have any tests, just provide a list of names and whether each of them is valid or not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T16:27:35.707",
"Id": "461016",
"Score": "0",
"body": "This is tangentially related to your question, but just to make sure you cover all the bases you may want to have a look at IDN (https://en.wikipedia.org/wiki/Internationalized_domain_name)"
}
] |
[
{
"body": "<p>Comments:</p>\n\n<ol>\n<li><p>Use type declarations! These are (IMO) easier to read than docstring comments and they also make your code <code>mypy</code>-able.</p></li>\n<li><p>Your <code>try/catch</code> block is just an indirect way of requiring that the parameter is at least 1 character long. It's more clear IMO to just check the length explicitly, especially since you're already doing that as the next step.</p></li>\n<li><p>Reassigning a different type to an existing variable is something you see a lot in quick-and-dirty Python scripts, but it's bad practice IMO (and mypy will treat it as an error unless you forward-declare it with a tricky <code>Union</code> type). Just use a new variable name when you generate a new object with a new type.</p></li>\n<li><p>Your regex already enforces the 63-character requirement. DRY (Don't Repeat Yourself)!</p></li>\n<li><p>Using Python's built-in <code>all</code> function is better than rolling your own <code>for</code> loop.</p></li>\n</ol>\n\n<pre><code>import re\n\ndef is_fqdn(hostname: str) -> bool:\n \"\"\"\n https://en.m.wikipedia.org/wiki/Fully_qualified_domain_name\n \"\"\"\n if not 1 < len(hostname) < 253:\n return False\n\n # Remove trailing dot\n if hostname[-1] == '.':\n hostname = hostname[0:-1]\n\n # Split hostname into list of DNS labels\n labels = hostname.split('.')\n\n # Define pattern of DNS label\n # Can begin and end with a number or letter only\n # Can contain hyphens, a-z, A-Z, 0-9\n # 1 - 63 chars allowed\n fqdn = re.compile(r'^[a-z0-9]([a-z-0-9-]{0,61}[a-z0-9])?$', re.IGNORECASE)\n\n # Check that all labels match that pattern.\n return all(fqdn.match(label) for label in labels)\n</code></pre>\n\n<p>I echo Roland's suggestion about writing a unit test. A function like this is really easy to write tests for; you'd do it like:</p>\n\n<pre><code>def test_is_fqdn() -> None:\n # Things that are FQDNs\n assert is_fqdn(\"homestarrunner.net\")\n assert is_fqdn(\"zombo.com\")\n\n # Things that are not FQDNs\n assert not is_fqdn(\"\")\n assert not is_fqdn(\"a*\")\n assert not is_fqdn(\"foo\") # no TLD means it's not a FQDN!\n</code></pre>\n\n<p>Note that the last assert in that test will fail...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T19:41:34.983",
"Id": "460919",
"Score": "0",
"body": "This is exactly what I needed Sam. Thank you for helping me learn! I thought by creating a new variable for a list when I could just reassign would be a waste of resources."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T19:44:08.463",
"Id": "460921",
"Score": "1",
"body": "You're creating the new object in memory regardless. :)\n\nSince you only use the list once, you could also just not name it, e.g. `return all(fqdn.match(label) for label in hostname.split('.'))`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T12:20:30.413",
"Id": "460985",
"Score": "1",
"body": "Note that `foo` is a perfectly valid FQDN: it resolves to the host named `foo` in the root domain, i.e. it is equivalent to `foo.`. There is an example of a small island country offering exactly that: Tonga sold an A record for `to` to a URI shortener service for some time. See https://serverfault.com/a/90753/1499 and https://superuser.com/q/78408/2571"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T19:04:14.283",
"Id": "235478",
"ParentId": "235473",
"Score": "4"
}
},
{
"body": "<p>Your requirements could be summed up in a single regex.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import re\n\ndef is_fqdn(hostname):\n return re.match(r'^(?!.{255}|.{253}[^.])([a-z0-9](?:[-a-z-0-9]{0,61}[a-z0-9])?\\.)*([a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?[.]?$', re.IGNORECASE)\n</code></pre>\n\n<p>I don't particularly condone this very condensed formulation; but this does everything in your requirements.</p>\n\n<p>Here's a rundown.</p>\n\n<ul>\n<li><code>^</code> beginning of line / expression</li>\n<li><code>(?!.{255}|.{253}[^.])</code> negative lookahead: don't permit 255 or more characters, or 254 where the last is not a dot.</li>\n<li><code>([a-z0-9](?:[-a-z-0-9]{0,61}[a-z0-9])?\\.)*</code> zero or more labels where the first and last characters are not hyphen, and a max of 61 characters between them can also be a hyphen; all followed by a dot. The last 62 are optional so that we also permit a single-character label where the first character is also the last.</li>\n<li><code>([a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?</code> the final label does not have to be followed by a dot</li>\n<li><code>[.]?</code> but it can be</li>\n<li><code>$</code> end of line / expression</li>\n</ul>\n\n<p>When you only use a regex once, there is no acute reason to <code>compile</code> it. Python will do this under the hood anyway (and in fact keep a cache of recently used compiled regexes and often reuse them more quickly than if you explicitly recompile).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T19:47:24.760",
"Id": "460922",
"Score": "0",
"body": "So what you’re saying is, just to clarify, that single regex could replace all of my code. However, it isn’t a good practice. Correct me if I’m wrong please."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T19:49:09.577",
"Id": "460923",
"Score": "1",
"body": "I'm sort of divided on \"good practice\". In a complex program where you use a lot of regex for other stuff, this would not at all be out of place."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T19:40:43.203",
"Id": "235484",
"ParentId": "235473",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "235478",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T16:11:05.550",
"Id": "235473",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"regex"
],
"Title": "FQDN Validation"
}
|
235473
|
<p>Recently I created a small app using JavaScript, and I would love for some JavaScript developers if they have the time of day, to tell me their opinions so I can grow and improve.</p>
<p>I'm mostly working on back-end tasks with PHP and Go, but I thought making something small in JS would be fun attempt.</p>
<p>Basically it's an app that sorts an image based on users choice of sorting algorithm. You first say how many rows and columns want, and past an image URL. The app then shuffles it and asks you what sort do you want.</p>
<p>It is then visual when sorting it back to original.</p>
<p>I know this is not a typical question, but I would love to get some opinions on code, and look of app. So, what do you think? Any recommendation ?</p>
<p>GitHub of project: </p>
<p><a href="https://github.com/fvukojevic/Image-Sorting-Visualizer" rel="nofollow noreferrer">https://github.com/fvukojevic/Image-Sorting-Visualizer</a> (if someone wants to star ) Application: <a href="https://image-sorting-visualizer.herokuapp.com/" rel="nofollow noreferrer">https://image-sorting-visualizer.herokuapp.com/</a></p>
<p>Example of one sorting algorithm where I'm saving every swap into an array of "animations":</p>
<pre><code>function bubbleSort(arrayCopy, animations) {
let sorted = false;
let counter = 0;
while(!sorted){
sorted = true;
for(let i=0;i<arrayCopy.length -1 - counter; i++) {
if(arrayCopy[i].val > arrayCopy[i+1].val){
swap(i, i+1, arrayCopy);
sorted = false;
animations.push([i, i+1]);
}
}
counter++
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T18:23:16.747",
"Id": "460918",
"Score": "1",
"body": "It would be helpful if you directly included all the code you want reviewed in the question. If you modify the code on github, it can invalidate answers to this question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T08:05:22.740",
"Id": "461238",
"Score": "0",
"body": "We can review the code you posted. We can not review the rest if you don't include it into the question itself. Since Code Review is a community where programmers improve their skills through peer review, we require that the code be posted by an author or maintainer of the code, that the code be **embedded directly**, and that the poster know why the code is written the way it is. Please take a look at the [help/on-topic]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T08:06:17.523",
"Id": "461239",
"Score": "0",
"body": "So, while your question is fine as-is, you probably won't get the full value out of it unless you modify it. Please keep in mind any such modifications to the code will have to be done *before* answers arrive. Otherwise you'll have to open a new question. Good thing they're free today."
}
] |
[
{
"body": "<p>A short review</p>\n<ul>\n<li>This code passes jshint perfectly, well done. Besides the obvious warning that you did not provide <code>swap</code> of course</li>\n<li>The name <code>arrayCopy</code> is perhaps unfortunate, since this works on any array whether it is a copy or not</li>\n<li>The name <code>bubbleSort</code> also does not perfectly describe what is going on, it not only bubble sorts the array, but it also tracks the swaps in an animations array</li>\n<li>I keep thinking that providing the animations array in the function call is weird, I would return the animations instead, the caller can <code>concat</code> if needed</li>\n<li>I see little point in providing an array with <code>i</code> and <code>i+1</code> unless you animate with different kind of sorting algorithms, so you could just <code>animations.push(i)</code></li>\n<li>Still, very maintainable, correct code.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T14:33:23.480",
"Id": "254897",
"ParentId": "235474",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T17:10:04.077",
"Id": "235474",
"Score": "5",
"Tags": [
"javascript",
"algorithm",
"sorting"
],
"Title": "Visualized bubble sort"
}
|
235474
|
<p>This program constantly sends an https request to Reddit's API for new comments.</p>
<p>Using a PostgreSQL Database containing Regular Expressions, find comments of interest and notify about them using faye.</p>
<p>When run locally, the information is sent to <code>localhost:8080</code>, otherwise data is sent to a heroku application.</p>
<p>Full code can be found <a href="https://github.com/LionelBergen/reddit-comment-reader" rel="nofollow noreferrer">here</a>.</p>
<h2>app.js - Entry point of program</h2>
<pre><code>// Local files
require('./DatabaseFetch.js')();
require('./CommonTools.js')();
const CommentSearchProcessor = require('./CommentFinder.js');
const RedditClientImport = require('./RedditClient.js');
const pg = require('pg');
const secondsTimeToWaitBetweenPostingSameCommentToASubreddit = 60 * 30;
const intervalToWaitInMillisecondsBetweenReadingComments = 1100;
const intervalToWaitBeforeSendingIdleMessage = 30;
const commentCacheSize = 2000;
const dissallowedSubreddits = ['suicidewatch', 'depression' ];
const userIgnoreList = ['agree-with-you'];
var lastMessageSentAt = new Date().getTime();
const clientConnection = isLocal() ? 'http://localhost:8000/' : 'http://reddit-agree-with-you.herokuapp.com/';
const faye = require('faye');
const client = new faye.Client(clientConnection);
var CommentFinder;
var redditClient = new RedditClientImport();
let commentHistory = GetUniqueArray(3000);
let subredditModsList = GetUniqueArray(3000);
console.log('is local?: ' + isLocal());
console.log('connecting to: ' + clientConnection);
console.log('Database URL: ' + process.env.DATABASE_URL);
if (!process.env.DATABASE_URL) {
throw 'Please set process.env.DATABASE_URL! e.g SET DATABASE_URL=postgres://.....';
}
// Execute
GetCommentSearchObjectsFromDatabase(pg, process.env.DATABASE_URL, function(commentSearchObjects) {
CommentFinder = new CommentSearchProcessor(commentSearchObjects, commentCacheSize);
console.log('starting...');
start();
});
function start()
{
client.publish('/messages', {message: 'starting up.'});
setInterval(function() {
redditClient.getCommentsFromSubreddit(RedditClientImport.MAX_NUM_POSTS, 'all', 'comments', function(comments) {
comments.forEach(
comment => {
var replyMessage = CommentFinder.searchComment(comment);
if (replyMessage)
{
// filter by disallowed subreddits
if (dissallowedSubreddits.includes(comment.subreddit.toLowerCase()))
{
console.log('Ignoring comment, disallowed subreddit found for comment: ');
console.log(comment);
}
else
{
processComment(comment, replyMessage);
}
}
});
});
if (GetSecondsSinceTimeInSeconds(lastMessageSentAt) > intervalToWaitBeforeSendingIdleMessage)
{
console.log('sending inactive message');
client.publish('/messages', {inactive: '1'});
lastMessageSentAt = new Date().getTime();
}
}, intervalToWaitInMillisecondsBetweenReadingComments);
}
function processComment(comment, replyMessage)
{
// So we don't spam a subreddit with the same message
let timeThisReplyWasLastSubmittedOnThisSubreddit = {id: (comment.subreddit + ':' + replyMessage), created: comment.created };
let thisSubredditModList = {id: comment.subreddit};
if (subredditModsList.includes(thisSubredditModList))
{
if (subredditModsList.get(thisSubredditModList).modList.includes(comment.author))
{
console.log('Modderator comment!!! :' + comment.author + ' comment: ' + comment.body);
return;
}
}
else
{
redditClient.getSubredditModList(thisSubredditModList.id, function(modList) {
thisSubredditModList.modList = modList;
subredditModsList.push(thisSubredditModList);
console.log('pushed: ' + thisSubredditModList.id);
processComment(comment, replyMessage);
return;
});
}
if (userIgnoreList.includes(comment.author))
{
console.log('Skipping comment, is posted by: ' + comment.author + ' comment: ' + comment.body);
return;
}
console.log('continue...');
if (!commentHistory.includes(timeThisReplyWasLastSubmittedOnThisSubreddit))
{
publishComment(comment, replyMessage);
commentHistory.push(timeThisReplyWasLastSubmittedOnThisSubreddit);
}
else
{
var existingComment = commentHistory.get(timeThisReplyWasLastSubmittedOnThisSubreddit);
if (GetSecondsSinceUTCTimestamp(existingComment.created) > secondsTimeToWaitBetweenPostingSameCommentToASubreddit)
{
publishComment(comment, replyMessage);
commentHistory.push(timeThisReplyWasLastSubmittedOnThisSubreddit);
}
else
{
console.log('skipping comment, we\'ve already posted to this subreddit recently!');
console.log(comment);
console.log(commentHistory);
}
}
}
function publishComment(comment, replyMessage)
{
console.log('posting comment');
client.publish('/messages', {comment: comment, reply: replyMessage});
lastMessageSentAt = new Date().getTime();
console.log(comment);
console.log('reply: ' + replyMessage);
}
/**
* Checks if this program is currently running locally
* We do this by checking if 'heroku' property is found in 'process.env._'
*/
function isLocal()
{
return !(process.env._ && process.env._.indexOf("heroku"));
}
</code></pre>
<p>Table layout for "RegexpComment":</p>
<pre><code>|subredditmatch|commentmatch|replymessage|id|
|--------------|------------|------------|--|
'SubredditMatch' - A regular expression containing Subreddits to find comments on. E.G '.*' for all
'commentMatch' - A regular expression for the comment. For example '^hello (.*)' would find all comments starting with 'hello'
'replyMessage' - The comment reply
'id' - the primary key, auto incremented
</code></pre>
|
[] |
[
{
"body": "<h2>Module inclusion</h2>\n<p>Some style guides recommend using <code>import</code> instead of <code>require</code> - e.g. the <a href=\"https://github.com/airbnb/javascript#modules\" rel=\"nofollow noreferrer\">AirBnB style guide</a>, and also recommend putting <code>import</code> statements above non-import statements (<a href=\"https://github.com/airbnb/javascript#modules--imports-first\" rel=\"nofollow noreferrer\">AirBnB</a>, <a href=\"https://google.github.io/styleguide/jsguide.html#source-file-structure\" rel=\"nofollow noreferrer\">Google</a>).</p>\n<blockquote>\n<p>Why? Since imports are hoisted, keeping them all at the top prevents surprising behavior. <sup><a href=\"https://github.com/airbnb/javascript#modules--imports-first\" rel=\"nofollow noreferrer\">1</a></sup></p>\n</blockquote>\n<h2>Indentation Levels</h2>\n<p>The function <code>start()</code> contains a call to <code>setInterval()</code> that passes an anonymous function/closure, which calls a method on <code>redditClient</code> that also has a callback function parameter, which then calls the <code>forEach()</code> method on the comments argument with a callback function. That makes me tired just typing it out. This is what some would call Callback Hell - look at how many indentation levels exist. This can be remedied with a few techniques:</p>\n<ol>\n<li>pulling out named functions</li>\n<li>using <a href=\"/questions/tagged/ecmascript-8\" class=\"post-tag\" title=\"show questions tagged 'ecmascript-8'\" rel=\"tag\">ecmascript-8</a> keywords <code>async</code> / <code>await</code> if possible</li>\n</ol>\n<p>For more tips see <a href=\"http://callbackhell.com/\" rel=\"nofollow noreferrer\">callbackhell.com</a></p>\n<h2>Variable declaration keywords</h2>\n<p>Some believe there is no use for <code>var</code> in modern JS, except if you intend to hoist variables. Some variables declared with <code>let</code> could be declared with <code>const</code> since they are not re-assigned - e.g. <code>timeThisReplyWasLastSubmittedOnThisSubreddit</code>, <code>thisSubredditModList</code>. Using <code>const</code> instead of <code>let</code> helps avoid <a href=\"https://softwareengineering.stackexchange.com/a/278653/244085\">accidental re-assignment and other bugs</a>.</p>\n<h2>Constants in CONSTANT_CASE</h2>\n<p>Just as you do in rust and other languages, a common convention is to have true constants named in ALL_CAPS with underscores separating words (style guide rules: <a href=\"https://github.com/airbnb/javascript#naming--uppercase\" rel=\"nofollow noreferrer\">AirBnB</a>, <a href=\"https://google.github.io/styleguide/jsguide.html#naming-constant-names\" rel=\"nofollow noreferrer\">Google</a>). This would apply to constants like <code>secondsTimeToWaitBetweenPostingSameCommentToASubreddit</code>, <code>intervalToWaitInMillisecondsBetweenReadingComments</code>, <code>intervalToWaitBeforeSendingIdleMessage</code>, <code>commentCacheSize</code>, etc.</p>\n<p>Note that constants cannot be re-assigned but are immutable - so variables like <code>dissallowedSubreddits</code> can be modified via methods like <code>push()</code> unless they are frozen via <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze\" rel=\"nofollow noreferrer\"><code>Object.freeze()</code></a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T16:05:21.807",
"Id": "494760",
"Score": "1",
"body": "Thanks, I knew there had to be a way to fix the callbacks issue. I'll come back to mark this as accepted once I finish implementing the suggestion!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T00:41:53.427",
"Id": "501499",
"Score": "1",
"body": "Great suggestions! Escaping callback hell & Moving pieces into separate modules has been especially helpful (suggested in the callback hell link). It's looking much cleaner now"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T15:53:29.727",
"Id": "251343",
"ParentId": "235476",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "251343",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T18:30:02.847",
"Id": "235476",
"Score": "5",
"Tags": [
"javascript",
"node.js",
"ecmascript-6",
"api",
"reddit"
],
"Title": "Searching all new Reddit comments for comments matching regular expressions and notify of matches"
}
|
235476
|
<p>This time I made a quiz game, in which the player is asked questions and receives points for each question answered correctly. Some people told me I should learn about classes, so this is what I came up with.</p>
<pre class="lang-py prettyprint-override"><code>import random
from Quiz_Questions import game_questions
questions = [*game_questions]
def game():
print('-' * 20)
player_score = 0
right_answers = 0
wrong_answers = 0
while len(questions) > 0:
question = random.choice(questions)
questions.remove(question)
print(question.text)
user_answer = input('Insert answer (Yes or No): ')
while user_answer not in ['yes', 'y', 'f', 'true', 'no', 'n', 'f', 'false']:
print('Sorry, that is an invalid answer')
user_answer = input('Please insert another answer (Yes or No): ')
if user_answer.lower() in question.correct_answer:
player_score += question.question_reward
right_answers += 1
print('You got it right! (+{} points)'.format(question.question_reward))
print('You have {} points'.format(player_score))
else:
wrong_answers += 1
print('You got it wrong, good luck next time!')
print('-' * 20)
print('Congratulations! You have answered all the questions!')
print('Your final score is {} points'.format(player_score))
print('You answered {} questions right'.format(right_answers))
print('And {} questions wrong.'.format(wrong_answers))
game()
</code></pre>
<p><code>Quiz_Question.py</code></p>
<pre><code>class Question():
def __init__(self, text, correct_answer, question_reward):
self.text = text
if correct_answer == 'True':
self.correct_answer = ['yes', 'y', 'f', 'true']
elif correct_answer == 'False':
self.correct_answer = ['no', 'n', 'f', 'false']
self.question_reward = question_reward
game_questions = [Question('Russia has a larger surface area than Pluto.', 'True', 7),
Question('There are as many stars in space than there are grains of sand on every beach in the world.', 'False', 5),
Question('For every human on Earth there are 1.6 million ants.', 'True', 8),
Question('On Jupiter and Saturn it rains diamonds.', 'True', 9),
Question('Scotland’s national animal is the phoenix.', 'False', 4),
Question('A banana is a berry.', 'True', 8),
Question('An octopus has three hearts.', 'True', 4),
Question('There are 10 times more bacteria in your body than actual body cells.', 'True', 9),
Question('Rhode Island is the closest US state to Africa.', 'False', 3),
Question('Shakespeare made up the name “Sarah” for his play Merchant of Venice.', 'False', 3)]
</code></pre>
|
[] |
[
{
"body": "<p>I would turn around the logic. The design you have has a lot of the general logic in the main program, and a lot of game-specific logic in the questions module. A better design for reusability would be to put the logic in a module, and the game-specific stuff (basically just the questions and perhaps some very superficial user interface) in the main program.</p>\n\n<p>I would also define a separate class for the collection of questions; so maybe the main game might look like</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from Quiz_Questions import QuestionsCollection, Question, PlayerState, QuestionsExhausted\n\ncollection = QuestionsCollection()\n\ncollection.add('Russia has a larger surface area than Pluto.', 'True', 7)\ncollection.add('There are as many stars in space than there are grains of sand on every beach in the world.', 'False', 5)\ncollection.add('For every human on Earth there are 1.6 million ants.', 'True', 8)\ncollection.add('On Jupiter and Saturn it rains diamonds.', 'True', 9)\ncollection.add('Scotland’s national animal is the phoenix.', 'False', 4)\ncollection.add('A banana is a berry.', 'True', 8),\ncollection.add('An octopus has three hearts.', 'True', 4)\ncollection.add('There are 10 times more bacteria in your body than actual body cells.', 'True', 9)\ncollection.add('Rhode Island is the closest US state to Africa.', 'False', 3)\ncollection.add('Shakespeare made up the name “Sarah” for his play Merchant of Venice.', 'False', 3)\n\ndef game():\n print('-' * 20)\n player = PlayerState()\n questions = collection.game()\n while True:\n try:\n question = questions.next()\n except QuestionsExhausted:\n break\n print(question.challenge())\n user_answer = input('Insert answer (Yes or No): ')\n response = player.assess(question, user_answer)\n print(response)\n print('-' * 20)\n print('Congratulations! You have answered all the questions!')\n print('Your final score is {} points'.format(player.score()))\n print('You answered {} questions right'.format(player.right_answers()))\n print('And {} questions wrong.'.format(player.wrong_answers()))\n\ngame()\n</code></pre>\n\n<p>This is just a rough sketch, but hopefully hints at a different design where the classes encapsulate the behavior specific to each, with enough freedom to reassemble things in a different arrangement (multi-player game? Add timeouts?) and also with the user-facing I/O and message strings (mostly) separate from the library module.</p>\n\n<p>This doesn't handle invalid input very elegantly but I'm thinking the way I started this, the <code>Player</code> class would be responsible for some I/O as well, so maybe actually refactor to</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>...\nwhile True:\n try:\n question = questions.next()\n except QuestionsExhausted:\n break\n player.handle(question)\nprint('Congratulations! You have answered all the questions!')\n...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T20:46:12.183",
"Id": "460928",
"Score": "0",
"body": "Hey, sorry, I didn't understand much of what you did, but I'll keep that thing you said about separating the general logic and game-specific logic in mind. Thanks for your suggestions!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T20:24:49.953",
"Id": "235485",
"ParentId": "235477",
"Score": "3"
}
},
{
"body": "<blockquote>\n<pre><code>if correct_answer == 'True':\n self.correct_answer = ['yes', 'y', 'f', 'true']\nelif correct_answer == 'False':\n self.correct_answer = ['no', 'n', 'f', 'false']\n</code></pre>\n</blockquote>\n\n<p><code>f</code> is recognized as a correct answer for both True and False answers, so I can collect all the points without knowing the correct answer to any of the questions by consistently answering <code>f</code>.</p>\n\n<p>This behavior is a bit counter-intuitive, so it makes sense to explicitly document it in the code</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T19:56:16.807",
"Id": "462735",
"Score": "0",
"body": "Yeah, you are right, for True answers it should have been ```'t'``` instead of ```'f'```, my mistake haha."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T07:04:50.137",
"Id": "236181",
"ParentId": "235477",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235485",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T19:01:13.840",
"Id": "235477",
"Score": "4",
"Tags": [
"python",
"beginner",
"python-3.x",
"quiz"
],
"Title": "Beginner Quiz game (True or False)"
}
|
235477
|
<p>I have to apply two deals on the cart.</p>
<ul>
<li>Buy 3 (equal) items and pay for 2 </li>
<li>Buy 3 (in a set of items) and the cheapest is free</li>
</ul>
<p>Items in cart:</p>
<pre class="lang-none prettyprint-override"><code>----
|Car|
----
{'itemcode': 4, 'cost': 20.5, 'type': 'car', 'name': 'volvo'}
{'itemcode': 5, 'cost': 25, 'type': 'car', 'name': 'tesla'}
{'itemcode': 6, 'cost': 15, 'type': 'car', 'name': 'Ford'}
-----
|Tractor|
--------
{'itemcode': 7, 'cost': 10, 'type': 'tractor', 'name': 'mahindra'}
{'itemcode': 8, 'cost': 10, 'type': 'tractor', 'name': 'hmt'}
{'itemcode': 9, 'cost': 5, 'type': 'tractor', 'name': 'farmtrac'}
</code></pre>
<p>Below is the code I have written.</p>
<pre class="lang-py prettyprint-override"><code>def print_receipts(types):
"""Prints the receipts with deals applied.
Args
types (collection.defaultdict) : items purchased with cost.
"""
print "\n\t-: Payment Receipt :-\n"
grand_total = []
new_total = 0
deal_one_msg = ""
types_two = copy.deepcopy(types)
for item, costs in types.items():
if len(costs) >= 3:
saving = costs.pop(costs.index(min(costs)))
total = sum(costs)
grand_total.append(total)
print u"\tSaving: \xa3{} on {}".format(saving, item)
deal_one_msg = "Deal Buy 3 for price of 2: "
print u"\tType: {} Total: \xa3{}".format(item, total)
else:
new_total -= min(costs) * -1
new_total = new_total if len(costs) > 1 else costs[0]
grand_total.append(new_total)
print u"\tType-: {} Total: \xa3{}".format(item, new_total)
print u"\t{}Grand Total: \xa3{}".format(deal_one_msg, sum(grand_total))
sets_cost = []
if len(types_two.items()) < 3:
return
deal_two = True
deal_two_msg = "3 sets: "
saved = 0
for item, _costs in types_two.items():
sets_cost.append(sum(_costs))
if len(_costs) != 3:
deal_two = False
if deal_two:
deal_two_msg = "Deal get 3rd set free: "
saved = sets_cost.pop(sets_cost.index(min(sets_cost)))
grand_total_sets = sum(sets_cost)
if grand_total_sets > 0 and saved > 0:
print u"\tSaved \xa3{} of cheapest set.".format(saved)
print u"\t{}Grand Total: \xa3{}".format(deal_two_msg, grand_total_sets)
print "\t", "~" * 40
</code></pre>
<p>An example for testing:</p>
<pre class="lang-py prettyprint-override"><code>import collections
types = collections.defaultdict(
list,
{u'car': [20.5, 25, 15], u'train': [5, 5, 5], u'tractor': [10, 10, 5]},
)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T19:54:39.703",
"Id": "460924",
"Score": "1",
"body": "If you are only just learning, you should ignore Python 2, and concentrate on the supported and recommended version of the language, which is Python 3."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T21:33:20.027",
"Id": "460940",
"Score": "0",
"body": "It looks like you're using both Python 2 and Python 3, just scanning over your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T08:40:20.643",
"Id": "460972",
"Score": "1",
"body": "This is unclear. What is the expected output? Are the conditions not equivalent to the single rule \"if you buy three of something, you get one free; the cheapest one will be free if the prices are different\"? If not, how are they different? Your code looks like there are two deductions in some cases. Or do you really mean the trains should be free and on top of that you only pay for the most expensive two of each of the remaining categories?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T11:28:24.973",
"Id": "460981",
"Score": "1",
"body": "@tripleee I have added items in the cart, I hope that explains well. the cheapest one free is for the cheapest set, for first deal the buy 3 and get 1 free.\n@Linny now I have updated the OP and its just `python2.7`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-15T15:38:44.457",
"Id": "468576",
"Score": "0",
"body": "Also, if you buy six of something, you should probably get two for free (otherwise you would have to buy three, walk out of the store and back in to get another three...), and so on."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T19:17:28.273",
"Id": "235481",
"Score": "3",
"Tags": [
"python",
"performance",
"python-2.x"
],
"Title": "Store special deals, like 3 for 2"
}
|
235481
|
<p>First time writing a Go script, just looking for feedback on language usage etc.</p>
<p>Using chromedp to run a headless (I think) browser to load some html, generate a PDF and then save the PDF to the file system.</p>
<pre class="lang-golang prettyprint-override"><code>package main
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
)
const PATH = "./../../"
func main() {
source := fmt.Sprintf("%s%s", PATH, "public/index.html")
dest := fmt.Sprintf("%s%s", PATH, "public/cv.pdf")
htmlBuf, err := readHtml(source)
if err != nil {
panic(err)
}
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
ts := createTestServer(htmlBuf)
defer ts.Close()
var buf []byte
if err := chromedp.Run(ctx, htmlToPdf(ts.URL, &buf)); err != nil {
panic(err)
}
if err := writePdf(dest, &buf); err != nil {
panic(err)
}
}
func createTestServer(buf []byte) (*httptest.Server) {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, string(buf))
}))
}
func writePdf(dest string, buf *[]byte) error {
return ioutil.WriteFile(dest, *buf, 0644)
}
func readHtml(source string) ([]byte, error) {
return ioutil.ReadFile(source)
}
func htmlToPdf(url string, res *[]byte) chromedp.Tasks {
return chromedp.Tasks{
chromedp.Navigate(url),
chromedp.ActionFunc(func(ctx context.Context) error {
buf, _, err := page.PrintToPDF().Do(ctx)
if err != nil {
return err
}
*res = buf
return nil
}),
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T20:54:52.883",
"Id": "460929",
"Score": "0",
"body": "the httptest server works, however it is not intended to be use for that purpose. You should rather use a regular http server with a static asset handler. But, this or that, ultimately both works. https://www.alexedwards.net/blog/serving-static-sites-with-go"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T20:59:06.917",
"Id": "460931",
"Score": "0",
"body": "it is little weird to use *[]byte as out argument. You could pass the out path as an argument and write directly to it within the task. or give it a callback that accepts the byte slice and do something with it. but this is not essential as there is no way to prevent that allocation. overall it appears to me it is using too many functions. I would inline most of this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T21:00:36.370",
"Id": "460932",
"Score": "0",
"body": "you could make use of flag package to take input argument, arguable in your case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T21:01:39.840",
"Id": "460933",
"Score": "0",
"body": "**dont** fmt.Sprintf your path, use filepath.Join instead. That is important."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T21:03:38.353",
"Id": "460934",
"Score": "0",
"body": "as you are not controlling the context or using it, you could use context.TODO() instead. https://godoc.org/context#TODO"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T21:04:44.273",
"Id": "460935",
"Score": "0",
"body": "overall okish, just need more reading of the friendly manual and practice to prevent weird writings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T10:01:56.380",
"Id": "460979",
"Score": "0",
"body": "@mb-cbon really useful thank you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T05:05:51.983",
"Id": "461076",
"Score": "0",
"body": "@mh-cbon you should put your comments into an answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T04:30:20.173",
"Id": "461347",
"Score": "0",
"body": "source and dest: Use path.Join() instead of Sprintf"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T04:30:39.540",
"Id": "461348",
"Score": "0",
"body": "suggestion: Define var buf []byte closer to where it is used."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-11T19:38:42.787",
"Id": "235483",
"Score": "3",
"Tags": [
"go"
],
"Title": "HTML -> PDF in Go"
}
|
235483
|
<p>I am trying to subclass <code>list</code> in order to implement a callback function that would be called whenever a list item is being set.</p>
<p>I have this:</p>
<pre><code>class CustomList(list):
def __init__(self, *args, **kwargs):
self.setitem_callback = kwargs['setitem_callback']
del kwargs['setitem_callback']
super().__init__(*args, **kwargs)
def __setitem__(self, *args, **kwargs):
super().__setitem__(*args, **kwargs)
self.setitem_callback()
def callback():
print('callback')
l = ['a', 'b', 'c']
custom_list = CustomList(l, setitem_callback=callback)
custom_list[1] = 'd' # prints 'callback'
</code></pre>
<p>It works as expected, but I am concerned about having to do <code>del kwargs['setitem_callback']</code> in order for the superclass' <code>__init__</code> to work. Is it a bad practice? Are there any other ways to achieve the same?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T02:26:06.307",
"Id": "460946",
"Score": "2",
"body": "Your indentation is broken, you will have lots of `SyntaxError`s. Yes it's possible as you can just do `def foo(*args, my_important_argument, **kwargs):`."
}
] |
[
{
"body": "<p>As @Peilonrayz said in the comments: You can just write</p>\n\n<pre><code>class CustomList(list):\n def __init__(self, *args, setitem_callback, **kwargs):\n self.setitem_callback = setitem_callback\n super().__init__(*args, **kwargs)\n\n def __setitem__(self, *args, **kwargs):\n super().__setitem__(*args, **kwargs)\n self.setitem_callback()\n\ndef callback():\n print('callback')\n\nl = ['a', 'b', 'c']\ncustom_list = CustomList(l, setitem_callback=callback)\ncustom_list[1] = 'd' # prints 'callback'\n</code></pre>\n\n<p>as long as you're okay with slightly different behavior when the caller forgets to pass <code>setitem_callback=</code> at all. With your original code, you get a KeyError:</p>\n\n<pre><code>Traceback (most recent call last):\n File \"test.py\", line 16, in <module>\n custom_list = CustomList(l)\n File \"test.py\", line 3, in __init__\n self.setitem_callback = kwargs['setitem_callback']\nKeyError: 'setitem_callback'\n</code></pre>\n\n<p>With a proper keyword argument, you get a <code>TypeError</code> with a more tailored message:</p>\n\n<pre><code>Traceback (most recent call last):\n File \"test.py\", line 16, in <module>\n custom_list = CustomList(l)\nTypeError: __init__() missing 1 required keyword-only argument: 'setitem_callback'\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T04:03:21.047",
"Id": "235491",
"ParentId": "235488",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "235491",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T01:15:28.177",
"Id": "235488",
"Score": "0",
"Tags": [
"python"
],
"Title": "How to properly add some new arguments in a subclass?"
}
|
235488
|
<p>I'm working on some code to find the max depth/height in a tree. I came up with a recursive solution, and I find myself needing to pass an integer "by reference". Currently, I'm using a mutable container to achieve this, but is there a more Pythonic way?</p>
<pre><code>class Node:
"""
Node in a tree, with children stored in a list.
"""
def __init__(self, keyParam, childrenParam = None):
self.key = keyParam #some id of the node; not strictly required, but often needed.
if childrenParam is None:
self.children = []
else:
self.children = childrenParam
def dfsWithDepth(node, currentDepth, currentMaxContainer):
currentDepth += 1
if currentDepth > currentMaxContainer[0]:
currentMaxContainer[0] = currentDepth
for child in node.children:
if child is not None:
dfsWithDepth(child, currentDepth, currentMaxContainer)
# %% Construct tree
rootNode = Node('n1')
rootNode.children = [Node('n2'), Node('n3')]
tempNode = rootNode.children[0] # n2
tempNode.children = [Node('n3'), Node('n4')]
tempNode = tempNode.children[1] # n4
tempNode.children = [None, Node('n5')]
currentMaxContainer = [0]
dfsWithDepth(rootNode, 0, currentMaxContainer)
print(currentMaxContainer)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T01:29:54.523",
"Id": "461070",
"Score": "0",
"body": "Variable and function names should follow the `lower_case_with_underscores` style."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T01:20:17.997",
"Id": "461205",
"Score": "0",
"body": "You don't need mutable parameters. Just `return`."
}
] |
[
{
"body": "<p>It seems simpler to me to return the value:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def dfsWithDepth(node, currentDepth, currentMax):\n currentDepth += 1\n if currentDepth > currentMax:\n currentMax = currentDepth\n\n for child in node.children:\n if child is not None:\n currentMax = dfsWithDepth(child, currentDepth, currentMax)\n\n return currentMax\n\n# ...\n\nprint(dfsWithDepth(rootNode, 0, 0))\n</code></pre>\n\n<p>You could even set default values for the two depth arguments to simplify the use of the recursive function:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def dfsWithDepth(node, currentDepth=0, currentMax=0):\n # ...\nprint(dfsWithDepth(rootNode))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T07:35:10.597",
"Id": "235497",
"ParentId": "235495",
"Score": "8"
}
},
{
"body": "<p>My preferred way to solve the mutable immutable, is to just us a closure. This has the benefit that you don't have to pass <code>currentDepthContainer</code>, and you can return just the maximum at the end.</p>\n\n<p>Note I have changed your variable names to be Pythonic too.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def maximum_depth(root):\n def inner(node, depth):\n nonlocal max_depth\n\n depth += 1\n if depth > max_depth:\n max_depth = depth\n\n for child in node.children:\n if child is not None:\n inner(child, depth)\n\n max_depth = 0\n inner(root, 0)\n return max_depth\n</code></pre>\n\n<p>But really, I don't think that your solution is that great readability wise. As you could just return the maximum depth so far and then just use <code>max</code>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def maximum_depth(node, depth=0):\n depth += 1\n return max(\n (\n maximum_depth(child, depth)\n for child in node.children\n if child is not None\n ),\n default=depth,\n )\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T19:38:06.810",
"Id": "461035",
"Score": "2",
"body": "Wouldn't `inner(child, depth+1)` be both shorter and cleaner?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T06:37:29.917",
"Id": "461080",
"Score": "0",
"body": "@hyde You also have to do `depth + 1 > max_depth` and `max_depth = depth + 1`. So yeah you save one line, to then add 3 `+ 1`s. Beauty is in the eye of the beholder. I personally don't think either is better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T06:53:42.990",
"Id": "461081",
"Score": "0",
"body": "Why? Now you do \"pass depth, depth+=1\" and there's nothing between. So just \"pass depth+1\" should do exactly the same thing."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T08:22:02.423",
"Id": "235498",
"ParentId": "235495",
"Score": "5"
}
},
{
"body": "<h3>Optimization and restructuring</h3>\n\n<p><code>Node</code> class constructor (<code>__init__</code> method)</p>\n\n<ul>\n<li>the arguments <code>keyParam, childrenParam</code> introduce unneeded verbosity and better named as just <strong><code>key</code></strong> and <strong><code>children</code></strong></li>\n<li>the whole <code>if ... else ...</code> condition for ensuring <code>children</code> list is simply replaced with <strong><code>self.children = children or []</code></strong> expression</li>\n</ul>\n\n<hr>\n\n<p>The initial <code>dfsWithDepth</code> function should be renamed to say <strong><code>find_max_depth</code></strong> to follow PEP8 style guide naming conventions.</p>\n\n<p>The former parameters <code>currentDepth, currentMaxContainer</code> become unneeded. <br>Within the crucial recursive function it's worth to capture \"empty\" node and node with no children beforehand. That's achieved by the following condition:</p>\n\n<pre><code>if node is None or not node.children:\n return 1\n</code></pre>\n\n<p>The remaining recursive search relies on the crucial <code>find_max_depth</code> and builtin <code>max</code> functions calls and accumulates the final <strong><em>max depth</em></strong> through traversing all subsequent sub-trees (child nodes).</p>\n\n<p>The final optimized version:</p>\n\n<pre><code>class Node:\n \"\"\"\n Node in a tree, with children stored in a list.\n \"\"\"\n\n def __init__(self, key, children=None):\n self.key = key # some id of the node; not strictly required, but often needed.\n self.children = children or []\n\n\ndef find_max_depth(node):\n if node is None or not node.children:\n return 1\n return 1 + max(map(find_max_depth, node.children))\n</code></pre>\n\n<hr>\n\n<p>Testing (I've added additional 5th level for demonstration):</p>\n\n<pre><code># Construct tree\nrootNode = Node('n1')\nrootNode.children = [Node('n2'), Node('n3')]\ntempNode = rootNode.children[0] # n2\ntempNode.children = [Node('n3'), Node('n4')]\ntempNode = tempNode.children[1] # n4\ntempNode.children = [None, Node('n5')]\ntempNode = tempNode.children[1] # n5\ntempNode.children = [Node('name7')]\n\nprint(find_max_depth(rootNode)) # 5\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T08:50:32.977",
"Id": "460973",
"Score": "0",
"body": "Even better default children to [] in the first place, rather than use a needless None flag value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T09:24:03.093",
"Id": "460977",
"Score": "9",
"body": "default `[]` is the #1 Python gotcha. Don't do it! https://docs.python-guide.org/writing/gotchas/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T09:32:20.337",
"Id": "460978",
"Score": "0",
"body": "@SamStafford Thanks Sam. I did wonder why nobody else had spotted the apparently obvious but I figured somebody would set me straight soon enough if I'd suggested something dumb."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T16:55:23.450",
"Id": "461018",
"Score": "1",
"body": "It bites everyone once! :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T16:55:26.013",
"Id": "461019",
"Score": "0",
"body": "@SamStafford I learned something new today!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T06:32:07.757",
"Id": "461079",
"Score": "0",
"body": "@SamStafford I was aware of this gotcha, but I never really understood *why* Python would implement default arguments this way. It seemed rather counterintuitive when I first learned it..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T22:15:47.047",
"Id": "461191",
"Score": "0",
"body": "That `children or []` is really smooth"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T08:24:44.827",
"Id": "235499",
"ParentId": "235495",
"Score": "11"
}
},
{
"body": "<p>I would suggest a turned around approach: compute the depth upon construction of the nodes. This is pure, and makes sure it is only computed once. It requires you to treat the class as immutable, though (i.e., no later extending of <code>children</code>), which might or might not be fine in your use case.</p>\n\n<pre><code>class Node:\n \"\"\"\n Node in a tree, with children stored in a list.\n \"\"\"\n\n def __init__(self, key, children = None):\n self.key = key\n\n if children is None:\n self.children = []\n else:\n self.children = children\n\n self.depth = max((c.depth for c in self.children), default = 0) + 1\n\nroot = Node('n1', [Node('n2'), Node('n3', [Node('n4'), Node('n5')])])\n\nprint(root.depth) # 3\nprint(root.children[0].depth) # 1\nprint(root.children[1].depth) # 2\nprint(root.children[1].children[0].depth) # 1\n</code></pre>\n\n<p><code>default</code> is an extra argument to <code>max</code> which tells it what to return in the case of <code>children</code> being empty.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T16:13:28.280",
"Id": "235513",
"ParentId": "235495",
"Score": "2"
}
},
{
"body": "<p>Modifying state in a recursive function is a bad idea if you can avoid it. If a function does not modify state, it becomes a pure function; such functions are easier to reason about and test. To produce output, the best way is usually to <em>return</em> a value.</p>\n\n<p>But first, a word on the <a href=\"https://stackoverflow.com/questions/2603692/what-is-the-difference-between-tree-depth-and-height\">terminology</a> you chose. In computer science, the <em>depth</em> of a tree node refers to how far it is from the root node; in other words, how far you can walk up. The value you are computing, is how far you can walk down from a node, which is commonly called the <em>height</em> of a node.</p>\n\n<p>Your original function, renamed to <code>height</code>, is:</p>\n\n<pre><code>def height(node, currentHeight, currentMaxContainer):\n currentHeight += 1\n if currentHeight > currentMaxContainer[0]:\n currentMaxContainer[0] = currentHeight\n\n for child in node.children:\n if child is not None:\n height(child, currentHeight, currentMaxContainer)\n</code></pre>\n\n<p>Let's modify it so it doesn't modify <code>currentMaxContainer</code>, but returns a value instead:</p>\n\n<pre><code>def height(node, currentHeight):\n for child in node.children:\n if child is not None:\n child_height = height(child, currentHeight)\n if child_height > currentHeight:\n currentHeight = child_height\n\n return currentHeight + 1\n</code></pre>\n\n<p>Now it finds the maximum height of its children, adds 1 (for the current node), and returns that. Usage is now <code>print(height(startNode, startHeight))</code>, or <code>print(height(rootNode, 0))</code>.</p>\n\n<p>We can make the fact that it finds the maximum height of its children more explicit:</p>\n\n<pre><code>def height(node, currentHeight):\n max_height = 0\n for child in node.children:\n if child is not None:\n child_height = height(child, 0)\n if child_height > max_height:\n max_height = child_height\n\n return currentHeight + max_height + 1\n</code></pre>\n\n<p>This brings into question: why is <code>currentHeight</code> passed as an argument? It's only used once, and added to the total result. Really, the function doesn't care what some height (depth?) above the current node is, it should only concern itself with the height <em>below</em> the current node. It's a bit of outside state that is irrelevant. After all, you can just add any <code>currentHeight</code> value to the return value of <code>height()</code>!</p>\n\n<pre><code>def height(node):\n max_height = 0\n for child in node.children:\n if child is not None:\n child_height = height(child)\n if child_height > max_height:\n max_height = child_height\n\n return max_height + 1\n</code></pre>\n\n<p>This finds the height of the subtree referred to by <code>node</code> (a definition now completely consistent with common CS terminology). Usage is now <code>print(height(startNode) + startHeight)</code>, or <code>print(height(rootNode) + 0)</code>, which obviously becomes <code>print(height(rootNode))</code>.</p>\n\n<p>Having removed unnecessary state from the function, it becomes easier to simplify. First, let's consider that <code>None</code> case; a child that is <code>None</code> should not increase <code>max_height</code>, that's what the <code>if</code> is for. But if we specify that <code>height(None) = 0</code>, then we don't need that test in the loop:</p>\n\n<pre><code>def height(node):\n if node is None:\n return 0\n\n max_height = 0\n for child in node.children:\n child_height = height(child)\n if child_height > max_height:\n max_height = child_height\n\n return max_height + 1\n</code></pre>\n\n<p>The remaining loop is just finding the maximum of <code>height(child)</code> for all children, which can be expressed a lot shorter and more Pythonic:</p>\n\n<pre><code>def height(node):\n if node is None:\n return 0\n\n return max(map(height, node.children), default=0) + 1\n</code></pre>\n\n<p>Alternatively, we could filter out the <code>None</code> children like we did before with the explicit test:</p>\n\n<pre><code>def height(node):\n return max(map(height, filter(None, node.children)), default=0) + 1\n</code></pre>\n\n<p>But I like the previous version better, because it is more explicit.</p>\n\n<p>Those <code>None</code> children are a bit of a recurring headache though, and that will be the case for any code that has to iterate over a node's children. I recommend simply disallowing that case. In other words, <code>node.children</code> should only contain (0 or more) valid children, never any <code>None</code>s. This should simplify a lot of code that interacts with your trees. The function then is simply:</p>\n\n<pre><code>def height(node):\n return max(map(height, node.children), default=0) + 1\n</code></pre>\n\n<p>And finally, this function should really be a method on the class:</p>\n\n<pre><code>class Node:\n ...\n\n def height(self):\n return max(c.height() for c in self.children), default=0) + 1\n</code></pre>\n\n<p>Usage then finally becomes <code>print(startNode.height() + startHeight)</code>, or <code>print(rootNode.height())</code>.</p>\n\n<p>Note that tree structures are very common, so there are libraries implementing them along with common tree operations. You may want to use one of those, or perhaps look at their APIs and/or source for inspiration. One such library for Python is <a href=\"https://pypi.org/project/anytree/\" rel=\"nofollow noreferrer\">anytree</a> (no affiliation or endorsement).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T17:48:33.883",
"Id": "235518",
"ParentId": "235495",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T07:00:19.817",
"Id": "235495",
"Score": "11",
"Tags": [
"python",
"python-3.x",
"recursion"
],
"Title": "Python: pass \"mutable integer\" in recursion"
}
|
235495
|
<p>I have a requirement to send emails when certain errors are logged(using <strong>log4j 1.2.17</strong>). But the SMTP appender sends emails in a synchronized manner. I <strong>can not use the AsyncAppender</strong> either. So I have written my own custom appender and an email sender which utilizes the <strong>javax.mail</strong> library. The custom appender creates a fixed thread pool of 5 threads using the ExecutorService, and in the custom Appenders <strong>append()</strong> method I create an object of the email sender class that I have written and submit that to the thread pool. </p>
<p>The Code for the custom appender is as following(some of the non-important segments have been removed eg: some parameters when creating an instance of emailSender)</p>
<pre class="lang-java prettyprint-override"><code>public class emailAppender extends AppenderSkeleton {
private static ExecutorService threadPool = null;
static {
threadPool = Executors.newFixedThreadPool(5);
}
@Override
protected void append(LoggingEvent event) {
if(this.closed != true){
emailSender emailNotification = new emailSender(
event.getMessage().toString(),getReceiver());
threadPool.submit(emailNotification);
}
}
public void close() {
this.closed=true;
}
public boolean requiresLayout() {
return false;
}
}
</code></pre>
<p>The code for the email sender is as follows</p>
<pre class="lang-java prettyprint-override"><code>public class emailSender implements Runnable {
public emailSender( password, String message, String receiver){
this.message=message;
this.receiver=receiver;
}
public void run() {
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", getSmtpPort());
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(getSmtpUsername(),getSmtpPassword());
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(getSmtpUsername()));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(getReceiver()));
message.setSubject(getSubject());
message.setText(getMessage());
Transport.send(message);
System.out.println("Notification sent successfully to " + getReceiver() + " for Error : " + getMessage());
} catch (MessagingException e) {
e.printStackTrace();
}
}
</code></pre>
<p>The size of the thread pool was determined considering the maximum number of errors that get logged at one time. And also the downside of the solution being asynchronous is that the logs might not actually get emailed which is acceptable for us.</p>
<p>Currently, this code works fine for me. I would want to know if this code is acceptable for production without considering the fact that the logs might not get emailed due to asynchronous behavior.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T12:54:41.003",
"Id": "460987",
"Score": "0",
"body": "Welcome to CodeReview@SE! Pretty good presentation of how context limited choice in design&implementation."
}
] |
[
{
"body": "<p>The <em>UpperCamelCase</em> format is used to name types. You should rename your classes (and constructors) to <code>EmailAppender</code> and <code>EmailSender</code>.</p>\n\n<p>The <code>ExecutorService</code> has a <code>shutdown</code> method that you can use to reject new tasks and terminate the current ones. You may shutdown your pool form the <code>close</code> method. And there is a nice code sample in the official documentation : <a href=\"https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/ExecutorService.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/ExecutorService.html</a></p>\n\n<p>I guess you should also avoid to use <code>System.out.println</code> and <code>e.printStackTrace()</code>. They will both print unexpected messages on the console. Imagine that your code will be shipped in a library, once a dev will use your library he will suddenly got things printed on his console.</p>\n\n<p>Aside of that I don't see anything wrong. </p>\n\n<p>On a more personal point of view, I would have tried to extract the \"configuration\" (Creation of <code>Properties</code> and creation of the instance) to another class so that you make a clear distinction between the conversion of the <code>LoggingEvent</code> to an email and the sending of an email message.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-16T11:44:39.053",
"Id": "461534",
"Score": "0",
"body": "should I be using `pool.shutdown()` or `pool.shutdownNow()` if the logging should happen until the server is shut down? I do not understand if there is a situation that I would want to explicitly stop receiving new tasks and terminating the current tasks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-20T10:54:29.680",
"Id": "461881",
"Score": "0",
"body": "Well, it is up to you. But teh documentation provide a great exampel of gracefull shutdown."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T13:02:21.930",
"Id": "235606",
"ParentId": "235501",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "235606",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T09:44:04.353",
"Id": "235501",
"Score": "1",
"Tags": [
"java",
"asynchronous",
"email"
],
"Title": "Asynchronous logging using custom log4j appender and ExecutorService"
}
|
235501
|
<p>This is a follow-up to <a href="https://codereview.stackexchange.com/questions/235337/nested-if-working-like-an-excel-sumif-for-two-unequal-lists-summing-the-distanc/235421#235421">previous post</a>, code is significantly better thanks to comments. The problem is that now it takes 0.25 seconds to iterate 1 row of VehicleEvents through 95000 rows of GPS information. At this rate, with 370k rows of VehicleEvents, it will take me days and I was wondering if you can find a better way.</p>
<pre><code>import csv
from openpyxl.utils.datetime import from_excel, to_ISO8601
import datetime
import timeit
tic = timeit.default_timer()
for x in range(1,2): # here the code will read from 34 csv files containing GPS informations into a list of lists
csvfilepath = "GpsData{}.csv".format(x)
# Here the gps data is loaded into list of lists gpsdata and the timestamp is converted to ISO8601
with open(csvfilepath, "r") as f:
reader = csv.reader(f)
headers = next(reader)
gpsdata = list(list(rec) for rec in csv.reader(f, delimiter=','))
for row in gpsdata:
try:
GpsTimestamp = datetime.datetime.strptime(row[10], '%m/%d/%Y %H:%M')
except:
GpsTimestamp = datetime.datetime.strptime(row[10], '%Y-%m-%d %H:%M:%S')
row[10] = to_ISO8601(dt=GpsTimestamp)
driving = 0
idle = 0
working = 0
prev_job_end = ['2219-12-16T05:02:10Z']
dists = [[], [], [], []] #this list of lists will capture the distances in the various states
vhfilepath = "VehicleEvents.csv"
# Capturing the headers in vehicle list
with open(vhfilepath, "r") as f:
reader = csv.reader(f)
headers = next(reader)
vehiclist = csv.DictReader(open(vhfilepath, "r"))
for r in vehiclist:
JobID = r["ID"]
vehicle_no = r['Vhcl']
mode = r['Mode']
Engineon = to_ISO8601(dt=from_excel(value=float(r["Engineon"])))
Engineoff = to_ISO8601(dt=from_excel(value=float(r["Engineoff"])))
try:
WorkStart = to_ISO8601(dt=from_excel(value=float(r["WorkStart"])))
WorkEnd = to_ISO8601(dt=from_excel(value=float(r["WorkEnd"])))
except:
WorkStart = 2000
WorkEnd = 2000
try:
ParkStart = to_ISO8601(dt=from_excel(value=float(r["ParkStart"])))
ParkEnd = to_ISO8601(dt=from_excel(value=float(r["ParkEnd"])))
except:
ParkStart = 2000
ParkEnd = 2000
driving = idle = working = 0.0
for i in range(len(gpsdata)): #I go through all rows of gps list
if i % 930000 == 0 and i != 0: # Keeping track of the program
toc = timeit.default_timer()
print('processing algorithm: {}'.format(toc - tic))
print('we are at row {}'.format(r["ID"]))
if vehicle_no == gpsdata[0][2] and Engineon <= gpsdata[i][10] <= Engineoff: #I want to exclude if the vehicle was off at the gps timestamp
c1 = gpsdata[i][10]
c2 = gpsdata[i][8]
if mode == 'DIS' :
if ParkStart <= c1 <= ParkEnd:
driving += float(c2)
if Engineon <= c1 <= ParkStart:
idle += float(c2)
else:
if ParkEnd <= c1 <= Engineoff :
driving += float(c2)
if Engineon <= c1 <= ParkEnd:
idle += float(c2)
elif vehicle_no == gpsdata[0][2] and Engineon >= gpsdata[i][10] >= prev_job_end[-1] :
working += float(gpsdata[i][8])
prev_job_end.append(Engineoff)
toc = timeit.default_timer()
dists[0].append(JobID)
dists[1].append(driving)
dists[2].append(idle)
dists[3].append(working)
driving = idle = working = 0.0
with open("outfile{}.csv".format(x), 'w') as outfile:
outfile_writer = csv.writer(outfile, delimiter=",", quotechar='"', quoting=csv.QUOTE_MINIMAL)
outfile_writer.writerow((dists[0], dists[1], dists[2], dists[3])),
tac = timeit.default_timer()
print('exporting {}'.format(tac - toc))
</code></pre>
<p>Sample data:</p>
<pre>
GpsData =
AA,ddate,gps_id,latitude,longitude,speed,accuracy,bearing,distance,ip,Timestamp
6631060599,20191216,V001,50.94269749,71.30314074,0.61,16.687,120.2,4564.41,,12/16/2019 0:00
6631065030,20191216,V001,50.9437751,71.30016186,7.46,33.374,0,48356.2,,12/16/2019 4:31
6631065153,20191216,V001,50.94291191,71.30116373,4.04,24.272,31.6,12747.4,,12/16/2019 19:07
6631060271,20191217,V001,50.94866914,71.30378451,4.49,4.551,0,8368.56,,12/17/2019 17:10
6631060630,20191218,V001,50.94821482,71.30276768,5.16,50.061,27.7,28869.4,,12/18/2019 4:54
6631069096,20191219,V001,50.94534268,71.30259522,2.11,24.272,63.1,9506.68,,12/19/2019 2:55
6631059877,20191219,V001,50.94332513,71.30145316,1.72,10.619,32.4,14834.6,,12/19/2019 17:13
6631068956,20191219,V001,50.94716712,71.30282306,3.14,21.238,300.4,11038.9,,12/19/2019 21:33
6631067712,20191220,V002,50.93724855,71.29651212,9.71,18.204,206,96770.7,,12/20/2019 16:22
6631065674,20191221,V002,50.9467955,71.30202786,6.96,15.008,31.1,28784.4,,12/21/2019 0:07
6631061274,20191221,V002,50.94207924,71.29937677,7.86,30.34,194.3,43064.3,,12/21/2019 14:15
6631063673,20191221,V002,50.94591501,71.30136721,0.83,22.755,293,27036.3,,12/21/2019 18:37
6631064438,20191221,V002,50.94743564,71.30240991,0.56,39.442,259.7,3525.12,,12/21/2019 22:25
6631060673,20191222,V002,50.94580669,71.30148016,5.55,13.653,204.3,53280,,12/22/2019 3:26
6631068423,20191222,V002,50.91783065,71.28983391,6.24,28.823,2.5,42947.8,,12/22/2019 4:14
6631066879,20191222,V002,50.94432872,71.30065772,6.25,19.721,209.8,36728.9,,12/22/2019 11:44
6631068174,20191223,V002,50.93346341,71.29449935,9.26,25.789,28.8,42795.9,,12/23/2019 4:02
VehicleEvents =
ID,Vhcl,Mode,CID,Engineon,Engineoff,WorkStart,WorkEnd,ParkStart,ParkEnd
85807835,V001,Manual,AAA5846129341,43815.08135,43815.08938,,,43815.07334,43815.08211
85809668,V001,Auto,AAA8022407504,43815.08938,43815.10535,43815.08938,43815.10535,43815.08938,43815.09535
85810976,V001,Auto,AAA0571518764,43815.10538,43815.11505,43815.10538,43815.11505,43815.10959,43815.11505
85813025,V001,Manual,AAA3189634914,43815.11506,43815.12703,43815.11506,43815.12703,43815.11506,43815.12303
85813028,V001,Manual,AAA1940741282,43815.11506,43815.12703,,,43815.11506,43815.12372
85815305,V001,Manual,AAA1894455904,43815.12705,43815.14505,43815.12705,43815.14692,43815.13366,43815.14505
85815467,V001,Auto,AAA9538532026,43815.12705,43815.14692,,,43815.13361,43815.14692
85821410,V001,Auto,AAA8391952906,43815.14696,43815.20984,43815.14696,43815.20984,43815.14696,43815.15206
85873358,V001,Manual,AAA4922964611,43815.72992,43815.74645,43815.72992,43815.74645,43815.73586,43815.74645
85875020,V001,Manual,AAA6039158858,43815.74646,43815.76461,43815.74646,43815.76601,43815.75975,43815.76461
85875137,V001,Manual,AAA7495366053,43815.74646,43815.76601,,,43815.75972,43815.76601
85877825,V001,Auto,AAA7638509608,43815.76602,43815.79272,43815.76602,43815.79429,43815.76602,43815.77079
85877942,V001,Auto,AAA1265572219,43815.76602,43815.79429,,,43815.76602,43815.76985
85879040,V001,Manual,AAA2968711840,43815.79431,43815.80431,43815.79431,43815.80431,43815.79431,43815.80127
85882028,V001,Manual,AAA7692514875,43815.80432,43815.83537,43815.80432,43815.83537,43815.80432,43815.82109
85884230,V001,Manual,AAA4674654439,43815.83538,43815.85745,43815.83538,43815.85745,43815.83538,43815.84685
85885460,V001,Auto,AAA8107186366,43815.85748,43815.86895,43815.85748,43815.86895,43815.86016,43815.86895
85885994,V001,Auto,AAA5796012701,43815.86916,43815.875,43815.86916,43815.875,43815.87164,43815.875
85886981,V001,Manual,AAA8719492664,43815.87502,43815.88547,43815.87502,43815.88547,43815.8795,43815.88547
85890116,V001,Manual,AAA2865936367,43815.88549,43815.91355,43815.88549,43815.91355,43815.89722,43815.9073
85890119,V001,Manual,AAA1887612592,43815.88549,43815.91355,,,43815.88549,43815.8972
85891310,V001,Auto,AAA1144467605,43815.91358,43815.92514,43815.91358,43815.92514,43815.91856,43815.92514
85892144,V001,Auto,AAA3719694551,43815.92516,43815.93397,43815.92516,43815.93523,43815.92922,43815.93397
</pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T13:12:34.590",
"Id": "460990",
"Score": "0",
"body": "Time has gone up from [3 seconds](https://codereview.stackexchange.com/revisions/235337/5) to 25? Bummer! I thought [Irnv' approach](https://codereview.stackexchange.com/a/235359) most promising - have you given it a try? Results?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T13:20:20.053",
"Id": "460991",
"Score": "1",
"body": "The data sample sucks for showing events for one vehicle, only. (For error tests, it would be essential to include at least one vehicle without events & vice-versa.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T13:55:04.090",
"Id": "460997",
"Score": "0",
"body": "`prev_job_end = ['2219-12-16T05:02:10Z']` is bound to give misleading timings on top of disappointing results."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T14:05:53.443",
"Id": "460999",
"Score": "0",
"body": "@greybeard Mistyped, it's much faster. It's 250ms! Noted for the error testing. Can you think of alternative for **prev_job_end = ['2219-12-16T05:02:10Z']** ? I have tested it though and I see no logical problem.\nAbout the approach I'll check now"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T14:16:15.580",
"Id": "461001",
"Score": "1",
"body": "It's almost two centuries 'till 2219, try `'2019-…'` (and adjust .25 as need arises)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T15:43:58.003",
"Id": "461007",
"Score": "1",
"body": "Why do I read a zero in two occurrences of `gpsdata[0][2]`? Shouldn't that be `gps_data[i][GPS_ID]`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T17:19:09.927",
"Id": "461020",
"Score": "0",
"body": "I'm not familiar with the performance characteristics of `csv.reader`, but is it possible you're getting sub-optimal I/O speeds because of how you're reading in the data? What if you loaded it all into memory up front?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T17:55:39.897",
"Id": "461022",
"Score": "0",
"body": "@SamStafford Thanks, how do I do that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T17:58:22.770",
"Id": "461023",
"Score": "0",
"body": "@greybeard gpsdata[0][2] is indeed column GPS_ID and should not be zero"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T17:59:17.443",
"Id": "461024",
"Score": "1",
"body": "I don't complain the value to be zero, but the 1st index."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T18:10:02.383",
"Id": "461025",
"Score": "0",
"body": "@greybeard yes you are right!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T01:28:24.560",
"Id": "461069",
"Score": "0",
"body": "Variable and function names should follow the `lower_case_with_underscores` style."
}
] |
[
{
"body": "<p>I find the code presented here notably more readable than the previous iteration - the main apparent difference is meaningful naming of variables (most not in snake_case, yet).</p>\n\n<p>It looks like you want the results in one file per file of GpsData:<br>\nsuch should be specified explicitly, as should be whether output records <em>need to</em> stay in the order of jobs in the vehicle event file (with \"prev\"<code>job_end</code> taken care of).</p>\n\n<p>You read the vehicle event file once per file of GpsData - if you don't expect it to change, don't:<br>\nread it once before even touching the GpsData. Into a <code>dict</code> with \"Vhcl\" as key (see below)</p>\n\n<p>Given <code>csv.DictReader</code>'s ability to handle fieldnames, don't open code that.</p>\n\n<p>You don't use the list of <code>prev_job_end</code>s: just keep one.</p>\n\n<p>Why convert datetimes to ISO8601?</p>\n\n<hr>\n\n<p>(running out of time.<br>\nChecking every combination of GPS×event record most likely kills your time performance, vectorised&filtered or not.<br>\nMy current take: event list per vehicle, ordered by timestamp<br>\ngot fed up with all the indexing and conversion, introduced classes. Work in progress:<br>\nclasses & reading vehicles</p>\n\n<pre><code>#@functools.total_ordering()\nclass Gps:\n def __init__(self, distance, timestamp):\n self.distance = distance\n self.timestamp = timestamp\n\n def __str__(self):\n return \"Gps(\" + str(self.distance) + \", \" + str(self.timestamp) + ')'\n\n def __eq__(self, other):\n return self.timestamp == other.timestamp\n\n def __lt__(self, other):\n return self.timestamp < other.timestamp\n\n def __le__(self, other):\n return self.timestamp <= other.timestamp\n\n def __ge__(self, other):\n return self.timestamp >= other.timestamp\n\n def __gt__(self, other):\n return self.timestamp > other.timestamp\n\n\nclass Vehicle_event:\n def __init__(self, mode, engine_on, engine_off,\n work_start, work_end, park_start, park_end):\n self.mode = mode\n self.engine_on = engine_on\n self.engine_off = engine_off\n self.work_start = work_start\n self.work_end = work_end\n self.park_start = park_start\n self.park_end = park_end\n\n def __str__(self):\n return '<'+self.mode+\", \".join((\"\",\n str(self.engine_on), str(self.engine_off),\n str(self.work_start), str(self.work_end),\n str(self.park_start), str(self.park_end)))+'>'\n\nclass Vehicle:\n def __init__(self, vid):\n self.id = vid\n self.events = []\n self.gps = []\n</code></pre>\n\n<p>reading vehicle events:</p>\n\n<pre><code>EVENTDEFAULT = 2000 # whatever is appropriate\n\n\ndef event2timestamp(index, row, default=None):\n if default:\n try:\n return from_excel(float(row[index] # .strip()\n )).timestamp()\n except:\n return default\n return from_excel(float(row[index] # .strip()\n )).timestamp()\n\n\ndef read_records(csv_path, key_name):\n \"\"\" Read records from the CSV file named into lists that are values of a\n dict keyed by the values of column key_name.\n Return this directory.\n \"\"\"\n with open(csv_path, \"r\") as f:\n records = dict() # defaultdict(list)\n rows = csv.reader(f)\n header = next(rows)\n KEY_INDEX = header.index(key_name)\n # JOB_ID = header.index(\"ID\")\n # VEHICLE_NO = header.index('Vhcl')\n MODE = header.index('Mode')\n ENGINE_ON = header.index(\"Engineon\")\n ENGINE_OFF = header.index(\"Engineoff\")\n WORK_START = header.index(\"WorkStart\")\n WORK_END = header.index(\"WorkEnd\")\n PARK_START = header.index(\"ParkStart\")\n PARK_END = header.index(\"ParkEnd\")\n for row in rows:\n vid = row[KEY_INDEX]\n vehicle = records.get(vid)\n if None is vehicle:\n vehicle = Vehicle(vid)\n records[vid] = vehicle\n vehicle.events.append(Vehicle_event(\n row[MODE],\n event2timestamp(ENGINE_ON, row),\n event2timestamp(ENGINE_OFF, row),\n event2timestamp(WORK_START, row, EVENTDEFAULT),\n event2timestamp(WORK_END, row, EVENTDEFAULT),\n event2timestamp(PARK_START, row, EVENTDEFAULT),\n event2timestamp(PARK_END, row, EVENTDEFAULT)))\n return records\n\n\ndef read_vehicle_events():\n return read_records(\"VehicleEvents.csv\", 'Vhcl')\n\n\nvehicles = read_vehicle_events()\n</code></pre>\n\n<p>outermost loop over GPS files, inner loops over vehicles and events:</p>\n\n<pre><code>for x in range(1, 2): # 34): # handle CSV files containing GPS records\n csvfilepath = \"GpsData{}.csv\".format(x)\n # Here the GPS data is appended to lists of Gps\n with open(csvfilepath, \"r\") as f:\n reader = csv.reader(f)\n headers = next(reader)\n COLUMNS = len(headers)\n ID = headers.index('gps_id')\n DISTANCE = headers.index('distance')\n TIMESTAMP = headers.index('Timestamp')\n eventless = defaultdict(int)\n for rec in reader:\n if len(rec) < COLUMNS:\n continue\n vid = rec[ID]\n vehicle = vehicles.get(vid)\n if None is vehicle:\n eventless[vid] += 1\n else:\n timestamp = rec[TIMESTAMP]\n try:\n gps_timestamp = datetime.datetime.strptime(timestamp, '%m/%d/%Y %H:%M')\n except:\n gps_timestamp = datetime.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S')\n vehicle.gps.append(Gps(float(rec[DISTANCE]),\n gps_timestamp.timestamp()))\n\n print(eventless)\n\n dists = [[]]*4 # distances in the various states\n\n for vehicle in vehicles.values():\n vehicle.gps = sorted(vehicle.gps)\n prev_job_end = datetime.datetime(2019, 12, 15, 5, 2, 10).timestamp()\n\n driving = idle = working = 0.0\n first, beyond = 0, len(vehicle.gps)\n\n for job in vehicle.events:\n first = bisect_left(vehicle.gps, Gps(0, prev_job_end), 0, # first?\n beyond)\n beyond = bisect_right(vehicle.gps, Gps(0, job.engine_off), first)\n for g in range(first, beyond): # all Gps from previous Engineoff to current\n gps = vehicle.gps[g]\n timestamp = gps.timestamp\n distance = gps.distance\n if timestamp < job.engine_on:\n if prev_job_end <= timestamp:\n working += distance\n elif job.mode == 'DIS':\n if timestamp <= job.park_start:\n idle += distance\n elif timestamp <= job.park_end:\n driving += distance\n else:\n if job.park_end <= timestamp:\n driving += distance\n else:\n idle += distance\n prev_job_end = job.engine_off\n vehicle.events.clear()\n\n dists[0].append(vehicle.id)\n dists[1].append(driving)\n dists[2].append(idle)\n dists[3].append(working)\n toc = timeit.default_timer()\n with open(\"outfile{}.csv\".format(x), 'w') as outfile:\n outfile_writer = csv.writer(outfile, delimiter=\",\", quotechar='\"',\n quoting=csv.QUOTE_MINIMAL)\n outfile_writer.writerow(dists)\n tac = timeit.default_timer()\n print('exporting {}'.format(tac - toc))\n</code></pre>\n\n<p>)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T20:40:25.723",
"Id": "461173",
"Score": "0",
"body": "This implementation takes 6.6 seconds per row, however since the rows are sorted, this may change\nI did not manage to use the bisect functions because I didn't understand the documentation\nHowever I did understand what you said and made an if -> continue which cut processing time a lot\nI convert to ISO8601 because I know not of a better way to compare datetimes\n\nI think I will let it run for a few hours and see if it gets faster, then compare with the previous one"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T18:49:55.537",
"Id": "235520",
"ParentId": "235502",
"Score": "2"
}
},
{
"body": "<p>With 90k gps records and 370k vehicle records, the inner loop of the current code runs <strong>33.3 Billion</strong> times. To get significant speed ups will require a different approach.</p>\n\n<p>I would suggest converting everything to an event: gps event, engineon event, engineoff event, and so on. Put it all into a big queue (list) and sort it by time stamp. It looks like the gps data and vehicle events are already sorted, or nearly so. On my machine, it takes less than a second to sort a million records. Could use a heap instead of sorting.</p>\n\n<p>Then loop through the events once, updating the status of the vehicles and jobs, and collecting data, as you go.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-29T00:22:10.053",
"Id": "236319",
"ParentId": "235502",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235520",
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T10:41:16.537",
"Id": "235502",
"Score": "6",
"Tags": [
"python",
"performance",
"datetime"
],
"Title": "Combining GPS and vehicle data using for loops and if statements to summarise the distance run under various conditions, much like a excel SUMIF"
}
|
235502
|
<p>I have this code which is a callback for Filter in WPF <code>ICollectionView</code>. When I run code analysis, the cyclometic complexity is reported to be 11. I consider this line by line comparison gives a better readability. How can I improve the cyclomatic complexity or improve this code in general?</p>
<pre><code> private bool FilterLicenseList(object item)
{
var license = item as LicenseEntry;
if (!string.IsNullOrEmpty(Filter.Firm) && !license.Firm.Contains(Filter.Firm)) return false;
if (!string.IsNullOrEmpty(Filter.RegistrationCode) && !license.RegistrationCode.Contains(Filter.RegistrationCode)) return false;
if (!string.IsNullOrEmpty(Filter.LicenseCode) && !license.LicenseCode.Contains(Filter.LicenseCode)) return false;
if (!string.IsNullOrEmpty(Filter.Branch) && !license.Branch.Contains(Filter.Branch)) return false;
if (Filter.Active != null && license.Active != Filter.Active) return false;
return true;
}
</code></pre>
|
[] |
[
{
"body": "<p>Your code has lots of duplication. You can make it more readable:</p>\n\n<pre><code>private bool FilterLicenseList(object item)\n{\n var license = item as LicenseEntry;\n return FilterString(Filter.Firm, license.Firm)\n && FilterString(Filter.RegistrationCode, license.RegistrationCode)\n && FilterString(Filter.LicenseCode, license.LicenseCode)\n && FilterString(Filter.Branch, license.Branch)\n && FilterBoolean(Filter.Active, license.Active);\n}\n</code></pre>\n\n<p>All you need to do now is to implement the two helper methods <code>FilterString</code> and <code>FilterBoolean</code>.</p>\n\n<p>I know that even the rewritten code is visually redundant since the field name appears twice in each line of code, but removing this would be more difficult. Compared to the original code I find the rewritten code much more readable, and there is no chance that in one of the lines an exclamation mark is missing, which would be pretty easy to overlook.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T12:58:49.003",
"Id": "460989",
"Score": "0",
"body": "yes this looks more readable, the `FilterString` seems to be nice Idea. But still cyclomatic complexity remains 6 (at least logically). I know many tools will point it to be a complexity of 2. \nRedundancy can be reduced (slightly) by using Exentsion methods, something like, `Filter.Firm.ApplyFilter(license.Filter)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T13:27:50.677",
"Id": "460993",
"Score": "1",
"body": "The remaining 6 is a flaw in the definition of \"cyclomatic complexity\". The code as written here is very easy to understand since in natural language it can be reduced to \"all of the conditions\", and all the conditions are independent of each other. This is something that the cyclomatic complexity does not take into account, but we humans do. Therefore, don't trust it blindly. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T15:35:28.493",
"Id": "461006",
"Score": "0",
"body": "Thank you, makes sense."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T12:43:08.990",
"Id": "235506",
"ParentId": "235503",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "235506",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T11:34:14.460",
"Id": "235503",
"Score": "4",
"Tags": [
"c#",
"wpf",
"cyclomatic-complexity"
],
"Title": "Method that filters a list parameters based on different fields"
}
|
235503
|
<p>I made a sidebar that has a slide-out feature. When you click on it, it shows more items. I made it with JS and HTML but I think the code can be done more efficiently. How can I clean the code up?</p>
<pre><code>$('.slide-out').on('click', function() {
let data = 'slideout-item';
if($(this).data(data)) {
let item = $('.slide-out-' + $(this).data(data));
if(item.hasClass('slideout-active')) {
item.hide("slide", { direction: "left" }, 250);
item.removeClass('slideout-active');
$('.slide-out-overlay').fadeOut()
} else {
item.show("slide", { direction: "left" }, 250);
item.addClass('slideout-active');
$('.slide-out-overlay').fadeIn()
}
}
});
$('.slide-out-overlay').on('click', function () {
let items = ['content', 'system', 'account', 'other'];
let item = '.slide-out-';
for (i = 0; i < items.length; i++) {
if($(item + items[i]).hasClass('slideout-active')) {
$(item + items[i]).hide("slide", { direction: "left"}, 250);
$(item + items[i]).removeClass('slideout-active');
$('.slide-out-overlay').fadeOut();
}
}
});
<ul class="list-unstyled">
<li class="sidebar-item title">{{ __('Information') }}</li>
<li class="sidebar-item"><a href="{{ route('home') }}" class="sidebar-link {{ Route::currentRouteNamed('home') ? 'sidebar-active' : '' }}">{{ __('Dashboard') }}</a></li>
<li class="sidebar-item title">{{ __('System') }}</li>
<li class="sidebar-item"><a href="#" class="sidebar-link slide-out" data-slideout-item="content">Content<i class="far fa-chevron-right" style="position:absolute; right: 0;"></i></a></li>
<li class="sidebar-item"><a href="#" class="sidebar-link slide-out" data-slideout-item="system">System<i class="far fa-chevron-right" style="position:absolute; right: 0;"></i></a></li>
<li class="sidebar-item"><a href="#" class="sidebar-link slide-out" data-slideout-item="account">Account<i class="far fa-chevron-right" style="position:absolute; right: 0;"></i></a></li>
<li class="sidebar-item"><a href="#" class="sidebar-link slide-out" data-slideout-item="other">Other<i class="far fa-chevron-right" style="position:absolute; right: 0;"></i></a></li>
</ul>
<div class="slide-out-block shadow slide-out-content" id="slide-out">
<nav class="sidebar-slideout">
<ul class="list-unstyled">
<li class="sidebar-item title">{{ __('Content') }}</li>
<li class="sidebar-item"><a href="{{ route('pages') }}" class="sidebar-link {{ Route::currentRouteNamed('pages') ? 'sidebar-active' : '' }}">{{ __('Pages') }}</a></li>
<li class="sidebar-item"><a href="{{ route('blocks') }}" class="sidebar-link {{ Route::currentRouteNamed('blocks') ? 'sidebar-active' : '' }}">{{ __('Blocks') }}</a></li>
<li class="sidebar-item"><a href="{{ route('layouts') }}" class="sidebar-link {{ Route::currentRouteNamed('layouts') ? 'sidebar-active' : '' }}">{{ __('Layouts') }}</a></li>
</ul>
</nav>
</div>
</code></pre>
|
[] |
[
{
"body": "<p>It has been a while since I worked with <code>jQuery</code> so I may not get specific API's correct.</p>\n\n<ol>\n<li>You are repeating <code>(\"slide\", { direction: \"left\"}, 250)</code>, if you ever changed one of the properties I would assume you'd want them to be consistent with each other. You can set an array then destructure that when calling <code>show</code> or <code>hide</code>. You can also apply this theory to your strings such as <code>slide-out-overlay</code> and <code>slideout-active</code> for example, if you find yourself typing the same strings out, generally you want to put them in a variable (ideally a <code>const</code>)</li>\n</ol>\n\n<pre><code>// OLD\n$('.slide-out').on('click', function() {\n ...\n item.hide(\"slide\", { direction: \"left\" }, 250);\n ...\n});\n\n$('.slide-out-overlay').on('click', function () {\n ...\n item.hide(\"slide\", { direction: \"left\" }, 250);\n});\n\n// NEW\nconst toggleArguments [\"slide\", { direction: \"left\" }, 250]\n$('.slide-out').on('click', function() {\n ...\n item.hide(...toggleArguments);\n ...\n});\n\n$('.slide-out-overlay').on('click', function () {\n ...\n item.hide(...toggleArguments);\n});\n</code></pre>\n\n<ol start=\"2\">\n<li>It's common practice to use guard clauses, to reduce nesting. Closely related is early return's too, you should never really need the <code>else</code> statement.</li>\n</ol>\n\n<pre><code>// OLD\n$('.slide-out').on('click', function() {\n let data = 'slideout-item';\n if($(this).data(data)) {\n let item = $('.slide-out-' + $(this).data(data));\n if (something) {\n ...\n } else {\n ...\n }\n }\n});\n\n// NEW\n$('.slide-out').on('click', function() {\n let data = 'slideout-item';\n if (!$(this).data(data)) {\n return;\n }\n\n if (item.hasClass('slideout-active') {\n ...\n return;\n }\n\n // do code for !item.hasClass('slideout-active')\n});\n</code></pre>\n\n<ol start=\"3\">\n<li>It is sometimes clearer to put a <code>$</code> in front of variables that are <code>jQuery</code> objects</li>\n</ol>\n\n<pre><code>// OLD\nlet item = $('.slide-out-' + $(this).data(data));\n\n// NEW\nlet $item = $('.slide-out-' + $(this).data(data));\n</code></pre>\n\n<ol start=\"4\">\n<li>In your <code>.slide-out-overlay</code> click function, you are finding <code>.slide-out-overlay</code> again within the function block, when you already have the element in <code>this</code></li>\n</ol>\n\n<pre><code>// OLD\n$('.slide-out-overlay').on('click', function () {\n ...\n $('.slide-out-overlay')...\n});\n\n// NEW\n$('.slide-out-overlay').on('click', function() {\n $(this)...\n});\n</code></pre>\n\n<ol start=\"5\">\n<li>In your <code>.slide-out-overlay</code> click function you are looping over any array of strings and then checking if the relevant element has class <code>slideout-active</code>. Could you not just look for elements that have <code>slideout-active</code>?</li>\n</ol>\n\n<pre><code>// OLD\n$('.slide-out-overlay').on('click', function () {\n let items = ['content', 'system', 'account', 'other'];\n let item = '.slide-out-';\n for (i = 0; i < items.length; i++) {\n if($(item + items[i]).hasClass('slideout-active')) {\n ...\n});\n\n// NEW\n$('.slide-out-overlay').on('click', function () {\n const $items = $('.slideout-active');\n $items.hide(\"slide\", { direction: \"left\"}, 250); // .hide works on an array of elements, as do most jQuery methods\n ...\n});\n</code></pre>\n\n<ol start=\"6\">\n<li><p>You seem to be using <code>let</code> where you can use <code>const</code>. Only ever use <code>let</code> if you are modifying the value later on. Otherwise use <code>const</code></p></li>\n<li><p>String interpolation is also an option to concatante your strings. Although with jQuery may look a little confusing</p></li>\n</ol>\n\n<pre><code>// OLD\nlet item = $('.slide-out-' + $(this).data(data));\n\n// NEW\nlet item = $(`.slide-out-${$(this).data(data)}`);\n</code></pre>\n\n<p>I would also challenge you to write this without jQuery and use vanilla javascript and CSS transitions on the classes.</p>\n\n<p>Hopefully that helps!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T16:40:17.023",
"Id": "235514",
"ParentId": "235504",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "235514",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T11:42:19.640",
"Id": "235504",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "Sidebar with slide-out feature"
}
|
235504
|
<p>I have the following function that is supposed to compare current and historical transactions for each id. The logic seems to work ok, but the performance is extremely low for the amount of data I'm processing (about 20 million records); more than 10 hours to run. What can I do to improve the performance?</p>
<h1>Functions</h1>
<pre><code>def compare_historical(data):
month_start = datetime.now().replace(day=1).isoformat()
data_1 = data[data['trxn_datetime'] >= month_start ]
data_1 = data_1[['id', 'amount']].groupby('id').agg(
{'amount': 'sum'}).reset_index()
data_n = data[data['trxn_datetime'] < month_start]
data_n = data_n[data_n['id'].isin(data_1['id'])
data_n = data_n.set_index('trxn_datetime')
data_n = data_n.groupby('id').apply(
lambda g: _compare_trend(g)).reset_index()
data_1 = data_1.merge(data_n, on='id', how='right')
data_1 = data_1[data_1['amount'] >= data_1[0]]
data = data[data['id'].isin(data_1['id'])]
return data
def _compare_trend(group):
group = group['amount'].resample('1M').apply('sum')
group = group[group != 0]
mean = group.mean()
std = group.std()
return mean + 2 * std
</code></pre>
<h1>Testing</h1>
<pre><code>import pandas as pd
import io
import requests
from datetime import datetime
url="https://api.mockaroo.com/api/49d8d220?count=1000&key=1d2c2410"
s=requests.get(url).content
c=pd.read_csv(io.StringIO(s.decode('utf-8')))
c['trxn_datetime'] = pd.to_datetime(c['trxn_datetime'])
compare_historical(c)
</code></pre>
<h1>cProfile-ing</h1>
<p>Here is some profiling I did using the mock data (with 40 million records and 3135 ids). The only difference is that this data has a limited number of id's compared to actual data.</p>
<p><a href="https://i.stack.imgur.com/gmG8x.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gmG8x.png" alt="enter image description here"></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T12:04:16.643",
"Id": "460984",
"Score": "2",
"body": "\"*performance is extremely low*\" - in what aspects? RAM, execution time? What are your current performance metrics?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T12:35:19.210",
"Id": "460986",
"Score": "0",
"body": "I'm mainly talking about time, it takes about 10+ hours currently."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T21:17:15.917",
"Id": "461041",
"Score": "2",
"body": "Have you tried using a profiler to figure out what part is running so slowly? You need to figure out what the problem is before you can fix it; it might be that the slow part isn't even in your own code. \nhttps://docs.python.org/3/library/profile.html"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T02:45:19.253",
"Id": "461075",
"Score": "0",
"body": "Thanks @SamStafford I added the cprofile."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T13:02:57.053",
"Id": "461109",
"Score": "1",
"body": "The image is of limited usefulness, but seems to suggest that your Python code is fine actually. If you don't have enough memory to keep all the data in core, that's probably the root cause for the slowness (the OS ends up swapping memory regions out to disk and back in repeatedly, i.e. [thrashing](https://en.wikipedia.org/wiki/Thrashing_%28computer_science%29))."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-15T14:35:22.833",
"Id": "468573",
"Score": "0",
"body": "It should be `data_n = data_n[data_n['id'].isin(data_1['id'])]`, you are missing the closing `]`. In addition, I get a `KeyError: 0` in the line `data_1 = data_1[data_1['amount'] >= data_1[0]]` when trying to run your code."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T11:44:03.207",
"Id": "235505",
"Score": "3",
"Tags": [
"python",
"performance",
"python-3.x",
"pandas"
],
"Title": "Compare historical data"
}
|
235505
|
<p>I'm attempting the <a href="https://practice.geeksforgeeks.org/problems/special-stack/1" rel="nofollow noreferrer">SpecialStack</a> problem on GeeksforGeeks.</p>
<blockquote>
<p>Design a data-structure <strong>SpecialStack</strong> (using the STL of stack) that
supports all the stack operations like <strong>push()</strong>, <strong>pop()</strong>, <strong>isEmpty()</strong>,
<strong>isFull()</strong> and an additional operation <strong>getMin()</strong> which should return
minimum element from the SpecialStack. Your task is to complete all
the functions, using stack data-Structure.</p>
<p><strong>Input Format</strong>: The first line of input contains an integer <strong>T</strong> denoting
the no of test cases. Then <strong>T</strong> test cases follow. Each test case
contains two lines. The first line of input contains an integer <strong>n</strong>
denoting the number of integers in a sequence. In the second line are
<strong>n</strong> space separated integers of the stack.</p>
<p><strong>Output Format</strong>: </p>
<p>For each testcase, in a new line, print the minimum
integer from the stack. </p>
<p><strong>Your Task</strong>: </p>
<p>Since this is a function problem, you don't need to take
inputs. Just complete the provided functions.</p>
<p><strong>Constraints</strong>: </p>
<p>1 <= <strong>T</strong> <= 100 </p>
<p>1 <= <strong>N</strong> <= 100</p>
<p><strong>Example</strong>: </p>
<p><strong>Input</strong>: </p>
<p>1 </p>
<p>5 18 19 29 15 16 </p>
<p><strong>Output</strong>: 15</p>
</blockquote>
<p>This is my code, including the Driver Code which was provided beforehand by the interface (the Driver Code is <em>not</em> modifiable):</p>
<pre><code>// { Driver Code Starts
#include<iostream>
#include<stack>
using namespace std;
void push(int a);
bool isFull(int n);
bool isEmpty();
int pop();
int getMin();
//This is the STL stack (http://quiz.geeksforgeeks.org/stack-container-adaptors-the-c-standard-template-library-stl/).
stack<int> s;
int main(){
int t;
cin>>t;
while(t--){
int n,a;
cin>>n;
while(!isEmpty()){
pop();
}
while(!isFull(n)){
cin>>a;
push(a);
}
cout<<getMin()<<endl;
}
}// } Driver Code Ends
/*Complete the function(s) below*/
int minEle = 0; // Holds minimum element so far, as elements are pushed into stack
void push(int a)
{
if (s.empty()) // If stack is empty push a and update minEle to a
{
minEle = a;
s.push(a);
return;
}
if (a < minEle) // If a is less than minEle push (a-minEle) and update minEle to a
{
s.push(a - minEle);
minEle = a;
return;
}
if (a > minEle) // If a is greater than minEle then push a but don't update minEle
{
s.push(a);
}
}
bool isFull(int n)
{
return (s.size() == n);
}
bool isEmpty()
{
return s.empty();
}
int pop()
{
int top = s.top();
if (top < 0) // If the top element of stack is negative, we reconstruct the previous minEle
{
minEle = minEle - top;
s.pop();
}
else // Otherwise, just pop the top element
{
s.pop();
}
return top;
}
int getMin()
{
return minEle;
}
</code></pre>
<p>I've tried to explain the logic in the comments. This code gives the correct solution for all the test cases (with positive integers) I tried so far. For instance:</p>
<blockquote>
<pre><code>For Input:
2
5
18 19 29 15 16
11
34 335 1814 86 82 7 332 82 221 95 40
Your Output is:
15
7
</code></pre>
</blockquote>
<p>which is the correct solution!</p>
<p>However, when I try to submit the code, it says:</p>
<blockquote>
<pre><code>Your program took more time than expected.Time Limit Exceeded
Expected Time Limit < 1.3672sec
Hint : Please optimize your code and submit again.
</code></pre>
</blockquote>
<p>As far as I understand, my code is <span class="math-container">\$\mathcal{O}(1)\$</span> in both time and space complexity and it uses no extra stacks. I'm not quite sure how to optimize the code runtime further. Any ideas?</p>
|
[] |
[
{
"body": "<h2>Avoid Global Variables</h2>\n<p>In the code there are 2 global variables:</p>\n<pre><code>int minEle = 0;\nstack<int> s;\n</code></pre>\n<p>Using global variables is something that all experienced programmers avoid. Global variables make the code very hard to write, debug and maintain. It is very difficult in programs larger than this one to local where a global variable is modified. Global variables can also cause C and C++ program that consist of multiple files not to link into an executable image. This is discussed on <a href=\"https://stackoverflow.com/questions/484635/are-global-variables-bad\">stackoverflow.com</a>, however, if you do a Google Search on <code>why are global variables bad</code> you will find many more references.</p>\n<h2>Avoid <code>using namespace std;</code></h2>\n<p>If you are coding professionally you probably should get out of the habit of using the <code>using namespace std;</code> statement. The code will more clearly define where <code>cout</code> and other identifiers are coming from (<code>std::cin</code>, <code>std::cout</code>). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifier<code>cout</code> you may override within your own classes, and you may override the operator <code><<</code> in your own classes as well. This <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">stack overflow question</a> discusses this in more detail.</p>\n<h2>Variable Types</h2>\n<p>It would be better to use the variable type <code>size_t</code> rather than <code>int</code> for the variables <code>t</code> and <code>n</code>. The restrictions on both <code>t</code> and <code>n</code> indicates that the value will never be less than 1, which means the value will never be less than zero. The variable type <code>size_t</code> is unsigned.</p>\n<h2>Variable Names</h2>\n<p>Single letter variable names such as <code>t</code>, <code>n</code> and <code>s</code> make reading and debugging code very difficult. The variable names should really indicate what the variable is for, examples <code>testCount</code>, <code>elementCount</code>, <code>specialStack</code>. The variable <code>minEle</code>, might be better named as <code>minElement</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T16:02:16.400",
"Id": "461014",
"Score": "0",
"body": "Well, I appreciate the answer, but it doesn't really answer the real issue at hand here. Even making the changes you point out would not significantly improve the runtime of the code. Moreover, please note that the Driver Code was pre-given and is not editable; it wasn't my choice to make the stack global."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T15:46:31.187",
"Id": "235511",
"ParentId": "235508",
"Score": "1"
}
},
{
"body": "<p>If the grader is complaining about \"time limit exceeded,\" it must be because some loop is executing too many times. All of your functions are clearly O(1) — they have no loops. So which loop is executing too many times? It must be the only loop in the entire program:</p>\n\n<pre><code> while(!isFull(n)){\n cin>>a;\n push(a);\n }\n</code></pre>\n\n<p>Is it possible that your <code>isFull</code> is returning an incorrect answer? It's very straightforward: it tests <code>s.size() == n</code>. Is it possible that <code>push(a)</code> is not updating <code>s.size()</code>?</p>\n\n<p>Reflowed for brevity and clarity, your <code>push</code> looks like this:</p>\n\n<pre><code>void push(int a)\n{\n if (s.empty()) {\n minEle = a;\n s.push(a);\n } else if (a < minEle) {\n s.push(a - minEle);\n minEle = a;\n } else if (a > minEle) {\n s.push(a); \n }\n}\n</code></pre>\n\n<p>Do you see the bug yet? The problem is that when <code>a == minEle</code>, you never push anything! So if you get the input <code>1 1</code>, you'll cause the test driver to loop forever... and that is what causes the timeout.</p>\n\n<p>Also consider that there is no limit on the values of the integers you're given (just on the number of test cases <code>T</code> and the number of integers per test case <code>N</code>). So you'll have to find a way to make your code work with input <code>-1</code> as well.</p>\n\n<p>Consider maintaining a second stack <code>std::stack<int> minEle</code> alongside your <code>std::stack<int> s</code>. Does that make the problem easier?</p>\n\n<hr>\n\n<p>EDITED TO ADD: If you kept the current <code>push</code>, then you could rewrite it for <em>even more clarity</em> by factoring the <code>s.push</code> to the bottom of the function, like this:</p>\n\n<pre><code>void push(int a)\n{\n if (s.empty()) {\n minEle = a;\n } else if (a < minEle) {\n a -= std::exchange(minEle, a);\n } else if (a > minEle) {\n // do nothing\n } else {\n return; // uh-oh!\n }\n s.push(a);\n}\n</code></pre>\n\n<p>This shows clearly that each call to <code>push</code> results in one and only one call to <code>s.push</code> (except for the buggy case).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T16:51:03.110",
"Id": "461017",
"Score": "0",
"body": "Brilliant! It was silly on my part to miss the `a == minEle` case."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T16:42:03.897",
"Id": "235515",
"ParentId": "235508",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "235515",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T13:46:34.827",
"Id": "235508",
"Score": "2",
"Tags": [
"c++",
"performance",
"algorithm",
"time-limit-exceeded",
"stack"
],
"Title": "Designing a stack such that getMin() is both constant time and constant space"
}
|
235508
|
<p>I've solved this problem: <a href="https://leetcode.com/problems/word-break" rel="nofollow noreferrer">https://leetcode.com/problems/word-break</a></p>
<blockquote>
<p>Given a non-empty string s and a dictionary wordDict containing a list
of non-empty words, determine if s can be segmented into a
space-separated sequence of one or more dictionary words.</p>
<p>Note:</p>
<p>The same word in the dictionary may be reused multiple times in the
segmentation. You may assume the dictionary does not contain duplicate
words. Example 1:</p>
</blockquote>
<pre><code>
impl Solution {
fn dfs(i: usize, words: &HashSet<String>, cur_word: &str, cache: &mut HashMap<usize, bool>, n: usize, orig:&str) -> bool {
if i == n {
return true;
}
if cache.contains_key(&i) {
return *cache.get(&i).unwrap();
}
if words.contains(cur_word) {
cache.insert(i, true);
return true;
}
let mut res = String::from("");
for k in i..n {
let s = orig.chars().nth(k).unwrap();
res.push(s);
if words.contains(&res) && Self::dfs(k + 1, &words, orig.get(k+ 1..).unwrap_or_default(), cache, n, orig) {
cache.insert(i, true);
return true;
}
}
cache.insert(i, false);
return false;
}
pub fn word_break(s: String, word_dict: Vec<String>) -> bool {
let set = word_dict.into_iter().collect::<HashSet<String>>();
let mut cache = HashMap::new();
Self::dfs(0, &set, "", &mut cache, s.len(), &s)
}
}
</code></pre>
<p>Please ignore the useless <code>Solution</code> struct -- that's part of the website's interface for solution.</p>
<p>I'm quite upset with how my <code>dfs</code> function is structured -- I am passing far too many arguments into it. </p>
<p>In python, I would've simply created a recursive nested function, which would have captured outer variables; rust doesn't allow for recursive closures, as a closure is an unnamed struct. So I've had to resort to creating a argument-heavy function. </p>
<p>How do I make my code more idiomatic?</p>
|
[] |
[
{
"body": "<p>My main issue with this code is the function interface as you already identified yourself. These are the most glaring issues in my opinion:</p>\n\n<ul>\n<li>Parameter names are not clear. Names like <code>i</code> and <code>n</code> might be good enough in very short, self-contained loops/closures, but not as function parameters. I similarly don't like abbreviations like <code>orig</code>, and <code>cur</code> because the full words are not much longer. Always consider you first see this function, is it <code>original</code> or <code>origin</code>, is it <code>current</code> or <code>cursor</code>? Your interface should be clear without reading the code.</li>\n<li>You are always passing a full string slice while you know you will only read from a certain offset (<code>i</code>).</li>\n<li>Passing <code>n</code> is redundant, as almost any check that you do against this can be replaced by checking if you reached the end of <code>orig</code>.</li>\n<li>Similarly but less obvious passing <code>i</code> is redundant. The obvious part is related to the first point, if you only pass the slice this represents offset <code>0</code>. Now, you also use this as a cache key, but that's not necessary. If instead of passing the full slice you only push the 'remaining' string you can use this as cache key to exactly the same effect.</li>\n<li>You insert <code>true</code> in the cache, which requires it to be a <code>map</code>, but there are several reasons why this is useless. I'd just use a <code>HashSet</code> that is only updated for <code>false</code>. Reasons are as follows:\n\n<ul>\n<li>If you found a 'true', the function finished anyway.</li>\n<li>When indexed by usize and with this judging system you can't use the cache for multiple string inputs (and never for multiple word inputs). So the <code>true</code> cache is even useless here.</li>\n<li>But even if you could re-use the cache, the true adds little, because you can quickly prune the false branches already.</li>\n</ul></li>\n<li>You explicitly end with <code>return false;</code>, it is more idiomatic to simply say <code>false</code> (without the semicolon).</li>\n<li>You have a whole construct that basically loops over a splitted version of your input. This can be significantly simplified by using the built-in <code>split_at</code>.</li>\n</ul>\n\n<p>Based on all this I refactored your original algorithm to the following:</p>\n\n<pre><code>use std::collections::HashSet;\nimpl Solution {\n fn dfs(remaining: &str, words: &HashSet<String>, mut cache: &mut HashSet<String>) -> bool {\n for i in 1..remaining.len() + 1 {\n let (word, remaining) = remaining.split_at(i);\n if words.contains(word.into())\n && !cache.contains(remaining.into())\n && Self::dfs(remaining, &words, &mut cache)\n {\n return true;\n }\n }\n if remaining.len() == 0 {\n true\n } else {\n cache.insert(remaining.into());\n false\n }\n }\n pub fn word_break(s: String, word_dict: Vec<String>) -> bool {\n let set = word_dict.into_iter().collect::<HashSet<String>>();\n let mut cache = HashSet::new();\n Self::dfs(&s.as_str(), &set, &mut cache)\n }\n}\n</code></pre>\n\n<p>This may not yet be ideal, I for example don't like <code>remaining</code> and <code>dfs</code> as names. Other improvements you could try but are honestly overkill for a braintease exercise:</p>\n\n<ul>\n<li>It seems somewhat weird to pass <code>words</code> and <code>cache</code> as a parameter. More idiomatic would be to make a <code>WordBreakChecker</code> struct. You provide it with a <code>new</code> initializer that sets the cache and words, and then have a single <code>dfs</code> (or better <code>check</code>) function that only takes the string as input.</li>\n<li>In my example I still index the slice explicitly by using a for loop and <code>split_at</code>. That's good enough for here, but it may be interesting practice to implement the Iterator trait to iterate over these combinations directly (honestly, it may exist already in std or a crate, I didn't look to hard).</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T13:54:46.780",
"Id": "235610",
"ParentId": "235510",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "235610",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T15:24:27.233",
"Id": "235510",
"Score": "2",
"Tags": [
"algorithm",
"rust"
],
"Title": "Rust dynamic programming : word break"
}
|
235510
|
<p><strong>EDIT</strong></p>
<p>A port of Björn's answer to C++ with further improvements <a href="https://codereview.stackexchange.com/a/235583/212940">at bottom</a> achieving up to 2.4GB/s on the reference machine. </p>
<hr>
<p>Text file parsing and processing continues to be a common task. Often it's slow, and can become a performance bottleneck if data is large or many files need to be processed. </p>
<p><strong>Background</strong></p>
<p>This is the next stage on from <a href="https://codereview.stackexchange.com/questions/235314/high-performance-txt-file-parsing">this question</a>. As before the <a href="https://www.reddit.com/r/dailyprogrammer/comments/dv0231/20191111_challenge_381_easy_yahtzee_upper_section/" rel="nofollow noreferrer">"Yahtzee" programming challenge</a> shall serve as an illustrative example. Follow that link for full details, but the task is basically:</p>
<ul>
<li>Read <a href="https://gist.githubusercontent.com/cosmologicon/beadf49c9fe50a5c2a07ab8d68093bd0/raw/fb5af1a744faf79d64e2a3bb10973e642dc6f7b0/yahtzee-upper-1.txt" rel="nofollow noreferrer">~1MB file</a> with about ~100,000 newline separated ints (we are using that file repeated x1,000 because we got too fast => ~900MB; see below). </li>
<li>Group them by hash map. We are using the 3rd party, <a href="https://github.com/skarupke/flat_hash_map" rel="nofollow noreferrer"><code>ska::bytell_hash_map</code></a>, instead of <code>std::unordered_map</code>, because it is about 2.5x faster.</li>
<li>Find the group with the largest sum and return that sum. </li>
</ul>
<p>In the first code review I focused on:</p>
<ul>
<li>How to read the file efficiently => conclusion <code>mmap</code> (linux specific, see the other question for details and alternatives). </li>
<li>How to parse efficiently => once we are efficiently reading the file, parsing becomes the bottleneck. The other question progressively moved to stripping the parsing right down to a tight loop incrementing a pointer over the mmap file with minimal checking / branching. </li>
</ul>
<p>The file format here is very simple. One integer per line terminated with <code>'\n'</code>. We are assuming the data is in ASCII and no illegal characters exist; only <code>[0-9]</code>. </p>
<p>The test file we used initially <a href="https://gist.githubusercontent.com/cosmologicon/beadf49c9fe50a5c2a07ab8d68093bd0/raw/fb5af1a744faf79d64e2a3bb10973e642dc6f7b0/yahtzee-upper-1.txt" rel="nofollow noreferrer">is this</a> repeated a 1,000 times with: <code>for i in {1..1000}; do cat yahtzee-upper-1.txt >> yahtzee-upper-big.txt ; done</code>. This produces a file about 900MB in size, but with a very low cardinality (only 791 unique integers), which means the hashmap part of the algorithm is not too much of a bottleneck. See below for the second part of the challenge with a file with higher cardinality. With such stripped down code and <code>mmap</code> we were able to achieve ~540MB/s (1.7seconds for this file) using a single thread.</p>
<p>(All timings are for a i7-2600 Sandy Bridge processor with 16GB of DDR3-1600 and a 500MB/s SSD, <strong>but</strong> note that we ensure that the file is <em>OS cached</em> so already in RAM. Hence the 500MB/s is not really relevant.)</p>
<p><strong>The next level</strong></p>
<p>In order to go faster still this question / code review focuses on going multi-threaded for the parsing. It turns out that the algorithm is <a href="https://en.wikipedia.org/wiki/Embarrassingly_parallel" rel="nofollow noreferrer">Embarrassingly parallel</a> if we chunk the mmap and just let each thread build its own hashmap and then combine them at the end. This last step is not significant (certainly not for the <code>yahtzee-upper-big.txt</code> file due to the low cardinality). </p>
<p>Code is at bottom. It can achieve < 400ms for the full (cached)read, parse, hashmap and combine using 8 threads (that CPU has 4 cores + HT). (Note the <code>os::fs::MemoryMappedFile</code> class is my own <a href="https://github.com/oschonrock/toolbelt/blob/master/os/fs.hpp" rel="nofollow noreferrer"><code>RAII</code> convenience wrapper</a> for <code>mmap</code>). Scaling is not bad to 8 threads, but it visibly tails off. (Note that a tight single threaded loop spinning a pointer through the <code>mmap</code> takes ~140ms). </p>
<pre><code>1 thread: ~1700ms
4 threads: ~680ms
6 threads: ~437ms
8 threads: ~390ms
</code></pre>
<p>This is quite good, although I would <strong>welcome feedback on the concurrency coding / style</strong>.</p>
<p>The real challenge for this approach comes when we use a file with a higher cardinality (ie more unique integers and therefore a much bigger hashmap with more entries). </p>
<p>Here is a small utility to generate a more challenging file:</p>
<pre><code>#include <iostream>
#include <random>
#include <fstream>
#include <iomanip>
int main(int argc, char* argv[]) {
if (argc < 2) return 1;
auto gen = std::mt19937{std::random_device{}()};
std::uniform_int_distribution<unsigned> dist(1'000'000, 2'000'000);
auto file = std::ofstream{argv[1]}; // NOLINT
for (std::size_t i = 0; i < 100'000'000; ++i) {
file << dist(gen) << '\n';
}
return 0;
}
</code></pre>
<p>run like this to make ~800MB file with cardinality 1,000,001. </p>
<pre><code>./build/bin/yahtzee_gen yahtzee-upper-big2.txt
</code></pre>
<p>The performance of this file, despite being slightly smaller, is <strong>much</strong> slower: ~2.1s on 8 threads. The single threaded performance is: 4.7seconds showing poor scalability. <code>perf stat</code> reports this:</p>
<pre><code> Performance counter stats for 'build/bin/yahtzee_mthr yahtzee-upper-big2.txt':
14,159.77 msec task-clock # 6.044 CPUs utilized
2,789 context-switches # 0.197 K/sec
8 cpu-migrations # 0.001 K/sec
169,114 page-faults # 0.012 M/sec
49,300,366,303 cycles # 3.482 GHz (83.26%)
44,125,329,192 stalled-cycles-frontend # 89.50% frontend cycles idle (83.26%)
39,070,916,691 stalled-cycles-backend # 79.25% backend cycles idle (66.68%)
16,818,483,760 instructions # 0.34 insn per cycle
# 2.62 stalled cycles per insn (83.36%)
2,613,261,878 branches # 184.555 M/sec (83.47%)
24,712,823 branch-misses # 0.95% of all branches (83.33%)
2.342779054 seconds time elapsed
13.755426000 seconds user
0.412222000 seconds sys
</code></pre>
<p><strong>Note</strong> the front and back-end idle cycles. I suspect that this kind of poor scalability can be typical where we are iterating through a large file whilst building up a significant size data structure from the input. A common use case? </p>
<p><strong>Note</strong>: We attempted CPU pinning (before switching from std::thread to std::async / std::future), but that made little difference.</p>
<p><strong>Feedback / Ideas Wanted</strong></p>
<ul>
<li>Coding style and technique for the concurrent implementation. </li>
<li>Ideas / code / tuning suggestions for helping improve the multi-threaded performance of the <strong>high cardinality</strong> file. </li>
</ul>
<p>And finally here is the code:</p>
<pre><code>#include "flat_hash_map/bytell_hash_map.hpp"
#include "os/fs.hpp"
#include <cstdint>
#include <future>
#include <iostream>
#include <string>
#include <string_view>
#include <vector>
using uint64 = std::uint64_t;
using map_t = ska::bytell_hash_map<uint64, uint64>;
std::pair<const char* const, const char* const> from_sv(std::string_view sv) {
return std::make_pair(sv.data(), sv.data() + sv.size());
}
std::string_view to_sv(const char* const begin, const char* const end) {
return std::string_view{begin, static_cast<std::size_t>(end - begin)};
}
map_t parse(std::string_view buf) {
auto map = map_t{};
auto [begin, end] = from_sv(buf);
const char* curr = begin;
uint64 val = 0;
while (curr != end) {
if (*curr == '\n') {
map[val] += val;
val = 0;
} else {
val = val * 10 + (*curr - '0');
}
++curr; // NOLINT
}
return map;
}
std::vector<std::string_view> chunk(std::string_view whole, int n_chunks, char delim = '\n') {
auto [whole_begin, whole_end] = from_sv(whole);
auto chunk_size = std::ptrdiff_t{(whole_end - whole_begin) / n_chunks};
auto chunks = std::vector<std::string_view>{};
const char* end = whole_begin;
for (int i = 0; end != whole_end && i < n_chunks; ++i) {
const char* begin = end;
if (i == n_chunks - 1) {
end = whole_end; // always ensure last chunk goes to the end
} else {
end = std::min(begin + chunk_size, whole_end); // NOLINT std::min for OOB check
while (end != whole_end && *end != delim) ++end; // NOLINT ensure we have a whole line
if (end != whole_end) ++end; // NOLINT one past the end
}
chunks.push_back(to_sv(begin, end));
}
return chunks;
}
uint64 yahtzee_upper(const std::string& filename) {
auto mfile = os::fs::MemoryMappedFile{filename};
unsigned n_threads = std::thread::hardware_concurrency();
auto fut_maps = std::vector<std::future<map_t>>{};
for (std::string_view chunk: chunk(mfile.get_buffer(), n_threads)) { // NOLINT
fut_maps.push_back(std::async(std::launch::async, parse, chunk));
}
uint64 max_total = 0;
auto final_map = map_t{};
for (auto&& fut_map: fut_maps) {
map_t map = fut_map.get();
for (auto pair: map) {
uint64 total = final_map[pair.first] += pair.second;
if (total > max_total) max_total = total;
}
}
std::cout << final_map.size() << "\n";
return max_total;
}
int main(int argc, char* argv[]) {
if (argc < 2) return 1;
std::cout << yahtzee_upper(argv[1]) << '\n'; // NOLINT
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T18:17:18.087",
"Id": "461026",
"Score": "0",
"body": "What about adversarial input? That is, are input files designed to break the hash data structure you are using allowed? Also, would a randomized algorithm be acceptable? One that is right say 99.99% of the time but sometimes wrong?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T18:22:34.590",
"Id": "461027",
"Score": "0",
"body": "@BjörnLindqvist \nIf you mean ill-formed txt filles with letters or space, then no, I am not focused on that right now. If/when we maximise MT parsing, I can reintroduce some checking. Apart from that, how would you break the hashmap? If you send all unique ints, then sure, it will be slower, but it won't break? Regarding probabilistic estimates, I would not like to go there. The idea for me behind this question is to learn more techniques about how to write efficient concurrent algorithms. This is already lock free, but of course that does not mean contention free. So that is the focus."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T18:27:30.710",
"Id": "461028",
"Score": "0",
"body": "Not malformed input, [algorithmic complexity attacks](https://www.freecodecamp.org/news/hash-table-attack-8e4371fc5261/). You can't break the hashmap, but you likely can trigger worst case performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T18:30:46.540",
"Id": "461029",
"Score": "0",
"body": "@BjörnLindqvist\nOK, I am aware of that, and that's an interesting topic. But for me, in this question, I am assuming this is a \"controlled file\". Like a CSV database backup or large \"world state\" game engine data file. Something which we \"reasonably trust\" and hence why we are prepared to parse and interpret GBs of it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T18:38:22.923",
"Id": "461030",
"Score": "1",
"body": "There's the risk when pinning a thread to a CPU that some other process will also have a thread pinned to that CPU, causing your thread to take much longer to run since it could be starved for CPU time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T18:40:24.130",
"Id": "461031",
"Score": "0",
"body": "@1201ProgramAlarm Thanks. In this case in my env, it seems to make no difference. Does the `perf stat` output: \"8 cpu-migrations\" tell us that these threads are hardly being migrated anyway (the number is very similarly tiny if I comment out the pinning)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T20:10:28.217",
"Id": "461038",
"Score": "0",
"body": "In the real world, the big file isn't buffered in memory before you start processing it, and as you have simple processing, actually reading the file will be the bottleneck, no matter how many threads you use."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T20:14:34.893",
"Id": "461039",
"Score": "0",
"body": "@D.Jurcau That may be, unless we have just written it (!) which is actually quite common. What if the file is already loaded as a string? Also common. I have to say, stating \"in some scenario the bottleneck will be somewhere else\", does not really add much to the discussion. The question (and therefore learning point is): \"In the stated scenario how do we reduce contention and gain performance?\" . Too hard?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T01:37:00.363",
"Id": "461206",
"Score": "0",
"body": "If you just wrote the file, wouldn't that be a domain-specific optimization? You could instead pipe the file writer into the parser and skip a disk file (pipes are still files I guess). Or even not write it as a text file at all, and make the producer produce shared structured data consumable to the consumer process. That should come pretty close to as fast as an in-proc consumer drinking from the firehose."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T01:40:44.290",
"Id": "461208",
"Score": "0",
"body": "@butt\nThe pipe would be no faster. Disk is not bottleneck if OS cached. Parsing was, now grouping is. Really what has happened on this iteration is that the parsing and (cached) reading is so fast that the \"grouping\" is everything, so that's where the effort went. That would be no different if you where to \"magically acquire\" a block of memory already in `uint64_t[]` form and `reinterpret_cast` it (technically that's UB I think, but it works)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T01:49:41.873",
"Id": "461209",
"Score": "0",
"body": "@butt What is true, is that the 4x improvement which Björn came up with below (and which I ported to C++) is not really about parsing or file reading anymore. So it's arguably \"off topic\". But that was the bottleneck and you should never optimise anything which is not the bottleneck, because that would be pointless."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T01:53:19.093",
"Id": "461210",
"Score": "0",
"body": "@butt On \"files in cache\": Among other things, I manage a rack of servers, for my sins. None of those servers ever use their disk, except for: a) writing logs b) writing DB transactions c) booting (which happens about twice per year after upgrades) . After that: everything is in RAM. That may not be typical. But it's a real scenario. And it's fast. So when I want something \"fast\", I am looking for it to be \"fast\" assuming that I don't have to consume it through a straw..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T02:31:31.103",
"Id": "461214",
"Score": "0",
"body": "Again I'd be careful of micro-optimizing this particular case. At first glance, a sequence of \"page fault => wait for memory => process => page fault new memory => wait for memory => process => ...\" appears like it has a ton of stalls where nothing is happening. However, it probably requires the minimal amount of *active* CPU time compared to any alternative. If you saturate a server with this, the server *could* have optimal overall throughput because each process is work-efficient, even if the latency of one task is higher than memory batching."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T02:35:15.983",
"Id": "461216",
"Score": "0",
"body": "In other words, say you want to instead parse 1000 1GB files, or some number of files much greater than the number of processors you have. Is this still a good solution?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T06:15:53.243",
"Id": "461230",
"Score": "0",
"body": "@butt\nSure, that will depend on the actual real work item, background load etc. I know that what we have managed to achieve in these 2 questions is reduce each phase to a reasonable minimum (probably slightly optimised in some ways). If it's cached it runs at ~1.7GB/s on 8 threads if it's not it runs at disk speed (I have tested that, there appears to be no significant \"stall / run / stall\"). Because each phase is at minimum, it would now be trivial to tune: 1. parsing tolerance 2. Thread number => load 3. data structure => number range for the actual particular use case. etc"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T06:16:30.807",
"Id": "461231",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/103282/discussion-between-oliver-schonrock-and-butt)."
}
] |
[
{
"body": "<p>I hope you don't mind a pure C solution. For me it is easier to\noptimize code without C++ abstractions. But it should be\nstraightforward to convert it to idiomatic C++ code.</p>\n\n<pre><code>#include <assert.h>\n#include <math.h>\n#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#ifdef _WIN32\n#include <windows.h>\n#else\n#include <fcntl.h>\n#include <pthread.h>\n#include <sys/mman.h>\n#include <sys/stat.h>\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n// Range of numbers, number of numbers and number of parser threads.\n//////////////////////////////////////////////////////////////////////////////\n#define MIN_VALUE (1 * 1000 * 1000)\n#define MAX_VALUE (2 * 1000 * 1000)\n#define N_VALUES 400 * 1000 * 1000\n#define N_THREADS 8\n\n//////////////////////////////////////////////////////////////////////////////\n// Timing functions.\n//////////////////////////////////////////////////////////////////////////////\n#define NS_TO_S(x) ((double)(x) / 1000 / 1000 / 1000)\n\nuint64_t\nnano_count() {\n#ifdef _WIN32\n static double scale_factor;\n static uint64_t hi = 0;\n static uint64_t lo = 0;\n\n LARGE_INTEGER count;\n BOOL ret = QueryPerformanceCounter(&count);\n if (ret == 0) {\n printf(\"QueryPerformanceCounter failed.\\n\");\n abort();\n }\n if (scale_factor == 0.0) {\n LARGE_INTEGER frequency;\n BOOL ret = QueryPerformanceFrequency(&frequency);\n if (ret == 0) {\n printf(\"QueryPerformanceFrequency failed.\\n\");\n abort();\n }\n scale_factor = (1000000000.0 / frequency.QuadPart);\n }\n#ifdef CPU_64\n hi = count.HighPart;\n#else\n if (lo > count.LowPart) {\n hi++;\n }\n#endif\n lo = count.LowPart;\n return (uint64_t)(((hi << 32) | lo) * scale_factor);\n#else\n struct timespec t;\n int ret = clock_gettime(CLOCK_MONOTONIC, &t);\n if (ret != 0) {\n printf(\"clock_gettime failed.\\n\");\n abort();\n }\n return (uint64_t)t.tv_sec * 1000000000 + t.tv_nsec;\n#endif\n}\n\n//////////////////////////////////////////////////////////////////////////////\n// Generate the data file.\n//////////////////////////////////////////////////////////////////////////////\nstatic int\nrand_in_range(int lo, int hi) {\n int range = hi - lo;\n int val = (rand() & 0xff) << 16 |\n (rand() & 0xff) << 8 |\n (rand() & 0xff);\n return (val % range) + lo;\n}\n\nstatic void\nrun_generate(const char *path) {\n srand(1234);\n FILE *f = fopen(path, \"wb\");\n for (int i = 0; i < N_VALUES; i++) {\n fprintf(f, \"%d\\n\", rand_in_range(MIN_VALUE, MAX_VALUE));\n }\n fclose(f);\n}\n\n//////////////////////////////////////////////////////////////////////////////\n// Fast number parser using loop unrolling macros.\n//////////////////////////////////////////////////////////////////////////////\n#define PARSE_FIRST_DIGIT \\\n if (*at >= '0') { \\\n val = *at++ - '0'; \\\n } else { \\\n goto done; \\\n }\n#define PARSE_NEXT_DIGIT \\\n if (*at >= '0') { \\\n val = val*10 + *at++ - '0'; \\\n } else { \\\n goto done; \\\n }\n\nstatic void\nparse_chunk(char *at, const char *end, size_t *accum) {\n uint64_t val = 0;\n while (at < end) {\n // Parse up to 7 digits.\n PARSE_FIRST_DIGIT;\n PARSE_NEXT_DIGIT;\n PARSE_NEXT_DIGIT;\n PARSE_NEXT_DIGIT;\n PARSE_NEXT_DIGIT;\n PARSE_NEXT_DIGIT;\n PARSE_NEXT_DIGIT;\n done:\n #ifdef _WIN32\n InterlockedExchangeAdd64(&accum[val], val);\n #else\n __sync_fetch_and_add(&accum[val], val);\n #endif\n // Skip newline character.\n at++;\n }\n}\n\n//////////////////////////////////////////////////////////////////////////////\n// Thread definition\n//////////////////////////////////////////////////////////////////////////////\ntypedef struct {\n char *chunk_start;\n char *chunk_end;\n uint64_t *accum;\n} parse_chunk_thread_args;\n\n#ifdef _WIN32\nstatic DWORD WINAPI\nparse_chunk_thread(LPVOID args) {\n parse_chunk_thread_args *a = (parse_chunk_thread_args *)args;\n parse_chunk(a->chunk_start, a->chunk_end, a->accum);\n return 0;\n}\n#else\nstatic void*\nparse_chunk_thread(void *args) {\n parse_chunk_thread_args *a = (parse_chunk_thread_args *)args;\n parse_chunk(a->chunk_start, a->chunk_end, a->accum);\n return NULL;\n}\n#endif\n\n//////////////////////////////////////////////////////////////////////////////\n// Parse the whole file.\n//////////////////////////////////////////////////////////////////////////////\nstatic bool\nrun_test(const char *path) {\n uint64_t time_start = nano_count();\n\n #ifdef _WIN32\n FILE *f = fopen(path, \"rb\");\n fseek(f, 0, SEEK_END);\n uint64_t n_bytes = ftell(f);\n fseek(f, 0, SEEK_SET);\n char *buf_start = (char *)malloc(sizeof(char) * n_bytes);\n char *buf_end = buf_start + n_bytes;\n assert(fread(buf_start, 1, n_bytes, f) == n_bytes);\n fclose(f);\n #else\n int fd = open(path, O_RDONLY);\n if (fd == -1) {\n return false;\n }\n struct stat sb;\n if (fstat(fd, &sb) == -1) {\n return false;\n }\n uint64_t n_bytes = sb.st_size;\n char *buf_start = mmap(NULL, n_bytes, PROT_READ, MAP_PRIVATE, fd, 0);\n char *buf_end = buf_start + n_bytes;\n #endif\n\n uint64_t time_read = nano_count();\n\n char *chunks[N_THREADS];\n for (int i = 0; i < N_THREADS; i++) {\n chunks[i] = buf_start + (n_bytes / N_THREADS) * i;\n if (i > 0) {\n // Adjust the chunks starting points until they reach past\n // a newline.\n while (*chunks[i] != '\\n') {\n chunks[i]++;\n }\n chunks[i]++;\n }\n }\n uint64_t *accum = calloc(MAX_VALUE, sizeof(uint64_t));\n\n #if _WIN32\n HANDLE threads[N_THREADS];\n #else\n pthread_t threads[N_THREADS];\n #endif\n parse_chunk_thread_args args[N_THREADS];\n for (int i = 0; i < N_THREADS; i++) {\n char *chunk_start = chunks[i];\n char *chunk_end = buf_end;\n if (i < N_THREADS - 1) {\n chunk_end = chunks[i + 1];\n }\n args[i].chunk_start = chunk_start;\n args[i].chunk_end = chunk_end;\n args[i].accum = accum;\n #if _WIN32\n threads[i] = CreateThread(NULL, 0, parse_chunk_thread,\n &args[i], 0, NULL);\n #else\n pthread_create(&threads[i], NULL, parse_chunk_thread, &args[i]);\n #endif\n }\n for (int i = 0; i < N_THREADS; i++) {\n #if _WIN32\n WaitForSingleObject(threads[i], INFINITE);\n #else\n pthread_join(threads[i], NULL);\n #endif\n }\n uint64_t max = 0;\n for (int i = 0; i < MAX_VALUE; i++) {\n uint64_t val = accum[i];\n if (val > max) {\n max = val;\n }\n }\n uint64_t time_parsed = nano_count();\n\n free(accum);\n #if _WIN32\n free(buf_start);\n #else\n if (munmap(buf_start, n_bytes) == -1) {\n return false;\n }\n #endif\n\n // Print timings.\n double read_secs = NS_TO_S(time_read - time_start);\n double parse_secs = NS_TO_S(time_parsed - time_read);\n double total_secs = NS_TO_S(time_parsed - time_start);\n printf(\"Read : %.3f seconds\\n\", read_secs);\n printf(\"Parse : %.3f seconds\\n\", parse_secs);\n printf(\"Total : %.3f seconds\\n\", total_secs);\n printf(\"-- Max: %zu\\n\", max);\n return true;\n}\n\nint\nmain(int argc, char *argv[]) {\n if (argc != 3) {\n printf(\"%s: [generate|test] path\\n\", argv[0]);\n return EXIT_FAILURE;\n }\n char *cmd = argv[1];\n if (strcmp(cmd, \"generate\") == 0) {\n run_generate(argv[2]);\n } else if (strcmp(cmd, \"test\") == 0) {\n if (!run_test(argv[2])) {\n printf(\"Test run failed!\\n\");\n return EXIT_FAILURE;\n }\n } else {\n printf(\"%s: [generate|test] path\\n\", argv[0]);\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>On my i7-6700 CPU desktop with 32 GB RAM, my code parses a 3.2 GB file\nin about 1.62 seconds and your code takes about eight\nseconds. I compile both programs with <code>-march=native -mtune=native -O3</code></p>\n\n<p>The main difference is that I'm using an array shared by all threads\nwhile you are using a hashmap for each thread. That is inefficient\nsince the range of possible values is only one million. A hashmap\nwould have the advantage over an array if the range of values was much\nlarger than the number of values but that is not the case in your\nscenario.</p>\n\n<p>The array can be concurrently modified by all threads by using locking\ncompiler intrinsics:</p>\n\n<pre><code>#ifdef _WIN32\nInterlockedExchangeAdd64(&accum[val], val);\n#else\n__sync_fetch_and_add(&accum[val], val);\n#endif\n</code></pre>\n\n<p>The intrinsics ensure that the updates are atomic and that threads\ndon't interfere with each other.</p>\n\n<p>The last difference is</p>\n\n<pre><code>#define PARSE_FIRST_DIGIT \\\n if (*at >= '0') { \\\n val = *at++ - '0'; \\\n } else { \\\n goto done; \\\n }\n#define PARSE_NEXT_DIGIT \\\n if (*at >= '0') { \\\n val = val*10 + *at++ - '0'; \\\n } else { \\\n goto done; \\\n }\nwhile (buf < end) {\n // Parse up to 7 digits.\n PARSE_FIRST_DIGIT;\n PARSE_NEXT_DIGIT;\n PARSE_NEXT_DIGIT;\n PARSE_NEXT_DIGIT;\n PARSE_NEXT_DIGIT;\n PARSE_NEXT_DIGIT;\n PARSE_NEXT_DIGIT;\n done:\n</code></pre>\n\n<p>Here I have manually unrolled the parsing loop using macros. It\nimproves performance by about 100 ms over your formulation when\ncompiling with gcc.</p>\n\n<h3>Linux vs. Windows</h3>\n\n<p>On my laptop, the code runs a lot faster on Linux than on Windows. On\nWindows with an 1 600 MB file and 4 threads:</p>\n\n<pre><code>Read : 1.170 seconds\nParse : 3.119 seconds\nTotal : 4.289 seconds\n-- Max: 498631000\n</code></pre>\n\n<p>Same setup on Linux:</p>\n\n<pre><code>Read : 0.000 seconds\nParse : 2.814 seconds\nTotal : 2.814 seconds\n-- Max: 498631000\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T18:39:01.153",
"Id": "461145",
"Score": "0",
"body": "Thanks. I like the approach. You are tackling the obvious bottleneck, ie the shared state. I will look into it further. As I see (apart from the manual unrolling) you have done 2 fundamental things: 1. used shared state for summing with atomics, rather than separate + combine 2. switched to different kinds of data structure. They are connected, but fundamentally: 1. is to do with concurrency and 2 is about a universality / efficiency trade-off. ie we could do 2 in a single threaded environment and it would also be faster at the cost being less universal. Agree?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T21:22:37.773",
"Id": "461185",
"Score": "0",
"body": "Correct. 1. I experimented with giving each thread its own array but that seemed slightly slower (and consumed 8 times as much memory). If there are lots of different numbers, contention shouldn't be bad. 2. If you know that the number of *actual* numbers is much smaller than the number of *possible* numbers, then a hashmap is better. For example, if there is only one million unique numbers, but the range is 2^64."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T23:03:51.463",
"Id": "461197",
"Score": "0",
"body": "Firstly: I like your C-style. Nice code. Secondly: I compiled it and my original \"big2\" file as above runs in ~0.53s on my machine that is about 4x gain over the 8 separate bytell_hashmaps in my code. So well done #2! Thirdly I translated your idea into c++. Wasn't too hard a good exercise for me, about what you can't do with `std::atomic`. You can't put them in `std::vector`s. So I used a `std::unique_ptr<std::atomic<uint64>>[1'000'001]`. Thirdly you had an \"off-by-one\" bug in your code for values 1M -> 2M the array needs to be size=1M+1 for the orig file which includes 2M (your file=OK)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T23:08:30.247",
"Id": "461198",
"Score": "0",
"body": "I also experimented with a single, concurrent hashmap: https://github.com/efficient/libcuckoo but this brought only small gains vs single-thread and was slower than the separate hashmaps and certainly slower than yours. The only slightly \"unsatisfying\" thing about your solution is that it assumes \"A LOT\" of knowledge about the file. I didn't implement the hand-unrolled-parse, because I felt it assumed too much (my C++ port of your code, is practically the same speed without it). But the assumptions about min/max and therefore map size are critical.... I guess it depends on the real scenario."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T23:11:53.967",
"Id": "461199",
"Score": "0",
"body": "BTW the distribution of numbers and therefore concurrent access to the array is such that there is almost zero contention on the atomics. How do I know? Before I worked out how to coax the atomics out of c++ abstractions, I ran it without. Always gave the correct answer. So the chance of the clash, ie the atomic having to retry, is very very small."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T23:30:01.097",
"Id": "461200",
"Score": "0",
"body": "BTW, my c++ version allocates half the memory 1M+1 vals, yours allocates 2M. Neither is better, it's a choice..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T23:36:36.903",
"Id": "461201",
"Score": "0",
"body": "giving your `#ifdef _WIN32` I prsume you ran this on windows (as well?). How did the performance compare? What about the non`mmap` file load? -- which I see you are timing separately."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T09:10:35.980",
"Id": "461243",
"Score": "0",
"body": "found another 33% gain + info on fast SSDs. See EDIT below."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T18:36:41.920",
"Id": "461292",
"Score": "0",
"body": "@OliverSchonrock Added timings. Windows doesn't have anything like mmap so it's hard to compare."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T19:01:03.123",
"Id": "461297",
"Score": "0",
"body": "https://docs.microsoft.com/en-us/windows/win32/memory/creating-a-file-mapping-object"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T19:09:19.443",
"Id": "461299",
"Score": "0",
"body": "Yes, but that's not faster than reading files the normal way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T20:35:14.103",
"Id": "461314",
"Score": "0",
"body": "@BjörnLindqvist Thanks for timings. Only a 10% diff between Windows and Linux really on the parse. We can't compare read. Uses a completely different mechanism. For windows to have a chance there you would have to do producer/consumer or double buffering (kind of the same thing), or similar. Have you tried the 32bit tweak from below?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T20:41:06.630",
"Id": "461316",
"Score": "0",
"body": "@BjörnLindqvist Actually you read the whole file in Windows right? So that's actually giving windows an advantage for the next stage. I found that mmap is slower than a full pre-read into a buffer (even when file is OS cached), by about 70ms."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T21:21:59.080",
"Id": "461321",
"Score": "0",
"body": "Yep, I incorporated your changes, but was to lazy to update the answer. :)"
}
],
"meta_data": {
"CommentCount": "14",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T17:58:26.850",
"Id": "235570",
"ParentId": "235517",
"Score": "6"
}
},
{
"body": "<p>C++ port of <a href=\"https://codereview.stackexchange.com/a/235570/212940\">Björn's code</a> using a single large array instead of one hashmap per thread. Björn's C code is very nice, but this question was tagged C++ so i thought it was worth showing that too. The changes from my code above are very small:</p>\n\n<ul>\n<li>Using std::thread instead of std::async, because we don't need to return anything</li>\n<li>Use a <code>std::unique_ptr</code> of <code>std::atomic<uint64_t>[1'000'001]</code> as the central datastructure and update with <code>.fetch_add()</code> (<code>std::vector</code> doesn't like atomics without writing wrappers). Note that Björn's <code>array</code> is 2M entries and mine is 1M+1, because I subtract <code>min_val</code> from key. </li>\n<li>the zero initialisation of the array was slightly tricky to find the right syntax for. can't do it with <code>make_unique</code> until we get <code>make_unique_init</code> in c++20 so used empty brace initialisation instead, see code. --- <strong>EDIT</strong>: this is incorrect. It's not complicated. I proved that the array is always zero initialised. Both with <a href=\"https://godbolt.org/z/aB7eJr\" rel=\"nofollow noreferrer\">make_unique</a>, and with <a href=\"https://godbolt.org/z/Cs_ENk\" rel=\"nofollow noreferrer\">new[]{}</a> and got a detailed explanation of <a href=\"https://www.reddit.com/r/cpp/comments/eomwv2/why_make_unique_default_init_stdsize_t_size/\" rel=\"nofollow noreferrer\">the standardese here</a>. So I have changed the code to the more idiomatic <code>make_unique<></code>.</li>\n<li>I didn't include Björn's hand-unrolling of the parsing. I tried limiting the loop iterations to 7, and as soon as I did that, the compiler automatically unrolled it for me. But I felt this was too restrictive on the file format and didn't provide any measurable performance benefit. </li>\n</ul>\n\n<p>For discussion of the prons/cons of this approach see comments under Björn's answer. </p>\n\n<p>Performance of this code on the <code>yahtzee-upper-big2.txt</code> (800MB of 100M 7digit ints with cardinality 1M+1) is ~0.55s on my machine. This is a 4x speedup against the original \"1x bytell_hash_map per thread\" approach at top. Putting it another way this is parsing ~1.7GB/s which is a fair clip on this old machine.</p>\n\n<p>The obvious downside is that it makes assumptions about the <em>range</em> of ints in the input file (they must be min=1M and max=2M inclusive). </p>\n\n<p>Björn put it well when he said in comments above: The global atomic array works very well when we have a relatively small range but many numbers. Whereas when we have a very large range (worst case 2^64) and not so many unique numbers (eg the original, low cardinality, \"-big\" file), then a hash map per thread is fastest.</p>\n\n<p><strong>EDIT</strong>: I changed the code to use <code>std::unit32_t</code> as the main value type in the array. Then just count each value and multiply during the final loop. This optimisation was suggested by someone else, in the previous question, but it never made a measurable difference for me. However, now that this array is central to the performance, particularly whether this array can fit in L3 cache, should make a bigger difference. At 1M * 4bytes => 4MB, it just about might and sure enough, I got a 33% performance gain. The \"big2\" file now runs in ~350ms, which is about 2.4GB/s.</p>\n\n<p>When you have a windfall, you should treat yourself just a little, so I reintroduced <em>some</em> parsing checks. ie the range of the integers is now checked, so we don't access out of bounds memory for UB, and the range of characters is strictly limited to <code>[0-9\\n]</code>. Performance is hardly affected by these \"never taken\" branches thanks to the CPU's branch predictor. </p>\n\n<p>On the subject of: \"Is this realistic? Why are you doing it cached? The disk will always be the bottleneck.\": I did some quick shopping and it seems that, even as of Q4 2017, there are NVMe SSDs which do sequential reads <a href=\"https://ssd.userbenchmark.com/SpeedTest/375784/INTEL-SSDPED1D480GA\" rel=\"nofollow noreferrer\">at a blistering 1800MB/s</a>. So it seems we need to work quite hard to stay ahead of these devices. </p>\n\n<pre><code>#include \"os/fs.hpp\"\n#include <cstdint>\n#include <future>\n#include <iostream>\n#include <memory>\n#include <string>\n#include <string_view>\n#include <vector>\n\nusing val_t = std::uint32_t;\n\nconstexpr val_t min_val = 1'000'000;\nconstexpr val_t max_val = 2'000'000;\nconstexpr std::size_t map_size = max_val - min_val + 1;\n\nstd::pair<const char* const, const char* const> from_sv(std::string_view sv) {\n return std::make_pair(sv.data(), sv.data() + sv.size());\n}\n\nstd::string_view to_sv(const char* const begin, const char* const end) {\n return std::string_view{begin, static_cast<std::size_t>(end - begin)};\n}\n\nvoid parse(std::string_view buf, std::atomic<val_t> map[]) {\n auto [begin, end] = from_sv(buf);\n const char* curr = begin;\n val_t val = 0;\n while (curr != end) {\n if (*curr == '\\n') {\n assert(min_val <= val && val <= max_val);\n map[val - min_val].fetch_add(1); // NOLINT\n val = 0;\n } else if ('0' <= *curr && *curr <= '9') {\n val = val * 10 + (*curr - '0');\n }\n ++curr; // NOLINT\n }\n}\n\nstd::vector<std::string_view> chunk(std::string_view whole, int n_chunks, char delim = '\\n') {\n auto [whole_begin, whole_end] = from_sv(whole);\n auto chunk_size = std::ptrdiff_t{(whole_end - whole_begin) / n_chunks};\n auto chunks = std::vector<std::string_view>{};\n const char* end = whole_begin;\n for (int i = 0; end != whole_end && i < n_chunks; ++i) {\n const char* begin = end;\n if (i == n_chunks - 1) {\n end = whole_end; // always ensure last chunk goes to the end\n } else {\n end = std::min(begin + chunk_size, whole_end); // NOLINT std::min for OOB check\n while (end != whole_end && *end != delim) ++end; // NOLINT ensure we have a whole line\n if (end != whole_end) ++end; // NOLINT one past the end\n }\n chunks.push_back(to_sv(begin, end));\n }\n return chunks;\n}\n\nval_t yahtzee_upper(const std::string& filename) {\n auto mfile = os::fs::MemoryMappedFile{filename};\n unsigned n_threads = std::thread::hardware_concurrency();\n // zero initialised via the empty {} and that's why we didn't use std::make_unique\n auto map = std::make_unique<std::atomic<val_t>[]>(map_size);\n auto threads = std::vector<std::thread>{};\n\n for (std::string_view chunk: chunk(mfile.get_buffer(), n_threads)) // NOLINT\n threads.emplace_back(parse, chunk, map.get());\n\n for (auto& t: threads) t.join();\n\n std::uint64_t max_total = 0;\n for (std::size_t i = 0; i < map_size; ++i) {\n std::uint64_t s = map[i].load() * (i + min_val);\n if (s > max_total) max_total = s;\n }\n return max_total;\n}\n\nint main(int argc, char* argv[]) {\n if (argc < 2) return 1;\n std::cout << yahtzee_upper(argv[1]) << '\\n'; // NOLINT\n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T23:23:26.457",
"Id": "235583",
"ParentId": "235517",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "235570",
"CommentCount": "16",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T17:16:15.383",
"Id": "235517",
"Score": "8",
"Tags": [
"c++",
"performance",
"concurrency"
],
"Title": "Multi Threaded High Performance txt file parsing"
}
|
235517
|
<p>I'm seeking a review of some code I've written for a small personal project. The project is not yet mature enough for any domain specific details to be of concern - but I'm happy to provide further details/examples should this help the review.</p>
<p>A description of what I hope to achieve and minimal working example has been provided below to help guide the review.</p>
<p>Comments relating to my use of the <a href="https://docs.python.org/3/library/asyncio.html" rel="noreferrer">Asyncio</a> library would be very much appreciated, as this is an area that is quite new to me, and I was not able to find any examples implemented in an OOP style.</p>
<p><strong>Concise problem statement</strong></p>
<blockquote>
<p>In a sentence, the <code>Limiter</code> class code should provide an extensible way to <strong>restrict the rate at which certain functions can be invoked.</strong></p>
<p>For this example, I have tried to limit the invocation of <code>increment()</code> to 5 calls every 10 seconds.</p>
<p>It is important that this limit is imposed asynchronously so that other computations can be performed in the background. For this example, simply display the count.</p>
<p>I have tried to maintain an OOP style interface.</p>
</blockquote>
<p><strong>Minimal working example</strong></p>
<p><strong>Limiter</strong></p>
<pre><code>class Limiter(object):
"""
The purpose of this class is to limit the invocation of increment()
based on a evaluation of 'some_condition' wrt. the class's internal state.
"""
def __init__(self: object) -> None:
self.counter, self.limit = 0, 5
self.loop = asyncio.get_event_loop()
self.schedule_tasks()
def schedule_tasks(self: object) -> None:
""" Minimal selection of tasks for this demonstation. """
self.loop.create_task(self.reset_counter())
self.loop.create_task(self.display())
def _increment(self: object) -> None:
""" Increment counter variable. """
print('Incrementing counter')
self.counter += 1
async def reset_counter(self: object) -> None:
""" Periodically (10s) reset the counter value. """
while True:
print('Resetting Counter')
self.counter = 0
await asyncio.sleep(10)
async def display(self: object) -> None:
""" Periodically (1s) display the counter value. """
while True:
print(self.counter)
await asyncio.sleep(1)
async def increment(self: object) -> bool:
""" Provided that some_condition is met, call increment(). """
some_condition = (self.counter < 5)
if (some_condition):
self._increment()
return True
print('some_condition not met - Not able to call increment().')
return False
</code></pre>
<p><strong>Caller</strong></p>
<pre><code>class Caller(object):
"""
An object interfacing with the limiter.
Periodicalyl call limiter.increment()
Calls to increment() should be restricted by the limiter based
on the evaluation of 'some_condition' wrt the limiters internal state.
"""
def __init__(self: object) -> None:
self.limiter = Limiter()
self.loop = asyncio.get_event_loop()
self.schedule_tasks()
def schedule_tasks(self: object) -> None:
""" Minimal selection of tasks for this demonstation. """
self.loop.create_task(self.make_call())
async def make_call(self: object) -> None:
""" Periodically (1s) call increment. """
while True:
await self.limiter.increment()
await asyncio.sleep(1)
</code></pre>
<p><strong>main.py</strong></p>
<pre><code>def main():
try:
loop = asyncio.get_event_loop()
caller = Caller()
loop.run_forever()
except KeyboardInterrupt:
print('Stopping event loop')
loop.stop()
if __name__ == "__main__":
main()
</code></pre>
<p><strong>Example console output</strong></p>
<blockquote>
<pre><code>Hodgson:Limiter hodgson$ python main.py
Resetting Counter
Counter: 0
Incrementing counter
Counter: 1
Incrementing counter
Counter: 2
Incrementing counter
Counter: 3
Incrementing counter
Counter: 4
Incrementing counter
Counter: 5
some_condition not met - Not able to call increment().
Counter: 5
some_condition not met - Not able to call increment().
Counter: 5
some_condition not met - Not able to call increment().
Counter: 5
some_condition not met - Not able to call increment().
Counter: 5
some_condition not met - Not able to call increment().
Resetting Counter
Counter: 0
Incrementing counter
Counter: 1
Incrementing counter
Counter: 2
Incrementing counter
Counter: 3
Incrementing counter
^CStopping event loop
</code></pre>
</blockquote>
<p><strong>The code can also be found here: <a href="https://repl.it/repls/BiodegradableKookyDeletion" rel="noreferrer">Repl.it</a></strong></p>
<p>I am using Python v3.7.3</p>
|
[] |
[
{
"body": "<h1>Old style declaration</h1>\n\n<pre><code>class Limiter(object):\n ...\n</code></pre>\n\n<p>Using <code>object</code> as a base class is no longer necessary. Simply write:</p>\n\n<pre><code>class Limiter:\n ...\n</code></pre>\n\n<p>Same for the other classes</p>\n\n<h1>Wrong receiver type-hint</h1>\n\n<pre><code> def __init__(self: object) -> None:\n ...\n</code></pre>\n\n<p><code>self</code> is not any <code>object</code>; it must be a <code>Limiter</code> (or class derived from <code>Limiter</code>). The proper type-hint to use would be <code>Limiter</code>, but that type is still being defined so you can’t use it directly. The type-hint <code>”Limiter”</code> would be possible to use. However, any type-checker knows that the <code>self</code> argument must be of the type of the class. It should be left implicit:</p>\n\n<pre><code> def __init__(self) -> None:\n ...\n</code></pre>\n\n<p>Same for the other methods.</p>\n\n<h1>Synchronous Async method</h1>\n\n<pre><code> async def increment(self: object) -> bool:\n ...\n</code></pre>\n\n<p>This method doesn’t await any results. It does not need to be <code>async</code>.</p>\n\n<pre><code> def increment(self) -> bool:\n ...\n</code></pre>\n\n<h1>PEP-8</h1>\n\n<pre><code> if (some_condition):\n ...\n</code></pre>\n\n<p>Conditionals do not need to be enclosed in <code>(...)</code>’s.</p>\n\n<p>Methods which are for internal usage only should be marked as “private” (leading underscore). These include <code>schedule_tasks</code>, <code>reset_counter</code>, <code>display</code>, and <code>make_call</code>.</p>\n\n<p>Similarly, non-public data members should have an leading underscore: <code>limiter</code>, <code>loop</code>, <code>limit</code> and <code>count</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T07:45:37.353",
"Id": "235540",
"ParentId": "235524",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "235540",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T20:29:11.623",
"Id": "235524",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"asynchronous",
"async-await"
],
"Title": "Python: Asyncio object-oriented style"
}
|
235524
|
<p>This is a follow up from my previous post: <a href="https://codereview.stackexchange.com/q/214512/194141">Program that converts a number to a letter of the alphabet</a></p>
<p>This is meant to teach my little brother (who only knows how to make games in <em>Geometry Dash</em>) about C, and computers. This is an example I've written meant to be shown and explained to him.</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <stdbool.h>
int main() {
//A string is an array of characters
const char * alphabet = "ABCDEFGHIJKLMNOPQRSTUVWSYZ";
int temp, letter = 0;
while( (1 <= letter && letter <= 26) == false){
/*
* if scanf fails, valadate input to avoid infinite loop
* (the below while statement).
* Uncomment the below printf and comment out the below
* while statement to see what happens if you type
* something like "asdef4grvgrthd" instead of a number.
*/
if(scanf("%d", &letter) != 1){
while((temp=getchar()) != EOF && temp != '\n');
//printf("Fun loop :) ");
}
}
printf("The number %i corresponds to the letter '%c'\n",
letter, alphabet[letter-1]);
}
</code></pre>
<p>This is intended to help beginners understand C by being a slightly harder "Hello World" program.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T21:19:45.377",
"Id": "461042",
"Score": "4",
"body": "C & C++ are two very different languages. Which is this supposed to be? It has aspects of both. Specifically, which compiler are you using."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T21:35:07.540",
"Id": "461043",
"Score": "4",
"body": "@AJNeufeld I tagged it in C++ as it works in both C && C++, although since this is supposed to be an example in C I've removed the C++ tag."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T00:13:43.117",
"Id": "461054",
"Score": "2",
"body": "`sizeof(alphabet) == 27`, there's a trailing null character in there. `strlen(alphabet) == 26`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T00:52:39.327",
"Id": "461058",
"Score": "5",
"body": "Hi I have rolled back quite a few of your edits. It is important on this site to preserve valid answers and we ask that you not update your code to include feedback. Please see [this meta post](https://codereview.meta.stackexchange.com/a/1765/162379) for more information on how you can share your improvements with the community."
}
] |
[
{
"body": "<ul>\n<li><p><code>int letter</code> is not a letter. When printing you call it <code>The number</code>. Name it accordingly: <code>int number</code>.</p></li>\n<li><p>The condition <code>(1 <= letter && letter <= 26) == false</code> is very hard to follow. As a general rule, avoid boolean constants in conditions. Rewriting it as:</p>\n\n<pre><code>!(1 <= letter && letter <= 26)\n</code></pre>\n\n<p>immediately calls for a deMorgan transformation into a much more readable form:</p>\n\n<pre><code>(letter < 1 || letter > 26)\n</code></pre>\n\n<p>It is also recommended to not rely on the operator precedence, which is very easy to get wrong. Use parenthesis instead:</p>\n\n<pre><code>((letter < 1) || (letter > 26))\n</code></pre></li>\n<li><p>Avoid raw loops. Each loop represent an important algorithm, and as such deserves a name. The goal of:</p>\n\n<pre><code>while((temp=getchar()) != EOF && temp != '\\n');\n</code></pre>\n\n<p>is to discard the line. Factor it out into a function:</p>\n\n<pre><code>void discard_line()\n{\n int temp;\n while((temp=getchar()) != EOF && temp != '\\n') {\n }\n}\n</code></pre>\n\n<p>As a perk benefit, <code>temp</code> is no longer cluttering the essential logic.</p>\n\n<p>I also recommend to be a bit more explicit with the empty loops.</p></li>\n<li><p>Avoid magic numbers. <code>26</code> is really <code>strlen(alphabet)</code>. Better yet, declare the alphabet as an array, rather than a pointer, and use <code>sizeof</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T22:46:51.113",
"Id": "461046",
"Score": "0",
"body": "Is \"((letter < 1) || (letter > 26)\" suppose to be \"((letter < 1) || (letter > 26))\" (extra parentheses messing)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T23:04:57.670",
"Id": "461047",
"Score": "0",
"body": "@AlexAngel Of course, thanks for noticing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T23:05:44.507",
"Id": "461048",
"Score": "7",
"body": "The pattern `min <= x && x <= max` is pretty standard for a _between_ test. I'd rather keep it that way instead of tearing the both `number` expressions apart."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T23:15:59.143",
"Id": "461049",
"Score": "0",
"body": "You make good points -- renaming \"letter\" to number && declaring \"alphabet\" as an array. I'll edit the example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T14:49:53.010",
"Id": "461275",
"Score": "1",
"body": "Your de Morgan transformation is terrible. At least make it `letter < 1 || 26 < letter` (but I still prefer the \"inside\" formatting). I also find the additional parens make the code much less readable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T12:18:09.007",
"Id": "461390",
"Score": "0",
"body": "I think `((letter < 1) || (letter > 26))` is the most readable form. You're reading it straight `if letter < 1 or letter > 26`. OP's `(1 <= letter && letter <= 26) == false` was one of the most confusing ifs I've seen for looong time"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T22:37:46.283",
"Id": "235528",
"ParentId": "235526",
"Score": "19"
}
},
{
"body": "<p>Bug: When you feed an empty file to your program, it ends up in an endless loop.</p>\n\n<p>Bug: the 24th letter of the English alphabet is X, not S.</p>\n\n<p>Instead of <code>const char *</code> you should rather declare <code>const char alphabet[]</code>, to make the code match the comment above it. Don't confuse strings and pointers to strings. The <a href=\"https://github.com/cs50/libcs50/issues/163\" rel=\"noreferrer\">authors of the cs50 library do that</a>, and they do much damage to the thousands of students who trust in them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T23:26:05.963",
"Id": "461052",
"Score": "0",
"body": "Changed the extra 'S' to an 'X' and changed the variable \"alphabet\" to an array. I don't know how to fix the empty file bug."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T08:03:26.890",
"Id": "461237",
"Score": "0",
"body": "@AlexAngel check for empty at the start and return null or 0."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T23:12:36.877",
"Id": "235530",
"ParentId": "235526",
"Score": "13"
}
},
{
"body": "<ol>\n<li><p>Never forget the trailing nul. <code>sizeof(alphabet)</code> is 27, not 26.</p></li>\n<li><p>Don't use <code>== false</code>. It is too close to <code>== true</code>, which almost never works, especially in C. Use prefix operator <code>!</code> instead. Then, as others suggest, consider reducing with de Morgan's laws, or maybe not.</p></li>\n<li><p><code>(EOF & '\\n' & '\\r')</code> evaluates to <code>8</code> (usually). This is not a set operation.</p></li>\n<li><p>Consider using a <code>do { ... } while (condition)</code> loop.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T00:37:38.637",
"Id": "461055",
"Score": "0",
"body": "1) Fixed by changing \"<= sizeof()\" to \"< sizeof()\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T00:42:36.247",
"Id": "461056",
"Score": "0",
"body": "2) Since most people are suggesting it I've made this change"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T01:03:29.280",
"Id": "461063",
"Score": "0",
"body": "3) EOF (26) & '\\n' (10) & '\\r' (13) does equal 8, why is it not a set operation?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T10:54:37.673",
"Id": "461097",
"Score": "0",
"body": "1, 2 and 3 don't correspond to any of the code in the question. Are you sure that this is a review?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T12:30:20.353",
"Id": "461103",
"Score": "0",
"body": "@TobySpeight: OP has been updating the source."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T12:35:04.583",
"Id": "461105",
"Score": "0",
"body": "@AlexAngel: Well, it looked like you were trying to write that the value on the left was not any of three values on the right. This entry on the right, in mathematics, is called a set. C doesn't have these. The test could be done with a switch, or with the now present temporary variable. Also, EOF (as a C constant, provided by stdio.h) is not 26, it is (usually) -1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T13:29:23.683",
"Id": "461113",
"Score": "0",
"body": "@DavidG.: Would the following work better?:\n```for(int temp, b=true;b;temp=getchar()){\n switch(temp){case EOF:case'\\n':case'\\r':b=false;break;}\n}```"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T18:32:44.287",
"Id": "461142",
"Score": "0",
"body": "@Alex No, it won't work better. Instead of the complicated `for` loops, you should better use `while` loops until you understand them better. The `for` loop you wrote accesses an uninitialized variable, which leads to undefined behavior."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T19:03:15.083",
"Id": "461152",
"Score": "0",
"body": "@AlexAngel: I think the best your going to get in this case calls for a goto, or a function. `for (;;) { switch (getchar()) { case EOF:case'\\n':case'\\r':goto after_loop;}}after_loop:;` The function version would use return instead of goto. The function solution is probably better. An even better solution might be to have read a full line with fgets() and parsed it with sscanf() or strtol() or atoi()."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T00:24:43.490",
"Id": "235535",
"ParentId": "235526",
"Score": "2"
}
},
{
"body": "<p>Robust input is difficult to get right in C!</p>\n<p>The input loop is broken when we reach end of file: it will loop indefinitely. What we want to do is to give up completely when we get <code>EOF</code> back from <code>scanf()</code>:</p>\n<pre><code> int items = scanf("%d", &letter);\n if (items == EOF) {\n fputs("Failed to read input\\n", stderr);\n return EXIT_FAILURE;\n }\n if (items != 1) {\n /* skip the rest of this line, discarding the return value\n (we'll deal with errors next time round the loop). */\n scanf("%*[^\\n]");\n continue;\n }\n</code></pre>\n<p>(We'll need to include <code><stdlib.h></code> for a definition of <code>EXIT_FAILURE</code>.)</p>\n<hr />\n<p>The alphabetic characters can be declared <code>static</code> rather than <code>auto</code>. Although <code>main()</code> is only executed once in this program, the <code>static</code> declaration can help your compiler avoid unnecessary code.</p>\n<hr />\n<p>The declaration of <code>main()</code> should be a prototype - explicitly show it takes no arguments by writing <code>(void)</code>.</p>\n<hr />\n<h1>Modified program</h1>\n<p>This includes some observations mentioned in other reviews; I won't repeat them here.</p>\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n\nint main(void)\n{\n static const char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";\n static const int length = sizeof alphabet - 1; /* don't count the NUL */\n\n int letter = 0;\n do {\n int items = scanf("%d", &letter);\n if (items == EOF) {\n fputs("Failed to read input\\n", stderr);\n return EXIT_FAILURE;\n }\n if (items != 1) {\n /* skip the rest of this line, discarding the return value\n (we'll deal with errors next time round the loop). */\n scanf("%*[^\\n]");\n continue;\n }\n } while (letter < 1 || letter > length);\n\n printf("The number %i corresponds to the letter '%c'\\n",\n letter, alphabet[letter-1]);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T14:55:22.100",
"Id": "461278",
"Score": "1",
"body": "1. You don't need to initialize letter because it is always initialized by scanf. 2. I would write the trailing `while` test as `while (letter < 1 || length < letter)` (it's much easier to read multiple comparisons of a single variable if they are all in the same direction). 3. I do miss BCPL's `DO ... UNTIL` which would have allowed `until (1 <= letter && letter <= length)`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T11:21:06.733",
"Id": "235549",
"ParentId": "235526",
"Score": "2"
}
},
{
"body": "<p>A cardinal rule of good programming is to process return values appropriately.</p>\n\n<p>Specifically, <code>getchar()</code> returns an <code>int</code>, not a success true/false boolean. Not processing the return value properly (here: <code>while(!getchar())</code>) leads to various undesirable effects, including the problem with the endless loop when fed an empty file.</p>\n\n<p>Additionally, as numerous others have already pointed out,\n<code>while( !(1 <= number && number < sizeof(alphabet)) )</code> is begging to be rewritten (not just for clarity, but for efficiency as well!) as <code>while ((letter < 1) || (letter > sizeof(alphabet)))</code></p>\n\n<p>And since you do not need to validate 'number' until after the number has been read.\nhaving two <code>while</code> loops is unnecessary. </p>\n\n<p>If you combine (a) check return values, (b) validate inputs properly, you get something like this:</p>\n\n<pre><code>int number = 0;\nwhile (1) {\n int c = getchar(); /* get something from stdin */\n if (c == EOF || c == '\\r' || c == '\\n') \n break; /* input completed */\n if (c < '0' || c > '9') \n break; /* invalid input - treat as input completed */\n number = (number * 10) + (c - '0');\n if (number > 99) /* overflow? (more than two digits?) */ \n number = 100; /* limit the overflow, but remember it */\n}\nif (number >= 1 && number < sizeof(alphabet))\n printf(\"The number %i corresponds to the letter '%c'\\n\", \n number, alphabet[number-1]);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T13:05:20.887",
"Id": "461110",
"Score": "1",
"body": "Be careful - in the code posted `alphabet` is a pointer, so `sizeof alphabet` has no relation to the string length!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T13:40:58.813",
"Id": "461114",
"Score": "0",
"body": "@user5438932: From what I can follow you check if the `character` == `'EOF'`, `'\\r'`, or `'\\n'` --> if `True` check if the number is in the bounds of the `alphabet` length; else check if `character` is numeric --> if `True` then check in bounds; from there I can't tell what is happening or why the line `number = (number * 10) + (c - '0');` and below is needed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T12:19:13.380",
"Id": "235553",
"ParentId": "235526",
"Score": "0"
}
},
{
"body": "<p>Neither C nor C++ are the friendliest languages to get acquainted with programming, and character I/O is not their forte either. Besides, these raw C arrays/pointers are both an eyesore and a headache.</p>\n\n<pre><code>int temp, letter = 0;\n</code></pre>\n\n<p>I wouldn't mix uninitialized and initialized variables.\nFor an educational code, each variable should be on a separate line with a comment defining its role.</p>\n\n<p>This tinkering with EOFs and newlines is painful to watch. Handling errors is certainly a part of a programmer's job, but I would rather start with a program that can be read without prior knowledge of circa 1970 technicalities and introduce the gritty details only later.</p>\n\n<p>I'd rather use <code>getline()</code> on <code>stdin</code> (letting the runtime handle this messy string allocation and terminators business) and <code>atoi()</code> to handle wrong input as simply as possible.<br>\nOr possibly use <code>argc</code>, <code>argv</code> to get rid of the I/O scan altogether, though the notion of command line arguments might not be terribly intuitive either at first glance.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T02:39:36.657",
"Id": "235587",
"ParentId": "235526",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T21:04:50.840",
"Id": "235526",
"Score": "11",
"Tags": [
"c",
"converting"
],
"Title": "Program that converts a number to a letter of the alphabet - follow-up"
}
|
235526
|
<p>I'm working on a library of shell utilities for Swift, and at the core of it is the need to spawn a subprocess.</p>
<p>For Linux, I came up with the following function to do the low-level work.</p>
<p>Requirements that led to this ugliness:</p>
<ul>
<li>it can remap FDs arbitrarily (like bash)</li>
<li>it must work in a library (can't assume files were opened with <code>O_CLOEXEC</code>)</li>
<li>it must work in a multithreaded environment (no doing anything fun after fork)</li>
<li>it can't leak any resources (FDs especially were a pain here)</li>
<li>it reports back <strong>any</strong> failures as an error</li>
</ul>
<p>I'm most interested in writing a bullet-proof piece of code, and any suggestions would be appreciated.</p>
<p>This should be entirely self-contained, but here's the <a href="https://github.com/cobbal/swsh/blob/linux/Sources/linuxSpawn/linux-spawn.c" rel="nofollow noreferrer">code in context</a>.</p>
<pre><code>/// spawn a process in a similar manner to posix_spawn using options
/// POSIX_SPAWN_CLOEXEC_DEFAULT and POSIX_SPAWN_START_SUSPENDED, neither of
/// which are available on linux.
/// - Parameter command: name of executable. Either the path to an executable,
/// or will be looked up in PATH. (Passed directly to `execvpe`)
/// - Parameter argv: null terminated list of arguments to pass to command.
/// (Passed directly to `execvpe`)
/// - Parameter envp: null terminated list of all environment variables to pass
/// to command. (Passed directly to `execvpe`)
/// - Parameter fdMap: a list of mappings from parent FDs to be inherited by child
/// FDs. Any FD not listed as a dst will be closed for the child. The list
/// must be -1 terminated, and in the format:
/// `{ src_0, dst_0, src_1, dst_1, ..., src_n, dst_n, -1 }`
/// - Returns: 0 if successful, an error code if an operation failed.
/// - Parameter child_pid_out: non-null, pid of child process will be written
/// to this pointer if successful.
int spawn(
const char *command,
char *const argv[],
char *const envp[],
int32_t *const fdMap,
pid_t *child_pid_out
) {
// First, create a table for fast lookup if an FD is a source and/or a
// destination for dup
int fdlimit = (int)sysconf(_SC_OPEN_MAX);
const int SRC = 1;
const int DST = 2;
uint8_t mentionedFds[fdlimit];
bzero(mentionedFds, sizeof(mentionedFds));
for (int32_t *p = fdMap; *p != -1; p += 2) {
mentionedFds[p[0]] |= SRC;
mentionedFds[p[1]] |= DST;
}
int pid;
int pipeFds[2];
// create a pipe so that the child can report to the parent on failure. If
// it's closed silently, it's a successful exec. If not, it will send an
// error code.
if (pipe2(pipeFds, O_CLOEXEC) != 0) {
return errno;
}
if (!(pid = fork())) {
// In child process. Prepare state for exec.
// Find an FD to store our pipe in that won't interfere with fdMap
int writePipe = -1;
for (int i = 0; i < fdlimit; i++) {
if (!mentionedFds[i]) {
if (i == pipeFds[i]) {
// pipe picked a good fd, nothing to do
writePipe = i;
} else if ((writePipe = dup3(pipeFds[1], i, O_CLOEXEC)) < 0) {
goto err;
}
break;
}
}
if (writePipe < 0) {
// All file descriptors seem to be in use, not one to spare for some
// bookkeeping :(
errno = EMFILE;
goto err;
}
// do the actual fd remapping
for (int32_t *p = fdMap; *p != -1; p += 2) {
if (dup2(p[0], p[1]) < 0) {
goto err;
}
}
for (int i = 0; i < fdlimit; i++) {
// close all the FDs we don't need, even ones that aren't open
// (faster than checking which ones are open I read somewhere on the
// internet)
if (!(mentionedFds[i] & DST) && i != writePipe) {
close(i);
}
}
// All good! If this returns, exec failed with an error.
execvpe(command, argv, envp);
err:;
int err = errno;
write(writePipe, &err, sizeof(err));
exit(err);
}
// parent code
// close our copy of the pipe's write end
close(pipeFds[1]);
int ret = 0;
if (pid < 0) {
// fork failed
ret = pid;
} else if (read(pipeFds[0], &ret, sizeof(ret)) == 0) {
// pipe was closed silently, fork and exec succeeded
*child_pid_out = pid;
}
close(pipeFds[0]);
return ret;
}
</code></pre>
|
[] |
[
{
"body": "<h1>Put <code>const</code> in the right place</h1>\n\n<p>You write <code>int32_t *const fdMap</code>, which means the pointer <code>fdMap</code> is constant, but it allows writes to the values inside the map. You probably meant that you want the contents of <code>fdMap</code> to be read-only, so you have to write instead:</p>\n\n<pre><code>const int32_t *fdMap\n</code></pre>\n\n<p>However, if you want you can make both the pointer and the values pointed to constant:</p>\n\n<pre><code>const int32_t *const fdMap\n</code></pre>\n\n<p>The same goes for <code>argv</code> and <code>envp</code>.</p>\n\n<h1>Filedescriptors are <code>int</code>s</h1>\n\n<p>They are not <code>int32_t</code>s. So write:</p>\n\n<pre><code>const int *fdMap\n</code></pre>\n\n<h1>Avoid unnecessary casts</h1>\n\n<p>Calls to <code>sysconf()</code> return a <code>long</code>, not an <code>int</code>, so store the result in a variable of type <code>long</code>:</p>\n\n<pre><code>long fdlimit = sysconf(_SC_OPEN_MAX);\n</code></pre>\n\n<p>And indeed, when you are looping over all possible filedescriptors, write <code>for (long i = 0; i < fdlimit; i++)</code>.</p>\n\n<h1>Avoid allocating potentially large arrays on the stack</h1>\n\n<p>The maximum number of open files can be very large. The stack size your program gets is not unlimited. So a declaration like:</p>\n\n<pre><code>uint8_t mentionedFds[fdlimit];\n</code></pre>\n\n<p>Can be larger than would fit in your stack. It is best to allocate memory on the heap for this:</p>\n\n<pre><code>uint8_t *mentionedFds = calloc(fdlimit, sizeof(*mentionedFds));\n</code></pre>\n\n<h1>Consider passing <code>fdMap</code> in a more structured way</h1>\n\n<p>The way you pass <code>fdMap</code> is a bit hackish. Since you actually pass an array of filedescriptor <em>pairs</em>, make this explicit, along with the size of that array:</p>\n\n<pre><code>struct fd_pair {\n int src;\n int dst;\n};\n...\nint spawn(..., const struct fd_pair *fdMap, size_t fdMap_size, ...)\n</code></pre>\n\n<p>Then later on, read the map like so:</p>\n\n<pre><code>for (size_t i = 0; i < fdMap_size; i++) {\n mentionedFds[fdMap[i].src] |= SRC;\n mentionedFds[fdMap[i].dst] |= DST;\n}\n</code></pre>\n\n<h1>Make constants the right type</h1>\n\n<p>Since <code>SRC</code> and <code>DST</code> are used to fill in <code>mentionedFds</code>, make sure they have the same type as the elements of the latter. You can also make them <code>static</code>:</p>\n\n<pre><code>static const uint8_t SRC = 1;\nstatic const uint8_t DST = 2;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T15:25:43.003",
"Id": "461280",
"Score": "0",
"body": "Good suggestions. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T06:53:17.967",
"Id": "235590",
"ParentId": "235529",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-12T23:06:01.907",
"Id": "235529",
"Score": "4",
"Tags": [
"c",
"linux",
"thread-safety",
"child-process"
],
"Title": "Spawn a Linux subprocess without leaking FDs"
}
|
235529
|
<p>I'm writing a few simple functions that compare the length of an iterator to an integer, returning as early as possible. Right now I have:</p>
<pre class="lang-py prettyprint-override"><code>class ILengthComparator:
def __init__(self, iterator: Iterator):
self.iterator = iterator
def has_more(self) -> bool:
try:
next(self.iterator)
except StopIteration:
return False
return True
def __eq__(self, length: int) -> bool:
if length < 0:
return False
if not self.has_more():
return length == 0
return self == length-1
def __gt__(self, length: int) -> bool:
if length < 1:
return False
if not self.has_more():
return True
return self > length-1
def __lt__(self, length: int) -> bool:
if length < 0:
return True
if not self.has_more():
return False
return self < length - 1
</code></pre>
<p>Clearly this class isn't finished (<code>__neq__</code>, <code>__gte__</code>, <code>__lte__</code>), and anything after the first comparison isn't guaranteed to work (as the iterator may be consumed), but I'm wondering: <strong>is it is possible to logically simplify this</strong> into a single function with an operator function as an argument (ie <code>operator.eq</code>, <code>operator.lt</code>), or at least just reduce the semi-duplicate parts (ie, every function has a comparison with <code>length</code> against a number, and a case for checking if the iterator is empty - each with a rather ad-hoc return value).</p>
<p>(any suggestions don't need to be recursive or use the <code>has_more</code> method, those were just the first thing I reached for when trying to solve this problem)</p>
<p>Pastebin with the above some quick and dirty unit tests: <a href="https://pastebin.com/N65Q2qcJ" rel="nofollow noreferrer">https://pastebin.com/N65Q2qcJ</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T01:00:10.097",
"Id": "461060",
"Score": "1",
"body": "(Would you believe in [total ordering](https://docs.python.org/3/library/functools.html#functools.total_ordering)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T01:06:24.407",
"Id": "461204",
"Score": "1",
"body": "@greybeard I could be wrong, but I don't think that would work, because these methods have the side effect of consuming the iterator. So if the implementation requires combining `__eq__` and `__lt__` to determine `__gt__`, by the time `__lt__` was called, `__eq__` would have already consumed the iterator."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T04:07:05.087",
"Id": "461224",
"Score": "0",
"body": "(For handling *consuming*, see [409_conflict's answer](https://codereview.stackexchange.com/a/235555/93149).)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T04:50:08.877",
"Id": "461227",
"Score": "0",
"body": "As I understand it, `.tee()` often isn't a good idea, because it has to store the results of each `next()` call for _re_iteration (which can consume a decent amount of memory depending on what the iterator is iterating over). Even if not for this specific use case, it still seems like a pretty awesome decorator!"
}
] |
[
{
"body": "<p>To know the answer to your comparison to <span class=\"math-container\">\\$N\\$</span>, you need to attempt at least:</p>\n\n<ul>\n<li><span class=\"math-container\">\\$N\\$</span> <code>next</code> calls if you test with <span class=\"math-container\">\\$\\lt\\$</span> (succeeding will result to <code>False</code>) or <span class=\"math-container\">\\$\\ge\\$</span> (succeeding will result to <code>True</code>);</li>\n<li><span class=\"math-container\">\\$N+1\\$</span> <code>next</code> calls in all 4 other cases.</li>\n</ul>\n\n<p>Obviously, if the iterator length is fewer than <span class=\"math-container\">\\$N\\$</span> there will be less calls.</p>\n\n<p>So, in order to simplify things, you could extract the first <span class=\"math-container\">\\$N+1\\$</span> elements of the iterator and count them to compare this count to <span class=\"math-container\">\\$N\\$</span>:</p>\n\n<ul>\n<li>extracting can be simplified with <a href=\"https://docs.python.org/3/library/itertools.html#itertools.islice\" rel=\"nofollow noreferrer\"><code>itertools.islice</code></a></li>\n<li><p>counting can be done using either</p>\n\n<ul>\n<li><p><code>enumerate</code> and dumping the content into a 1-length <a href=\"https://docs.python.org/3/library/collections.html#collections.deque\" rel=\"nofollow noreferrer\"><code>collections.deque</code></a></p>\n\n<pre><code>from itertools import islice\nfrom collections import deque\n\n\ndef compare_length(iterable, n, operation):\n chunck = islice(iterable, max(0, n+1))\n try:\n (length, _) = deque(enumerate(chunk, 1), maxlen=1)\n except ValueError:\n length = 0\n return operation(length, n)\n</code></pre></li>\n<li><p><code>sum</code></p>\n\n<pre><code>from itertools import islice\n\n\ndef compare_length(iterable, n, operation):\n chunck = islice(iterable, max(0, n+1))\n length = sum(1 for _ in chunck)\n return operation(length, n)\n</code></pre></li>\n</ul></li>\n</ul>\n\n<p>The former should be more efficient, the latter more readable. As suggested in the question, this function takes the operation to perform as its third argument and compares <code>min(<iterable length>, n+1)</code> to <code>n</code>. This is sufficient in most cases.</p>\n\n<hr>\n\n<p>If you truly want to reduce the amount of <code>next</code> calls needed for <span class=\"math-container\">\\$\\lt\\$</span> and <span class=\"math-container\">\\$\\ge\\$</span>, you can keep your class approach and factorize the <code>min(<iterable length>, n)</code> part into an helper method:</p>\n\n<pre><code>from itertools import islice\n\n\nclass ILengthComparator:\n def __init__(self, iterable):\n self._iterable = iterable\n\n def _length_up_to(self, n):\n return sum(1 for _ in islice(self._iterable, max(0, n)))\n\n def __eq__(self, n):\n return self._length_up_to(n+1) == n\n\n def __ne__(self, n):\n return self._length_up_to(n+1) != n\n\n def __lt__(self, n):\n return self._length_up_to(n) < n\n\n def __le__(self, n):\n return self._length_up_to(n+1) <= n\n\n def __gt__(self, n):\n return self._length_up_to(n+1) > n\n\n def __ge__(self, n):\n return self._length_up_to(n) >= n\n</code></pre>\n\n<hr>\n\n<p>Lastly, if you want to avoid consuming the iterator while performing those tests, you can check <a href=\"https://docs.python.org/3/library/itertools.html#itertools.tee\" rel=\"nofollow noreferrer\"><code>itertools.tee</code></a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T13:29:36.810",
"Id": "235555",
"ParentId": "235536",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "235555",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T00:41:07.850",
"Id": "235536",
"Score": "2",
"Tags": [
"python",
"iterator"
],
"Title": "Compare length of iterator with as few `next` calls as possible. How can I deduplicate this code?"
}
|
235536
|
<p>Relatively new to Python. Have some experience in C++.</p>
<p>I have written a small program that reads a <code>CSV</code> file <a href="https://drive.google.com/file/d/1XGDi36auMY0NPnZa1J6g0KZ2dm259oT3/view?usp=sharing" rel="nofollow noreferrer">(SAMPLE)</a> and initialises two arrays and few values. There are 2 values in each line, and there are 8763 such lines. The first value of each line is put into one array and the second value is put into the second array. The last three values of each array (total 6) are then given to another variable.</p>
<p>I want further calculations as accurate as possible hence I've tried the decimal.Decimal approach for Float Point Arithmetic, but for some reason, it's not that accurate. I think I'm using it wrong. It is still in an acceptable tolerance.</p>
<p>Also, would like to know if there is a better/efficient way to initialise the array and/or variables.</p>
<p>Here is code:</p>
<pre class="lang-py prettyprint-override"><code> alpha = np.zeros(8763, dtype='float32') # Edited in later for clarity
gamma = np.zeros(8763, dtype='float32') # Edited in later for clarity
rf = 100
counter = 0
with open('CSVData.csv', 'r') as csv_file_in:
csv_reader = csv.reader(csv_file_in)
for line in csv_reader:
alpha[counter] = (float(decimal.Decimal(line[0]))) # Alpha Angle Initialized
gamma[counter] = (float(decimal.Decimal(line[1]))) # Gamma Angle Initialized
if counter == 8762:
break
counter = counter + 1
csv_file_in.close()
# Initializing last 6 parameters
C_NSX = rf * alpha[8760]
C_NSY = rf * gamma[8760]
C_EWX = rf * alpha[8761]
C_EWY = rf * gamma[8761]
NSC = int(alpha[8762])
EWC = int(gamma[8762])
</code></pre>
<p>Here the value of C_NSX should be 2790 but is 2789.9999185. <a href="https://i.imgur.com/KwLeSRi.png" rel="nofollow noreferrer">(Debug Image)</a></p>
<p><strong>EDIT: ADDED INFO ON THE PURPOSE OF THIS CODE</strong></p>
<p>Following is my problem statement: </p>
<p>There is a matrix of octagons, for example, 4 octagons in a row and 3 such rows. So 4 columns and 3 rows of octagons. But they are not arranged in a perfect rectangle form. </p>
<p><strong>Case1:</strong></p>
<p><a href="https://i.stack.imgur.com/bi1NH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bi1NH.png" alt="Matrix of Octagons"></a></p>
<p>The first Octagon, O(0,0) has coordinates(0,0), while the one at its right and the one at the bottom are at a bit offset. So O(0,1) has coordinates (15,50) and O(1,0) has coordinates (30,15). This information is enough to define the whole array of octagons. Now next requirement is to find how much is the net visible area of these octagons. In the first example, as the coordinates are far away, there would be no overlapping and total visible area is simply...</p>
<pre><code>Total_Visible_Area = Area_of_Single_Octagon * No_Of_Rows * No_Of_Columns
</code></pre>
<p>But when the coordinates are a bit complex, for example, <strong>Case 2:</strong>
<a href="https://i.stack.imgur.com/QVa6H.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QVa6H.png" alt="enter image description here"></a>
Here, the distance between the adjacent octagons is less than their width and hence they are overlapping. Coordinates also are negative (which does not matter much actually, just something to note). Now to determine the visible area for this I wrote the following function.</p>
<p>The piece of code that I have written above is the first step to calculate all these. Each case is defined using Alpha, Gamma, C_NSX, C_NSY, C_EWX, C_EWY, NSC and EWC. Among these Alpha and Gamma have 8760 different values (mostly zeroes) and all others (capitals) are constants. I have to find the overlapping area in each of the 8760 cases. The code for finding those <a href="https://codereview.stackexchange.com/questions/230524/find-overlapping-area-of-octagons">I had discussed here earlier</a>, and thought won't be necessary to bring out again. After that last question, I have moved to python from CPP and started learning OpenCV.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T07:41:55.027",
"Id": "461084",
"Score": "0",
"body": "@JanneKarila Both are dtype='float32'"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T08:04:48.820",
"Id": "461085",
"Score": "0",
"body": "@AdityaSoni, On one hand you said that \"*decimal.Decimal approach but for some reason, it's not that accurate*\", on the other hand - you concerned with *should be 2790 but is 2789.9999185* . Contradiction?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T08:14:39.590",
"Id": "461086",
"Score": "0",
"body": "@RomanPerekhrest I saw that Float Point issues are solved with the decimal approach, hence I tried it. But it is not working. I may be doing something wrong. It is still not accurate. It should be 2790 but is 2789.9999. I may have sentenced something wrong, but I'm not seeing any contradiction. In the end, I did say that this is still an acceptable tolerance but I posted this question as I want to make it better."
}
] |
[
{
"body": "<p>You don't really mention what are the values used for. You'll always have a tradeoff between speed and memory (in this case memory amounts to how many digits you have).</p>\n\n<p>Some issues with your code:</p>\n\n<p>1) You're casting your <code>decimal.Decimal(line[0])</code> as <code>float</code>, that should negate the advantage of using <code>Decimal</code>. And this might be a reason why you see the unexpected inconsistency. You have two options (in my opinion), you drop the use of numpy in favor of <code>array</code> from the standard library or you drop the pretense of using <code>Decimal</code> and use a pure numpy solution. But this will depend on what exactly you're doing.</p>\n\n<p>2) Looping over the CSV Reader is a way to read out the data, but numpy implements better ways to load a csv. See the last example in the documentation <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html#numpy.loadtxt\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Thus, in the end the question back is, what for do you want the numbers to be a accurate as possible? Keep in mind that the values in the file are already \"wrong\" as they most likely come already from a float type, so in my opinion, you don't gain anything by using <code>Decimal</code> in this case. A different scenario would be if the values are integers and then in your program you're doing some divisions or multiplications, in that case, you have from the beginning control of the floating-point values and then using <code>Decimal</code> might be what you want to do.</p>\n\n<p>Keep in mind, that highly sophisticated scientific research and their calculations use 64-bit floats and they do just fine.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T13:06:01.893",
"Id": "461401",
"Score": "0",
"body": "How do I show what I'm doing with these numbers, comment here or edit the question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T13:15:31.997",
"Id": "461408",
"Score": "0",
"body": "@AdityaSoni make an edit to the question, but for what I wrote is not really relevant as I described both cases already. It still would be a good idea for completeness of your question to add that info."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-16T05:26:37.983",
"Id": "461505",
"Score": "0",
"body": "added some info, hope I have not made it more complicated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-16T05:39:46.903",
"Id": "461506",
"Score": "0",
"body": "the first 8760 values are angles and won't make much difference. But the last 3x2 values are constants and need to be accurate. And I'm having trouble only in that. I guess rounding that up into an int would be my best solution right now.\n\nThe NumPy method of reading the CSV looks great, I'm going to give that a try and start using it. Also, I'm thinking of directly reading the excel sheet from where all these numbers are coming. \n\nThanks for your inputs. You've been a great help."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T11:05:10.223",
"Id": "235548",
"ParentId": "235538",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "235548",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T04:48:48.723",
"Id": "235538",
"Score": "2",
"Tags": [
"python",
"floating-point"
],
"Title": "A program that reads 8763x2 values from a CSV file and initialises an array and few other variables"
}
|
235538
|
<p>I'd recommend thinking of <code>readimage.py</code>'s <code>tess()</code> and <code>cune()</code> as sort of black boxes that use the OCRs. Anyway, this code is meant to be used for a science fair project where I am testing Tesseract and Cuneiforms' abilities to read text on images with various font sizes and colors, etc. Any thoughts, obvious mistakes, etc.? </p>
<p><code>main.py:</code></p>
<pre><code># Command-line arguments and other functionalities
import os
import sys
import math
import random
import ast
import argparse
# Image handling and OCR
import readimage
import drawimage
import distance
# Constants
DIMENSIONS = [850, 1100, 50, 50] # Width, Height, Side Margin, Top Margin
DICTLOC = "dict.txt"
COLORS = {
"R" : ((255,0,0), "Red"),
"G" : ((0,255,0), "Green"),
"W" : ((255,255,255), "White"),
"B" : ((0,0,0), "Black"),
"Y1" : ((255,252,239), "Yellow1"),
"Y2" : ((255,247,218), "Yellow2"),
"Y3" : ((255,237,176), "Yellow3"),
"Y4" : ((255,229,139), "Yellow4"),
}
# Read command-line arguments
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--pages", type=int, help="Pages per Setting", default=1)
parser.add_argument("-f", "--fonts", help="Comma-Seperated List of fonts", default="freefont/FreeMono.ttf")
parser.add_argument("-tc", "--txtcolors", help="Comma-Seperated Color Initials", default="B")
parser.add_argument("-bc", "--bgcolors", help="Comma-Seperated Color Initials", default="W")
parser.add_argument("-hs", "--headsizes", type=str, help="Comma-Seperated Header Font Heights", default="50")
parser.add_argument("-bs", "--bodysizes", type=str, help="Comma-Serperated Body Font Heights", default="25")
parser.add_argument("-v", "--verbose", help="Print progress", action="store_true")
args = parser.parse_args()
pages = args.pages
fonts = args.fonts.split(",")
txtcolors = [COLORS[c] for c in args.txtcolors.split(",")]
bgcolors = [COLORS[c] for c in args.bgcolors.split(",")]
headsizes = [int(s) for s in args.headsizes.split(",")]
bodysizes = [int(s) for s in args.bodysizes.split(",")]
verbose = args.verbose
# Grab dictionary as list of words
worddict = open(DICTLOC).read()
worddict = worddict.split("\n")
def image_stats(file, correct, language="eng", tessconfig=""):
tess = {}
tess_out, tess["time"] = readimage.tess_ocr("img.png")
tess_out = " ".join(tess_out.split()).strip()
tess["dist"] = distance.lev(correct, tess_out)
tess["per"] = round((len(correct)-tess["dist"])/len(correct),4)
tess["tpc"] = round(tess["time"]/len(correct)*1000, 4)
cune = {}
cune_out, cune["time"] = readimage.cune_ocr("img.png")
cune_out = " ".join(cune_out.split()).strip()
cune["dist"] = distance.lev(correct, cune_out)
cune["per"] = round((len(correct)-cune["dist"])/len(correct),4)
cune["tpc"] = round(cune["time"]/len(correct)*1000, 4)
return tess, cune
def main():
if os.path.exists("fullout.txt"):
os.remove("fullout.txt")
if os.path.exists("avgout.txt"):
os.remove("avgout.txt")
fullout = open("fullout.txt",mode='a')
fullout.write("\tCuneiform\tTesseract\tCuneiform\tTesseract\tCuneiform\tTesseract\tCuneiform\tTesseract\n")
avgout = open("avgout.txt", mode='a')
avgout.write("\tCuneiform\tTesseract\tCuneiform\tTesseract\tCuneiform\tTesseract\tCuneiform\tTesseract\n")
for font in fonts:
for txtcolor in txtcolors:
for bgcolor in bgcolors:
fullout.write(f"Font: {font}, {txtcolor[1]} on {bgcolor[1]}\tCuneiform\tTesseract\tCuneiform\tTesseract\tCuneiform\tTesseract\tCuneiform\tTesseract\n")
avgout.write(f"Font: {font}, {txtcolor[1]} on {bgcolor[1]}\tCuneiform\tTesseract\tCuneiform\tTesseract\tCuneiform\tTesseract\tCuneiform\tTesseract\n")
for headsize in headsizes:
for bodysize in bodysizes:
cune_stats = []
tess_stats = []
avgout.write(f"{bodysize}")
for page in range(pages):
fullout.write(f"{bodysize}")
title = drawimage.generate_words(worddict, random.randint(1,10))
body = drawimage.generate_words(worddict, 10000)
img, correct = drawimage.create_page(title, body, DIMENSIONS, txtcolor[0], bgcolor[0], headsize, bodysize, font)
img.save("img.png")
correct = " ".join(correct).replace("\n", " ")
tess, cune = image_stats("img.png", correct)
tess_stats.append(tess)
cune_stats.append(cune)
fullout.write(f"\t{cune['time']}\t{tess['time']}\t{cune['tpc']}\t{tess['tpc']}\t{cune['dist']}\t{tess['dist']}\t{cune['per']}\t{tess['per']}\n")
cune = {}
tess = {}
for stat in cune_stats[0]:
cune[stat] = round(sum([i[stat] for i in cune_stats]) / len(cune_stats), 4)
tess[stat] = round(sum([i[stat] for i in tess_stats]) / len(tess_stats), 4)
avgout.write(f"\t{cune['time']}\t{tess['time']}\t{cune['tpc']}\t{tess['tpc']}\t{cune['dist']}\t{tess['dist']}\t{cune['per']}\t{tess['per']}\n")
fullout.close()
avgout.close()
if __name__ == "__main__":
main()
</code></pre>
<p><code>drawimage.py:</code></p>
<pre><code>from PIL import Image, ImageDraw, ImageFont
import random
# Turn words into lines, based on size of page and font, then return lines and height of lines
def word_space(words, font, height, spaceh=30):
linew = 0
linet = ""
lines = []
wordnum = 0
while wordnum < len(words):
if len(linet) > 0: linet += " "
linet += words[wordnum]
if font.getsize(linet)[0] > DIMENSIONS[0] - (2*DIMENSIONS[2]):
if spaceh * (len(lines)+1) > height:
linet = linet[:-(len(words[wordnum])+1)]
break
else:
linet = linet[:-(len(words[wordnum])+1)]
if font.getsize(words[wordnum])[0] > DIMENSIONS[0] - (2*DIMENSIONS[2]):
print("Word too long, skipping: " + words[wordnum])
wordnum += 1
else:
lines.append(linet)
linet = ""
else:
wordnum += 1
if linet:
lines.append(linet)
return lines, spaceh * len(lines)
# Add text to an image, return new image
def add_text(img, text, pos, font, fcolor):
d = ImageDraw.Draw(img)
d.text(pos, text, font=font, fill=fcolor)
return img
# Draw an entire page, return image and correct text
def create_page(title, body, DIM, txtcolor, bgcolor, titlesize, bodysize, font):
global DIMENSIONS
DIMENSIONS = DIM
img = Image.new('RGBA', (DIMENSIONS[0], DIMENSIONS[1]), bgcolor+(255,))
titlefont = ImageFont.truetype(font, titlesize)
bodyfont = ImageFont.truetype(font, bodysize)
titlespaced, titleh = word_space(title, titlefont, DIMENSIONS[1]-40, spaceh=titlesize+10)
for i, line in enumerate(titlespaced):
img = add_text(img, line, (50,(titlesize+10)*i+20),titlefont,txtcolor)
bodyspaced, margin = word_space(body, bodyfont, DIMENSIONS[1]-40-titleh-20, spaceh=bodysize+10)
for i, line in enumerate(bodyspaced):
img = add_text(img, line, (50,((bodysize+10)*i)+titleh+20), bodyfont, txtcolor)
return img, titlespaced+bodyspaced
# Generate and return a given number of words
def generate_words(worddict, length):
words = []
for j in range(length):
word = random.choice(worddict)
mod = random.randint(1,10)
if mod == 1:
word = word.upper()
elif mod == 2:
word = word.capitalize()
elif random.randint(1,15) == 1:
word += "."
words.append(word)
return words
</code></pre>
<p><code>readimage.py:</code></p>
<pre><code>import subprocess
import os
import time
from PIL import Image
import pytesseract
# Functions to run either OCR on a given image.
def tess_ocr(file, language="eng", config=""):
# Run and time Tesseract, return output
start = time.time()
out = pytesseract.image_to_string(Image.open(file), language, config=config)
return out, round(time.time() - start, 4)
def cune_ocr(file, language="eng"):
# Run Cuneiform on image
start = time.time()
subprocess.call(["cuneiform", "-o", "cuneout.txt",file], stdout=subprocess.PIPE)
# Fetch and return output
if os.path.exists("cuneout.txt"):
out = open("cuneout.txt").read()
return out, round(time.time() - start, 4)
else:
print("Cuneiform reported no output, returning empty string")
return "", round(time.time() - start, 4)
</code></pre>
<p><code>distance.py:</code></p>
<pre><code>import numpy
# Find Levenshtein Distance between two strings
def lev(a,b):
sizex = len(a)+1
sizey = len(b)+1
matrix = numpy.zeros((sizex,sizey))
for x in range(sizex):
matrix[x,0] = x
for y in range(sizey):
matrix[0,y] = y
for y in range(1, sizey):
for x in range(1, sizex):
cost = 0
if a[x-1] != b[y-1]:
cost = 2
matrix[x,y] = min(
matrix[x-1,y] + 1,
matrix[x,y-1] + 1,
matrix[x-1,y-1] + cost
)
return int(matrix[sizex-1,sizey-1])
</code></pre>
|
[] |
[
{
"body": "<p>Some small comments:</p>\n\n<ul>\n<li><p>In <code>main.py</code>: <code>argparse</code> can already deal with argument types and multiple arguments (it even enforces the type across multiple arguments). If you change it to multiple arguments being separated by whitespace, you can simply use this:</p>\n\n<pre><code>parser = argparse.ArgumentParser()\nparser.add_argument(\"-p\", \"--pages\", type=int, help=\"Pages per Setting\", default=1)\nparser.add_argument(\"-f\", \"--fonts\", nargs=\"+\", help=\"Space seperated List of fonts\", default=[\"freefont/FreeMono.ttf\"])\nparser.add_argument(\"-tc\", \"--txtcolors\", nargs=\"+\", help=\"Space seperated Color Initials\", default=[\"B\"])\nparser.add_argument(\"-bc\", \"--bgcolors\", nargs=\"+\", help=\"Space seperated Color Initials\", default=[\"W\"])\nparser.add_argument(\"-hs\", \"--headsizes\", nargs=\"+\", type=int, help=\"Space seperated Header Font Heights\", default=[50])\nparser.add_argument(\"-bs\", \"--bodysizes\", nargs=\"+\", type=int, help=\"Space seperated Body Font Heights\", default=[25])\nparser.add_argument(\"-v\", \"--verbose\", help=\"Print progress\", action=\"store_true\")\nargs = parser.parse_args()\n</code></pre></li>\n<li><p>In <code>readimage.py</code>: If you need something more than once, don't repeat yourself. Write a wrapper function that does the timing for you:</p>\n\n<pre><code>from time import perf_counter\nfrom functools import wraps\n\ndef timeit(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n start = perf_counter()\n ret = f(*args, **kwargs):\n return ret, round(perf_counter() - start, 4)\n return wrapper\n\n\n@timeit\ndef tess_ocr(file, language=\"eng\", config=\"\"):\n return pytesseract.image_to_string(Image.open(file), language, config=config)\n\n@timeit\ndef cune_ocr(file, language=\"eng\"):\n # Run Cuneiform on image\n subprocess.call([\"cuneiform\", \"-o\", \"cuneout.txt\",file], stdout=subprocess.PIPE)\n\n # Fetch and return output\n if os.path.exists(\"cuneout.txt\"):\n with open(\"cuneout.txt\") as f:\n return f.read()\n else:\n print(\"Cuneiform reported no output, returning empty string\")\n return \"\"\n</code></pre>\n\n<p>Note that I used the more accurate <a href=\"https://docs.python.org/3/library/time.html#time.perf_counter\" rel=\"nofollow noreferrer\"><code>time.perf_counter</code></a> and ensured that the docstring etc are conserved using <a href=\"https://docs.python.org/3/library/functools.html#functools.wraps\" rel=\"nofollow noreferrer\"><code>functools.wraps</code></a>. I also made sure the file is properly closed using a <a href=\"https://effbot.org/zone/python-with-statement.htm\" rel=\"nofollow noreferrer\"><code>with</code> statement</a>. </p>\n\n<p>Arguably, the <code>wrapper</code> function should only print/log the timing instead of returning it and thereby changing the signature of the function, but I left your interface as is here. You might even want to put this function into its own module, since it is quite reusable (especially when modifying it not to change the function signature).</p></li>\n<li><p>There are already Levenshtein distance modules, like <a href=\"https://pypi.org/project/editdistance/\" rel=\"nofollow noreferrer\"><code>editdistance</code></a> and <a href=\"https://pypi.org/project/python-Levenshtein/\" rel=\"nofollow noreferrer\"><code>python-Levenshtein</code></a>, both of which are quite fast.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T13:09:11.357",
"Id": "235607",
"ParentId": "235539",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T05:25:46.483",
"Id": "235539",
"Score": "3",
"Tags": [
"python",
"python-3.x"
],
"Title": "Test OCRs on Generated Images"
}
|
235539
|
<p>I've written a 2D ray-tracer in GLSL ES for GameMaker for dynamic lighting. I've also written a blog post on how it works... though it is out-dated. I am looking to have JUST my shaders reviewed to see if there is anything that can be done to simplify or improve performance. Here is a <a href="https://drive.google.com/open?id=1c8s4QCsBDUJjpMfbDKrixg4fyCuNWLjt" rel="nofollow noreferrer">download</a> link to the full working example as well as a link to the <a href="https://forum.yoyogames.com/index.php?threads/quick-ray-traced-qrt-lighting-tutorial.60842/" rel="nofollow noreferrer">blog post</a>.</p>
<p>Here is a visual example of how it works:
<a href="https://i.stack.imgur.com/BPDD8.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BPDD8.gif" alt="enter image description here"></a></p>
<p>The first shader takes in a small texture--small enough to just store the results of the rays traced as colors--and traces out the length of each ray of the light until a collision is made on the world map (collision texture/surface). The resulting ray length is converted into an RG color and sent to gl_FragColor. This creates an index lookup table for the second shader to reconstruct the actual light from the ray table. You can see in the reference image how each ray maps to the lookup table texture onto the light.</p>
<p>The second shader takes the ray lookup table and reconstructs the light using the pre-traced rays. Each pixel will check 1 ray and at worst case 2 rays. In the event that a pixel fails the first ray check it looks up the next closest ray and checks against that just in case.</p>
<p><a href="https://i.stack.imgur.com/Pka33.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Pka33.gif" alt="enter image description here"></a></p>
<p>An important bit of info here:</p>
<pre><code>// The maximum radius allowed for the light.
MAXRADIUS = 64.0;
// The pow2 size of the ray-map texture calc'd as: exp2(ceil(0.5 * log2(2 * PI * MAXRADIUS)));
in_RayTexSize = 32.0;
// The pow2 size of the light texture calc'd as: exp2(ceil(log2(2 * MAXRADIUS)));
in_LightTexSize = 128.;
</code></pre>
<p>You can see in the shaders below and the example I've commented out the uniform inputs in the shaders and hand-inputted them myself for testing.</p>
<pre><code>/*
This shader does the ray-tracing and stores the resulting length of each ray as a 2-byte float in the RG(red-green) color of gl_FragColor.
*/
uniform sampler2D in_WorldMap;
uniform vec3 in_Light;
uniform vec2 in_World;
varying vec2 in_Coord;
//uniform float in_RayTexSize;
const float in_RayTexSize = 32.0;
const float PI2 = 2. * 3.1415926535897932384626433832795;
const float MAXRADIUS = 64.0;
void main() {
// Gets the current pixel position in X,Y coordinates (instead of UV).
vec2 Coord = floor(in_Coord * in_RayTexSize), xyRay = vec2(0.),
// Gets the ray index in the ray lookup texture and calcs out the number total rays to check against (2 * pi * r).
RayMap = vec2((Coord.y * in_RayTexSize) + Coord.x, (PI2 * in_Light.z));
// Checks if the ray index we're writting to is within bounds.
if (RayMap.x <= RayMap.y) {
// Gets the ray direction around the light center.
float Theta = (PI2 * (RayMap.x / RayMap.y));
vec2 Step = vec2(cos(Theta), -sin(Theta));
// Traces the ray to max radius (since GLSL requires const loops).
for(float rad = 0., d = 0.; d < MAXRADIUS; d++) {
// Performs ray checks only within light bounds.
if (rad >= in_Light.z) break;
// Steps across the light ray.
xyRay = floor((Step * d) + 0.5);
// Fancy trick to cancel ray checking by moving out of light bounds.
rad = d + (in_Light.z * texture2D(in_WorldMap, (in_Light.xy + xyRay) * in_World).a);
}
// Converts the length of the ray to a 2-byte float color (RG).
float rayLength = length(xyRay) / in_Light.z;
xyRay = vec2(floor(rayLength * 255.0) / 255.0, fract(rayLength * 255.0));
}
// Passes the ray info into the ray texture lookup table.
// This will be black (no ray, if out of bounds).
gl_FragColor = vec4(xyRay, 0.0, 1.0);
}
</code></pre>
<pre><code>uniform sampler2D in_WorldMap, in_LightMap;
uniform vec3 in_Light, in_Color;
uniform vec2 in_World;
varying vec2 in_Coord;
//uniform float in_RayTexSize, in_LightTexSize;
const float in_RayTexSize = 32.0, in_LightTexSize = 128.;
const vec2 in_TexCenter = vec2((in_LightTexSize * 0.5) + 0.5);
const float PI2 = 2. * 3.1415926535897932384626433832795;
// Takes in the ray-index and does a lookup in the ray texture lookup table.
// This will convert the RG ray length to a float for the actual length.
float getRayFromIndex(float index) {
vec2 RayPos = vec2(mod(index, in_RayTexSize), index / in_RayTexSize) * (1./in_RayTexSize),
TexRay = texture2D(in_LightMap, RayPos).rg;
return clamp(TexRay.r + (TexRay.g / 255.0), 0.0, 1.0) * in_Light.z;
}
// Gets the next closest index to the input.
float getNearIndex(float index) {
return 1. + (-2. * (1. - floor(fract(index) + 0.5)));
}
void main() {
// Gets the current pixel position in X,Y coordinates (instead of UV).
vec2 Coord = in_Coord * in_LightTexSize;
// Gets the distance of the pixel to the light center.
float Distance = distance(Coord, in_TexCenter);
vec4 Color = vec4(0.);
// Only light up this pixel if it's within light bounds.
if (Distance < in_Light.z-1.) {
// Gets the relative position/distance around the light.
vec2 Delta = Coord - in_TexCenter;
// Constructs and pre-computes our light's tonemap.
float ToneMap = 1. - (Distance/in_Light.z), RayCount = (PI2 * in_Light.z),
// Gets the ray index relevant to the current pixel.
RayIndex = RayCount * fract(atan(-Delta.y, Delta.x)/PI2),
// Gets the next closest ray index relevant to the current pixel.
RayIndexNear = RayIndex + getNearIndex(RayIndex),
// Calculates the pixel's luminescence.
xyRay = sign(getRayFromIndex(RayIndex) - Distance) * ToneMap;
// If the ray check fails, check the next closest ray for validation.
if (xyRay <= 0.)
if ((RayIndexNear-RayCount) * RayIndexNear <= 0.)
xyRay = sign(getRayFromIndex(RayIndexNear) - Distance) * ToneMap;
// Do not light up any pixel that has a collision under it.
xyRay *= (1. - texture2D(in_WorldMap, (in_Light.xy + Delta) * in_World).a);
Color = vec4(in_Color, 1.) * xyRay;
}
// Output the final constructed light pixel.
gl_FragColor = Color;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T15:18:11.623",
"Id": "461122",
"Score": "1",
"body": "How come you don't use Github instead of google drive?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T15:54:43.153",
"Id": "461125",
"Score": "0",
"body": "I have it under a private repo. I just haven't had the tine to set up a proper public repo with documentation, etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-06T09:23:11.573",
"Id": "514052",
"Score": "1",
"body": "Please add a language tag."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-07T16:07:11.963",
"Id": "514153",
"Score": "1",
"body": "@Mast the deed is done."
}
] |
[
{
"body": "<p>It appears that you're doing a ray march when you could be using the <a href=\"https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm</a></p>\n\n<hr>\n\n<p>If the maximum distance of your ray is 64, why do you need two components (RG) to store it? Consider other formats like R8, R16, floating point texture formats, or <code>floatBitsToInt</code>. </p>\n\n<hr>\n\n<p>Multiple declarations in a statement is hard to read, especially when they're not aligned.</p>\n\n<hr>\n\n<p>You can vary in texel (XY) space instead of texture(UV) space, and skip some multiplications. You can also use something like gl_FragCoord which may be easier to manage.</p>\n\n<hr>\n\n<p>breaking from the inside of a loop is fine, you don't need tricks like cancelling out the distance. </p>\n\n<hr>\n\n<p>Prefer <code>texelFetch</code> instead of <code>texture2D</code> when appropriate -- i.e. when you don't need filtering. <code>texture2D</code> implies lod calculations may be relevant and can adversely affect branching.</p>\n\n<hr>\n\n<p>Finally, I don't believe this will perform better than rasterizing 2D data into a set of 1D viewports in a way similar to shadow mapping. The rasterization approach has many huge advantages like being able to batch-cull an enormous amount of data.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T02:27:59.703",
"Id": "461213",
"Score": "0",
"body": "The max radius is adjustable. Hence the RG component."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T02:33:59.583",
"Id": "461215",
"Score": "0",
"body": "Bresenham would be more accurate, but would it be more efficient...?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T02:39:24.590",
"Id": "461217",
"Score": "1",
"body": "I haven't personally benchmarked it but I would bet that it's more efficient. It should yield the minimal number of necessary points to test. Compare to a diagonal ray march -- it will do sqrt(dx^2+dy^2) iterations, where bressenham will do dx(==dy)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T02:45:35.700",
"Id": "461218",
"Score": "0",
"body": "Final question, at the second shader at comment/section \"// If the ray check fails,\" is there a way I can avoid this second ray check? The second ray is validation in the event that the first ray doesn't collide with the light pixel, but the second might. Right now it's necessary via this implementation, any way around this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T03:10:51.967",
"Id": "461219",
"Score": "0",
"body": "With the current algorithm I'm not sure -- if I understand it right, the rays will get more sparse the farther a pixels from a light, and the rays in the second shader will be potentially further and further away? If your texture is too small, I would expect there to be slight holes where there's no light near the edges of lines."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T03:13:24.687",
"Id": "461221",
"Score": "1",
"body": "Instead, what if you did: 1. for each light's bounding box, collect all intersecting lines. 2. for each pixel in the bounding box, perform ray-line intersection tests on every line with every pixel position going to the light. This has very different performance characteristics -- it will run very fast if there is minimal geometry, but crushingly slow if there's a ton of lines all stacked on each other. Note that the collection process can be run on the GPU, but since it's outputting variable (but bounded) data, it's much more complex."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T04:11:40.477",
"Id": "461225",
"Score": "0",
"body": "Yeah that's a bad idea. Because of the particular kind of work being done here, shaders are perfect for this. I am actually receiving performance in orders of hundreds to thousands of lights depending upon light radius size. The concept already works, just working towards cleanup and optimization. See also: https://twitter.com/FatalSleep/status/1213395686663737344?s=20"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T04:13:35.420",
"Id": "461226",
"Score": "0",
"body": "Not to mention that the flexibility here to enable pixel-level detail + ray traced lighting is enormously powerful. So I don't see any benefit moving towards slower, more complicated shadow casting and geometry calculations."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T02:20:57.260",
"Id": "235586",
"ParentId": "235541",
"Score": "4"
}
},
{
"body": "<p>Alright so I am going to give myself and <a href=\"https://twitter.com/XorDev\" rel=\"nofollow noreferrer\">@XorDev on Twitter</a> kudos on this one. We worked together to optimize and simplify the process of ray-tracing the lights and removed a bunch of redundant code. Here are the final versions:</p>\n\n<pre><code>///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n///Shd_RayTracer (Final)\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\nuniform sampler2D in_WorldMap;\nuniform vec3 in_Light;\nuniform vec2 in_World;\nuniform float in_RayTexSize;\nvarying vec2 in_Coord;\nconst float MAXRADIUS = 65535., TAU = 6.2831853071795864769252867665590;\n\nvoid main() {\n vec2 Coord = floor(in_Coord * in_RayTexSize),\n xyRay = vec2((Coord.y * in_RayTexSize) + Coord.x, TAU * in_Light.z);\n float Theta = TAU * (xyRay.x / xyRay.y);\n vec2 Delta = vec2(cos(Theta), -sin(Theta));\n\n float Validated = step(xyRay.x,xyRay.y);\n for(float d = 0.; d < MAXRADIUS * Validated; d++) {\n if (in_Light.z < d + in_Light.z * texture2D(in_WorldMap, (in_Light.xy + xyRay) * in_World).a) break;\n xyRay = floor(Delta * d + 0.5);\n }\n\n float rayLength = length(xyRay) / in_Light.z;\n gl_FragColor = vec4(vec2(floor(rayLength * 255.0) / 255.0, fract(rayLength * 255.0)), 0.0, 1.0);\n}\n</code></pre>\n\n<pre><code>///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n///Shd_LightSampler (Final)\n///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\nuniform sampler2D in_WorldMap, in_LightMap;\nuniform vec3 in_Light, in_Color;\nuniform vec2 in_World, in_LightCenter, in_TexCenter;\nuniform float in_RayTexSize, in_LightTexSize;\nvarying vec2 in_Coord;\nconst float TAU = 6.2831853071795864769252867665590;\n\nvoid main() {\n vec2 Coord = in_Coord * in_LightTexSize,\n Delta = Coord - in_TexCenter;\n float RayCount = TAU * in_Light.z,\n RayIndex = floor((RayCount * fract(atan(-Delta.y, Delta.x)/TAU)) + 0.5);\n vec2 RayPos = vec2(mod(RayIndex, in_RayTexSize), RayIndex / in_RayTexSize) * (1./in_RayTexSize),\n TexRay = texture2D(in_LightMap, RayPos).rg;\n float Distance = distance(Coord, in_TexCenter),\n RayLength = clamp(TexRay.r + (TexRay.g / 255.0), 0.0, 1.0) * in_Light.z,\n RayVisible = sign(RayLength - Distance) * (1. - texture2D(in_WorldMap, (in_Light.xy + Delta) * in_World).a),\n ToneMap = 1. - (Distance/in_Light.z);\n gl_FragColor = vec4(in_Color * ToneMap, RayVisible);\n}\n</code></pre>\n\n<p><strong>SHADER: Shd_RayTracer</strong></p>\n\n<p>The first major hurdle was just eliminating IF-Statements. I didn't actually know that if-statements and the code they encapsulate still continue to run despite the fact that typically IF-statements keep that from happening. Not in shaders, IF-statements and the code they encapsulate all still get evaluated regardless....</p>\n\n<p>So instead what @XorDev mentioned was that I should be using the <code>step(a,b)</code> as a comparative validation statement to multiply by the condition for my <code>for loop</code>. This multiplies out and cancels the for-loop by setting the condition to 0 loops in the event that a pixel is out of range of the set of rays to be indexed. Fancy.</p>\n\n<p>Next I realized that specifically for GameMaker when running GLSL ES shaders that the size of the for-loop does not affect run-time or compile time. So I don't think GameMaker is particularly unrolling the for loop here when compiling the shader. So I set the for loop to the maximum radius of what this shader will be processing on, <code>2^16-1</code> radius or a <code>2*(2^16-1)</code> diameter light. Plenty for games IMO. The reason for this restriction is to reduce the actual floating point conversion to RG components when rendering to the texture for a total of 2 bytes instead of 3 or 4 for efficiency purposes.</p>\n\n<p><strong><em>CANCELING OUT DISTANCE IN LOOP</strong>\nAs another user mentioned, I do not need to cancel out the distance in order to break away from the loop. This is false and actually highly necessary. The reason for the trickery here is to prematurely exit the for-loop in the event that we've hit a collision and don't want to proceed tracing out the full length of the ray.</em></p>\n\n<p><strong>SHADER: Shd_LightSampler</strong></p>\n\n<p>Again the same idea was used here as well, just simply eliminate the if-statements. The shader still runs the same, but more efficiently, even if I am not evaluating out each pixel via an IF-statement. Branching is slow. The reason here that the shader still runs the same is that I actually multiply out the color to black if the pixel is out of range regardless, so pixels outside the light radius still end up blank.</p>\n\n<p>Finally one of the bigger hurdles was eliminating the secondary ray check. Originally I had designed the shader to check the 2 closest rays to the pixel being rendered in the event that the first ray failed to validate the pixel. Essentially this was unnecessary and all I did was <code>floor()</code> the desired ray index so as to get the correct ray appropriate for the pixel where as before it was hit or miss depending upon rounding errors.</p>\n\n<p>This all allowed for several other small optimizations such as not using several multiplication maths to calculate out the <code>ToneMap</code> based on whatever IF-condition.</p>\n\n<p><strong>TL:DR</strong></p>\n\n<p>IF-statements are bad, GPUs love floating point operations and I can prematurely exit loop iterations. Fantastic, I saw about a 6x improvement on speed roughly, though I'm not doing rigorous highly skilled testing. All I know is that now I can render more lights at higher radius (roughly 600 lights at a 512px radius on a 1080 Ti) and in the order of thousands of lights with smaller and smaller radius, eventually hitting a bandwidth cap I believe on the part of either GameMaker or my GPU, no idea.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-17T06:52:31.427",
"Id": "235765",
"ParentId": "235541",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "235765",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T08:00:01.480",
"Id": "235541",
"Score": "7",
"Tags": [
"glsl",
"shaders"
],
"Title": "2D Real-Time Ray-tracing"
}
|
235541
|
<p>I need some constructive feedback for the working <code>OOPs</code> project which I created to introduce to Object Oriented Programming in a class. Hence is for beginners, I did not include interfaces or abstract functions nor singleton or factories. Can you give me some feedback on the code style, some possible anti patterns? Thanks</p>
<pre class="lang-php prettyprint-override"><code><?php
declare(strict_types=1);
namespace MidoriKocak;
use function array_key_exists;
/**
*
*/
final class User
{
/**
* @var Database
*/
private Database $db;
/**
* @var string
*/
private ?string $id = null;
/**
* @var string
*/
private string $email;
/**
* @var string
*/
private string $username;
/**
* @var string
*/
private string $password;
/**
*
*/
public function __construct(Database $db)
{
$this->db = $db;
}
/**
* @param string $password
*
* @return void
*/
public function setPassword(string $password): void
{
$this->password = password_hash($password, PASSWORD_DEFAULT);
}
public function getPassword(): string
{
return $this->password;
}
/**
* @param string $email
*
* @return void
*/
public function setEmail(string $email): void
{
$this->email = $email;
}
/**
* @param string $username
*
* @return void
*/
public function setUsername(string $username): void
{
$this->username = $username;
}
/**
* @return void
*/
public function save()
{
if ($this->id) {
$this->db->update($this->id, $this->toArray(), 'users');
} else {
$this->db->insert($this->toArray(), 'users');
$this->id = $this->db->lastInsertId();
}
}
/**
* @return array
*/
public function toArray(): array
{
return [
'username' => $this->username,
'email' => $this->email,
'password' => $this->password
];
}
/**
* @param array $data
*
* @return void
*/
public function fromArray(array $data): void
{
if (array_key_exists('id', $data)) {
$this->id = (string)$data['id'];
}
$this->setEmail($data['email']);
$this->setUsername($data['username']);
$this->setPassword($data['password']);
}
}
</code></pre>
<p>Thank you for your feedback. </p>
<p>(P.S. Please be harsh as possible.)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T09:30:29.390",
"Id": "461088",
"Score": "1",
"body": "Please be advised that your question may be closed under the formal pretext that it is not an excerpt from a working code but an educational example. I would remove that beginners stuff from the question, make sure you have this very code up and running as a part of some application and then just ask to review it. this is a very good code for the review and don't want to lose the opportunity to post it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T09:34:59.537",
"Id": "461089",
"Score": "0",
"body": "thank you, where should I post it then? There is a working example project but I did not want to overwhelm the question with details."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T09:37:07.813",
"Id": "461090",
"Score": "0",
"body": "Keep it here, just change the description. It should say this is just a working code from your project. Make sure it is indeed so. For example, make sure there is no copy-paste error in the login() method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T09:59:25.670",
"Id": "461091",
"Score": "0",
"body": "Thank you, let me update it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T10:07:45.173",
"Id": "461092",
"Score": "1",
"body": "Thank you. What is the relation between User and Users classes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T10:12:22.083",
"Id": "461094",
"Score": "0",
"body": "I just put it to separate finding user from database responsibility from User class but it feels like login and logout actions is not in user classes responsibilities. I also feel like the User class knows too much about db class, but without interfaces it would be hard to clarify."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T12:35:31.563",
"Id": "461106",
"Score": "0",
"body": "The title of this question is not what is expected/required. The title should uniquely represent what the script does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T13:07:16.703",
"Id": "461111",
"Score": "0",
"body": "Well, looking at *private* properties, I would say this post is not salvageable in its current form. Please make this code a part of some actual application, use it to perform some basic tasks and only then post if for a review."
}
] |
[
{
"body": "<h1>Inconsistent Function Imports</h1>\n\n<p>Import all used functions or none.\nIf I see this:</p>\n\n<pre><code>use function array_key_exists;\n</code></pre>\n\n<p>I assume that it is the only global function being used in that file. To my surprise, it is not true as <code>password_hash</code> is used inside the same file too.</p>\n\n<p>Either import them all, or none.\nI myself prefer no imports and instead prefix global function calls with the backslash to denote global scope (ie <code>return \\array_key_exists($k, $a);</code>).</p>\n\n<h1>Useless Docblocks</h1>\n\n<p>In PHP 7.4 you get the benefit of typehinting properties. I dont see a reason to repeat that type in a docblock anymore in that case. Furthermore it may cause confusion of what the original intent was, if docblock and typehint mismatch. Like here:</p>\n\n<pre><code>/**\n * @var string\n */\nprivate ?string $id = null;\n</code></pre>\n\n<p>So can it be null or not? I suppose it can, but you never know if you made it this confusing...</p>\n\n<h1>Active Record Anti-pattern</h1>\n\n<p>You asked to identify possible anti patterns. Active record is one of them. It combines two responsibilities. The entity should not know anything about where it is going to be stored and how. It may eventualy get stored on multiple places or be stored in various ways. The entity should only know that it has some structured data. Then another class(es) should know how to store it and reconstruct it from its permanent representation (ie a db row).</p>\n\n<p>Also notice that <code>save()</code> is either going to have to be repeated in every entity. Or all entities must inherit the same parent or use the same trait (inheritance is oftne not a good idea, and multiple inheritance (traits) even worse).</p>\n\n<p>Also notice that only one of User class's methods (namely the save) uses the database object. That only confirms that it should not be there. You should pass the user entity/structure to another object asking him to save the user into its persistent storage for later retrieval.</p>\n\n<h1>Check Your Arrays' Keys</h1>\n\n<p>In the <code>fromArray()</code> you are copying the values from array data without making sure that those data is there.</p>\n\n<pre><code>$this->setEmail($data['email']);\n$this->setUsername($data['username']);\n$this->setPassword($data['password']);\n</code></pre>\n\n<pre><code>if (isset($data['email']) && \\is_string($data['email'])) $this->setEmail($data['email']);\n</code></pre>\n\n<p>or set it to some default</p>\n\n<pre><code>$this->setEmail($data['email'] ?? '');\n</code></pre>\n\n<h1>Handling Login</h1>\n\n<p>Although you have removed that part from your post, I will address it nevertheless.</p>\n\n<p>isLoggedIn should not be persistent property of user entity (table). It should be stored (or inferred) from session. Otherwise how you make sure that it is turend to false after some time of inactivity?</p>\n\n<p>Anyway <code>User::login(string $email, string $pass): bool</code> again breaks SRP. You should have it more like this: <code>Authenticator::login(string $email, string $pass): ?User</code>. You may be tempted to make it <code>UsersRepository::login()</code> but repository usualy does not need access to session while the login method does, therefore it should be in its own class, not in the repository.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T15:32:19.673",
"Id": "235563",
"ParentId": "235542",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235563",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T09:27:46.183",
"Id": "235542",
"Score": "0",
"Tags": [
"php",
"object-oriented"
],
"Title": "User class implemented with PHP 7.4 using Active Record"
}
|
235542
|
<p>This is different from classic LIS problem. Here I want number of contiguous longest increasing subsequences!</p>
<p>For example:</p>
<pre class="lang-none prettyprint-override"><code>INPUT: arr[] = { 3, 6, 10, 8, 11, 17, 16, 100 }
OUTPUT: 2
</code></pre>
<p>Explanation: There are 2 longest contiguous subsequences: <code>{ 3, 6, 10 }</code> and <code>{ 8, 11, 17 }</code>.</p>
<p>Here is a function that I have made to achieve the task. But is there any optimized way instead of this brute force approach?</p>
<pre><code>#define ll long long int
ll longestIncSeq(vector<ll> temp, ll n)
{
ll count=0,mymax = -1,flag=0,dummy=0;
while( (flag==0) && (!(temp.empty())) )
{
ll max = 1, len = 1, maxIndex = 0;
for (ll i=1; i<n; i++)
{
if (temp[i] > temp[i-1])
len++;
else
{
if (max < len)
{
max = len;
maxIndex = i - max;
}
len = 1;
}
}
if (max < len)
{
max = len;
maxIndex = n - max;
}
if( max == 1 )
{
return count;
}
if( (mymax == max) || (dummy==0) )
{
count++;
dummy++;
}
else
{
flag = 1;
}
temp.erase(temp.begin()+maxIndex , temp.begin()+maxIndex+max);
mymax = max;
n = temp.size();
}
return count;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T10:52:18.313",
"Id": "461096",
"Score": "1",
"body": "Welcome to Code Review! Can you provide a full program, with some test cases?"
}
] |
[
{
"body": "<p>I have no C/C++ compiler at the moment, but the algorithm only needs one loop, the while+flag being a tiny bit too unreadable.</p>\n\n<p>There are two counters:</p>\n\n<ol>\n<li><p>Finding the maximum length: <code>maxLength</code></p>\n\n<p>Sequences with next value >= <code>prior</code> value.</p></li>\n<li><p>Counting the maximum length: <code>maxCount</code>.</p>\n\n<ul>\n<li>length > maxLength reset maxCount to 1</li>\n<li>length == maxLength increment maxCount</li>\n</ul></li>\n</ol>\n\n<p>So (in java):</p>\n\n<pre><code>static int longestIncSeq(int[] arr) {\n int maxCount = 0;\n int maxLength = 0;\n boolean start = true;\n int prior = Integer.MAX_VALUE;\n int length = 0;\n for (int n : arr) {\n if (start || n < prior) {\n if (length > maxLength) {\n maxLength = length;\n maxCount = 1;\n } else if (length == maxLength) {\n ++maxCount;\n }\n length = 0;\n start = false;\n }\n ++length;\n prior = n;\n }\n if (length > maxLength) {\n maxLength = length;\n maxCount = 1;\n } else if (length == maxLength) {\n ++maxCount;\n }\n return maxCount;\n}\n</code></pre>\n\n<p>Complexity <strong>O(N)</strong>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T10:59:18.377",
"Id": "235547",
"ParentId": "235543",
"Score": "4"
}
},
{
"body": "<h1>The code</h1>\n\n<p>Before switching to a better algorithm, let's polish the code first. Almost every line of your code can be improved.</p>\n\n<ol>\n<li><p>Get rid of <code>#define ll long long int</code>. This is a standard way to lower the quality of your code. If you mean <code>long long</code>, use <code>long long</code>.</p></li>\n<li><p>Qualify names from the <code>std</code> namespace with <code>std::</code>.</p></li>\n<li><p>Make the parameter <code>temp</code> a const reference (<code>const std::vector<long long>& temp</code>). Copying a vector is expensive.</p></li>\n<li><p>Remove the unnecessary parameter <code>n</code>, which can be calculated with <code>temp.size()</code> if I correctly understand the code.</p></li>\n<li><p>Avoid declaring a bunch of variables at the start of a scope, which makes it hard to follow the logic of the code.</p></li>\n<li><p>Be consistent with your spacing:</p>\n\n<ul>\n<li><p>insert a space after a control keyword, and remove whitespace immediately enclosed by parentheses: <code>if (max < len)</code>, not <code>if( max == 1 )</code>;</p></li>\n<li><p>insert a space around <code>=</code>: <code>mymax = -1</code>, not <code>count=0</code>;</p></li>\n<li><p>insert a space around binary operators: <code>flag == 0</code>, <code>i < n</code>, <code>temp.begin() + maxIndex + max</code>, not <code>flag==0</code>, <code>i<n</code>, or <code>temp.begin()+maxIndex+max</code>.</p></li>\n</ul></li>\n<li><p>Remove all trailing whitespaces (whitespace characters at the end of each line).</p></li>\n<li><p>Always use prefix <code>++</code> instead of postfix <code>++</code> in a discarded-value expression.</p></li>\n<li><p>You are using <code>long long</code> for two different purposes: the value type, and the index type. Use <code>std::size_t</code> or <code>std::vector<long long>::size_type</code> for the second, and templatize the first (or at least make a type alias to it). In fact, restricting yourself to <code>std::vector</code> is not necessary — any container will do.</p></li>\n</ol>\n\n<h1>The algorithm</h1>\n\n<p>The better algorithm with <span class=\"math-container\">\\$\\operatorname{O}(n)\\$</span> time complexity is described in <a href=\"https://codereview.stackexchange.com/a/235547/188857\">Joop Eggen's answer</a> — scan the sequence and find the maximum length and count the subsequences simultaneously. Standard algorithms can be of great help here to simplify the code and avoid manual loops. For example, <a href=\"https://en.cppreference.com/w/cpp/algorithm/is_sorted_until\" rel=\"nofollow noreferrer\"><code>std::is_sorted_until</code></a> can be used to find contiguous increasing subsequences.</p>\n\n<p>Here's how I'd put the whole thing together:</p>\n\n<pre><code>template <class RandomIt, class Compare = std::less<>>\nauto count_longest_sorted_subsequences(RandomIt first, RandomIt last, Compare comp = {})\n{\n using Diff = typename std::iterator_traits<RandomIt>::difference_type;\n Diff size{};\n Diff count{};\n for (auto it = first; it != last;) {\n first = std::exchange(it, std::is_sorted_until(first, last, comp));\n if (it - first == size) {\n ++count;\n } else if (it - first > size) {\n size = it - first;\n count = 1;\n }\n }\n return count;\n}\n</code></pre>\n\n<p>Usage example:</p>\n\n<pre><code>std::array arr{2, 7, 1, 8, 2, 8, 1, 8, 2, 8};\nassert(count_longest_sorted_subsequences(arr.begin(), arr.end()) == 5);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T08:38:42.160",
"Id": "461241",
"Score": "0",
"body": "OK, you're using algorithms. But you are \"doing it twice\" compared to Joops code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T10:59:50.840",
"Id": "461249",
"Score": "1",
"body": "@OliverSchonrock My mistake. I've updated the answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T11:21:49.570",
"Id": "235550",
"ParentId": "235543",
"Score": "4"
}
},
{
"body": "<p>For the algorithm, it can be shortened by only checking if a sub-sequence qualifies when it is finished.</p>\n\n<pre><code>using ll = long long;\n\nint LongestSubSeq(const std::vector<ll>& arr)\n{\n int numSeq = 0;\n int longest = 0;\n int length = 0;\n size_t size = arr.size();\n for(size_t i = 1; i < size; ++i)\n {\n ++length;\n if(arr[i] <= arr[i-1])\n {\n if(length > longest)\n {\n longest = length;\n numSeq = 1;\n } \n else if(length == longest)\n {\n ++numSeq;\n }\n length = 0;\n }\n\n\n }\n return numSeq;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T12:03:21.907",
"Id": "461099",
"Score": "2",
"body": "Please ... don't use that nasty `ll` ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T12:09:18.943",
"Id": "461100",
"Score": "0",
"body": "It's very common and easy to understand."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T12:14:18.320",
"Id": "461101",
"Score": "0",
"body": "Can you backup your claim? To me, `ll` is just like `tmpl <cls T> cls Arr;`, which I don't think will pass the majority of code review :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T12:34:49.697",
"Id": "461104",
"Score": "0",
"body": "I should have been more specific in my comment I guess. Since this code is obviously for some sort of challenge/competition, I find that this type of shortcut is very common in those sorts of situations. With common use comes understanding."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T02:08:52.270",
"Id": "461211",
"Score": "0",
"body": "I would argue that in the context of this question, `using namespace std`, user-specific defines and bits includes are perfectly fine. However the question does not sepcify. I also like the \"using\" over \"typedef\" or \"#define\" as it expresses the intent of the name more clearly IMO"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T09:32:02.297",
"Id": "461245",
"Score": "2",
"body": "@mackycheese21 It definitely isn't fine to teach terrible programming practice like `#define ll` or `#include <bits/stdc++.h>` on *Code Review*, a place for *readable* and *production quality* code. Remember that Code Review, like every other Stack Exchange site, is designed to benefit the whole community, rather than just OP."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T16:15:55.983",
"Id": "461283",
"Score": "0",
"body": "Very true! In a competition context this is good, natural, encouraged, and productive, but anywhere else (including this site) it is horrible."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T12:01:29.850",
"Id": "235552",
"ParentId": "235543",
"Score": "1"
}
},
{
"body": "<ul>\n<li><p>Don't use <code>#define ll long long int</code> and don't use <code>long long int</code> either. Use <code>auto</code> for values and <code>size_t</code> for indices and cardinalities.</p></li>\n<li><p>Your method should take iterators as parameters. It will still work with vectors, but also with linked lists and other containers.</p></li>\n<li><p>Have a well defined behaviour for corner cases, such as empty lists. This behaviour should be documented in a comment.</p></li>\n<li><p>Don't use indices and index calculations if not neccessary. There are container types that don't support indexing.</p></li>\n<li><p>Dont't erase or otherwise modify the container or its contents if not neccessary or expected by the caller.</p></li>\n<li><p>This particular problem can be solved by iterating over the list just once (see code below).</p></li>\n</ul>\n\n<p>I would have written it like this:</p>\n\n<pre><code>template <class ForwardIterator>\nsize_t count_longest_sorted_subsequences (ForwardIterator first, ForwardIterator last)\n{\n // The empty list contains no subsequences. If you want a different behavior,\n // such as one subsequence of zero length, modify these two lines.\n size_t maxlength = 0;\n size_t maxcount = 0;\n auto next = first;\n while (next != last)\n {\n // Move the 'next'-iterator until a decreasing element is discovered.\n // Count the number of moves (also works for non-random access iterators).\n size_t length = 1;\n auto prev = next++;\n while (next != last && *prev <= *next)\n {\n length++;\n prev = next++;\n }\n // Adjust 'maxlength' and 'maxcount'\n if (length == maxlength)\n {\n maxcount++;\n }\n else if (length > maxlength)\n {\n maxlength = length;\n maxcount = 1;\n }\n }\n return maxcount;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T15:48:38.800",
"Id": "235564",
"ParentId": "235543",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T09:37:23.317",
"Id": "235543",
"Score": "4",
"Tags": [
"c++",
"algorithm",
"programming-challenge"
],
"Title": "Finding the number of longest contiguous increasing subsequences in a given array"
}
|
235543
|
<p>This is a basic React problem, how to handle global listener and change state in callback without attaching a listener on each rerender.</p>
<p>Here is a common solution:</p>
<pre><code> useEffect(() => {
const handleScroll = () => {
var rect = selectedRingElement.current.getBoundingClientRect();
if(isElementInViewport(rect)) {
console.log(`${isInViewPort} ${initialViewPortTop}`)
if(!isInViewPort&&!initialViewPortTop) {
setInitialViewPortTop(rect.top)
}
setIsInViewport(true)
} else {
setIsInViewport(false)
}
}
window.addEventListener('scroll', handleScroll)
return () => {
window.removeEventListener("scroll", handleScroll)
}
}, [initialViewPortTop, isInViewPort])
</code></pre>
<p>So it works and shouldn't create memory leaks, however I find it not nice to have to remove et add event listener all the time. Do you know a cleaner solution to this problem, or is it the best we can do?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T10:23:21.030",
"Id": "235544",
"Score": "1",
"Tags": [
"javascript",
"react.js"
],
"Title": "React useEffect with handleScroll"
}
|
235544
|
<p>Task: given a number (positive or negative), square every digit of it and concatenate them, forming a resulting number.</p>
<p>For example:</p>
<p>9119 should become 811181 = 9^2*10^0 + 1*10^1 + 1*10^2 + 9^2*10^3
(-1) should become (-1)</p>
<p>My code:</p>
<pre><code>-- convert a number to the list of digits
-- doesn't work with negative numbers
digs :: Integral x => x -> [x]
digs 0 = [0]
digs x = let
helper :: Integral x => x -> [x]
helper 0 = []
helper n = helper (n `div` 10) ++ [n `mod` 10]
in
helper x
squareDigit :: Int -> Int
squareDigit n = let sign = signum n
digits = (digs (abs n))
digs_sq = map (^ 2) digits
-- we can't concat squares as they may have more then 1 digit
digs_sq_flat = map digs digs_sq >>= id
in
sign * foldl (\acc x -> x + (acc * 10)) 0 digs_sq_flat
</code></pre>
<p>Basically, it works:</p>
<pre><code>*SquareDigit> squareDigit 9119
811181
*SquareDigit> squareDigit (-9119)
-811181
</code></pre>
<p>But maybe, my solution can be made more elegant.</p>
|
[] |
[
{
"body": "<p>Separate out combinators that apply some perspective to your data.</p>\n\n<pre><code>squareDigit = overAbs $ overDigits $ concatMap $ digs . (^ 2) where\n overAbs f n = signum n * f (abs n)\n overDigits f = foldl (\\acc x -> x + (acc * 10)) 0 . f . digs\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T14:08:56.777",
"Id": "235559",
"ParentId": "235546",
"Score": "3"
}
},
{
"body": "<p>You could replace</p>\n\n<pre><code>digs_sq_flat = map digs digs_sq >>= id\n</code></pre>\n\n<p>with </p>\n\n<pre><code>digs_sq_flat = concatMap digs digs_sq\n</code></pre>\n\n<p><code>(>>= id)</code> is the definition of <code>join</code> from Control.Monad, which, when specialized to <code>[a]</code> is the same thing as <code>concat</code>. So you basically have a <code>map</code> followed by <code>concat</code> which is exactly <code>concatMap</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T15:27:47.557",
"Id": "235562",
"ParentId": "235546",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235559",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T10:58:00.897",
"Id": "235546",
"Score": "2",
"Tags": [
"haskell"
],
"Title": "Concatenate the square of all the digits of a number"
}
|
235546
|
<p>I am working on a game engine and in order to learn the math behind graphics programming I decided to write my own mathmathical structs and operations.</p>
<p>I went for an union class that gives me the oppertunity to use an array and x, y, z, w accessors without using extra memory. Being the first time I'm using unions I am curious if I am using them the correct way. Also because both Quaternion and Vector4 have a lot of similarities I am trying to find out how I could share some more code between the two unions.</p>
<p><strong>Quaternion.h</strong></p>
<pre><code>#ifndef CHEETAH_CORE_MATH_QUATERNION_H_
#define CHEETAH_CORE_MATH_QUATERNION_H_
#include "Vector4.h"
#include "Vector3.h"
#include "Mat4x4.h"
#include<math.h>
#include "Core/Core.h"
namespace cheetah
{
template<typename T>
union Quaternion
{
public:
Quaternion();
Quaternion(const T& axisX, const T& axisY, const T& axisZ, const T& degrees);
Quaternion(const Vector3<T>& axis, const T& degrees);
Quaternion(const T fill[4]);
struct
{
T axisX, axisY, axisZ, degrees;
};
inline const T* get() const;
inline Mat4x4<T> getMatrix() const;
inline void normalize();
inline Quaternion<T> normalize(const Quaternion<T>& vector) const;
inline void operator *= (const T& rhs);
inline void operator += (const T& rhs);
inline void operator -= (const T& rhs);
inline void operator /= (const T& rhs);
inline Quaternion<T> operator + (const Vector4<T>& rhs) const;
inline Quaternion<T> operator - (const Vector4<T>& rhs) const;
inline T operator * (const Vector4<T>& rhs) const;
private:
struct
{
T m_data[4];
};
};
template union CH_API Quaternion<float>;
template union CH_API Quaternion<int>;
template union CH_API Quaternion<double>;
using Quaternionf = Quaternion<float>;
using Quaternioni = Quaternion<int>;
using Quaterniond = Quaternion<double>;
}
#include "Quaternion.inl"
#endif // !CHEETAH_CORE_MATH_QUATERNION_H_
</code></pre>
<p><strong>Quaternion.inl</strong></p>
<pre><code>namespace cheetah
{
// ctors
template<typename T>
inline Quaternion<T>::Quaternion()
: m_data{ 0, 0, 0, 0 }
{
}
template<typename T>
inline Quaternion<T>::Quaternion(const T& axisX, const T& axisY, const T& axisZ, const T& degrees)
: m_data{ axisX, axisY, axisZ, degrees }
{
}
template<typename T>
inline Quaternion<T>::Quaternion(const Vector3<T>& axis, const T& degrees)
: m_data{ axis.x, axis.y, axis.z, degrees }
{
}
template<typename T>
inline Quaternion<T>::Quaternion(const T fill[4])
: m_data{ fill[0], fill[1], fill[2], fill[3] }
{
}
// getters
template<typename T>
inline const T* Quaternion<T>::get() const
{
return &m_data[0];
}
template<>
inline Mat4x4<int> Quaternion<int>::getMatrix() const
{
Quaternion<int> quat = normalize(Quaternion<int>(axisX, axisY, axisZ, degrees));
std::vector<int> mat = std::vector<int>
{
1 - 2 * quat.m_data[1] * quat.m_data[1] - 2 * quat.m_data[2] * quat.m_data[2], 2 * quat.m_data[0] * quat.m_data[1] - 2 * quat.m_data[2] * quat.m_data[3], 2 * quat.m_data[0] * quat.m_data[2] + 2 * quat.m_data[1] * quat.m_data[3], 0,
2 * quat.m_data[0] * quat.m_data[1] + 2 * quat.m_data[2] * quat.m_data[3], 1 - 2 * quat.m_data[0] * quat.m_data[0] - 2 * quat.m_data[2] * quat.m_data[2], 2 * quat.m_data[1] * quat.m_data[2] - 2 * quat.m_data[0] * quat.m_data[3], 0,
2 * quat.m_data[0] * quat.m_data[2] - 2 * quat.m_data[1] * quat.m_data[3], 2 * quat.m_data[1] * quat.m_data[2] + 2 * quat.m_data[0] * quat.m_data[3], 1 - 2 * quat.m_data[0] * quat.m_data[0] - 2 * quat.m_data[1] * quat.m_data[1], 0,
0, 0, 0, 1
};
return Mat4x4i(mat);
}
template<>
inline Mat4x4<double> Quaternion<double>::getMatrix() const
{
Quaternion<double> quat = normalize(Quaternion<double>(axisX, axisY, axisZ, degrees));
std::vector<double> mat = std::vector<double>
{
1 - 2 * quat.m_data[1] * quat.m_data[1] - 2 * quat.m_data[2] * quat.m_data[2], 2 * quat.m_data[0] * quat.m_data[1] - 2 * quat.m_data[2] * quat.m_data[3], 2 * quat.m_data[0] * quat.m_data[2] + 2 * quat.m_data[1] * quat.m_data[3], 0,
2 * quat.m_data[0] * quat.m_data[1] + 2 * quat.m_data[2] * quat.m_data[3], 1 - 2 * quat.m_data[0] * quat.m_data[0] - 2 * quat.m_data[2] * quat.m_data[2], 2 * quat.m_data[1] * quat.m_data[2] - 2 * quat.m_data[0] * quat.m_data[3], 0,
2 * quat.m_data[0] * quat.m_data[2] - 2 * quat.m_data[1] * quat.m_data[3], 2 * quat.m_data[1] * quat.m_data[2] + 2 * quat.m_data[0] * quat.m_data[3], 1 - 2 * quat.m_data[0] * quat.m_data[0] - 2 * quat.m_data[1] * quat.m_data[1], 0,
0, 0, 0, 1
};
return Mat4x4d(mat);
}
template<>
inline Mat4x4<float> Quaternion<float>::getMatrix() const
{
Quaternion<float> quat = normalize(Quaternion<float>(axisX, axisY, axisZ, degrees));
std::vector<float> mat = std::vector<float>
{
1.0f - 2 * quat.m_data[1] * quat.m_data[1] - 2.0f * quat.m_data[2] * quat.m_data[2], 2.0f * quat.m_data[0] * quat.m_data[1] - 2.0f * quat.m_data[2] * quat.m_data[3], 2.0f * quat.m_data[0] * quat.m_data[2] + 2.0f * quat.m_data[1] * quat.m_data[3], 0.0f,
2.0f * quat.m_data[0] * quat.m_data[1] + 2.0f * quat.m_data[2] * quat.m_data[3], 1.0f - 2.0f * quat.m_data[0] * quat.m_data[0] - 2.0f * quat.m_data[2] * quat.m_data[2], 2.0f * quat.m_data[1] * quat.m_data[2] - 2.0f * quat.m_data[0] * quat.m_data[3], 0.0f,
2.0f * quat.m_data[0] * quat.m_data[2] - 2.0f * quat.m_data[1] * quat.m_data[3], 2.0f * quat.m_data[1] * quat.m_data[2] + 2.0f * quat.m_data[0] * quat.m_data[3], 1.0f - 2.0f * quat.m_data[0] * quat.m_data[0] - 2.0f * quat.m_data[1] * quat.m_data[1], 0.0f,
0.0f, 0.0f, 0.0f, 1.0f
};
return Mat4x4f(mat);
}
template<typename T>
inline Mat4x4<T> Quaternion<T>::getMatrix() const
{
}
// math
template<>
inline void Quaternion<int>::normalize()
{
const int n = 1 / sqrt(axisX * axisX + axisY * axisY + axisZ * axisZ + degrees * degrees);
m_data[0] *= n;
m_data[1] *= n;
m_data[2] *= n;
m_data[3] *= n;
}
template<>
inline void Quaternion<double>::normalize()
{
const double n = 1 / sqrt(axisX * axisX + axisY * axisY + axisZ * axisZ + degrees * degrees);
m_data[0] *= n;
m_data[1] *= n;
m_data[2] *= n;
m_data[3] *= n;
}
template<>
inline void Quaternion<float>::normalize()
{
const float n = 1.0f / sqrt(axisX * axisX + axisY * axisY + axisZ * axisZ + degrees * degrees);
m_data[0] *= n;
m_data[1] *= n;
m_data[2] *= n;
m_data[3] *= n;
}
template<typename T>
inline void Quaternion<T>::normalize()
{
}
template<>
inline Quaternion<int> Quaternion<int>::normalize(const Quaternion<int>& quat) const
{
const int n = 1 / sqrt(quat.axisX * quat.axisX + quat.axisY * quat.axisY + quat.axisZ * quat.axisZ + quat.degrees * quat.degrees);
Quaternion<int> q(quat.axisX, quat.axisY, quat.axisZ, quat.degrees);
q.m_data[0] *= n;
q.m_data[1] *= n;
q.m_data[2] *= n;
q.m_data[3] *= n;
return quat;
}
template<>
inline Quaternion<double> Quaternion<double>::normalize(const Quaternion<double>& quat) const
{
const double n = 1 / sqrt(quat.axisX * quat.axisX + quat.axisY * quat.axisY + quat.axisZ * quat.axisZ + quat.degrees * quat.degrees);
Quaternion<double> q(quat.axisX, quat.axisY, quat.axisZ, quat.degrees);
q.m_data[0] *= n;
q.m_data[1] *= n;
q.m_data[2] *= n;
q.m_data[3] *= n;
return quat;
}
template<>
inline Quaternion<float> Quaternion<float>::normalize(const Quaternion<float>& quat) const
{
const float n = 1.0f / sqrt(quat.axisX * quat.axisX + quat.axisY * quat.axisY + quat.axisZ * quat.axisZ + quat.degrees * quat.degrees);
Quaternion<float> q(quat.axisX, quat.axisY, quat.axisZ, quat.degrees);
q.m_data[0] *= n;
q.m_data[1] *= n;
q.m_data[2] *= n;
q.m_data[3] *= n;
return quat;
}
template<typename T>
inline Quaternion<T> Quaternion<T>::normalize(const Quaternion<T>& quat) const
{
}
template<typename T>
inline void Quaternion<T>::operator *= (const T& rhs)
{
m_data[0] *= rhs;
m_data[1] *= rhs;
m_data[2] *= rhs;
m_data[3] *= rhs;
}
template<typename T>
inline void Quaternion<T>::operator += (const T& rhs)
{
m_data[0] += rhs;
m_data[1] += rhs;
m_data[2] += rhs;
m_data[3] += rhs;
}
template<typename T>
inline void Quaternion<T>::operator -= (const T& rhs)
{
m_data[0] -= rhs;
m_data[1] -= rhs;
m_data[2] -= rhs;
m_data[3] -= rhs;
}
template<typename T>
inline void Quaternion<T>::operator /= (const T& rhs)
{
m_data[0] /= rhs;
m_data[1] /= rhs;
m_data[2] /= rhs;
m_data[3] /= rhs;
}
template<typename T>
inline Quaternion<T> Quaternion<T>::operator + (const Vector4<T>& rhs) const
{
return Quaternion<T>(m_data[0] + rhs.x, m_data[1] + rhs.y, m_data[2] + rhs.z, m_data[3] + rhs.w);
}
template<typename T>
inline Quaternion<T> Quaternion<T>::operator - (const Vector4<T>& rhs) const
{
return Quaternion<T>(m_data[0] + (-rhs.x), m_data[1] + (-rhs.y), m_data[2] + (-rhs.z), m_data[3] + (-rhs.w));
}
template<typename T>
inline T Quaternion<T>::operator * (const Vector4<T>& rhs) const
{
return (m_data[0] * rhs.x) + (m_data[1] * rhs.y) + (m_data[2] * rhs.z) + (m_data[3] * rhs.w);
}
}
</code></pre>
<p><strong>Vector4.h</strong></p>
<pre><code>#ifndef CHEETAH_ENGINE_MATH_VECTOR4_H_
#define CHEETAH_ENGINE_MATH_VECTOR4_H_
#include "Core/Core.h"
#include "Vector3.h"
namespace cheetah
{
template<typename T>
union Vector4
{
inline Vector4();
inline Vector4(const T& fill);
inline Vector4(const T fill[4]);
inline Vector4(const Vector3<T>& fill, const T& w);
inline Vector4(const T& x, const T& y, const T& z, const T& w);
struct
{
T x, y, z, w;
};
inline const T* get() const;
inline T magnitude() const;
inline void operator *= (const T& rhs);
inline void operator += (const T& rhs);
inline void operator -= (const T& rhs);
inline void operator /= (const T& rhs);
inline Vector4<T> operator + (const Vector4<T>& rhs) const;
inline Vector4<T> operator - (const Vector4<T>& rhs) const;
inline T operator * (const Vector4<T>& rhs) const;
private:
struct
{
T m_data[4];
};
};
template union CH_API Vector4<float>;
template union CH_API Vector4<int>;
template union CH_API Vector4<double>;
using Vector4f = Vector4<float>;
using Vector4i = Vector4<int>;
using Vector4d = Vector4<double>;
}
#include "Vector4.inl"
#endif // !CHEETAH_ENGINE_MATH_VECTOR_H_
</code></pre>
<p><strong>Vector4.inl</strong></p>
<pre><code>namespace cheetah
{
// ctors
template<typename T>
inline Vector4<T>::Vector4()
: m_data{ 0, 0, 0, 0 }
{
}
template<typename T>
inline Vector4<T>::Vector4(const T& fill)
: m_data{ fill, fill, fill, fill }
{
}
template<typename T>
inline Vector4<T>::Vector4(const T fill[4])
: m_data{ fill[0], fill[1], fill[2], fill[3] }
{
}
template<typename T>
inline Vector4<T>::Vector4(const Vector3<T>& fill, const T& w)
: m_data{ fill.x, fill.y, fill.z, w }
{
}
template<typename T>
inline Vector4<T>::Vector4(const T& x, const T& y, const T& z, const T& w)
: m_data{ x, y, z, w }
{
}
// getters
template<typename T>
inline const T* Vector4<T>::get() const
{
return &m_data[0];
}
//math
template<typename T>
inline T Vector4<T>::magnitude() const
{
return sqrt(pow(x, 2) + pow(y, 2) + pow(z, 2) + pow(w, 2));
}
// operators
template<typename T>
inline void Vector4<T>::operator *= (const T& rhs)
{
m_data[0] *= rhs;
m_data[1] *= rhs;
m_data[2] *= rhs;
m_data[3] *= rhs;
}
template<typename T>
inline void Vector4<T>::operator /= (const T& rhs)
{
m_data[0] /= rhs;
m_data[1] /= rhs;
m_data[2] /= rhs;
m_data[3] /= rhs;
}
template<typename T>
inline void Vector4<T>::operator += (const T& rhs)
{
m_data[0] += rhs;
m_data[1] += rhs;
m_data[2] += rhs;
m_data[3] += rhs;
}
template<typename T>
inline void Vector4<T>::operator -= (const T& rhs)
{
m_data[0] -= rhs;
m_data[1] -= rhs;
m_data[2] -= rhs;
m_data[3] -= rhs;
}
template<typename T>
inline Vector4<T> Vector4<T>::operator + (const Vector4<T>& rhs) const
{
return Vector4<T>(m_data[0] + rhs.x, m_data[1] + rhs.y, m_data[2] + rhs.z, m_data[3] + rhs.w);
}
template<typename T>
inline Vector4<T> Vector4<T>::operator - (const Vector4<T>& rhs) const
{
return Vector4<T>(m_data[0] + (-rhs.x), m_data[1] + (-rhs.y), m_data[2] + (-rhs.z), m_data[3] + (-rhs.w));
}
template<typename T>
inline T Vector4<T>::operator * (const Vector4<T>& rhs) const
{
return (m_data[0] * rhs.m_data[0]) + (m_data[1] * rhs.m_data[1]) + (m_data[2] * rhs.m_data[2]) + (m_data[3] * rhs.m_data[3]);
}
}
</code></pre>
<p>The core file included defines the CH_API macro that expands to either dllexport or dllimport like below:</p>
<p><strong>Core.h</strong></p>
<pre><code>#ifdef CH_PLATFORM_WINDOWS
#ifdef CH_BUILD_DLL
#define CH_API __declspec(dllexport)
#else
#define CH_API __declspec(dllimport)
#endif // CH_BUILD_DLL
#else
#error Cheetah currently only supports windows!
#endif // CH_PLATFORM_WINDOWS
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T14:23:33.593",
"Id": "461118",
"Score": "0",
"body": "You missed `Core/Core.h`, which seems to be needed by the other headers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T14:31:10.417",
"Id": "461120",
"Score": "0",
"body": "@TobySpeight it declares CH_API macro that expands to either dllimport or dllexport. If you want I can add the file but it contains also useless other defines"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T18:24:15.223",
"Id": "461140",
"Score": "1",
"body": "I think my main criticism would be that there's got to be code out there to implement this already, why re-invent the wheel. Also `sqrt` is likely to be too slow for a real game."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T18:32:07.290",
"Id": "461141",
"Score": "0",
"body": "@markspace as stated above, for learning purposes. I could use libraries like glm but then I would have a much more difficult time actually understanding what is happening. Thanks for the suggestion about sqrt, I will look in to it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T18:41:21.977",
"Id": "461146",
"Score": "0",
"body": "Eberly's *3D Game Engine Architecture* is a good book (though not a great book) with some good low-level optimizations for 3D engines. For example: https://www.lomont.org/papers/2003/InvSqrt.pdf"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T18:54:16.983",
"Id": "461149",
"Score": "0",
"body": "@markspace wow thanks for the source, I currently use the book _Game Engine Architecture_ by Jason Gregory, helps a lot but doesn't get very deep in to the mathematics"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T21:30:05.007",
"Id": "461186",
"Score": "1",
"body": "I'm dubious about the definition `inline void Quaternion<T>::operator += (const T& rhs)`. It doesn't make sense to add a quaternion (or vector) to a scalar."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T07:30:19.493",
"Id": "461236",
"Score": "0",
"body": "@DavidKnipe I added most of the functionality a vector4 has also the the quaternion, I will remove this one because it doesnt make really sense. good finding!"
}
] |
[
{
"body": "<p>The utility of writing your own vector/quaternion code for the purposes of writing a game seems very minimal, considering its been done many times before. Glm/eigen are notable examples, but there's plenty of others. They also support portable vector instruction implementations that have gone through rigorous testing, an extremely time consuming and arguably boring task. This isn't to say there's no value in writing your own math library, but is the product you're trying to make/learn about a math library or a game engine? If you were hired by someone to write a game engine, would they really appreciate you working on a math library?</p>\n\n<p>If you're truly interested in exploring the development of a math library, I would look at the source of existing ones and try to understand the rationale behind them. For example, they might often declare a byte alignment of their types -- why would that be important? What does their code look like when compiled to assembly compared to yours? </p>\n\n<hr>\n\n<p>Do not label the w component of quaternions as <code>degrees</code>, it is very incorrect and will surely cause confusion.</p>\n\n<hr>\n\n<p>An integer quaternion is bizarre and I don't know how that would be used.</p>\n\n<hr>\n\n<p>The template specializations seem unnecessary and confusing.</p>\n\n<hr>\n\n<p>There's no 3D vector rotation implementation on the quaternions. There's also no quaternion-quaternion multiplication, so they cannot be composed easily.</p>\n\n<hr>\n\n<p>It seems like it would be fine to expose the array data since the xyzw data is exposed already.</p>\n\n<hr>\n\n<p>Constructing a <code>std::vector</code> to initialize a matrix does not seem ideal.</p>\n\n<hr>\n\n<p><code>sqrt(pow(x, 2) + pow(y, 2) + pow(z, 2) + pow(w, 2))</code> This optimizes correctly on gcc but will be unnecessarily slow in unoptimized builds.</p>\n\n<hr>\n\n<p>Nitpicky, but using a union like this feels wrong. I understand that it's working as intended, but it doesn't seem typical. If you forgot that the data structure is a union, it might be possible to forget that data and xyzw have the same storage, rather than putting them in a union within a class or struct. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T21:34:33.527",
"Id": "461187",
"Score": "0",
"body": "Thanks, I also write it because I have fun doing it, this is mainly a hobby project, I do agree with you on the renaming of the degrees to w and exposing the array so I change those, I will also remove the integer quaternion specialization. The fact that the utilities seem minimal is because currently I have added only the utilities I need, I will for sure extend the classes with extra funtionality when I need the functionality."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T21:40:05.340",
"Id": "461188",
"Score": "0",
"body": "I understand the sentiment but beware that it can incur unnecessary technical debt by writing it yourself. You may want to briefly put on a producer hat and estimate the total time you are likely to use this code, the amount of time spent on potential bugs (design/functional/performance), and the potential time saved with writing automated tests. Testing a math library is a good learning experience because there's few dependencies and a gentle introduction to using test frameworks. I say this because I think you would be confronted with things like how to properly test an integer quaternion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T21:46:57.867",
"Id": "461190",
"Score": "1",
"body": "Thanks for your additional findings, I will take a look at a library, still might go with building my own because I had fun trying stuf out, it is a good idea to try to write tests, havent done that before in c++ so might try to find a nice test framework. If you know any that work well for you let me know!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T21:27:25.147",
"Id": "235578",
"ParentId": "235556",
"Score": "5"
}
},
{
"body": "<p>In addition to butt's comments:</p>\n\n<h1>Avoid repetition</h1>\n\n<p>There are lots of places in the code where you are unnecessarily repeating yourself, in particular when it comes to types. For example, take this line:</p>\n\n<pre><code>Quaternion<int> quat = normalize(Quaternion<int>(axisX, axisY, axisZ, degrees));\n</code></pre>\n\n<p>You are writing <code>Quaternion<int></code> on both sides of the declaration. You can easily get rid of one by using <code>auto</code>. But why are you explicitly constructing a copy of the quaternion in the first place? You can just use <code>*this</code>, and then the whole line reduces to:</p>\n\n<pre><code>auto quat = normalize(*this);\n</code></pre>\n\n<p>In this line:</p>\n\n<pre><code>std::vector<int> mat = std::vector<int> {...};\n</code></pre>\n\n<p>You also repeat the type twice. Either use <code>auto</code> on the left, or just write:</p>\n\n<pre><code>std::vector<int> mat {...};\n</code></pre>\n\n<p>In fact, if you want to <code>return</code> a quaternion, and the compiler already knows the return type of a member function, then you don't need to explicitly specify this a second time. For example, <code>operator+()</code> can be written as:</p>\n\n<pre><code>template<typename T>\ninline Quaternion<T> Quaternion<T>::operator+(const Vector4<T>& rhs) const\n{\n return {m_data[0] + rhs.x, m_data[1] + rhs.y, m_data[2] + rhs.z, m_data[3] + rhs.w};\n}\n</code></pre>\n\n<p>Also, butt already mentioned the template specializations, this is another case of unnecessary repetition.</p>\n\n<p>Another thing is that you don't have to write <code>Quaternion<T></code> inside the definition of <code>class Quaternion</code>, you can omit the <code><T></code>. A lot of repetition can be avoided if you would define all member functions inside <code>class Quaternion</code> instead of putting them in <code>\"Quaternion.inl\"</code>, but if you think it is better to have those separated then you'll have to live with it.</p>\n\n<h1>Make functions that don't use member variables <code>static</code></h1>\n\n<p>A function that does not access member variables should be made <code>static</code>, so it can be used without needing an instance of the class. For example:</p>\n\n<pre><code>inline Quaternion<T> normalize(const Quaternion<T>& vector) const;\n</code></pre>\n\n<p>This should be written as:</p>\n\n<pre><code>static inline Quaternion normalize(const Quaternion& vector);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T07:17:30.160",
"Id": "461233",
"Score": "0",
"body": "Thanks for your findings, good catch of the normalize method, that one needs to be static for sure, will change it. I think I will keep my implementations inside the .inl file, this for providing a clear interface for users using the engine. I agree on the avoid repetition, at first I went for showing all the types because I thought it would be more clear but that is obviously not really the case and it indeed does add a lot of repetition."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T22:08:59.133",
"Id": "235580",
"ParentId": "235556",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "235578",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T13:31:36.557",
"Id": "235556",
"Score": "5",
"Tags": [
"c++"
],
"Title": "Quaternion and Vector4 union classes for use in game engine"
}
|
235556
|
<p>My solution to the Coderbyte task 'Vowel Square'. It's a simple task, but I'm sure there's a more Pythonic solution than mine.</p>
<p>The problem:</p>
<p><strong>Vowel Square</strong>
Have the function <code>VowelSquare(strArr)</code> take the <code>strArr</code> parameter being passed
which will be a 2D matrix of some arbitrary size filled with letters from
the alphabet, and determine if a 2x2 square composed entirely of vowels
exists in the matrix. For example: <code>strArr</code> is <code>["abcd", "eikr", "oufj"]</code> then
this matrix looks like the following:</p>
<pre><code>a b c d
e i k r
o u f j
</code></pre>
<p>Within this matrix there is a 2x2 square of vowels starting in the second
row and first column, namely, ei, ou. If a 2x2 square of vowels is found
your program should return the top-left position (row-column) of the square,
so for this example your program should return 1-0. If no 2x2 square of
vowels exists, then return the string not found. If there are multiple
squares of vowels, return the one that is at the most top-left position
in the whole matrix. The input matrix will at least be of size 2x2.</p>
<p>Examples:</p>
<ul>
<li>Input: <code>["aqrst", "ukaei", "ffooo"]</code></li>
<li>Output: 1-2,</li>
<li>Input: <code>["gg", "ff"]</code></li>
<li>Output: not found</li>
</ul>
<p>My solution:</p>
<pre><code>VOWELS = "aeiouAEIOU"
def find_vowel_square(strs: list):
"""Return the top left grid ref of any 2x2 sq composed of vowels only
If more than one 2x2 sq exists. Return that which is at the most top-left
position.
"""
height, width = len(strs), len(strs[0])
# Ensure all strings within strs are of equal length
assert all(len(s) == width for s in strs)
for string_i in range(height-1):
for i in range(width-1):
if strs[string_i][i] in VOWELS and strs[string_i][i+1] in VOWELS:
if strs[string_i+1][i] in VOWELS and strs[string_i+1][i+1] in VOWELS:
return f"{i}-{string_i}"
return "Not found"
assert find_vowel_square(strs=["aqree", "ukaei", "ffooo"]) == "3-0"
assert find_vowel_square(strs=["aqrst", "ukaei", "ffooo"]) == "2-1"
assert find_vowel_square(strs=["gg", "ff"]) == "Not found"
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T16:51:23.480",
"Id": "461136",
"Score": "0",
"body": "What does \"most top-left\" mean? Minimum value of x+y, or something else?"
}
] |
[
{
"body": "<p>These are all relatively minor notes:</p>\n\n<ol>\n<li><p>You can use <code>typing.List</code> to provide a better type definition for the parameter (<code>List[str]</code>), precisely defining what it's a list of.</p></li>\n<li><p>I always try to avoid giving variables names that are just a variation on the Python type to tell me what its type is (that's the type annotation's job); the problem description calls this the \"matrix\" so I'll use that.</p></li>\n<li><p>If the problem description doesn't say what to do with invalid input, I'd assume it's fine (and preferable) to just let the code raise an exception if any assumptions are violated.</p></li>\n<li><p>If you're checking that a bunch of iterable conditions are all true, I think it generally looks nicer to use the <code>all</code> function than to do a bunch of <code>and</code>s.</p></li>\n<li><p>For iterating over indices (i.e. where it's super obvious from context what the variable represents and a longer name only serves to distract) I always prefer using short, generic variable names like <code>i, j</code> or <code>x, y</code>.</p></li>\n</ol>\n\n<pre><code>from typing import List\n\nVOWELS = \"aeiouAEIOU\"\n\ndef find_vowel_square(matrix: List[str]):\n \"\"\"Return the top left grid ref of any 2x2 sq composed of vowels only\n\n If more than one 2x2 sq exists. Return that which is at the most top-left\n position.\n \"\"\"\n for y in range(len(matrix) - 1):\n for x in range(len(matrix[y]) - 1):\n if all (matrix[i][j] in VOWELS \n for i, j in [(y, x), (y+1, x), (y, x+1), (y+1, x+1)]):\n return f\"{x}-{y}\"\n\n return \"Not found\"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T16:09:49.333",
"Id": "235565",
"ParentId": "235561",
"Score": "8"
}
},
{
"body": "<p>We can use <code>doctest</code> instead of the asserts:</p>\n\n<pre><code>import doctest\n\ndef find_vowel_square(strs: list):\n \"\"\"Return the top left grid ref of any 2x2 sq composed of vowels only.\n\n >>> find_vowel_square(strs=[\"aqree\", \"ukaei\", \"ffooo\"])\n '3-0'\n >>> find_vowel_square([\"aqrst\", \"ukaei\", \"ffooo\"])\n '2-1'\n >>> find_vowel_square(strs=[\"gg\", \"ff\"])\n 'Not found'\n \"\"\"\n # (snip implementation)\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n</code></pre>\n\n<hr>\n\n<p>I'd write a function with a more conventional interface: return positions as a list of two integers, and <code>None</code> when not found. It's easy to provide a simple adapter from that to the strings that the problem statement requires.</p>\n\n<p>Consider how you would extend this to find a <em>N</em>×<em>N</em> block of vowels in the grid. Hint: for efficiency, we can start by reading only every <em>N</em>th line and only when we find a suitable run of vowels, look up and down in the matrix.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T17:03:55.560",
"Id": "235568",
"ParentId": "235561",
"Score": "6"
}
},
{
"body": "<p>Toby & Sam both make excellent points; I won't repeat them. I would like the add the following:</p>\n\n<h1>Use sets with in</h1>\n\n<p>You are repeatedly testing whether a letter is <code>in</code> the string <code>VOWELS</code>. This requires a linear search through the string, checking each substring to see if it matches.</p>\n\n<p>If instead, you declared <code>VOWELS</code> as a <code>set</code>:</p>\n\n<pre><code>VOWELS = set(\"aeiouAEIOU\")\n</code></pre>\n\n<p>then the <code>in</code> operation should become a much faster <span class=\"math-container\">\\$O(1)\\$</span> lookup.</p>\n\n<h1>Repeated tests</h1>\n\n<p>You may be checking <code>strs[x][y] in VOWELS</code> up to 4 times. Once for <code>strs[string_i][i]</code>, once for <code>strs[string_i][i+1]</code>, once for <code>strs[string_i+1][i]</code>, and once for <code>strs[string_i+1][i+1]</code>.</p>\n\n<p>You could perform the check exactly once per character:</p>\n\n<pre><code>vowel = [[ch in VOWELS for ch in line] for line in strs]\n</code></pre>\n\n<p>With <code>[\"abcd\", \"eikr\", \"oufj\"]</code>, this would yield the matrix:</p>\n\n<pre><code>[[True, False, False, False],\n [True, True, False, False],\n [True, True, False, False]]\n</code></pre>\n\n<p>Then testing <code>vowel[x][y]</code>, <code>vowel[x+1][y]</code>, <code>vowel[x][y+1]</code>, <code>vowel[x+1][y+1]</code> would be simple lookup operations, instead of more complicated <code>in</code> containment tests.</p>\n\n<h1>An alternate approach</h1>\n\n<p>Using this matrix of vowel flags, you could compute whether pairs of vowels exist in a row, by AND-ing each adjacent pair of boolean values together:</p>\n\n<pre><code>vowel_pairs = [[a and b for a, b in zip(row[:-1], row[1:])] for row in vowels]\n</code></pre>\n\n<p>resulting in</p>\n\n<pre><code>[[False, False, False],\n [True, False, False],\n [True, False, False]]\n</code></pre>\n\n<p>Then, you could AND each pair of adjacent rows:</p>\n\n<pre><code>vowel_square = [[a and b for a, b in zip(row_a, row_b)] \n for row_a, row_b in zip(vowel_pairs[:-1], vowel_pairs[1:])]\n</code></pre>\n\n<p>resulting in</p>\n\n<pre><code>[[False, False, False],\n [True, False, False]]\n</code></pre>\n\n<p>The <code>True</code> in the row 1, column 0 means a 2x2 vowel square occurs there. Assuming \"most top-left\" means first in top-to-bottom, then left-to-right ordering, we can extract the locations of all vowel squares using a generator expression:</p>\n\n<pre><code>locations = (f\"{x}-{y}\"\n for x, row in enumerate(vowel_square) for y, flag in enumerate(row)\n if flag)\n</code></pre>\n\n<p>and extract only the first if it exists:</p>\n\n<pre><code>return next(locations, \"Not found\")\n</code></pre>\n\n<p><strong>Note</strong>: this matrix row/column AND'ing does a complete analysis of the matrix, finding any and all 2x2 vowel matrices. It does not stop when the first one is found, so may be slower if the required 2x2 matrix is found early on. In the case of no 2x2 vowel matrix existing, it may perform the fastest, since every possibility would need to be checked. However, it would not scale well to larger submatrices. Toby's recommendation of searching every <em>N</em>th line would be better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T10:30:19.910",
"Id": "461246",
"Score": "0",
"body": "Note that the vowels string is pretty short. It might be worth testing the speed of string vs set."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T17:58:20.757",
"Id": "461289",
"Score": "3",
"body": "@JollyJoker I did test this: str was ~35% slower on my setup."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T22:55:36.120",
"Id": "235582",
"ParentId": "235561",
"Score": "6"
}
},
{
"body": "<p>Taking into account the three answers(at the time of posting) posted, I've come up with the below answer(hope I didn't miss anything).</p>\n\n<p>I have attempted to use every search every nth line as per Toby's suggestion but ran into issues with it finding a solution that was not the top, leftmost. I will hopefully get a chance to pursue it further and do some speed tests.</p>\n\n<pre><code>import doctest\n\nfrom typing import List\n\n\nVOWELS = set(\"aeiouAEIOU\")\n\n\ndef _make_coderbyte_compliant(result: None or List[int]) -> str:\n \"\"\"Make Coderbyte compliant, the result of find_vowel_square func call\n\n Helper function.\n\n >>> _make_coderbyte_compliant(result=None)\n 'Not found'\n >>> _make_coderbyte_compliant(result=[1, 2])\n '1-2'\n \"\"\"\n if result == None:\n return \"Not found\"\n return f\"{result[0]}-{result[1]}\"\n\n\ndef find_vowel_square(matrix: List[str], n: int) -> list:\n \"\"\"Return the top left grid ref of any N x N sq composed of vowels only\n\n If more than one N x N sq exists, return that which is at the most top-left\n position.\n\n :param matrix: the matrix as a list of strings, all equal length\n :param n: int. The width and height of the vowel square for which to search\n\n :returns: None or list of top, left index coordinated of the found vowel square\n\n >>> find_vowel_square(matrix=[\"aqree\", \"ukaei\", \"ffooo\"], n=2)\n [3, 0]\n >>> find_vowel_square(matrix=[\"aqrst\", \"ukaei\", \"ffooo\"], n=2)\n [2, 1]\n >>> find_vowel_square(matrix=[\"aqiii\", \"ukaei\", \"ffooo\"], n=3)\n [2, 0]\n >>> find_vowel_square(matrix=[\"aqtyt\", \"rtrtt\", \"aaaaa\", \"ukaei\", \"ffooo\"], n=3)\n [2, 2]\n >>> find_vowel_square(matrix=[\"aqtyt\", \"aaaaa\", \"aaaaa\", \"uuuuu\", \"oooo\"], n=4)\n [0, 1]\n >>> find_vowel_square(matrix=[\"gg\", \"ff\"], n=2)\n \"\"\"\n height, width = len(matrix), len(matrix[0])\n\n # True if vowel else False\n bool_matrix = [[l in VOWELS for l in line] for line in matrix]\n\n for y in range(height-(n-1)):\n for x in range(width-(n-1)):\n if all(cell for row in bool_matrix[y:y+n]\n for row in bool_matrix[x:x+n]):\n return [x, y]\n\n return None\n\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n\n assert _make_coderbyte_compliant(\n result=find_vowel_square(matrix=[\"aqree\", \"ukaei\", \"ffooo\"], n=2)) == \"3-0\"\n assert _make_coderbyte_compliant(\n result=find_vowel_square(matrix=[\"gg\", \"ff\"], n=2)) == \"Not found\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T19:12:10.367",
"Id": "461300",
"Score": "1",
"body": "Now you don’t need the first `if all(...)`; it is completely covered by the second."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T19:23:01.397",
"Id": "461301",
"Score": "1",
"body": "Avoid the slow Python addition and indexing. Use `all(cell for row in bool_matrix[y:y+n] for cell in row[x:x+n])`. My testing shows a 2.7x speed up for n = 99, when all cells are True."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T14:10:16.390",
"Id": "461420",
"Score": "1",
"body": "`find_vowel_square` returns a `List[int]`, not a `str`. Your type hint is wrong."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T18:03:54.447",
"Id": "235619",
"ParentId": "235561",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "235565",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T14:50:24.660",
"Id": "235561",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"programming-challenge"
],
"Title": "Find a 2x2 vowel square in a grid (Coderbyte 'Vowel Square' problem)"
}
|
235561
|
<p>I'm trying to create the most efficient (not nicest/prettiest) way of moving particular values within an np.array() to the back of said array. </p>
<p>I currently have two different solutions:</p>
<pre><code>import numpy as np
from numba import jit
@jit(nopython = True)
def move_to_back_a(a, value):
new_a = []
total_values = 0
for v in a:
if v == value:
total_values += 1
else:
new_a.append(v)
return new_a + [value] * total_values
@jit(nopython = True)
def move_to_back_b(a, value):
total_values = np.count_nonzero(a == value)
ind = a == value
a = a[~ind]
return np.append(a, [value] * total_values)
</code></pre>
<p>Which give the following output:</p>
<pre><code>In [7]: move_to_back_a(np.array([2,3,24,24,24,1]), 24)
Out[7]: [2, 3, 1, 24, 24, 24]
In [8]: move_to_back_b(np.array([2,3,24,24,24,1]), 24)
Out[8]: array([ 2, 3, 1, 24, 24, 24], dtype=int64)
</code></pre>
<p>It doesn't really matter whether I get back my output as a list or as an array, though I expect that returning an array will be more helpful in my future code.</p>
<p>The current timing on these tests is as follows:</p>
<pre><code>In [9]: %timeit move_to_back_a(np.array([2,3,24,24,24,1]), 24)
2.28 µs ± 20.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [10]: %timeit move_to_back_b(np.array([2,3,24,24,24,1]), 24)
3.1 µs ± 50.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code></pre>
<p>Is there any way to make this code even faster?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T16:26:05.047",
"Id": "461126",
"Score": "1",
"body": "Which Python/NumPy/numba version are you using? When I run it using 3.69/1.13.3/0.45.1 I get a numba error about `np.count_nonzero` being used in a wrong way"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T16:28:05.247",
"Id": "461127",
"Score": "0",
"body": "@Graipher I'm using 3.7/1.16.4/0.46.0 for Python, NumPy and Numba, respectively."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T16:41:56.110",
"Id": "461133",
"Score": "1",
"body": "Is this the typical size of your arrays or can they get larger?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T16:45:09.117",
"Id": "461134",
"Score": "0",
"body": "@MennoVanDijk: OK, I just updated to Numba 0.47.0, which fixed the problem."
}
] |
[
{
"body": "<p>Your second function is faster for me when simplifying it like this:</p>\n\n<pre><code>@jit(nopython=True)\ndef move_to_back_c(a, value):\n mask = a == value\n return np.append(a[~mask], a[mask])\n</code></pre>\n\n<p>In addition, Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, recommends <em>not</em> surrounding a <code>=</code> with spaces if it is used for keyword arguments, like your <code>nopython=True</code>.</p>\n\n<p>Since <code>numba</code> apparently <a href=\"http://numba.pydata.org/numba-doc/0.18.1/developer/generators.html\" rel=\"nofollow noreferrer\">recently gained generator support</a>, this might also be worth checking out:</p>\n\n<pre><code>@jit(nopython=True)\ndef _move_to_back_d(a, value):\n count = 0\n for x in a:\n if x != value:\n yield x\n else:\n count += 1\n for _ in range(count):\n yield value\n\n@jit(nopython=True)\ndef move_to_back_d(a, value):\n return list(_move_to_back_d(a, value))\n</code></pre>\n\n<p>The timings I get on my machine for the given testcase are:</p>\n\n<pre><code>move_to_back_a 1.63 µs ± 14.5 ns\nmove_to_back_b 2.33 µs ± 21 ns\nmove_to_back_c 1.92 µs ± 17.5 ns\nmove_to_back_d 1.66 µs ± 9.69 ns\n</code></pre>\n\n<p>What is in the end as least as important is the scaling behavior, though. Here are some timings using larger arrays:</p>\n\n<pre><code>np.random.seed(42)\nx = [(np.random.randint(0, 100, n), 42) for n in np.logspace(1, 7, dtype=int)]\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/3Ng6c.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3Ng6c.png\" alt=\"enter image description here\"></a></p>\n\n<p>While slightly slower for small arrays, for larger the mask approach is consistently faster.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T16:37:11.517",
"Id": "461130",
"Score": "0",
"body": "Thanks for the solution as well as the recommendation on style. I do get ~ `6.5 µs` on this solution, which is quite a bit slower than `move_to_back_a()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T16:37:51.387",
"Id": "461131",
"Score": "0",
"body": "@MennoVanDijk: Did you compare it either with both `@jit` or both without, so it is fair?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T16:39:37.440",
"Id": "461132",
"Score": "1",
"body": "Just did, unfortunately, this still consistently runs about `0.3 µs` above `move_to_back_a()`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T16:49:39.530",
"Id": "461135",
"Score": "1",
"body": "@MennoVanDijk: Added timings and another function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-17T13:41:46.487",
"Id": "461636",
"Score": "0",
"body": "Was waiting with accepting this answer in hopes of receiving other answers. I have just accepted it since there does not seem to be more coming my way. Thanks a bunch for helping me with this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-17T13:49:19.650",
"Id": "461637",
"Score": "0",
"body": "@MennoVanDijk: Yes, some more alternatives and maybe reviews of the other stuff would ahve been nice. Glad to have helped some, though!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T16:32:50.010",
"Id": "235567",
"ParentId": "235566",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "235567",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T16:12:04.933",
"Id": "235566",
"Score": "4",
"Tags": [
"python",
"numpy",
"numba"
],
"Title": "Move values to back of an np.array()"
}
|
235566
|
<p>I have a voxelization that I need to write out to a binary STL file. These voxels are inside a higher-level 3D grid, with each cell in the grid being made up of voxels. Individual cells may or may not have any active voxels in them.</p>
<p>I've optimized the file size significantly by not writing out triangles for interior faces - faces between active voxels. </p>
<p>However, the method I used is very ugly, and I think could be improved. I'm not sure if there's an applicable design pattern or just a better way of thinking about it. </p>
<ul>
<li>It's ugly</li>
<li>It's repetitive</li>
</ul>
<p>Regardless, I want to learn something from this code and see how I can do better in the future.</p>
<p>Note spacing might be a bit odd, using clang-format and an 80-character limit.</p>
<p>writeVoxelSTL():</p>
<pre><code>void writeVoxelAsSTL(
std::ofstream& fileStream,
unsigned& numTris,
const unsigned xCell,
const unsigned yCell,
const unsigned zCell,
const unsigned xVoxel,
const unsigned yVoxel,
const unsigned zVoxel) const
{
// Now need to check if each of its sides need to be written out
bool left = isNeighborActive(
xCell, yCell, zCell, static_cast<int>(xVoxel) - 1, yVoxel, zVoxel);
bool right =
isNeighborActive(xCell, yCell, zCell, xVoxel + 1, yVoxel, zVoxel);
bool bottom = isNeighborActive(
xCell, yCell, zCell, xVoxel, static_cast<int>(yVoxel) - 1, zVoxel);
bool top = isNeighborActive(xCell, yCell, zCell, xVoxel, yVoxel + 1, zVoxel);
bool front = isNeighborActive(
xCell, yCell, zCell, xVoxel, yVoxel, static_cast<int>(zVoxel) - 1);
bool back = isNeighborActive(xCell, yCell, zCell, xVoxel, yVoxel, zVoxel + 1);
Point minPoint = highLevelGridMinpoint;
// Center of the voxel
Point center;
center.x = minPoint.x + (((xCell * cellDim.x) + xVoxel) * voxelWidth);
center.y = minPoint.y + (((yCell * cellDim.y) + yVoxel) * voxelWidth);
center.z = minPoint.z + (((zCell * cellDim.z) + zVoxel) * voxelWidth);
// From this center, we can get the 8 corners of the voxel and thus the 12
// triangles
// They are defined like this:
// 7-------6
// /| /|
// 4-+-----5 |
// | | | | y
// | 3-----+-2 | z
// |/ |/ |/
// 0-------1 +--x
Point p0(center.x - halfVoxel, center.y - halfVoxel, center.z - halfVoxel);
Point p1(center.x + halfVoxel, center.y - halfVoxel, center.z - halfVoxel);
Point p2(center.x + halfVoxel, center.y - halfVoxel, center.z + halfVoxel);
Point p3(center.x - halfVoxel, center.y - halfVoxel, center.z + halfVoxel);
Point p4(center.x - halfVoxel, center.y + halfVoxel, center.z - halfVoxel);
Point p5(center.x + halfVoxel, center.y + halfVoxel, center.z - halfVoxel);
Point p6(center.x + halfVoxel, center.y + halfVoxel, center.z + halfVoxel);
Point p7(center.x - halfVoxel, center.y + halfVoxel, center.z + halfVoxel);
// Now for the 12 triangles made of these points
// Left side
if (!left)
{
writeTriangleSTL(fileStream, p0, p3, p4);
writeTriangleSTL(fileStream, p3, p4, p7);
numTris += 2;
}
// Right Side
if (!right)
{
writeTriangleSTL(fileStream, p1, p2, p5);
writeTriangleSTL(fileStream, p2, p5, p6);
numTris += 2;
}
// Bottom Side
if (!bottom)
{
writeTriangleSTL(fileStream, p0, p1, p2);
writeTriangleSTL(fileStream, p0, p2, p3);
numTris += 2;
}
// Top Side
if (!top)
{
writeTriangleSTL(fileStream, p4, p5, p6);
writeTriangleSTL(fileStream, p4, p6, p7);
numTris += 2;
}
// Front side
if (!front)
{
writeTriangleSTL(fileStream, p0, p1, p4);
writeTriangleSTL(fileStream, p1, p4, p5);
numTris += 2;
}
// Back side
if (!back)
{
writeTriangleSTL(fileStream, p3, p2, p7);
writeTriangleSTL(fileStream, p2, p7, p6);
numTris += 2;
}
}
</code></pre>
<p>isNeighborActive():</p>
<p>Note: cellDim is the number of voxels in each direction for a cell.
gridDim is the number of cells in each direction. </p>
<pre><code>bool isNeighborActive(
long xCell, long yCell, long zCell, long xVoxel, long yVoxel, long zVoxel)
const
{
// Get the "real" coordinates
if (xVoxel < 0)
{
xCell--;
xVoxel = cellDim.x - 1;
if (xCell < 0)
{
return false;
}
}
else if (xVoxel > (cellDim.x - 1))
{
xCell++;
xVoxel = 0;
if (xCell > (gridDim.x - 1))
{
return false;
}
}
if (yVoxel < 0)
{
yCell--;
yVoxel = cellDim.y - 1;
if (yCell < 0)
{
return false;
}
}
else if (yVoxel > (cellDim.y - 1))
{
yCell++;
yVoxel = 0;
if (yCell > (gridDim.y - 1))
{
return false;
}
}
if (zVoxel < 0)
{
zCell--;
zVoxel = cellDim.z - 1;
if (zCell < 0)
{
return false;
}
}
else if (zVoxel > (cellDim.z - 1))
{
zCell++;
zVoxel = 0;
if (zCell > (gridDim.z - 1))
{
return false;
}
}
const cellVoxelization& cell = modelVoxelization.at(xCell, yCell, zCell);
if (cell.getSize() == 0)
{
return false;
}
bool active = cell.at(xVoxel, yVoxel, zVoxel).active;
return active;
}
</code></pre>
<p>I considered using some kind of enum for the directions, but then that just shifts the ugliness down to the next method which has have a switch, sadly. </p>
|
[] |
[
{
"body": "<p><code>writeVoxelAsSTL</code> takes <code>unsigned</code> arguments, but it seems like the native type is actually a long. Could it take longs instead? For example, <code>unsigned(2^31)</code> looks like it would not be a valid value since it would overflow into -1 upon conversion.</p>\n\n<hr>\n\n<p>You could take an <code>ostream&</code> argument instead so the code isn't coupled to files. </p>\n\n<hr>\n\n<p>You could factor out the bools and directions into arrays, and rewrite much of the code into loops.</p>\n\n<hr>\n\n<p>Further improvement would depend on how this is being used. How is the grid represented? Can you combine neighboring voxel faces? For example, would a 100x1x1 stack require 804 triangles, or 12? Perhaps you could split this into multiple phases, one that extracts relevant planes, and one that writes planes to a stream. Maybe even one that first extracts a sparse list of relevant voxels depending on how you're visiting them.</p>\n\n<p>If this needs to be performant, surface extraction from voxels is a very parallelizable algorithm. Consider just a 2x2x2 box: 38 out of 64 points computed are going to be shared. The center point will be computed 8 times but never used. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T19:08:05.737",
"Id": "461153",
"Score": "0",
"body": "The cells and voxel positions are ```unsigned``` for sure. I had to adjust isNeighbor to use some kind of signed argument so I would have a way of (for example) getting the previous neighbor of a voxel in the 0th position, which in this case would now be the -1th position in that axis."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T19:08:16.790",
"Id": "461154",
"Score": "0",
"body": "2: I actually do want fstream here, this will only be used for writing out to a file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T19:11:27.650",
"Id": "461156",
"Score": "0",
"body": "4: Combining voxel faces would be ideal, but seems exceptionally challenging. We would only want to combine flush faces, and the only way to tell if the faces are flush would be to step outwards to the 26 voxels in each direction to determine their activation as well. IE, if my front face is active, AND my neighbors front face is active, but the neighbors FRONT neighbor isn't active, then we can make them flush. But what about the voxel to the right of my right neighbor, can I combine that as well? there may be an algorithm for this but I do not know it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T19:40:08.273",
"Id": "461161",
"Score": "0",
"body": "One idea could be to collect only surface voxels. For example only voxels for which their +XYZ neighbor's occupancy state is different from their state, a total of 3 tests per voxel. It could be stored as a relative position and a bitflag indicating adjacency. Then each entry outputs [1-3] planes instead of [0-6], and you never need to check for duplicate planes. \n\nRegarding looping, I was imagining something like this: https://godbolt.org/z/PzkJDP"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T19:00:02.667",
"Id": "235573",
"ParentId": "235572",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T18:37:01.067",
"Id": "235572",
"Score": "1",
"Tags": [
"c++",
"c++11"
],
"Title": "Check if neighbors are active in spatially subdivided voxelization"
}
|
235572
|
<p>I am working my way through a Django book and part of that covers the test cases. In the current chapter I have the following code form the start of the test cases but some of it feels like it breaking the DRY principle.</p>
<pre class="lang-py prettyprint-override"><code>from django.test import TestCase, SimpleTestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
# Create your tests here.
class HomePageTests(SimpleTestCase):
def test_home_page_status_code(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
def test_view_url_by_name(self):
response = self.client.get(reverse('home'))
self.assertEqual(response.status_code, 200)
def test_view_uses_correct_template(self):
response = self.client.get(reverse('home'))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'home.html')
</code></pre>
<p>I understand the difference between the first and second test case. One is testing the path explicitly the second is testing against the name look up that some of my views might use. However In the third test it feels to me a bit redundant to again test the status code of the response object from the reverse look up when we just tested that functionality in the previous test case.</p>
<p>Is there a particular benefit to testing the status code again on the reverse look up in the third test case. </p>
<p>Also given that the second and third test case are calling for the exact same get response couldn't this be taken out the methods and stored in the class its self so its only run once, or at least set the reverse_path look up once. Again is there any specific reason or benefit of calling it each time in the individual test cases. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T21:14:21.123",
"Id": "461180",
"Score": "0",
"body": "There's definitely something fishy going on here, but is this your code or the code from the book?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T21:15:54.097",
"Id": "461181",
"Score": "0",
"body": "This is the code from the book."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T21:17:52.833",
"Id": "461182",
"Score": "0",
"body": "Since Code Review is a community where programmers improve their skills through peer review, we require that the code be posted by an author or maintainer of the code and that the poster know why the code is written the way it is. Why was it written like this? Probably because it's an educational book that wants to focus more on getting things done than on DRY."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T21:18:10.043",
"Id": "461183",
"Score": "0",
"body": "Please take a look at our [help/on-topic]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T21:19:29.047",
"Id": "461184",
"Score": "0",
"body": "Okie doke thanks."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T20:54:19.660",
"Id": "235577",
"Score": "2",
"Tags": [
"python",
"django"
],
"Title": "Django View tests"
}
|
235577
|
<p><strong>[I'm awaiting suggestions for improvement/optimization/more speed/general feedback ...]</strong></p>
<p>This code takes a label and a folder path of subfolders as input that have certain labels ex: trees, cats with each folder containing a list of HD photos corresponding to the folder name, then a multithreaded image processor converts data to .h5 format and classifies photos with the given label (75% accuracy with default parameters but might get better or worse). It's a very simple algorithm using logistic regression model(implementation) not <code>sklearn</code>'s <code>LogisticRegression()</code> and some visualizations using matplotlib(read the docs).</p>
<p>The following link has the code as well as the necessary .h5 files to make it work and demonstrate an example on classifying dog photos but feel free to test with your own image data.</p>
<ul>
<li><a href="https://drive.google.com/open?id=1b5uWn4-a7T_B3d_A67AhjS8x2PIv6SCb" rel="nofollow noreferrer">https://drive.google.com/open?id=1b5uWn4-a7T_B3d_A67AhjS8x2PIv6SCb</a></li>
</ul>
<p>Running the example in the code with the random seed set to 127 should give these results:</p>
<ol>
<li><strong>Labeled predicted images(sample):</strong>
The following figure represents n samples of the correct predicted results and displays 1 for dog and 0 for non-dog images. </li>
</ol>
<p><a href="https://i.stack.imgur.com/iBvgD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iBvgD.png" alt="Results"></a></p>
<ol start="2">
<li><strong>Learning curve with the given parameters:</strong>
This is the cost function/degree of error with respect to gradient descent iteration number (max_iter=3000)</li>
</ol>
<p><a href="https://i.stack.imgur.com/t51aT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/t51aT.png" alt="Learning curve"></a>
<strong>Code:</strong></p>
<pre><code>from concurrent.futures import ThreadPoolExecutor, as_completed
import matplotlib.pyplot as plt
from time import perf_counter
import pandas as pd
import numpy as np
import cv2
import os
def read_and_resize(img, new_size):
"""
Read and resize image.
Args:
img: Image path.
new_size: New image size.
Return:
Resized Image.
"""
img = cv2.imread(img)
return cv2.resize(img, new_size)
def folder_to_hdf(folder_path, label, new_size, threads=5):
"""
Save a folder images to hdf format.
Args:
folder_path: Path to folder containing images.
label: Data label.
new_size: New image size(tuple).
threads: Number of parallel threads.
Return:
None
"""
data, resized = pd.DataFrame(), []
with ThreadPoolExecutor(max_workers=threads) as executor:
future_resized_images = {
executor.submit(read_and_resize, folder_path + img, new_size): img
for img in os.listdir(folder_path)
if img != '.DS_Store'
}
for future in as_completed(future_resized_images):
result = future.result()
resized.append(result)
print(f'Processing ({label})-{future_resized_images[future]} ... done.')
del future_resized_images[future]
data['Images'] = resized
data['Label'] = label
data.to_hdf(folder_path + label + '.h5', label)
def folders_to_hdf(folder_path, new_size, threads=5):
"""
Save folders containing images to hdf format.
Args:
folder_path: Path to folder containing folders containing images.
new_size: New image size(tuple).
threads: Number of parallel threads.
Return:
None
"""
for folder_name in os.listdir(folder_path):
if folder_name != '.DS_Store':
path = ''.join([folder_path, folder_name, '/'])
folder_to_hdf(path, folder_name, new_size, threads)
def clear_hdf(folder_path):
"""
Delete .h5 files in every sub-folder in folder_path.
Args:
folder_path: A folder containing folders of images and their .h5.
Return:
None
"""
for folder_name in os.listdir(folder_path):
if folder_name != '.DS_Store':
file_name = ''.join([folder_path, folder_name, '/', folder_name, '.h5'])
os.remove(file_name)
print(f'Removed {file_name.split("/")[-1]}')
def load_hdf(folder_path, label, random_seed=None):
"""
Load all classification data.
Args:
folder_path: Folder containing folders with respective images.
label: Label to set to 1.
random_seed: int, representing the random seed.
Return:
X and Y as numpy arrays and frames.
"""
if random_seed:
np.random.seed(random_seed)
file_names = [
''.join([folder_path, folder_name, '/', folder_name, '.h5'])
for folder_name in os.listdir(folder_path)
if folder_name != '.DS_Store'
]
frames = [pd.read_hdf(file_name) for file_name in file_names]
frames = pd.concat(frames)
frames['Classification'] = 0
frames.loc[frames['Label'] == label, 'Classification'] = 1
new_index = np.random.permutation(frames.index)
frames.index = new_index
frames.sort_index(inplace=True)
image_data, labels = (
np.array(list(frames['Images'])),
np.array(list(frames['Classification'])),
)
return image_data, labels, frames
def pre_process(
data, test_size, label, max_pixel=255, display_images=None, show_details=False
):
"""
Split the data into train and test sets and prepare the data for further processing.
Args:
data: X and Y as numpy arrays and frames.
test_size: Percentage of test set.
label: label to classify.
max_pixel: The maximum value of a pixel channel.
display_images: A tuple (n_images, rows, columns)
show_details: If True, details about the sizes will be displayed.
Return:
x_train, y_train, x_test, y_test, frames.
"""
image_data, labels, frames = data
total_images = len(image_data)
if display_images:
fig = plt.figure()
plt.title(
f'Initial(before prediction) {display_images[1]} x {display_images[2]} '
f'data sample (Classification of {label})'
)
rows, columns = display_images[1], display_images[2]
for i in range(display_images[0]):
img = image_data[i]
fig.add_subplot(rows, columns, i + 1)
plt.imshow(img)
plt.show()
image_data = image_data.reshape(total_images, -1) / max_pixel
labels = labels.reshape(total_images, -1)
separation_index = int(test_size * total_images)
x_train = image_data[separation_index:].T
y_train = labels[separation_index:].T
x_test = image_data[:separation_index].T
y_test = labels[:separation_index].T
if show_details:
print(f'Total number of images: {total_images}')
print(f'x_train shape: {x_train.shape}')
print(f'y_train shape: {y_train.shape}')
print(f'x_test shape: {x_test.shape}')
print(f'y_test shape: {y_test.shape}')
return x_train, y_train, x_test, y_test, frames
def sigmoid(x):
"""
Calculate sigmoid function.
Args:
x: Image data in the following shape(pixels * pixels * 3, number of images).
Return:
sigmoid(x).
"""
return 1 / (1 + np.exp(-x))
def compute_cost(w, b, x, y):
"""
Compute cost function using forward and back propagation.
Args:
w: numpy array of weights(also called Theta).
b: Bias(int)
x: Image data in the following shape(pixels * pixels * 3, number of images)
y: Label numpy array of labels(0s and 1s)
Return:
Cost and gradient(dw and db).
"""
total_images = x.shape[1]
activation = sigmoid(np.dot(w.T, x) + b)
cost = (-1 / total_images) * (
np.sum(y * np.log(activation) + (1 - y) * np.log(1 - activation))
)
cost = np.squeeze(cost)
dw = (1 / total_images) * np.dot(x, (activation - y).T)
db = (1 / total_images) * np.sum(activation - y)
return cost, dw, db
def g_descent(w, b, x, y, max_iter, learning_rate, iteration_number=None):
"""
Optimize weights and bias using gradient descent algorithm.
Args:
w: numpy array of weights(also called Theta).
b: Bias(int)
x: Image data in the following shape(pixels * pixels * 3, number of images)
y: Label numpy array of labels(0s and 1s)
max_iter: Maximum number of iterations
learning_rate: The rate of learning.
iteration_number: Display iteration and current cost every n.
Return:
w, b, dw, db, costs
"""
dw, db, costs = 0, 0, []
for iteration in range(max_iter):
cost, dw, db = compute_cost(w, b, x, y)
w -= dw * learning_rate
b -= db * learning_rate
costs.append(cost)
if iteration_number and iteration % iteration_number == 0:
print(f'Iteration number: {iteration} out of {max_iter} iterations')
print(f'Current cost: {cost}\n')
return w, b, dw, db, costs
def predict(w, b, x):
"""
Predict labels of x.
Args:
w: numpy array of weights(also called Theta).
b: Bias(int)
x: Image data in the following shape(pixels * pixels * 3, number of images)
Return:
Y^ numpy array of predictions.
"""
w = w.reshape(x.shape[0], 1)
activation = sigmoid(np.dot(w.T, x) + b)
activation[activation > 0.5] = 1
activation[activation <= 0.5] = 0
return activation
def predict_from_folder(
folder_path,
target_label,
test_size=0.2,
max_iter=3000,
learning_rate=0.0001,
random_seed=None,
max_pixel=255,
display_initial_images=None,
show_initial_details=False,
create_hdf=False,
threads=5,
new_image_sizes=(150, 150),
display_results=False,
iteration_number=100,
plot_learning_curve=False,
photo_results=None,
):
"""
Classify a target label from different folders containing HD images in a way that each folder contains
only images that represent the folder name/label.
Args:
folder_path: A folder path that contains other folders named according to what label they contain.
target_label: One of the folder labels in folder_path.
test_size: Test size in percentage ex: 0.7
max_iter: Maximum number of iterations for gradient descent.
learning_rate: Learning rate for gradient descent,
random_seed: int, representing a random seed.
max_pixel: The maximum value of a pixel channel.
display_initial_images: A tuple (n_images, rows, columns)
show_initial_details: If True, details about the initial sizes will be displayed.
create_hdf: If True, old .h5 files found in the labeled folders will be cleared(if any)
and new ones will be created.
threads: int, representing the number of parallel threads for .h5 creation process.
new_image_sizes: New dimensions to store in .h5 files.
display_results: If True, training accuracy will be calculated and displayed.
iteration_number: Display gradient descent iteration number and current cost.
plot_learning_curve: If True, learning curve will be plotted.
photo_results: A tuple (n_photos, rows, columns) to display n labeled results.
Return:
pandas DataFrame with the results.
"""
start_time = perf_counter()
if create_hdf:
clear_hdf(folder_path)
folders_to_hdf(folder_path, new_image_sizes, threads)
data = load_hdf(folder_path, target_label, random_seed)
x_train, y_train, x_test, y_test, frames = pre_process(
data,
test_size,
target_label,
max_pixel,
display_initial_images,
show_initial_details,
)
w, b = np.zeros((len(x_train), 1)), 0
w, b, dw, db, costs = g_descent(
w, b, x_train, y_train, max_iter, learning_rate, iteration_number
)
train_predictions = predict(w, b, x_train)
test_predictions = predict(w, b, x_test)
all_predictions = np.append(train_predictions, test_predictions)
training_accuracy = 100 - np.mean(np.abs(train_predictions - y_train)) * 100
test_accuracy = 100 - np.mean(np.abs(test_predictions - y_test)) * 100
frames['Predictions'] = all_predictions
frames['Accuracy'] = 0
frames.loc[frames['Predictions'] == frames['Classification'], 'Accuracy'] = 1
if display_results:
print(f'Training accuracy: {training_accuracy}%')
print(f'Test accuracy: {test_accuracy}%')
print(f'Train predictions: \n{train_predictions}')
print(f'Train actual: \n{y_train}')
print(f'Test predictions: \n{test_predictions}')
print(f'Test actual: \n{y_test}')
if plot_learning_curve:
plt.title('Learning curve')
plt.plot(range(max_iter), costs)
plt.xlabel('Iterations')
plt.ylabel('Cost')
if photo_results:
to_display = frames[frames['Accuracy'] == 1][['Images', 'Predictions']].head(
photo_results[0]
)
images = np.array(list(to_display['Images']))
predictions = np.array(list(to_display['Predictions']))
fig = plt.figure()
plt.title(f'Classification of {target_label} results sample')
rows, columns = photo_results[1], photo_results[2]
for i in range(photo_results[0]):
img = images[i]
ax = fig.add_subplot(rows, columns, i + 1)
ax.title.set_text(f'Prediction: {predictions[i]}')
plt.imshow(img)
plt.show()
end_time = perf_counter()
print(f'Time: {end_time - start_time} seconds.')
return frames
if __name__ == '__main__':
folder = 'test_photos/'
target = 'Dog'
photo_display_size = (10, 2, 5)
predict_from_folder(
folder,
target,
display_initial_images=photo_display_size,
show_initial_details=True,
display_results=True,
plot_learning_curve=True,
photo_results=photo_display_size,
random_seed=127
)
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-13T22:41:15.117",
"Id": "235581",
"Score": "7",
"Tags": [
"python",
"numpy",
"pandas",
"machine-learning",
"data-visualization"
],
"Title": "Multithreaded HD Image Processing + Logistic reg. Classifier + Visualization"
}
|
235581
|
<p>I made todo app in vanilla JS with functionalities like add todo, delete todo, edit todo, complete todo.. so, I think my code is not really good and I want to hear any suggestions on how to improve code and similar..</p>
<p>Here is the link: <a href="http://dash.vision-themes.com/" rel="nofollow noreferrer">http://dash.vision-themes.com/</a></p>
<h2>HTML:</h2>
<pre><code><section id="todo">
<!---- Todo navigation ---->
<div class="todo-nav">
<div class="nav__logo">
<img src="images/K.png" alt="">
</div>
<div class="nav__form-container">
<h1>Make your first task!</h1>
<a href="#" class="nav__button">New task <span><i class="fas fa-plus"></i></span></a>
<form onsubmit = "event.preventDefault();" class="nav__form">
<i class="fas fa-times"></i>
<input type="text" class="form__title" placeholder="Todo Title">
<textarea name="" class="form__details" cols="35" rows="10" placeholder="Todo detailes"></textarea>
<label for="select" class="priority">Priority:</label>
<select class="styled-select">
<option value="High">High</option>
<option value="Low">Low</option>
</select>
<input type="submit" class="form__button" value="Create todo">
</form>
</div>
</div>
<!----- Todo Content ------>
<div id="scrollbar" class="todo-content">
<div class="content__header">
<h2 class="content__title"> <span><i class="fas fa-tasks fa-title"></i></span>Your active tasks:</h2>
<ul class="content__todo"></ul>
</div>
<div class="content__modal-succes">
<span><i class="fas fa-check"></i></span><p>Todo task will be shown in section bellow.</p>
</div>
<div class="content__modal-warning">
<span><i class="fas fa-exclamation-triangle"></i></span><p>You cannot leave that empty!</p>
</div>
</div>
</section>
</code></pre>
<h2>JavaScript:</h2>
<pre><code>(function() {
const showFormButton = document.querySelector(".nav__button");
var form = document.querySelector(".nav__form");
const createTodoButton = document.querySelector(".form__button");
var todos = document.querySelector(".content__todo");
var modalWarning = document.querySelector(".content__modal-warning");
var modalSucces = document.querySelector(".content__modal-succes");
var closeformIcon = document.querySelector(".fa-times");
// Create todo task
function createTodoTask() {
// Store todo title
var todoTitle = document.querySelector(".form__title");
// Store todo details
var todoDetailes = document.querySelector(".form__details");
// Store todo priority level
var todoPriority = document.querySelector(".styled-select")
.selectedOptions[0].value;
// Create li with class
var todoTask = document.createElement("li");
todoTask.classList.add("todo__task");
// Create h6 with class and append title value
var todoTaskTitle = document.createElement("h6");
todoTaskTitle.classList.add("todo__title");
todoTaskTitle.innerHTML = todoTitle.value;
// Create priority icon
var completedIcon = document.createElement("i");
completedIcon.classList.add(
"fas",
"fa-check-circle",
"fa-pulse",
"fa-completed"
);
// Create delete icon
var deleteIcon = document.createElement("i");
deleteIcon.classList.add("fas", "fa-ban", "fa-delete");
// Create span
var paragraphTitle = document.createElement("span");
paragraphTitle.innerHTML = "Details:";
// Create paragraph and append value
var todoTaskDetails = document.createElement("p");
todoTaskDetails.innerHTML = todoDetailes.value;
// Create priority level and append value
if (todoPriority === "High") {
var priorityLeverHigh = document.createElement("span");
priorityLeverHigh.classList.add("priority-title");
priorityLeverHigh.innerHTML = "Priority:" + " " + todoPriority;
todoTask.appendChild(priorityLeverHigh);
} else if (todoPriority === "Low") {
var priorityLeverLow = document.createElement("span");
priorityLeverLow.classList.add("priority-title");
priorityLeverLow.innerHTML = "Priority:" + " " + todoPriority;
todoTask.appendChild(priorityLeverLow);
}
// Append h6 to li
todoTask.appendChild(todoTaskTitle);
// Append priority icon to li
todoTask.appendChild(completedIcon);
// Append delete icon to li
todoTask.appendChild(deleteIcon);
// Append span to li
todoTask.appendChild(paragraphTitle);
// Append p to li
todoTask.appendChild(todoTaskDetails);
// Append li to ul
todos.appendChild(todoTask);
// Clear title and details fields
todoTitle.value = "";
todoDetailes.value = "";
}
// Edit todo
function editTodo() {
var todoTitle = document.querySelectorAll(".todo__title");
for (let i = 0; i < todoTitle.length; i++) {
todoTitle[i].addEventListener("click", () => {
todoTitle[i].contentEditable = true;
});
}
}
// Delete todo
function deleteTodo() {
var deleteTodoIcon = document.querySelectorAll(".fa-delete");
for (let i = 0; i < deleteTodoIcon.length; i++) {
deleteTodoIcon[i].addEventListener("click", e => {
// Delete parent element from DOM
e.currentTarget.parentNode.remove();
});
}
}
// Complete todo
function checkComplete() {
var todoTaskItem = document.querySelectorAll(".fa-completed");
for (let i = 0; i < todoTaskItem.length; i++) {
todoTaskItem[i].addEventListener("click", e => {
// Change class of parent
e.currentTarget.parentNode.classList.add("completed");
});
}
}
// Display todo task
createTodoButton.addEventListener("click", () => {
var todoTitle = document.querySelector(".form__title");
if (todoTitle.value === "") {
showModalWarning();
} else {
showModalSucces();
hideTodoForm();
createTodoTask();
editTodo();
deleteTodo();
checkComplete();
}
});
// Show todo task form on click
showFormButton.addEventListener("click", () => {
showTodoForm();
});
// Close todo task form on click on x icon
closeformIcon.addEventListener("click", () => {
hideTodoForm();
});
// Show modal warning
function showModalWarning() {
modalWarning.querySelector(".content__modal-warning");
modalWarning.classList.add("show");
// Hide modal after 1 second
setTimeout(() => {
modalWarning.classList.remove("show");
}, 1000);
}
// Show modal succes
function showModalSucces() {
modalSucces.querySelector(".content__modal-succes");
modalSucces.classList.add("show");
// Hide modal after 1 second
setTimeout(() => {
modalSucces.classList.remove("show");
}, 1000);
}
// Show
function showTodoForm() {
form.style.display = "inline-block";
}
// Hide
function hideTodoForm() {
form.style.display = "none";
}
})();
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T01:21:07.290",
"Id": "235585",
"Score": "2",
"Tags": [
"javascript",
"to-do-list"
],
"Title": "Todo app with few functionalities"
}
|
235585
|
<p>My below solution to the following problem is exceeding the maximum recursion depth. I am looking for any improvements which i can make. </p>
<p><strong>Problem</strong></p>
<blockquote>
<p>Alice and Bob need to send secret messages to each other and are
discussing ways to encode their messages:</p>
<p>Alice: “Let’s just use a very simple code: We’ll assign ‘A’ the code
word 1, ‘B’ will be 2, and so on down to ‘Z’ being assigned 26.”</p>
<p>Bob: “That’s a stupid code, Alice. Suppose I send you the word ‘BEAN’
encoded as 25114. You could decode that in many different ways!”
Alice: “Sure you could, but what words would you get? Other than
‘BEAN’, you’d get ‘BEAAD’, ‘YAAD’, ‘YAN’, ‘YKD’ and ‘BEKD’. I think
you would be able to figure out the correct decoding. And why would
you send me the word ‘BEAN’ anyway?” Bob: “OK, maybe that’s a bad
example, but I bet you that if you got a string of length 5000 there
would be tons of different decodings and with that many you would find
at least two different ones that would make sense.” Alice: “How many
different decodings?” Bob: “Jillions!”</p>
<p>For some reason, Alice is still unconvinced by Bob’s argument, so she
requires a program that will determine how many decodings there can be
for a given string using her code.</p>
</blockquote>
<p><strong>Input</strong></p>
<p>Input will consist of multiple input sets. Each set will consist of a single line of at most 5000 digits representing a valid encryption (for example, no line will begin with a 0). There will be no spaces between the digits. An input line of ‘0’ will terminate the input and should not be processed.</p>
<p><strong>Output</strong></p>
<p>For each input set, output the number of possible decodings for the input string. All answers will be within the range of a 64 bit signed integer.</p>
<p><strong>Example</strong></p>
<p>Input:</p>
<pre><code>25114
1111111111
3333333333
0
</code></pre>
<p>Output:</p>
<pre><code>6
89
1
</code></pre>
<p>The following is my solution -</p>
<pre class="lang-py prettyprint-override"><code>def helper_dp(input_val, k, memo):
if k == 0:
return 1
s = len(input_val) - k
if input_val[s] == '0':
return 0
if memo[k] != -1:
return memo[k]
result = helper_dp(input_val, k - 1, memo)
if k >= 2 and int(input_val[s:s+2]) <= 26:
result += helper_dp(input_val, k - 2, memo)
memo[k] = result
return memo[k]
def num_ways_dp(input_num, input_len):
memo = [-1] * (len(input_num) + 1)
return helper_dp(input_num, input_len, memo)
if __name__ == '__main__':
number = input()
while number != '0':
print(num_ways_dp(number, len(number)))
number = input()
</code></pre>
<p>Problem Link - <a href="https://www.spoj.com/problems/ACODE/" rel="nofollow noreferrer">https://www.spoj.com/problems/ACODE/</a> </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T11:20:01.587",
"Id": "461252",
"Score": "3",
"body": "What exactly is the purpose of `MAX_LIMIT = 5001`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T20:31:00.060",
"Id": "461311",
"Score": "3",
"body": "@pacmaninbw If it can be fixed by raising the limit (and on local machines, that's trivial to do by orders of magnitude), that's about as bad as a Time-limit exceeded. And we haven't outlawed those."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T06:07:36.447",
"Id": "461350",
"Score": "0",
"body": "@Linny That's a hold over from my previous code. I will remove that line. Thanks for pointing it out"
}
] |
[
{
"body": "<p>Your code performs one recursion per character and <a href=\"https://stackoverflow.com/q/3323001\">recursion depth is limited</a>. For long inputs, your code will raise <code>RecursionError: maximum recursion depth exceeded</code>. Replacing recursion with an explicit loop solves the issue.</p>\n\n<p>Also, if you start the calculation at <code>k = 1</code> with <code>memo[-1]</code> and <code>memo[0]</code> properly initialized and then work upwards to <code>k = len(s)</code>, the code will become significantly simpler. When calculating <code>memo[k]</code>, you only ever access <code>memo[k-2]</code> and <code>memo[k-1]</code>, so you can store only those. I renamed them <code>old</code> and <code>new</code>. Here is how it could look like:</p>\n\n<pre><code>def num_ways_dp(s):\n old = new = 1\n for i in range(len(s)-1):\n if int(s[i:i+2]) > 26: old = 0 # no two-digit solutions\n if int(s[i+1]) == '0': new = 0 # no one-digit solutions\n (old, new) = (new, old + new)\n return new\n\nif __name__ == '__main__':\n number = input()\n while number != '0':\n print(num_ways_dp(number))\n number = input()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T15:03:00.657",
"Id": "461279",
"Score": "0",
"body": "Your inner loop could be `old, new = new, (old + new) if int(s[i:i+2]) <= 26 else new`. The parenthesis on the right are not needed and on the left you can constrain the ternary to the part where it actually matters."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T19:29:31.147",
"Id": "461302",
"Score": "0",
"body": "Almost, but you forgot to properly handle 0. In particular, the string \"101\" has value 1, not 3."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T20:05:16.580",
"Id": "461306",
"Score": "0",
"body": "The updated code is maps \"101\" to 2. Still not quite right. That both version accept invalid string \"1001\" is not necessarily unreasonable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T20:49:58.203",
"Id": "461318",
"Score": "0",
"body": "Thanks @DavidG. for the feedback. It now returns 1 and 0 for 101 and 1001."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T07:25:51.843",
"Id": "461360",
"Score": "1",
"body": "Do you have a good reason for the two `not` operators? I find the code easier to understand when the first condition is negated and the second condition is simply `s[i+1] == '0'`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T08:17:57.327",
"Id": "461364",
"Score": "1",
"body": "@RainerP. I didn't quite understand the logic for the (old, new) = (new, old + new) line"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T09:07:57.840",
"Id": "461369",
"Score": "1",
"body": "@strawhatsai - The `(old, new) = (new, old + new)` is equivalent to `(memo[k-2], memo[k-1]) = (memo[k-1], memo[k])`. I store only the latest two `memo`-entries so I need to rename them each time I increment the loop counter."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T12:03:06.683",
"Id": "235602",
"ParentId": "235593",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "235602",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T08:50:28.170",
"Id": "235593",
"Score": "7",
"Tags": [
"python",
"performance",
"python-3.x",
"recursion",
"dynamic-programming"
],
"Title": "Printing the number of ways a message can be decoded"
}
|
235593
|
<p>I often find myself doing rebase manually in an interactive form in a way as follows. Say I want to squash two last commit to third commit.</p>
<p>First I execute:</p>
<pre><code>$ git rebase -i HEAD~3
</code></pre>
<p>Now editor pops up, I mark two last commits as fixup. I close the editor and then rebasing is done (if there are no errors). I'd like to automate this by executing a script with a parameter that gives a number of commits, i.e. when 2 is given as parameter, last two commits are fixup to third commit. Please see an example:</p>
<blockquote>
<p>some other commits...</p>
<p>add nice feature</p>
<p>fix 1</p>
<p>fix 2</p>
</blockquote>
<p>In that scenario I'd like <code>add nice feature</code> to incorporate changes from <code>fix 1</code> and <code>fix 2</code>, and I like to <code>fix 1</code> and <code>fix 2</code> not be present at all.</p>
<p>I wrote a bash script that does what I want. It works seems to work fine.</p>
<p><strong>UPDATE</strong></p>
<p>In this review, I'm most interested in knowing whether my approach to git is a proper one, especially if it doesn't break anything during rebasing.</p>
<pre><code>fixup() {
local no_of_commits="$1"
if [ -z "$no_of_commits" ]; then
echo "You must provide a number of commits to fixup!"
return 1
elif ! [[ $1 =~ ^[0-9]+$ ]]; then
echo "$no_of_commits is not a number!"
return 2
fi
#git stash save
git reset --soft "HEAD~$(no_of_commits)" &&
git add --all &&
git commit --fixup "$(git rev-parse HEAD)" &&
GIT_SEQUENCE_EDITOR=true git rebase --interactive --autosquash --no-fork-point "$(git rev-parse HEAD~2)" &&
echo "Rebased $(no_of_commits) succesfully!"
#git stash pop
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T14:02:09.980",
"Id": "461272",
"Score": "1",
"body": "I'd suggest using `[[` consistently instead of `[`. It will help you avoid surprises like variables ending up empty. In your case quoting the variable takes care of it, but `[[` is still a good habit to get into."
}
] |
[
{
"body": "<p>The error messages should go to standard error, rather than standard output:</p>\n\n<pre><code> if [ -z \"$no_of_commits\" ]; then\n echo \"You must provide a number of commits to fixup!\" >&2\n return 1 ### HERE\n</code></pre>\n\n<p>I don't think there's a good case for returning distinct error codes for missing argument and invalid argument. Are you ever going to make use of the different status values?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T14:26:29.267",
"Id": "461274",
"Score": "0",
"body": "No, I'm not. One return value will suffice."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T09:46:05.320",
"Id": "235595",
"ParentId": "235594",
"Score": "2"
}
},
{
"body": "<h3>Syntax errors</h3>\n\n<p>The posted code has some syntax errors:</p>\n\n<blockquote>\n<pre><code> git reset --soft \"HEAD~$(no_of_commits)\" &&\n git add --all &&\n git commit --fixup \"$(git rev-parse HEAD)\" &&\n GIT_SEQUENCE_EDITOR=true git rebase --interactive --autosquash --no-fork-point \"$(git rev-parse HEAD~2)\" &&\n echo \"Rebased $(no_of_commits) succesfully!\"\n</code></pre>\n</blockquote>\n\n<p>That is, all the <code>$(no_of_commits)</code> must really be <code>$no_of_commits</code> or <code>${no_of_commits}</code> if you like.</p>\n\n<h3>Use <code>git commit --amend</code></h3>\n\n<p><code>git commit --fixup</code> is useful when you will have a bunch of fixup commits in the midst of other commits. To squash together the last N commits, is a special case, and can be done simpler using <code>git reset ... && git commit --amend</code>:</p>\n\n<pre><code> git reset --soft \"HEAD~$no_of_commits\" &&\n git commit --amend -C HEAD\n echo \"Rebased $no_of_commits successfully!\"\n</code></pre>\n\n<p>I also dropped the <code>git add --all</code> in the middle, because it's not necessary for the purpose you described, in fact it may have unintended effects.\nThat is, any uncommitted changes will get added. If I want to fixup the last N commits, I would want \"just that\", and nothing else. If I wanted the uncommitted changes included, I would commit them.</p>\n\n<h3>Use more functions</h3>\n\n<p>I would extract the conditional that checks if <code>$no_of_commits</code> is a number to its own function.\nThen you could easily copy-paste and reuse in other scripts.</p>\n\n<p>Also, the <code>elif</code> should use <code>$no_of_commits</code> instead of <code>$1</code>.</p>\n\n<h3>About rebasing...</h3>\n\n<blockquote>\n <p>In this review, I'm most interested in knowing whether my approach to git is a proper one, especially if it doesn't break anything during rebasing.</p>\n</blockquote>\n\n<p>Collapsing the last N commits isn't really <em>rebasing</em>, because no commits are applied on top of some other commit, it's really just <em>amending</em> a commit.</p>\n\n<p>As mentioned in the previous section, I think the <code>git add --all</code> operation is a mistake, which I would consider a defect of the otherwise nice functionality.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T17:17:04.063",
"Id": "235617",
"ParentId": "235594",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235617",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T08:51:21.050",
"Id": "235594",
"Score": "7",
"Tags": [
"bash",
"git"
],
"Title": "Fix last n commits to previous commit automatically"
}
|
235594
|
<p>Firstly I was using regex to get if the number of parentheses in a string is balanced or not, but the performance was quite slow when any large string was passed to the regex. So I created this custom method, which returns whether a string contains balanced parentheses or not. Please review this code and point out any mistakes and improvements.</p>
<pre><code>checkBalancedBrackets(str) {
var b1 = [];
var b2 = [];
for ( var i=0; i < str.length; i++ ) {
var ch = str.charAt(i);
if (ch == "(" ) b1.push(ch);
else if ( ch == "[" ) b2.push(ch);
else if ( ch == ")" ) {
if (b1.length < 1) {
return false;
} else {
b1.pop();
}
}
else if ( ch == "]" ) {
if (b2.length < 1) {
return false;
} else {
b2.pop();
}
}
}
return b1.length == 0 && b2.length == 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T11:34:17.470",
"Id": "461253",
"Score": "0",
"body": "https://codereview.stackexchange.com/questions/147259/validate-that-brackets-are-balanced see this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T11:49:59.007",
"Id": "461254",
"Score": "0",
"body": "Also this actually: https://codereview.stackexchange.com/q/45991/14625"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T12:59:26.477",
"Id": "461262",
"Score": "0",
"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)*. Please consider waiting for a day and posting a follow-up question with the new code linking back to this one instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T13:03:02.197",
"Id": "461265",
"Score": "1",
"body": "oops, will keep that in mind next time"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T22:10:57.283",
"Id": "461328",
"Score": "0",
"body": "Make a copy of the string, omitting any character that is not `[]()`. While `[]` or `()` are present in the copy, remove them. If any characters remain in the copy, the original string was not balanced."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T23:51:21.853",
"Id": "461342",
"Score": "0",
"body": "Regex can’t detect balanced parens. It’s probably not powerful enough. You need at least something equivalent to a context-free grammar, such as a PDA (you can do it with e.g. a stack)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T10:12:14.457",
"Id": "461989",
"Score": "0",
"body": "@D.BenKnoble I think he was expecting it in a loop like this example I whipped up - https://ideone.com/BR1c1L"
}
] |
[
{
"body": "<p>A short review;</p>\n\n<ul>\n<li><code>checkBalancedBrackets(\"([)]\")</code> returns <code>true</code>, not sure that was the intention</li>\n<li><code>b1</code> and <code>b2</code> are not great names, what does the b stand for?</li>\n<li>Using arrays is not needed, all the code does is counting numbers, you can just use numbers</li>\n<li>The inconsistent use of curly braces in your <code>if</code> and <code>else if</code> clauses is not good</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T18:46:02.880",
"Id": "461294",
"Score": "2",
"body": "\"You can just use numbers\" — only if `[(])` should really count as balanced. Otherwise you do need an array."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T12:08:28.973",
"Id": "235603",
"ParentId": "235597",
"Score": "5"
}
},
{
"body": "<p>The only numbers one should use in coding are 0, 1, and many.</p>\n\n<p>This code implicitly uses 2, the number of special cases, \"[]\" and \"()\", for which you wrote code. So right away you know the fundamental design is wrong.</p>\n\n<p>If this were a real program and next week your boss told you to handle \"<>\" as well, you'd have to write another section of code. Then next year you're asked to handle \"«»\" too. If it had been written properly, each time you'd only have to add those characters to a table and not make any changes to the actual code. As it is, you'll have to make extensive changes to the code, especially if you've already corrected it to check for proper nesting (e.g. \"[(])\" is wrong).</p>\n\n<p>The key to writing this is keeping track of what state your string is in at any point: which bracket type is it immediately within. Hint: try stacking the opening characters as you encounter them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T18:47:48.410",
"Id": "461295",
"Score": "0",
"body": "_Why_ should I \"only use numbers 0, 1, many\", and not, say, 12 or 365 or 100, which are all well-known?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T19:51:13.783",
"Id": "461304",
"Score": "0",
"body": "@RolandIllig, because numbers might need to be changed in the future. If you define something like: `[ [ '[', ']'], ['(', ')'] ]` and your code works with that, you'll only have to add `, ['<', '>']` to make it work with angle-brackets. If your code *knows* that there are two pairs of brackets, you'll have to significantly change it in order to make it work with additional kinds of brackets."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T19:52:37.577",
"Id": "461305",
"Score": "0",
"body": "@RolandIllig, It's okay to use numbers that are part of a well-known formula and not intrinsic to the code.\nBut generally most numbers can be computed.\nE.g. `monthNames.length`. \nOne reason is if the data changes someday, the code won't break.\nIt's unlikely we'll add another month, but what if there is another number that *can* change and it has the same value?\n\"12\" could occur for other purposes, and searching for *all* instances of \"12\" won't make it easy to determine which ones need to change and which ones don't.\nIf the raw number \"12\" never occurs, nothing needs to be done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T20:40:34.117",
"Id": "461315",
"Score": "2",
"body": "I think there is a good start of an answer in here somewhere, but it's written a bit convoluted. It starts by stating a truth that isn't generally considered a truth (so a source might be in order). The idea of using characters in a table or map is sound and would majorly improve maintainability if done right, but then you start talking about states of string. You can't make a state machine without violating your first statement, adding to the unclarity. I'm sure it can be salvaged."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T00:49:24.727",
"Id": "461343",
"Score": "0",
"body": "@Mast, I don't understand your last statement. How does \"*if it is an open character, push it; if it is a close character, if it matches the top of the stack, pop it, otherwise it's a mismatch*\" violate my first statement?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T14:26:40.403",
"Id": "235613",
"ParentId": "235597",
"Score": "0"
}
},
{
"body": "<p>You have the right idea, and your function <em>almost</em> works, but your code is only checking that ( is balanced with ), and [ is balanced with ]. So it will handle cases like <code>aaa(bbb[ccc]ddd)eee</code> correctly. But it will also accept <code>aaa(bbb[ccc)ddd]eee</code>, and that is wrong.</p>\n\n<p>You should only have a <em>single</em> stack, and you should push all the opening brackets onto it. When you get a closing bracket, pop off the most recent opening bracket and make sure it matches.</p>\n\n<p>Here I've taken your code and replaced the two stacks with one, which I've given a more meaningful name.</p>\n\n<pre><code>def checkBalancedBrackets(str) {\n var bracketStack = [];\n for (var i=0; i < str.length; i++) {\n var ch = str.charAt(i);\n // For opening brackets, we push the character that will match them\n if (ch == \"(\") bracketStack.push(\")\");\n else if (ch == \"[\") bracketStack.push(\"]\");\n else if (ch == \")\" || ch == \"]\") {\n if (bracketStack.length < 1) {\n return false;\n } else {\n match = bracketStack.pop();\n if (ch != match) {\n return false\n }\n }\n }\n }\n return bracketStack.length == 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-20T22:23:24.807",
"Id": "235920",
"ParentId": "235597",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "235603",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T11:08:02.417",
"Id": "235597",
"Score": "6",
"Tags": [
"javascript",
"strings"
],
"Title": "Validate parentheses \"()\" and \"[]\" are balanced"
}
|
235597
|
<p>The given code reverses an array of input characters.</p>
<p>The additional <code>while</code> loop in <code>reverse()</code> function is unnecessary I guess.
Any other method or way to remove it?</p>
<p>I would prefer to keep <code>reverse()</code> as <code>void</code>.</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#define MAXLEN 65535 /* maximum length of input line */
void reverse(char s[], int l);
/* reverses given input line */
void main()
{
int i, c;
char line[MAXLEN];
i = 0;
while(i < MAXLEN-1 && (c = getchar()) != EOF && c != '\n') /* input characters in array */
{
line[i] = c;
++i;
}
reverse(line, i);
printf("%s", line);
}
void reverse(char s[], int l)
{
char rev[MAXLEN];
int i, len;
i = 0;
len = l; /* duplicate length of initial array */
if(s[l] == '\0')
{
--l;
}
while(i < len)
{
rev[i] = s[l]; /* reversing */
++i;
--l;
}
i = 0;
while (i < len) /* what i think is unnecessary */
{
s[i] = rev[i]; /* storing back to initial array */
++i;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T17:32:39.677",
"Id": "461287",
"Score": "0",
"body": "Why you use `while` over `for` when you know exactly how many iterations do you need? I am saying about `while(i < len)`."
}
] |
[
{
"body": "<p>Standard C requires that <code>main()</code> return <strong><code>int</code></strong>:</p>\n\n<pre><code>int main(void)\n</code></pre>\n\n<p>There's no need (for 20 years now) to write all local declarations before the code. Introduce variables as you need them, so they can be initialised immediately:</p>\n\n<pre><code>{\n char line[MAXLEN];\n\n int i = 0;\n</code></pre>\n\n<p>There's no need for the extra storage <code>rev</code> in <code>reverse()</code>. We can reverse the string in place, by swapping first and last characters, then the second and second-last, and so on.</p>\n\n<p>Use the Standard Library - it provides functions such as <code>scanf()</code>, <code>getline()</code>, <code>strcpy()</code> and <code>strlen()</code>. Don't write your own code to do these things - it makes your code much less clear, and causes readers to wonder what's being done that's different to the standard.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T12:10:25.733",
"Id": "461255",
"Score": "0",
"body": "I was making a repo of all exercises in C language by K&R 2E and was thinking of keeping things simple according to the chapter and not using additional standard libraries.\nCan you actually answer how extra while loop can be eliminated ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T12:30:21.623",
"Id": "461258",
"Score": "0",
"body": "As I said, reverse the string in-place, swapping pairs of characters until you're done. When you've removed the need for `rev`, you won't need that `strcpy()` loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T13:02:06.460",
"Id": "461264",
"Score": "0",
"body": "can you provide a code snippet, my implementation is just printing palindrome strings ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T13:21:42.393",
"Id": "461267",
"Score": "1",
"body": "No. This is Code Review, not a \"write my program\" service."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T13:23:18.220",
"Id": "461269",
"Score": "0",
"body": "okay, thanks for your insight, appreciate it"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T11:23:58.823",
"Id": "235600",
"ParentId": "235598",
"Score": "1"
}
},
{
"body": "<p>First off, the second loop should be a for loop:</p>\n\n<pre><code>for (i = 0; i < len; ++i) /* what i think is unnecessary */\n{\n s[i] = rev[i]; /* storing back to initial array */\n}\n</code></pre>\n\n<p>But to eliminate that, try:</p>\n\n<pre><code>while(i < l)\n{\n char tmp = s[i]; /* swapping */\n s[i] = s[l]; /* swapping */\n s[l] = tmp; /* swapping */\n ++i;\n --l;\n}\n</code></pre>\n\n<p>If there is a true middle character, you don't wind up moving it.</p>\n\n<p>The check for the trailing NUL is also questionable. If you've been told the length, you should honor it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T13:26:39.200",
"Id": "235609",
"ParentId": "235598",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "235600",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T11:12:14.620",
"Id": "235598",
"Score": "1",
"Tags": [
"beginner",
"c"
],
"Title": "Reversing input characters"
}
|
235598
|
<p>Let's say I have this function called <code>coolName</code> that takes an argument <code>name</code> and decides whether it's a cool name:</p>
<pre><code>function coolName(name) {
const n = name.toLowerCase();
return n === 'peter' || n === 'paul' || n === 'mary';
}
</code></pre>
<p>You could achieve the same using this approach:</p>
<pre><code>function coolName(name) {
return ['peter', 'paul', 'mary'].includes(name.toLowerCase());
}
</code></pre>
<p>For 3 or more values I need to compare to, I prefer the second approach.</p>
<p>Your thoughts?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T19:01:54.817",
"Id": "461298",
"Score": "3",
"body": "If you expect many calls to occur, you could use a `Set` and call `has`. The set is slower to construct than an array, but `has` is much faster than `includes` on large collections. It also notifies the reader that the collection is not meant to have duplicates. Otherwise the second approach is canonical and readable. Even a very large list would maintain strong readability."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T05:08:06.243",
"Id": "461955",
"Score": "0",
"body": "For such a simple case the only difference is down to a personal preference. Some people use yoda style with the first approach to improve its glanceability and break it into multiple lines ending on `||`. Unless you see a difference in devtools profiler you shouldn't speculate on performance and change the code based on a guess or an idea what will run faster because the actual difference is likely to be within 0.001% of the task's total running time."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T16:49:25.283",
"Id": "235616",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Compare contents of a variable with several values"
}
|
235616
|
<p>I used the "long" form of all math statements, avoided the use of pointers, and used only while loops for aesthetic purposes (simply put, I think the code is prettier when it is written like that.) I am mainly concerned about the CPU efficiency of the code.</p>
<p>Bubble Sort - The quintessential example of an "inefficient" sorting algorithm. Often the first sorting algorithm introduced to college students.</p>
<pre><code>void BubbleSort(int Array[], int Length)
{
int CurrentIndex[2];
int TemporaryValue;
int WasThereASwap;
WasThereASwap = 1;
while (WasThereASwap == 1)
{
WasThereASwap = 0;
CurrentIndex[0] = 0;
CurrentIndex[1] = 1;
while (CurrentIndex[1] != Length)
{
if (Array[CurrentIndex[0]] > Array[CurrentIndex[1]])
{
WasThereASwap = 1;
TemporaryValue = Array[CurrentIndex[0]];
Array[CurrentIndex[0]] = Array[CurrentIndex[1]];
Array[CurrentIndex[1]] = TemporaryValue;
}
CurrentIndex[0] = CurrentIndex[0] + 1;
CurrentIndex[1] = CurrentIndex[1] + 1;
}
}
}
</code></pre>
<p>Selection Sort - Usually outperforms bubble sort, but it is still not a very good sorting algorithm for large arrays.</p>
<pre><code>void SelectionSort(int Array[], int Length)
{
int BeginComparisonsIndex;
int CurrentComparisonIndex;
int CurrentLowestIndex;
int TemporaryValue;
BeginComparisonsIndex = 0;
while(BeginComparisonsIndex != Length)
{
CurrentComparisonIndex = BeginComparisonsIndex;
CurrentLowestIndex = BeginComparisonsIndex;
while (CurrentComparisonIndex != Length)
{
if (Array[CurrentComparisonIndex] < Array[CurrentLowestIndex])
{
CurrentLowestIndex = CurrentComparisonIndex;
}
CurrentComparisonIndex = CurrentComparisonIndex + 1;
}
TemporaryValue = Array[BeginComparisonsIndex];
Array[BeginComparisonsIndex] = Array[CurrentLowestIndex];
Array[CurrentLowestIndex] = TemporaryValue;
BeginComparisonsIndex = BeginComparisonsIndex + 1;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T22:05:21.443",
"Id": "461327",
"Score": "3",
"body": "`a[x]` is `*(a+x)`, so I'd say you've confined your use of pointers to a specific syntax."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T23:22:17.087",
"Id": "461340",
"Score": "1",
"body": "(Well, there's bogosort, stoogesort, …)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T23:28:18.517",
"Id": "461341",
"Score": "1",
"body": "Can you please provide a reference which presentation of the bubble-sort algorithm you're following?"
}
] |
[
{
"body": "<p>It's a very unusual style to begin identifiers with uppercase letters.</p>\n\n<p>Include <code><stdbool.h></code> and use the <code>bool</code> type for flags.</p>\n\n<p>Many of the variables can be moved to smaller scopes.</p>\n\n<p>I think you should use <code>for</code> loops where appropriate - grouping the initialisation, predicate and advance clauses together improves clarity.</p>\n\n<p>Obviously this code lacks the generality of <code>qsort()</code> in that it can only work on arrays of <code>int</code>, but that may be acceptable for code that's merely didactic.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T18:11:28.800",
"Id": "235620",
"ParentId": "235618",
"Score": "7"
}
},
{
"body": "<h1>About aesthetics</h1>\n\n<blockquote>\n <p>I used the \"long\" form of all math statements, avoided the use of pointers, and used only while loops for aesthetic purposes (simply put, I think the code is prettier when it is written like that.)</p>\n</blockquote>\n\n<p>While making the code look aesthetically pleasing can be beneficial (especially if it makes it more readable), you should not give that a higher priority than writing maintainable code. The \"short\" form of modifying variables has the advantage that you don't have to repeat the variable name. This might make the code easier to read, but the big advantage is that it reduces potential errors: for example, it's impossible to accidentily put the wrong variable name on the right hand side if there is none to begin with. So if you'd write:</p>\n\n<pre><code>CurrentIndex[0]++;\n</code></pre>\n\n<p>You can't accidentily misspell the variable name, you can't accidentily use <code>[1]</code> on the right hand side, and you can't accidentily write <code>+ 2</code> instead of <code>+ 1</code>.</p>\n\n<p>Another benefit is that incrementing a counter using <code>++</code> is more ideomatic, which means that there is a big chance that other programmers that are used to C will find the short form more natural.</p>\n\n<p>Toby Speight already mentioned why <code>for</code>-loops can improve clarity over <code>while</code>-loops with separate initialization and incrementing statements.</p>\n\n<p>The use of arrays instead of pointers is perfectly fine here, since you are indeed manipulating arrays.</p>\n\n<h1>Variable names</h1>\n\n<p>Descriptive variable names help understand code, but having too long variable names can start to hinder readability. Also, some one-letter variable names are justified, for example it is idiomatic to use <code>i</code> and <code>j</code> as loop counters.</p>\n\n<p>Also, when you write <code>CurrentIndex</code> in <code>BubbleSort()</code>, it makes me wonder: is there also <code>PreviousIndex</code> or a <code>NextIndex</code>? If not, just <code>Index</code> would be better (or even just <code>i</code>). In <code>SelectionSort()</code> it makes more sense.</p>\n\n<h1>CPU efficiency</h1>\n\n<p>Your bubblesort implementation might have the advantage of quiting early if the input array was already sorted, but if it was not, then it takes twice as long as necessary. Instead of comparing two consecutive elements at a time, sort by first comparing the first element to all other elements, and swapping when necessary. After that first pass, you know that the first element is the lowest, so you don't have to consider it in the next pass anymore, and so on.</p>\n\n<p>If you want to sort arrays of integers in the most efficient way, you probably want to implement <a href=\"https://en.wikipedia.org/wiki/Radix_sort\" rel=\"noreferrer\">radix sort</a>.</p>\n\n<h1>Make sure you handle corner cases</h1>\n\n<p>In <code>BubbleSort()</code>, if the length of the input array is zero, then your code will go into an infinite loop and read out of bounds. Always check that you handle corner cases like arrays of length <code>0</code> and <code>1</code>.</p>\n\n<p>Another issue is that since <code>Length</code> is an <code>int</code>, someone could pass a negative value. To avoid that, use <code>size_t Length</code> instead (and change the type of the indices to match), or at least add in a check that <code>Length</code> is not negative. It still make sense to allow a length of <code>0</code> or <code>1</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T20:20:53.043",
"Id": "235623",
"ParentId": "235618",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "235623",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T18:02:17.237",
"Id": "235618",
"Score": "1",
"Tags": [
"c",
"sorting"
],
"Title": "Bubble Sort and Selection Sort (C)"
}
|
235618
|
<p>How can I refactor it to elegant way? This code is about parse birthday from Rodne Cislo string. I don't know how to do it clever and add more clean code style details</p>
<pre><code>public static void extractBirthdayFromRodneCislo(String rodneCislo) {
rodneCislo = rodneCislo.replace("/", "=");
int year;
int month;
int day;
if (rodneCislo.length() < 10) {
year = Integer.parseInt("19" + rodneCislo.charAt(0) + rodneCislo.charAt(1));
} else {
String century = Integer.parseInt(String.valueOf(rodneCislo.charAt(0)) + String.valueOf(rodneCislo.charAt(1))) < 53 ? "20" : "19";
year = Integer.parseInt(century + rodneCislo.charAt(0) + rodneCislo.charAt(1));
}
month = Integer.parseInt(String.valueOf(rodneCislo.charAt(2)) + String.valueOf(rodneCislo.charAt(3)));
if (month > 12) {
month -= 50;
}
day = Integer.parseInt(String.valueOf(rodneCislo.charAt(4)) + rodneCislo.charAt(5));
System.out.println(year + " " + month + " " + day);
}
</code></pre>
<p>The form is YYXXDD/SSSC, where XX=MM (month of birth) for male (numbers 01-12) and XX=MM+50 for female (numbers 51-62), SSS is a serial number separating persons born on the same date and C is a check digit, but for people born before 1 January 1954 the form is without the check digit - YYXXDD/SSS. This enables the system to work until the year 2054. The whole number must be divisible by 11. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T20:16:19.673",
"Id": "461308",
"Score": "1",
"body": "Please clarify what format `rodneCislo` has."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T21:22:08.817",
"Id": "461322",
"Score": "0",
"body": "Who is Rodne Cislo ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T21:34:53.117",
"Id": "461323",
"Score": "0",
"body": "I edited it llook my question"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T06:42:21.037",
"Id": "461352",
"Score": "0",
"body": "We sometimes write birth numbers without the slash. You might want to remove/ignore that character instead of replacing it with equal sign. Why you do that btw? I dont see you using the equal sign anywhere later on..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T07:03:21.450",
"Id": "461355",
"Score": "0",
"body": "@GaVaRaVa Rodné číslo = birth number. It uniquely encodes person's gender And day of birth. (Uniquely Meaning each person with samé gender And samé day of birth have a differrent birth number)"
}
] |
[
{
"body": "<p>I have some suggestions for your code.</p>\n\n<p>1) I suggest that you extract the different parts of the date in methods; it will make the code more readable and will be easier to refactor.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void extractBirthdayFromRodneCislo(String rodneCislo) {\n rodneCislo = rodneCislo.replace(\"/\", \"=\");\n\n int year = getYear(rodneCislo);\n int month = getMonth(rodneCislo);\n int day = getDay(rodneCislo);\n\n System.out.println(year + \" \" + month + \" \" + day);\n}\n\nprivate static int getDay(String rodneCislo) {\n return Integer.parseInt(String.valueOf(rodneCislo.charAt(4)) + rodneCislo.charAt(5));\n}\n\nprivate static int getMonth(String rodneCislo) {\n int month = Integer.parseInt(String.valueOf(rodneCislo.charAt(2)) + String.valueOf(rodneCislo.charAt(3)));\n\n if (month > 12) {\n month -= 50;\n }\n\n return month;\n}\n\nprivate static int getYear(String rodneCislo) {\n int year;\n\n if (rodneCislo.length() < 10) {\n year = Integer.parseInt(\"19\" + rodneCislo.charAt(0) + rodneCislo.charAt(1));\n } else {\n String century = Integer.parseInt(String.valueOf(rodneCislo.charAt(0)) + String.valueOf(rodneCislo.charAt(1))) < 53 ? \"20\" : \"19\";\n year = Integer.parseInt(century + rodneCislo.charAt(0) + rodneCislo.charAt(1));\n }\n\n return year;\n}\n</code></pre>\n\n<p>2) <code>getYear</code> method, you can use multiple return to remove the variable.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static int getYear(String rodneCislo) {\n if (rodneCislo.length() < 10) {\n return Integer.parseInt(\"19\" + rodneCislo.charAt(0) + rodneCislo.charAt(1));\n } else {\n String century = Integer.parseInt(String.valueOf(rodneCislo.charAt(0)) + String.valueOf(rodneCislo.charAt(1))) < 53 ? \"20\" : \"19\";\n return Integer.parseInt(century + rodneCislo.charAt(0) + rodneCislo.charAt(1));\n }\n}\n</code></pre>\n\n<p>3) Instead of using <code>java.lang.String#charAt</code>, I suggest that you use <code>java.lang.String#substring</code></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static int getDay(String rodneCislo) {\n return Integer.parseInt(rodneCislo.substring(4, 6));\n}\n\nprivate static int getMonth(String rodneCislo) {\n int month = Integer.parseInt(rodneCislo.substring(2, 4));\n\n if(month > 12) {\n month -= 50;\n }\n\n return month;\n}\n\nprivate static int getYear(String rodneCislo) {\n String currentRange = rodneCislo.substring(0, 2);\n\n if (rodneCislo.length() < 10) {\n return Integer.parseInt(\"19\" + currentRange);\n } else {\n String century = Integer.parseInt(currentRange) < 53 ? \"20\" : \"19\";\n return Integer.parseInt(century + currentRange);\n }\n}\n</code></pre>\n\n<h3>Refactored code</h3>\n\n<pre class=\"lang-java prettyprint-override\"><code> public static void main(String[] args) {\n extractBirthdayFromRodneCislo(\"8001015009087\");\n }\n\n public static void extractBirthdayFromRodneCislo(String rodneCislo) {\n rodneCislo = rodneCislo.replace(\"/\", \"=\");\n\n int year = getYear(rodneCislo);\n int month = getMonth(rodneCislo);\n int day = getDay(rodneCislo);\n\n System.out.println(year + \" \" + month + \" \" + day);\n }\n\n private static int getDay(String rodneCislo) {\n return Integer.parseInt(rodneCislo.substring(4, 6));\n }\n\n private static int getMonth(String rodneCislo) {\n int month = Integer.parseInt(rodneCislo.substring(2, 4));\n\n if (month > 12) {\n month -= 50;\n }\n\n return month;\n }\n\n private static int getYear(String rodneCislo) {\n String currentRange = rodneCislo.substring(0, 2);\n\n if (rodneCislo.length() < 10) {\n return Integer.parseInt(\"19\" + currentRange);\n } else {\n String century = Integer.parseInt(currentRange) < 53 ? \"20\" : \"19\";\n return Integer.parseInt(century + currentRange);\n }\n }\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T01:16:41.963",
"Id": "461345",
"Score": "1",
"body": "For `getYear` I suggest to define `int yy = Integer.parseInt(rodneCislo.substring(0, 2));`. After that, you don't need `Integer.parseInt` anymore since you can work on the numbers directly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T06:09:39.620",
"Id": "461351",
"Score": "1",
"body": "It might be better to define a factory method `parseBirthNumber()` that would return an object with methods like getCentury, getYear, getMonth, getDay, getGender, getSerial, getCheckDigit instead of having a separate parser for every component. Such a factory could make sure the check Digit Is ok And the number Is divisible by 11. And decoupling IT from systém.out. but that would ofc extend the capabilities beyond those of OPs code..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T06:48:17.083",
"Id": "461353",
"Score": "0",
"body": "Btw 8001015009087 Is not a valid czech birth number. Not even close :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T23:34:48.773",
"Id": "235629",
"ParentId": "235621",
"Score": "1"
}
},
{
"body": "<p>In addition to Doi9t's answer, which gives good advice, I'll add that your function name, <code>extractBirthdayFromRodneCislo</code>, is wrong, as it merely prints the birthday instead extracting it.</p>\n\n<p>The easy fix is to rename the function <code>extractBirthdayFromRodneCislo</code>, which may fit you case, but doesn't allow you to do anything more fancy than that.</p>\n\n<p>The better way to do things would be to return the date, allowing you to do anything with it after calling the method.</p>\n\n<p>I'm completely new to Java, so I might miss something here, but it seems that the <code>java.time.LocalDate</code> datatype is a good fit for the job.</p>\n\n<p>So your function becomes something like this:</p>\n\n<pre><code>public static LocalDate extractBirthdayFromRodneCislo(String rodneCislo) {\n\n // your logic here\n\n return LocalDate.of(year, month, day);\n}\n</code></pre>\n\n<p>This approach has the added advantage that, should there be a mistake in the input string leading to an invalid date, it will throw an exception instead of silently accepting an invalid date – if you pass <code>622754/1234</code> to your function or Doi9t's, it will not care that <code>1962 -23 54</code> is not an acceptable output and print it just like any other date.</p>\n\n<p>This illustrates to another problem: input validation. Your code doens't care if the input is indeed a Rodne Cislo. It will take any string as input. It may fail if <code>Integer.parseInt</code> encounter non-digit characters, but will accept strings that are too long, too short, has a properly placed <code>/</code> character or not (comments pointed out that Czech people don't always include the <code>/</code>, any other character in this place, etc., leading to a big risk of improperly parsing the string.</p>\n\n<p>One possible tool for validating strings are regular expressions (regex). A lot of different patterns can be used to validate the input string, a simple one would be:</p>\n\n<pre><code>^[0-9]{6}\\/[0-9]{3}[0-9]?$\n</code></pre>\n\n<p>If you are unfamiliar with regex, here is a breakdown of this expression:</p>\n\n<pre><code>^[0-9]{6}\\/?[0-9]{3}[0-9]?$\n\n^ # start with (no leading characater)\n [0-9]{6} # 6 digits\n \\/? # may or may not include a \"/\" character\n [0-9]{3} # 3 additional digits\n [0-9]? # 1 optional additional digit\n $ # ends here (no trailing character)\n</code></pre>\n\n<p>Checking if the input string matches this pattern will call out a lot of invalid input strings, although it doesn't check if the month and day numbers are within valid ranges – it is definitely possible, but will get nasty quite quickly, and the <code>LocalDate.of()</code> method already takes care of it.</p>\n\n<p>Another nice thing about regex is that you can extract specific ranges within the expression easily with capture groups. A little modifications on the previous expression gives (with explanation):</p>\n\n<pre><code>^([0-9]{2})([0-9]{2})([0-9]{2})\\/?[0-9]{3}[0-9]?$\n\n^ # starts with (no leading characater)\n ([0-9]{2}) # 2 digits, capture them in group 1\n ([0-9]{2}) # 2 digits, capture them in group 2\n ([0-9]{2}) # 2 digits, capture them in group 3\n \\/? # an optional \"/\" character\n [0-9]{3} # 3 digits\n ([0-9]?) # 1 optional digit, capture it in group 4\n $ # ends here (no trailing character)\n</code></pre>\n\n<p>You can then used the captured strings to parse the numbers (groups 1 to 3), or identify if the birth year is before or after 1954 (group 4).</p>\n\n<p>My final take on the problem is this code:</p>\n\n<pre><code>import java.time.LocalDate;\nimport java.util.regex.Pattern;\nimport java.util.regex.Matcher;\n\nclass Main {\n public static void main(String[] args) {\n System.out.println(extractBirthdayFromRodneCislo(\"535223/1234\"))\n // > 2053-02-23\n System.out.println(extractBirthdayFromRodneCislo(\"530223/123\"))\n // > 1953-02-23\n System.out.println(extractBirthdayFromRodneCislo(\"7503121234\"))\n // > 1975-03-12\n System.out.println(extractBirthdayFromRodneCislo(\"753312/1234\"))\n // > Throws an exception (invalid month)\n System.out.println(extractBirthdayFromRodneCislo(\"753312/12345\"))\n // > Throws an exception (doesn't match pattern)\n }\n\n public static LocalDate extractBirthdayFromRodneCislo(String rodneCislo){\n Pattern p = Pattern.compile(\"^([0-9]{2})([0-9]{2})([0-9]{2})\\\\/?[0-9]{3}[0-9]?$\");\n\n Matcher m = p.matcher(rodneCislo);\n\n if (!m.matches()){\n // Input doesn't match the pattern\n // throw a relevant exception\n // although I can't seem to do that propely with Java\n }\n\n int year = Integer.parseInt(m.group(1));\n if (year < 54 && !m.group(4).isEmpty()){\n year += 2000;\n }else{\n year += 1900;\n }\n\n int month = Integer.parseInt(m.group(2));\n if (month > 12){month -= 50;}\n\n int day = Integer.parseInt(m.group(3));\n\n return LocalDate.of(year, month, day); // will throw an exception if month or day ends up invalid\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T17:17:25.670",
"Id": "461451",
"Score": "0",
"body": "There's no need to escape the `/` in a regular expression in Java. It would only be necessary in JavaScript or PHP."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T17:19:10.140",
"Id": "461452",
"Score": "1",
"body": "What about `throw new IllegalArgumentException(rodneCislo)`?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T12:01:46.600",
"Id": "235653",
"ParentId": "235621",
"Score": "4"
}
},
{
"body": "<p>Others have improved the parsing, but the code surrounding it is lacking. You asked for help for parsing the date but if the code should be made more \"elegant\", then instead of defining a single purpose static method for accessing the birth date, you should define a class to represent the Rodne Cislo number. Provide a constructor that performs validation and getters for accessing different fields in the number:</p>\n\n<pre><code>public class RodneCislo {\n private final LocalDate birthate;\n private final int serialNumber;\n\n public RodneCislo(final String rodneCislo) throws ValidationException {\n // Check format for correctness with regex.\n // Extract date and serial number.\n // Verify that checksum is correct.\n }\n\n public LocalDate getBirthDate() {\n ...\n }\n\n public int getSerialNumber() {\n ...\n }\n\n public Optional<Character> getChecksum() {\n ...\n }\n}\n</code></pre>\n\n<p>Now you have one reusable component that contains all the responsibilities involved in reading Rodne Cislo numbers. Define unit tests in a separate <code>RodneCisloTest</code> class.</p>\n\n<p>The point of representing the Rodne Cislo number as a dedicated class instead of a string is to provide code level guarantee to whoever processes the numbers that it is actually a valid number and not just a random piece of text (and thus input validation needs to be performed only once).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T14:30:50.567",
"Id": "461423",
"Score": "1",
"body": "Many try to use a typed constructor `RodneCislo(year, month, day)` with a static factory method `valueOf(String):RodneCislo` throwing ValidationException or (subclass of) IllegalArgumentException. The \"valueOf\" or \"fromString\" is a kind of stanard used by many frameworks to automagically convert a string to a class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T15:15:22.450",
"Id": "461430",
"Score": "0",
"body": "Great addition! Had I been even a little bit familiar with Java, I would have worked up to something very close to this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T15:25:18.487",
"Id": "461433",
"Score": "0",
"body": "@gervais.b Not sure this is the best approach here, as there is no way to infer the `SSS` digits from the birthdate, the `month` value also encodes gender, the optional presence of a checksum disambiguates the value of `year`... Having a constructor take a string as argument seems to me as a better alternative for working with this kind of object."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T20:13:54.803",
"Id": "461480",
"Score": "0",
"body": "Factory methods are good if you want to create a type that may be a subclass of the containing class or return an optional etc. In this case it doesn't bring any advantages, so constructors are ok."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-18T08:38:06.543",
"Id": "461693",
"Score": "0",
"body": "@TorbenPutkonen, except that creating rodné číslo from a string can be done in multiple ways (ie the dash separátor May be required, optional or unexpected). Having distinct named static factory for each of those ways May not be bad idea. Or maybe if there Is just one that Takes a string And some discriminator of the separátor presence strategy..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-18T09:10:19.923",
"Id": "461698",
"Score": "0",
"body": "Different construction methods that accept the same data type as parameter and produce the same result type is a pretty bad idea. Just let the computer detect the format and don't bother the user."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T13:43:33.303",
"Id": "235664",
"ParentId": "235621",
"Score": "3"
}
},
{
"body": "<p>All suggestions posted before my answer are valid, I'm writing some personal thoughts about your code:</p>\n\n<blockquote>\n<pre><code>public static void extractBirthdayFromRodneCislo(String rodneCislo) {\n //omitted\n System.out.println(year + \" \" + month + \" \" + day);\n}\n</code></pre>\n</blockquote>\n\n<p>Instead of printing values inside this method you can return the String object as a result and after print it like the code below:</p>\n\n<pre><code>public static void extractBirthdayFromRodneCislo(String rodneCislo) {\n //omitted\n return String.format(\"%d %d %d\", yy, mm, dd);\n}\n</code></pre>\n\n<p>I used the String.<a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#format-java.lang.String-java.lang.Object...-\" rel=\"nofollow noreferrer\">format</a> that permits to create string composed by values in a more readable way instead of composing the final String using the <code>+</code> operator.</p>\n\n<p>The purpose of your code is basically extract some characters from your string and use them as <code>int</code> digits from your use of <code>Integer.parseInt</code> method like your code below:</p>\n\n<blockquote>\n<pre><code>if (rodneCislo.length() < 10) {\n year = Integer.parseInt(\"19\" + rodneCislo.charAt(0) + rodneCislo.charAt(1));\n } else {\n String century = Integer.parseInt(String.valueOf(rodneCislo.charAt(0)) + String.valueOf(rodneCislo.charAt(1))) < 53 ? \"20\" : \"19\";\n year = Integer.parseInt(century + rodneCislo.charAt(0) + rodneCislo.charAt(1));\n }\n}\n</code></pre>\n</blockquote>\n\n<p>You can refactor your code and rewrite your method like below:</p>\n\n<pre><code>public static String extractBirthdayFromRodneCislo1(String rodneCislo) {\n\n int sum = Integer.parseInt(rodneCislo.substring(0, 2));\n int yy = (rodneCislo.length() < 10 || sum > 53) ? 1900 + sum : 2000 + sum;\n\n int mm = Integer.parseInt(rodneCislo.substring(2, 4));\n if (mm > 12) { mm -= 50; }\n\n int dd = Integer.parseInt(rodneCislo.substring(4, 6));\n\n return String.format(\"%d %d %d\", yy, mm, dd);\n}\n</code></pre>\n\n<p>As already suggested your code should be integrated with a validation method that ensures that characters used in the method extractBirthdayFromRodneCislo are digits otherwise the method will fail.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T15:24:40.383",
"Id": "235675",
"ParentId": "235621",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T19:54:48.830",
"Id": "235621",
"Score": "4",
"Tags": [
"java"
],
"Title": "Elegant way for parsing birthday from rodne cislo (czech republic ID)"
}
|
235621
|
<p>Context: <a href="https://gitlab.com/panStachowski/zoo-mobilka/tree/master/app/src/main/java/com/example/zootopia" rel="nofollow noreferrer">gitlab link</a></p>
<p>I know, it's a lot of code but I need your help ladies and gentleman. I'm not sure if I can ask for code review for the whole project so I just ask to review this activity. I would like to add this project to my summary (still looking for first work and I'm still student).</p>
<p><strong>This is how interface looks like:</strong> </p>
<p><a href="https://i.stack.imgur.com/CMS3q.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CMS3q.jpg" alt="ZooRater ZooWallActivity.kt interface"></a></p>
<p><em>Usuń z odwiedzonych</em> stands for <em>remove from visited</em> (text changes to <em>add to visited</em> after clicking this button and reverse)</p>
<p><em>Atrakcje</em> stands for <em>featured</em>.</p>
<p><em>Zobacz opinie</em> stands for <em>opinions</em>.</p>
<p><em>Zostaw opinie</em> stands for <em>add opinion</em></p>
<p>First button is described above, next two buttons redirect you to another activities and the last button displays alert dialog for your opinion. Every star is separate transparent button and star image underneath. This is how it looks like:</p>
<p><a href="https://i.stack.imgur.com/CyBZb.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CyBZb.jpg" alt="ZooRater ZooWallActivity.kt alertDialog"></a></p>
<p><strong>This is the code</strong></p>
<pre><code>class ZooWallActivity : AppCompatActivity() {
val db = FirebaseFirestore.getInstance()
private lateinit var currentUID: String
private lateinit var zooUID: String
private var flag = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_zoo_wall)
zooUID = intent.getStringExtra("ZOO_UID")
currentUID = FirebaseAuth.getInstance().uid ?: ""
getZooData(zooUID)
getImage(zooUID)
fetchRating(zooUID)
checkIfVisited(currentUID, zooUID)
zoowall_opinions.setOnClickListener {
val intent = Intent(this, OpinionsActivity::class.java)
intent.putExtra("ZOO_UID", zooUID)
startActivity(intent)
}
zoowall_add.setOnClickListener {
performAddOrRm(currentUID, zooUID)
}
zoowall_featured.setOnClickListener {
featured(zooUID)
}
zoowall_addopinion.setOnClickListener {
var rating = 0
var customView = layoutInflater.inflate(R.layout.alertdialog_comment, null)
val builder = AlertDialog.Builder(this)
.setView(customView)
val alertDialog = builder.show()
val opinionsRef =
db.collection("zoos").document(zooUID).collection("opinions").document(currentUID)
opinionsRef.get()
.addOnSuccessListener { opinion ->
var temp = opinion.data.toString()
if (temp != "" && temp != "null" && temp != "[]") {
customView.alert_comment.setText(opinion.get("comment").toString())
rating = opinion.get("rating").toString().toInt()
when (rating) {
1 -> {
customView.alert_rating1_img.setImageResource(android.R.drawable.btn_star_big_on)
customView.alert_rating2_img.setImageResource(android.R.drawable.btn_star_big_off)
customView.alert_rating3_img.setImageResource(android.R.drawable.btn_star_big_off)
customView.alert_rating4_img.setImageResource(android.R.drawable.btn_star_big_off)
customView.alert_rating5_img.setImageResource(android.R.drawable.btn_star_big_off)
}
2 -> {
customView.alert_rating1_img.setImageResource(android.R.drawable.btn_star_big_on)
customView.alert_rating2_img.setImageResource(android.R.drawable.btn_star_big_on)
customView.alert_rating3_img.setImageResource(android.R.drawable.btn_star_big_off)
customView.alert_rating4_img.setImageResource(android.R.drawable.btn_star_big_off)
customView.alert_rating5_img.setImageResource(android.R.drawable.btn_star_big_off)
}
3 -> {
customView.alert_rating1_img.setImageResource(android.R.drawable.btn_star_big_on)
customView.alert_rating2_img.setImageResource(android.R.drawable.btn_star_big_on)
customView.alert_rating3_img.setImageResource(android.R.drawable.btn_star_big_on)
customView.alert_rating4_img.setImageResource(android.R.drawable.btn_star_big_off)
customView.alert_rating5_img.setImageResource(android.R.drawable.btn_star_big_off)
}
4 -> {
customView.alert_rating1_img.setImageResource(android.R.drawable.btn_star_big_on)
customView.alert_rating2_img.setImageResource(android.R.drawable.btn_star_big_on)
customView.alert_rating3_img.setImageResource(android.R.drawable.btn_star_big_on)
customView.alert_rating4_img.setImageResource(android.R.drawable.btn_star_big_on)
customView.alert_rating5_img.setImageResource(android.R.drawable.btn_star_big_off)
}
5 -> {
customView.alert_rating1_img.setImageResource(android.R.drawable.btn_star_big_on)
customView.alert_rating2_img.setImageResource(android.R.drawable.btn_star_big_on)
customView.alert_rating3_img.setImageResource(android.R.drawable.btn_star_big_on)
customView.alert_rating4_img.setImageResource(android.R.drawable.btn_star_big_on)
customView.alert_rating5_img.setImageResource(android.R.drawable.btn_star_big_on)
}
else -> {
rating = 0
customView.alert_rating1_img.setImageResource(android.R.drawable.btn_star_big_off)
customView.alert_rating2_img.setImageResource(android.R.drawable.btn_star_big_off)
customView.alert_rating3_img.setImageResource(android.R.drawable.btn_star_big_off)
customView.alert_rating4_img.setImageResource(android.R.drawable.btn_star_big_off)
customView.alert_rating5_img.setImageResource(android.R.drawable.btn_star_big_off)
}
}
}
}
.addOnFailureListener {
}
customView.alertdialog_cancel.setOnClickListener {
alertDialog.dismiss()
}
customView.alertdialog_ok.setOnClickListener {
val temp = customView.alert_comment.text.toString()
if (rating == 0) {
Toast.makeText(this, "Zapomniałeś o ocenie", Toast.LENGTH_LONG).show()
} else if (temp == "" || temp == "null") {
Toast.makeText(this, "Komentarz nie może być pusty", Toast.LENGTH_LONG).show()
} else {
alertDialog.dismiss()
val comment = customView.alert_comment.text.toString()
addComment(rating, comment, currentUID, zooUID)
}
}
customView.alert_rating1_btn.setOnClickListener {
rating = 1
customView.alert_rating1_img.setImageResource(android.R.drawable.btn_star_big_on)
customView.alert_rating2_img.setImageResource(android.R.drawable.btn_star_big_off)
customView.alert_rating3_img.setImageResource(android.R.drawable.btn_star_big_off)
customView.alert_rating4_img.setImageResource(android.R.drawable.btn_star_big_off)
customView.alert_rating5_img.setImageResource(android.R.drawable.btn_star_big_off)
}
customView.alert_rating2_btn.setOnClickListener {
rating = 2
customView.alert_rating1_img.setImageResource(android.R.drawable.btn_star_big_on)
customView.alert_rating2_img.setImageResource(android.R.drawable.btn_star_big_on)
customView.alert_rating3_img.setImageResource(android.R.drawable.btn_star_big_off)
customView.alert_rating4_img.setImageResource(android.R.drawable.btn_star_big_off)
customView.alert_rating5_img.setImageResource(android.R.drawable.btn_star_big_off)
}
customView.alert_rating3_btn.setOnClickListener {
rating = 3
customView.alert_rating1_img.setImageResource(android.R.drawable.btn_star_big_on)
customView.alert_rating2_img.setImageResource(android.R.drawable.btn_star_big_on)
customView.alert_rating3_img.setImageResource(android.R.drawable.btn_star_big_on)
customView.alert_rating4_img.setImageResource(android.R.drawable.btn_star_big_off)
customView.alert_rating5_img.setImageResource(android.R.drawable.btn_star_big_off)
}
customView.alert_rating4_btn.setOnClickListener {
rating = 4
customView.alert_rating1_img.setImageResource(android.R.drawable.btn_star_big_on)
customView.alert_rating2_img.setImageResource(android.R.drawable.btn_star_big_on)
customView.alert_rating3_img.setImageResource(android.R.drawable.btn_star_big_on)
customView.alert_rating4_img.setImageResource(android.R.drawable.btn_star_big_on)
customView.alert_rating5_img.setImageResource(android.R.drawable.btn_star_big_off)
}
customView.alert_rating5_btn.setOnClickListener {
rating = 5
customView.alert_rating1_img.setImageResource(android.R.drawable.btn_star_big_on)
customView.alert_rating2_img.setImageResource(android.R.drawable.btn_star_big_on)
customView.alert_rating3_img.setImageResource(android.R.drawable.btn_star_big_on)
customView.alert_rating4_img.setImageResource(android.R.drawable.btn_star_big_on)
customView.alert_rating5_img.setImageResource(android.R.drawable.btn_star_big_on)
}
}
}
private fun fetchRating(zooUID: String) {
val opinionsRef = db.collection("zoos").document(zooUID).collection("opinions")
opinionsRef.get()
.addOnSuccessListener { opinions ->
var rating = 0.0
var counter = 0.0
if (opinions.toString() != "null" && opinions.toString() != "[]") {
opinions.forEach { opinion ->
counter++
rating += opinion.get("rating").toString().toInt()
}
}
zoowall_counter.text = "(" + counter.toInt().toString() + ")"
var average = rating.div(counter)
when (average) {
in 1.0..1.5 -> {
zoowall_rating1.setImageResource(android.R.drawable.btn_star_big_on)
zoowall_rating2.setImageResource(android.R.drawable.btn_star_big_off)
zoowall_rating3.setImageResource(android.R.drawable.btn_star_big_off)
zoowall_rating4.setImageResource(android.R.drawable.btn_star_big_off)
zoowall_rating5.setImageResource(android.R.drawable.btn_star_big_off)
}
in 1.5..2.5 -> {
zoowall_rating1.setImageResource(android.R.drawable.btn_star_big_on)
zoowall_rating2.setImageResource(android.R.drawable.btn_star_big_on)
zoowall_rating3.setImageResource(android.R.drawable.btn_star_big_off)
zoowall_rating4.setImageResource(android.R.drawable.btn_star_big_off)
zoowall_rating5.setImageResource(android.R.drawable.btn_star_big_off)
}
in 2.5..3.5 -> {
zoowall_rating1.setImageResource(android.R.drawable.btn_star_big_on)
zoowall_rating2.setImageResource(android.R.drawable.btn_star_big_on)
zoowall_rating3.setImageResource(android.R.drawable.btn_star_big_on)
zoowall_rating4.setImageResource(android.R.drawable.btn_star_big_off)
zoowall_rating5.setImageResource(android.R.drawable.btn_star_big_off)
}
in 3.5..4.5 -> {
zoowall_rating1.setImageResource(android.R.drawable.btn_star_big_on)
zoowall_rating2.setImageResource(android.R.drawable.btn_star_big_on)
zoowall_rating3.setImageResource(android.R.drawable.btn_star_big_on)
zoowall_rating4.setImageResource(android.R.drawable.btn_star_big_on)
zoowall_rating5.setImageResource(android.R.drawable.btn_star_big_off)
}
in 4.5..5.0 -> {
zoowall_rating1.setImageResource(android.R.drawable.btn_star_big_on)
zoowall_rating2.setImageResource(android.R.drawable.btn_star_big_on)
zoowall_rating3.setImageResource(android.R.drawable.btn_star_big_on)
zoowall_rating4.setImageResource(android.R.drawable.btn_star_big_on)
zoowall_rating5.setImageResource(android.R.drawable.btn_star_big_on)
}
else -> {
}
}
}
}
private fun addComment(rating: Int, comment: String, userUID: String, zooUID: String) {
val opinionsRef = db.collection("zoos").document(zooUID).collection("opinions")
val opinion = mapOf<String, Any>(
"comment" to comment,
"rating" to rating
)
opinionsRef.document(currentUID).set(opinion)
.addOnSuccessListener {
fetchRating(zooUID)
}
}
private fun featured(UID: String) {
val intent = Intent(this, FeaturedActivity::class.java)
intent.putExtra("ZOO_UID", UID)
startActivity(intent)
}
private fun performAddOrRm(uid: String, UID: String) {
zoowall_add.isEnabled = false
zoowall_add.isClickable = false
if (flag) {
db.collection("users").document(uid).update(
"visited_zoos", FieldValue.arrayRemove(UID)
)
.addOnSuccessListener {
zoowall_add.isEnabled = true
zoowall_add.isClickable = true
zoowall_add.text = "Dodaj do odwiedzonych"
flag = false
}
.addOnFailureListener {
Toast.makeText(this, "${it.message}", Toast.LENGTH_LONG).show()
}
} else {
db.collection("users").document(uid).update(
"visited_zoos", FieldValue.arrayUnion(UID)
)
.addOnSuccessListener {
zoowall_add.isEnabled = true
zoowall_add.isClickable = true
zoowall_add.text = "Usuń z odwiedzonych"
flag = true
}
.addOnFailureListener {
Toast.makeText(this, "${it.message}", Toast.LENGTH_LONG).show()
}
}
}
private fun checkIfVisited(uid: String, UID: String) {
db.collection("users").document(uid).get()
.addOnSuccessListener { user ->
val temp = user.get("visited_zoos").toString()
if (temp != "" && temp != "[]" && temp != "null") {
val visitedZoos = user.get("visited_zoos") as List<String>
visitedZoos.forEach { zoo ->
if (zoo == UID) {
zoowall_add.text = "Usuń z odwiedzonych"
flag = true
}
}
}
}
}
private fun getImage(UID: String) {
val storage = FirebaseStorage.getInstance()
val storageRef = storage.reference
db.collection("zoos").document(UID).get()
.addOnSuccessListener { zoo ->
val path = zoo.get("photo").toString()
if (path != "" && path != "null") {
storageRef.child(path).downloadUrl
.addOnSuccessListener {
Picasso.get().load(it).into(zoowall_photo)
}
.addOnFailureListener {
zoowall_photo_text.text = "Brak zdjęcia"
}
}
}
}
private fun getZooData(UID: String) {
db.collection("zoos").document(UID).get()
.addOnSuccessListener {
val name: String = it.get("name").toString()
val address: String = it.get("address").toString()
if (name != "" && name != "null") zoowall_name.text = name
else zoowall_name.text = "Brak nazwy zoo"
if (address != "" && address != "null") zoowall_address.text = address
else zoowall_address.text = "Brak adresu zoo"
}
.addOnFailureListener {
Toast.makeText(this, "${it.message}", Toast.LENGTH_LONG).show()
zoowall_name.text = "Brak nazwy zoo"
zoowall_address.text = "Brak adresu zoo"
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T20:28:30.337",
"Id": "461309",
"Score": "0",
"body": "\"I'm not sure if I can ask for code review for the whole project\" Depends, how big is it in character count? We got a fairly high limit, but if you have enough sections the size of the piece you posted it's going to be tricky. Welcome to the site anyway :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T20:29:31.530",
"Id": "461310",
"Score": "0",
"body": "How do you handle your back-end and CRUD actions on the permanent storage?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T20:34:01.303",
"Id": "461312",
"Score": "0",
"body": "@Mast I thought about adding gitlab repo link - is it permitted on this site or should I just post whole project code here?\n\nHow I handle CRUD operations - I create database reference and then I use on it get/set/update method on it.\n\n\n`val opinionsRef =\n db.collection(\"zoos\").document(zooUID).collection(\"opinions\").document(currentUID)\n opinionsRef.get()\n .addOnSuccessListener { opinion ->`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T20:35:07.620",
"Id": "461313",
"Score": "0",
"body": "Is it permitted to post a link to GitHub? Yes. Will the code be reviewed? No. Only the code that's posted in the question is up for review, the rest is context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T13:25:52.523",
"Id": "461413",
"Score": "0",
"body": "I recommend you to follow the Android-tutorial created by google.\nhttps://www.udacity.com/course/developing-android-apps-with-kotlin--ud9012\n\nFollowed by:\nhttps://www.udacity.com/course/advanced-android-with-kotlin--ud940\n\nOptionally, you can first follow a kotlin-course if you want:\nhttps://www.udacity.com/course/kotlin-bootcamp-for-programmers--ud9011\n\nAll the courses are provided by Google themselves and are free.\n\nThe kotlin course goes through Kotlin reasonable quick and the Android-courses will focus a lot on architecture."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T18:06:43.173",
"Id": "461457",
"Score": "0",
"body": "@tieskedh I will look at it, but I need an opinion about this code of mine. I see some flaws right now but I'd like to hear a professional advice about it. Like pointing out my bad habits etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T18:55:43.810",
"Id": "461466",
"Score": "0",
"body": "I will look at the code tommorrow. I focus foremost on language features. I will tell you how you access firebase using coroutines. This will, however, improve the code a bit. The code needs to be split up in several classes with strict rules about those classes, preferable using well known and proven patterns, or in other words, this class needs architecture. That's what both Android-courses mainly focus on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T19:03:15.353",
"Id": "461467",
"Score": "0",
"body": "See also https://developer.android.com/jetpack/docs/guide"
}
] |
[
{
"body": "<h1>Anko commons</h1>\n\n<p>I think Anko is dead, however, their library is still pretty useful.<br>\nI would recommend commons, such that you can rewrite the activity-starting</p>\n\n<pre><code>zoowall_opinions.setOnClickListener {\n val intent = Intent(this, OpinionsActivity::class.java)\n intent.putExtra(\"ZOO_UID\", zooUID)\n startActivity(intent)\n}\n</code></pre>\n\n<p>with Anko-commons will become:</p>\n\n<pre><code>zoowall_opinions.setOnClickListener {\n startActivity<OpinionsActivity>(\"ZOO_UID\", zooUID)\n}\n</code></pre>\n\n<h1>rating</h1>\n\n<p>You should extract setting the buttons in another function:</p>\n\n<pre><code>fun setRating(customView : View, ratingNr: Int){\n val views = listOf(\n customView.alert_rating1_img,\n customView.alert_rating2_img,\n customView.alert_rating3_img,\n customView.alert_rating4_img,\n customView.alert_rating5_img\n )\n\n //takes ratingNr buttons and turns them on.\n views.take(rating).forEach{ \n it.setImageResource(android.R.drawable.btn_star_big_on)\n }\n //drops ratingNr buttons and turns the rest of\n views.drop(rating).forEach{\n it.setImageResource(android.R.drawable.btn_star_big_off)\n }\n}\n</code></pre>\n\n<p>BTW, It's called a RatingBar.<br>\nYou can find multiple libraries on GitHub and you can find the build-in one <a href=\"https://developer.android.com/reference/kotlin/android/widget/RatingBar.html\" rel=\"nofollow noreferrer\">RatingBar</a>.</p>\n\n<h1>fetchRating</h1>\n\n<p>Kotlin has <a href=\"https://kotlinlang.org/docs/reference/operator-overloading.html\" rel=\"nofollow noreferrer\">operator overloadingin</a>. This means that <code>rating.div(counter)</code> can be rewritten as <code>rating/counter</code>.<br>\nNext, if you devide, only one side has to be an double in order to get a double as result. therefor, counter can be an int.</p>\n\n<h3>takeIf</h3>\n\n<p>Kotlin has a function named takeIf. It will return the receiver if the value is met and otherwise, it will return null.</p>\n\n<pre><code>if (opinions.toString() != \"null\" && opinions.toString() != \"[]\") {\n opinions.forEach { opinion ->\n counter++\n rating += opinion.get(\"rating\").toString().toInt()\n }\n}\n</code></pre>\n\n<p>can therefor be rewritten as</p>\n\n<pre><code>opionions\n .takeIf{it.toString() != \"null\" && it.toString() != \"[]\" }\n ?.forEach{...}\n</code></pre>\n\n<p>or using <a href=\"https://www.baeldung.com/kotlin-string-template#string-templates\" rel=\"nofollow noreferrer\">string interprolation</a></p>\n\n<pre><code>opionions\n .takeIf{\"$it\" != \"null\" && \"$it\" != \"[]\" }\n ?.forEach{...}\n</code></pre>\n\n<p>Next, you want to change the opions to a list of Int:</p>\n\n<pre><code>val intOpinions = opinions.map{ it.get(\"rating\").toString().toInt() }\n</code></pre>\n\n<p>Now you can simply calculate the average, using <a href=\"https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/average.html\" rel=\"nofollow noreferrer\">average</a> and the size using size.</p>\n\n<p>Average is a double and if you RatingBar, you need to have an Int to call our function. Therefor use <a href=\"https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.math/round-to-int.html\" rel=\"nofollow noreferrer\">roundToInt</a>.</p>\n\n<h1>checkIfVisited</h1>\n\n<pre><code>visitedZoos.forEach { zoo ->\n if (zoo == UID) {\n zoowall_add.text = \"Usuń z odwiedzonych\"\n flag = true\n }\n}\n</code></pre>\n\n<p>can be rewritten using <a href=\"https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/any.html\" rel=\"nofollow noreferrer\">any</a>:</p>\n\n<pre><code>val isVisited = visited.any { zoo == UID }\nif(isVisited) {\n zoowall_add.text = \"Usuń z odwiedzonych\"\n flag = true\n}\n</code></pre>\n\n<h1>coroutines:</h1>\n\n<p>using <a href=\"https://github.com/Kotlin/kotlinx.coroutines/tree/master/integration/kotlinx-coroutines-play-services\" rel=\"nofollow noreferrer\">kotlinx-coroutines-play-services</a>, you can replace </p>\n\n<pre><code>ref.get()\n .addOnsucceccListener{ value -> println(value) }\n .addOnFailureListener{ println(\"failure\") }\n</code></pre>\n\n<p>with</p>\n\n<pre><code>try {\n val value = ref.get().await()\n println(value)\n} catch(e : Exception) {\n println(\"failure\")\n}\n</code></pre>\n\n<p>To call coroutine-functions, you have to be in a coroutine-context.<br>\nIf you want to learn more about coroutine, follow <a href=\"https://codelabs.developers.google.com/codelabs/kotlin-coroutines/#0\" rel=\"nofollow noreferrer\">Google's Codelab</a>.<br>\nI think (don't know for sure), that they are also explained in the course In the comments of your question.\n<a href=\"https://github.com/Kotlin/anko/wiki/Anko-Layouts\" rel=\"nofollow noreferrer\">Anko-layouts</a> gives you easy access to coroutine-contexts.</p>\n\n<h1>Architecture</h1>\n\n<p>I will hint very slightly to the architecture.</p>\n\n<p>Everything should do one thing and one thing only. </p>\n\n<ul>\n<li>Your activity should therefor (almost) only deal with how the screen looks. </li>\n<li>Your firebase-calls should in their callbacks only format the data and give data back.</li>\n<li>There should be one or more classes that deal with the logic:\n\n<ul>\n<li>What should happens if a button is clicked.</li>\n<li>What data does the view need</li>\n<li>How to change the data in the format that the view can use</li>\n</ul></li>\n</ul>\n\n<p>The reason why I push you towards this architecture is that if you learn and stick to a good architecture, it will push you towards classes and functions that do one thing and one thing well. Therefor, your classes and functions will become a lot smaller and also more reuseable. Therefor your code will become better. Almost all you have to do for that is stick to the architecture.</p>\n\n<h1>note</h1>\n\n<p>I didn't look into firebase functions like <a href=\"https://firebase.google.com/docs/firestore/query-data/queries\" rel=\"nofollow noreferrer\">queries</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-17T11:19:34.120",
"Id": "461627",
"Score": "0",
"body": "Wow thank you so much <3 as soon as I correct this code I will post it in the comment. Have a good day!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-17T11:22:44.887",
"Id": "461628",
"Score": "0",
"body": "OK, then I will add an Update-header to my answer and review the new code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-16T13:27:27.227",
"Id": "235732",
"ParentId": "235622",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T20:11:12.570",
"Id": "235622",
"Score": "2",
"Tags": [
"android",
"kotlin",
"firebase"
],
"Title": "ZooRater mobile app. This code is responsible for displaying and handling zoo dashboard. Need general advice"
}
|
235622
|
<p>I have this program that takes two strings from the user, stores them in <code>mixArray</code>, then "mixes" them with <code>mixItUp()</code> and outputs a bit of flavor text, depending on the combination. Duplicate combinations (red-blue, blue-red) also give the same outcome.</p>
<p>I've gotten to a nested switch statement that's miles shorter than my previous tries, but I'm trying figure out if there's a more optimal, or readable method to do this, since I intend to scale it up.</p>
<pre class="lang-js prettyprint-override"><code>mixItUp() {
this.mixArray.sort(); // Sorts the array
switch (this.mixArray[0]) { // Goes through the first object
case "blue":
switch (this.mixArray[1]) { // Goes through the second if the first is "blue"
case "green":
console.log("bf");
break;
case "purple":
console.log("bg");
break;
case "yellow":
console.log("bp");
break;
default:
console.log("??");
break;
}
break;
case "green": // If [0] is "green"...
switch (this.mixArray[1]) {
case "purple":
console.log("fg");
break;
case "yellow":
console.log("fp");
break;
default:
console.log("??");
break;
}
break;
case "purple": // If [0] is "purple"...
switch (this.mixArray[1]) {
case "yellow":
console.log("gp");
break;
default:
console.log("??");
break;
}
break;
default:
break;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T22:55:51.930",
"Id": "461335",
"Score": "2",
"body": "Can you provide more context - what is the purpose of this code? See [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask), where you will find advice for titling your question, too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T22:59:31.193",
"Id": "461338",
"Score": "1",
"body": "The simplest fix I can think of would be to define the output strings in a single `const` object like so : ```const colors = {\n \"red\" : {\n \"red\" : \"a\",\n \"blue\" : \"b\",\n \"green\" : \"c\"\n },\n \"green\" : {\n \"red\" : \"x\",\n \"blue\" : \"y\",\n \"green\" : \"z\"\n }\n};``` then you can access them like this ```str[\"red\"][\"blue\"]```. I'd also recommend you make the function return a string which you then print in the program, rather than printing the output directly from the function; this makes it more flexible and easier to adapt/modify later."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T12:53:29.867",
"Id": "461400",
"Score": "0",
"body": "Thanks, @cliesens! Didn't even think of using a json object, but this works wonderfully and is way easier to read and change. Kudos!"
}
] |
[
{
"body": "<p>It seems this could be simplified with a small lookup table and then concatenating strings. Using a table as simple as:</p>\n\n<pre><code>const lookup = {\n blue: 'b',\n green: 'f',\n purple: 'g',\n yellow: 'p'\n};\n</code></pre>\n\n<p>we can then lookup the color values and concatenate them together. Combined with a simple check to make sure the color is valid and the 2 colors aren't the same, and it seems to produce the same result. </p>\n\n<p>Here's the full function:</p>\n\n<pre><code>mixItUp: function() {\n this.mixArray.sort();\n const lookup = {\n blue: 'b',\n green: 'f',\n purple: 'g',\n yellow: 'p'\n };\n\n let mix;\n const color1 = lookup[this.mixArray[0]];\n const color2 = lookup[this.mixArray[1]];\n\n if (color1 && color2 && (color1 !== color2)) {\n mix = `${color1}${color2}`;\n } else {\n mix = '??';\n }\n\n return mix;\n}\n</code></pre>\n\n<p>And here it is in action:</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>function createMix(color1, color2) {\n return {\n mixArray: [color1, color2],\n mixItUp: function() {\n this.mixArray.sort();\n const lookup = {\n blue: 'b',\n green: 'f',\n purple: 'g',\n yellow: 'p'\n };\n\n let mix;\n const color1 = lookup[this.mixArray[0]];\n const color2 = lookup[this.mixArray[1]];\n \n if (color1 && color2 && (color1 !== color2)) {\n mix = `${color1}${color2}`;\n } else {\n mix = '??';\n }\n\n return mix;\n }\n }\n}\n\n\n// Handle the form\nconst form = document.getElementById('mixitup');\n\nform.addEventListener('submit', event => {\n event.preventDefault();\n const color1 = document.getElementById('color1').value;\n const color2 = document.getElementById('color2').value;\n\n const mixedArray = createMix(color1, color2)\n console.log(mixedArray.mixItUp())\n})</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><form id=\"mixitup\">\n <select id=\"color1\">\n <option value=\"\">Select...</option>\n <option value=\"blue\">Blue</option>\n <option value=\"green\">Green</option>\n <option value=\"purple\">Purple</option>\n <option value=\"yellow\">Yellow</option>\n </select>\n <select id=\"color2\">\n <option value=\"\">Select...</option>\n <option value=\"blue\">Blue</option>\n <option value=\"green\">Green</option>\n <option value=\"purple\">Purple</option>\n <option value=\"yellow\">Yellow</option>\n </select>\n <input type=\"submit\" value=\"Mix it up!\">\n</form></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-01-18T00:20:38.907",
"Id": "235803",
"ParentId": "235624",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235803",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T20:46:03.050",
"Id": "235624",
"Score": "4",
"Tags": [
"javascript",
"performance",
"beginner",
"array",
"combinatorics"
],
"Title": "Outputting flavor text depending on inputted strings"
}
|
235624
|
<p>I am new to stackoverflow and a newbie to VBA coding. At my work, we are supplied with shipment data in the form of Ms Word which is not very useful. I have found a way to transfer the data using VBA and have a code that is fully functional. However, the data set contains hundreds of thousands of records. I tried running a month's worth of data with 200k records and it took 5 days. Just wondering if there is anything in my code that I could be improved to speed up the process. I've tried turning off screen updates, events, calculations but it didn't do much. Thanks in advance for your help.</p>
<pre><code>Sub Word_to_Excel()
Dim FName As String, FD As FileDialog
Dim wdApp As Object
Dim wdDoc As Object
Dim WDR, WDCheck, ShipmentID As Object
Dim ExR As Range
Dim file
Dim Path As String
Dim ImportDate As Object
Dim ImportValue As String
Dim ShipmentIDcheck As String
Dim objResult
Set objShell = CreateObject("WScript.Shell")
Set ExR = Selection ' current location in Excel Sheet
' Select Folder containing word documents
Set FD = Application.FileDialog(msoFileDialogFolderPicker)
FD.Show
FName = FD.SelectedItems(1)
file = Dir(FName & "\*.docx")
Set wdApp = CreateObject("Word.Application")
' Open word document in the folder, run macro, close it and open the next word document until there are none left
Do While file <> ""
wdApp.Documents.Open Filename:=FName & "\" & file
wdApp.ActiveWindow.ActivePane.View.Type = 1
wdApp.Visible = True
' Once the word doc is open, go to beginning of document and search for CTY/SITE/SORT:
wdApp.Selection.HomeKey Unit:=6
wdApp.Selection.Find.ClearFormatting
wdApp.Selection.Find.Execute "CTY/SITE/SORT:"
Set WDCheck = wdApp.Selection
' If "CTY/SITE/SORT:" is found, then look for Shipment ID
Do While WDCheck = "CTY/SITE/SORT:"
' Find first shipment
wdApp.Selection.HomeKey Unit:=5
wdApp.Selection.MoveDown Unit:=5, Count:=11
wdApp.Selection.MoveRight Unit:=1, Count:=1
wdApp.Selection.MoveRight Unit:=1, Count:=11, Extend:=1
Set ShipmentID = wdApp.Selection
ShipmentIDcheck = Replace(ShipmentID, " ", "")
' Transfer information from Word to Excel for a Shipment ID and go to the next one.
' Shipment ID should be a string that is 11 characters long
' If Shipment ID no longer exist, go to next page by searching for the next CTY/SITE/SORT:
Do While Len(Trim(ShipmentIDcheck)) = 11
i = i + 1
ExR(i, 1) = file
ExR(i, 2) = ShipmentIDcheck
' Consignee Name
wdApp.Selection.MoveUp Unit:=5, Count:=1
wdApp.Selection.MoveRight Unit:=1, Count:=12
wdApp.Selection.MoveRight Unit:=1, Count:=23, Extend:=1
Set WDR = wdApp.Selection
ExR(i, 3) = Trim(WDR)
' Importer Name
wdApp.Selection.MoveRight Unit:=1, Count:=2
wdApp.Selection.MoveRight Unit:=1, Count:=23, Extend:=1
Set WDR = wdApp.Selection
ExR(i, 8) = Trim(WDR)
' Shipper Name
wdApp.Selection.MoveRight Unit:=1, Count:=2
wdApp.Selection.MoveRight Unit:=1, Count:=23, Extend:=1
Set WDR = wdApp.Selection
ExR(i, 13) = Trim(WDR)
' Quantity
wdApp.Selection.MoveRight Unit:=1, Count:=2
wdApp.Selection.MoveRight Unit:=1, Count:=10, Extend:=1
Set WDR = wdApp.Selection
ExR(i, 19) = Trim(WDR)
' Weight
wdApp.Selection.MoveRight Unit:=1, Count:=2
wdApp.Selection.MoveRight Unit:=1, Count:=12, Extend:=1
Set WDR = wdApp.Selection
ExR(i, 20) = Trim(WDR)
' Value
wdApp.Selection.MoveRight Unit:=1, Count:=2
wdApp.Selection.MoveRight Unit:=1, Count:=12, Extend:=1
Set WDR = wdApp.Selection
ExR(i, 21) = Trim(WDR)
' Broker
wdApp.Selection.MoveRight Unit:=1, Count:=2
wdApp.Selection.MoveRight Unit:=1, Count:=11, Extend:=1
Set WDR = wdApp.Selection
ExR(i, 23) = Trim(WDR)
' Consignee Street
wdApp.Selection.HomeKey Unit:=5
wdApp.Selection.MoveDown Unit:=5, Count:=1
wdApp.Selection.MoveRight Unit:=1, Count:=13
wdApp.Selection.MoveRight Unit:=1, Count:=23, Extend:=1
Set WDR = wdApp.Selection
ExR(i, 4) = Trim(WDR)
' Importer Street
wdApp.Selection.MoveRight Unit:=1, Count:=2
wdApp.Selection.MoveRight Unit:=1, Count:=23, Extend:=1
Set WDR = wdApp.Selection
ExR(i, 9) = Trim(WDR)
' Shipper Street
wdApp.Selection.MoveRight Unit:=1, Count:=2
wdApp.Selection.MoveRight Unit:=1, Count:=23, Extend:=1
Set WDR = wdApp.Selection
ExR(i, 14) = Trim(WDR)
' Description
wdApp.Selection.MoveRight Unit:=1, Count:=8
wdApp.Selection.MoveRight Unit:=1, Count:=40, Extend:=1
Set WDR = wdApp.Selection
ExR(i, 18) = Trim(WDR)
' Consignee City
wdApp.Selection.HomeKey Unit:=5
wdApp.Selection.MoveDown Unit:=5, Count:=1
wdApp.Selection.MoveRight Unit:=1, Count:=13
wdApp.Selection.MoveRight Unit:=1, Count:=13, Extend:=1
Set WDR = wdApp.Selection
ExR(i, 5) = Trim(WDR)
' Consignee Province
wdApp.Selection.MoveRight Unit:=1, Count:=2
wdApp.Selection.MoveRight Unit:=1, Count:=2, Extend:=1
Set WDR = wdApp.Selection
ExR(i, 6) = Trim(WDR)
' Consignee Postal
wdApp.Selection.MoveRight Unit:=1, Count:=2
wdApp.Selection.MoveRight Unit:=1, Count:=6, Extend:=1
Set WDR = wdApp.Selection
ExR(i, 7) = Trim(WDR)
' Importer City
wdApp.Selection.MoveRight Unit:=1, Count:=2
wdApp.Selection.MoveRight Unit:=1, Count:=13, Extend:=1
Set WDR = wdApp.Selection
ExR(i, 10) = Trim(WDR)
' Importer Province
wdApp.Selection.MoveRight Unit:=1, Count:=2
wdApp.Selection.MoveRight Unit:=1, Count:=2, Extend:=1
Set WDR = wdApp.Selection
ExR(i, 11) = Trim(WDR)
' Importer Postal
wdApp.Selection.MoveRight Unit:=1, Count:=2
wdApp.Selection.MoveRight Unit:=1, Count:=6, Extend:=1
Set WDR = wdApp.Selection
ExR(i, 12) = Trim(WDR)
' Shipper City
wdApp.Selection.MoveRight Unit:=1, Count:=2
wdApp.Selection.MoveRight Unit:=1, Count:=13, Extend:=1
Set WDR = wdApp.Selection
ExR(i, 15) = Trim(WDR)
' Shipper Province
wdApp.Selection.MoveRight Unit:=1, Count:=2
wdApp.Selection.MoveRight Unit:=1, Count:=2, Extend:=1
Set WDR = wdApp.Selection
ExR(i, 16) = Trim(WDR)
' Shipper Postal
wdApp.Selection.MoveRight Unit:=1, Count:=2
wdApp.Selection.MoveRight Unit:=1, Count:=6, Extend:=1
Set WDR = wdApp.Selection
ExR(i, 17) = Trim(WDR)
' Country of Origin
wdApp.Selection.MoveRight Unit:=1, Count:=29
wdApp.Selection.MoveRight Unit:=1, Count:=21, Extend:=1
Set WDR = wdApp.Selection
ExR(i, 22) = Trim(WDR)
wdApp.Selection.HomeKey Unit:=5
wdApp.Selection.MoveDown Unit:=5, Count:=2
wdApp.Selection.MoveRight Unit:=1, Count:=1
wdApp.Selection.MoveRight Unit:=1, Count:=11, Extend:=1
Set ShipmentID = wdApp.Selection
' Remove spaces from selection. Selection is then used to check if it is a shipment ID.
' If it is, then data for that shipment ID is transferred. If not, macro will go to the next page in the Word Doc.
ShipmentIDcheck = Replace(ShipmentID, " ", "")
ActiveCell.Offset(1).Select
Loop
'Simulate keyboard press "NUMLOCK" to prevent screen from locking
objResult = objShell.SendKeys("{NUMLOCK}")
wdApp.Selection.HomeKey Unit:=5
wdApp.Selection.Find.ClearFormatting
wdApp.Selection.Find.Execute "CTY/SITE/SORT:"
Set WDCheck = wdApp.Selection
Loop
wdApp.ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
ActiveWorkbook.Save
file = Dir()
Loop
wdApp.Quit
MsgBox "Data extraction completed at:" & vbNewLine & Format(Now, "mmmm d, yyyy hh:mm AM/PM")
End Sub
</code></pre>
<p>This is how the data is formatted in Ms Word. There are multiple word documents containing pages and pages of this dataset per day. Number of shipments per page varies. But the format are the same throughout. There are no tables in the word documents, just text separated by spaces. CTY/SITE/SORT: is unique to every page and I used it as an anchor point. if the macro finds it, then it goes down 11 lines and takes the first shipment ID and the other information. It then checks for the next shipment ID. If it is not there, then it goes to the next page and repeats the process.</p>
<pre><code>REPORT NUM : ABC1234 OPERATIONS SYSTEM PAGE NUM: 2
CTY/SITE/SORT: CA 00123 SUMMARY CARGO RUN TIME: 07:33:43
SORT DATE : INBOUND - SCAN RUN DATE: 01AUG19
OPER ID : ABC123
MVMT: 12345678 MVMT DT: 01AUG19 MAWB: PROD TYP: DTY TYP: IMP CTY: EXP CTY: BL TYP:
COURIER REMISSION MANIFEST EXPORT SITE: US 12345
GCCN ID: EXPECTED SHPTS: EXPECTED PKGS: EXPECTED WEIGHT:
CUSTOMS NUM CONSIGNEE NAME IMPORTER NAME SHIPPER NAME CSA QTY WGT(LBS) VALUE BROKER
SHIPMENT ID DESCRIPTION (CAD) CTRY OF ORIGIN
JOHN SMITH ABC COMPANY XYZ COMPANY 1 1.1 1000.00 UNCONSIGNED
ABC12345678 123 MAIN STREET 345 RANDOM ROAD UNIVERSITY OF WASHINGTO BICYCLE PARTS
VANCOUVER BC V1A1A1 VANCOUVER BC V2B1B2 SEATTLE WA 981234 US
JOHN SMITH ABC COMPANY XYZ COMPANY 1 1.1 1000.00 UNCONSIGNED
ABC12345678 123 MAIN STREET 345 RANDOM ROAD UNIVERSITY OF WASHINGTO BICYCLE PARTS
VANCOUVER BC V1A1A1 VANCOUVER BC V2B1B2 SEATTLE WA 981234 US
JOHN SMITH ABC COMPANY XYZ COMPANY 1 1.1 1000.00 UNCONSIGNED
ABC12345678 123 MAIN STREET 345 RANDOM ROAD UNIVERSITY OF WASHINGTO BICYCLE PARTS
VANCOUVER BC V1A1A1 VANCOUVER BC V2B1B2 SEATTLE WA 981234 US
JOHN SMITH ABC COMPANY XYZ COMPANY 1 1.1 1000.00 UNCONSIGNED
ABC12345678 123 MAIN STREET 345 RANDOM ROAD UNIVERSITY OF WASHINGTO BICYCLE PARTS
VANCOUVER BC V1A1A1 VANCOUVER BC V2B1B2 SEATTLE WA 981234 US
TOTAL FOR DUTY TYPE COURIER REMISSION
TOTAL SHIPMENTS: 4
TOTAL PACKAGES : 4
TOTAL WEIGHT : 70.9 LBS
TOTAL VALUES : 4000.00
* * *
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T14:14:42.747",
"Id": "461421",
"Score": "1",
"body": "Is the word document laid out with tables? If so I'd consider plain copy-pasting the Word tables into a spreadsheet, and try processing that instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T15:42:30.360",
"Id": "461435",
"Score": "0",
"body": "no tables. it is laid out into columns and separated by spaces."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T15:56:22.037",
"Id": "461437",
"Score": "2",
"body": "Then I try text import. Anything but line-by-line, column-by-column processing ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-22T01:41:33.457",
"Id": "462131",
"Score": "0",
"body": "[the-macro-recorder-curse](https://rubberduckvba.wordpress.com/2019/06/30/the-macro-recorder-curse/) can be cured! And 200K data should be stored in a database!"
}
] |
[
{
"body": "<h2>Declarations</h2>\n\n<p>My first comment is <code>Option explicit</code>. <strong>Every. Single. Time.</strong> </p>\n\n<p>Your first line of code is :</p>\n\n<pre><code>Set objShell = CreateObject(\"WScript.Shell\")\n</code></pre>\n\n<p>Why? <code>objshell</code> is not declared or used. And while on the matter of declarations:</p>\n\n<pre><code>Dim WDR, WDCheck, ShipmentID As Object\n</code></pre>\n\n<p>declares <code>WDR</code> and <code>WDCheck</code> as Variant, not Object. </p>\n\n<p>Youi are writing a utility tool - using <em>early binding</em> instead of <em>late binding</em> will improve the code. (<code>Dim wdApp as Word.Application</code> : <code>Set wdApp = New Word.Application</code>, assuming you are running this from Excel).</p>\n\n<h2>Macro recorder</h2>\n\n<p>To me it is obvious you used the macro recorder and then simply copied the code to get what you wanted. In order to improve your code, look at each step that has been recorded (a couple of lines each time) to work out what is really happening</p>\n\n<p>You open a word document, but do not assign that open document to the declared variable <code>wdDoc</code>. Which should be declared as <code>Word.Document</code> not <code>Object</code>. Hint: <code>Word.Application.Documents.Open</code> returns a Document.</p>\n\n<p>Once you start looking at the recorded code and making sensible changes, you will stop working with the nebulous <code>Selection</code> and start working directly with defined objects that you can control better.</p>\n\n<h2>Approach</h2>\n\n<p>A good approach is to first clean the input data. This can be as simple as identifying the block of text to be imported, copying that to an intermediate work area (perhaps a temporary word document, or a work area in your excel file) and then setting up the data format to suit your next step (the direct import).</p>\n\n<p>What I have inferred from your code is that each column is separated by multiple spaces to create a nicely formatted output. So you can have two approaches here:</p>\n\n<ul>\n<li>replace those spaces with a known delimiter</li>\n<li>use the fixed column widths to do a text input into Excel (noted by\n@MathieuGuindon in the comments)</li>\n</ul>\n\n<p>The first approach is useful if there is no consistency between the documents. The second is useful if there is this consistency.</p>\n\n<p>Either way, at the end of these steps you have a consistent form of input data that you can now directly import into Excel. </p>\n\n<p>I have deliberately not included any example code. The initial steps of refactoring the macro-recorded code is great learning experience for yourself and is something that will give you good insight into how you can improve your own code.</p>\n\n<p>Looking forwards to the seeing the refactored code as a new article here for further review! </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T19:41:03.827",
"Id": "235691",
"ParentId": "235625",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T22:04:10.147",
"Id": "235625",
"Score": "2",
"Tags": [
"vba",
"excel"
],
"Title": "How to speed up VBA to Extract data from Word to Excel"
}
|
235625
|
<p>(I hope this isn't too general a question given I'm just pasting a bunch of code in, if that's the case then sorry)</p>
<p><em>edited to remove the bit that wasn't working</em></p>
<p>I've written a brute force implementation of the N-body simulation in Python with a leapfrog integration method (using numpy & numba's jit function to speed it up) but I'm not sure it's as well-written as it could be. Any comment on how I've done the various parts of this would be much appreciated, or any technique I'm missing to speed the code up or make it 'better'.</p>
<p>Bonus, please tell me if I've got any obvious rookie errors in my code!</p>
<p>The following code is my gravsim module which is then called by the second bit of code:</p>
<pre><code>import numpy as np
from numba import jit
"""
units:
G = 1
All other units can be defined as needed
"""
# G = 6.67430e-11
G = 1
@jit(nopython=True)
def force_point(location, m, masses, positions, eps, soft):
"""
calculates gravitational force & GPE on an object at a location
* both are softened by epsilon *
Inputs:
location: 1x3 array (location of point you want to measure, cartesian)
m: float (mass of object)
masses: Nx1 array
positions: Nx3 array (cartesian)
eps: float (softening constant) [assumes eps = 0]
soft: bool (True = softening considered, False = not)
Outputs:
force: 1x3 array
gpe: float
"""
force = np.zeros((1, 3))
gpe = 0.0
for j in range(len(masses)):
rj = positions[j, :]
dr = rj - location # vector distance between location & j
dist_sq = (dr ** 2).sum() # scalar distance between i & j squared
softened_dist_sq = dist_sq + (eps ** 2)
force_j = dr * (G * m * masses[j] / (softened_dist_sq ** (3 / 2)))
force += force_j
if soft:
gpe -= G * m * masses[j] / np.sqrt(softened_dist_sq)
else:
gpe -= G * m * masses[j] / np.sqrt(dist_sq)
return (force, gpe)
@jit(nopython=True)
def force_calculator(masses, positions, eps):
"""
calculates: force due to gravity between N objects.
Inputs:
masses: Nx1 array
positions: Nx3 array (cartesian)
velocities: Nx3 array (only used for working out velocity
of combined particles)
combined: dict - set of combined particles
eps: float (softening constant) [assumes eps = 0]
Outputs:
forces: Nx3 array (cartesian)
gpe: Nx1 array
"""
forces = np.zeros_like(positions) # 3-vector
gpe = np.zeros_like(masses) # scalar
for i in range(len(masses)):
for j in range(i + 1, len(masses)):
ri = positions[i, :]
rj = positions[j, :]
dr = rj - ri # vector distance between i & j
dist_sq = np.sum(dr ** 2) # scalar distance between i & j squared
softened_dist = (dist_sq + (eps ** 2)) ** (3 / 2)
force_ij = dr * (G * masses[i] * masses[j] / softened_dist)
forces[i, :] += force_ij
forces[j, :] += force_ij * -1
gpe_ij = -1 * G * masses[i] * masses[j] / (np.sqrt(dist_sq) + eps)
gpe[i] += gpe_ij
gpe[j] += gpe_ij
return (forces, gpe)
@jit(nopython=True)
def one_step(timestep, masses, mass3, positions, velocities, eps):
"""
takes a set of masses, with positions & velocities, calc's force on them
then finds positions & velocities at next timestep, using leapfrog
integration method
Inputs:
timestep: float
masses: Nx1 array
mass3: Nx3 array (for matrix ops see below)
positions: Nx3 array (cartesian)
velocities: Nx3 array (cartesian)
eps: float (softening constant) [assume eps = 0]
currently, can't figure out how to add an ext field as an optional variable
with numba (type is specified at runtime, so can't fuck with it)
Outputs:
r_update: Nx3 array of new positions (cartesian)
v_update: Nx3 array of new velocities (cartesian)
forces: Nx3 array of new forces (cartesian)
kinetic: Nx1 array of KE's for position 2
gpe: Nx1 array of GPE's for position 1
mass3 is an Nx3 array of masses ie. {[m1 m1 m1] / [m2 m2 m2] / ...}
this allows matrix ops to be used to update velocity & position which are
quicker than looping
"""
forces, gpe = force_calculator(masses, positions, eps)
v_update = velocities + (forces * timestep / mass3)
v_half = velocities + (forces * 0.5 * timestep / mass3)
v_half_mag_sq = np.array([(v_half[i, :] ** 2).sum() for i in range(len(masses))])
r_update = positions + v_update * timestep
kinetic = 0.5 * masses * v_half_mag_sq
return (r_update, v_update, forces, kinetic, gpe)
@jit(nopython=True)
def timeloop(nsteps, timestep, masses, positions, velocities, eps):
"""
repeats the one-step process for n steps and records params at each step
into Nx3x(nsteps) arrays
Inputs:
nsteps: int
timestep: float
masses: Nx1 array
positions: Nx3 array (cartesian)
velocities: Nx3 array (cartesian)
eps: float (softening constant) [assume eps = 0]
Outputs:
r_times: Nx3x(nsteps) array (positions)
v_times: Nx3x(nsteps) array (velocities)
f_times: Nx3x(nsteps) array (forces)
kinetic: Nx1x(nsteps) array
gpe: Nx1x(nsteps) array
"""
kinetic = np.empty((nsteps + 1, len(masses)))
kinetic[0, :] = (
0.5
* masses
* np.array([(velocities[i, :] ** 2).sum() for i in range(len(masses))])
)
gpe = np.empty((nsteps + 1, len(masses)))
"""
in one_step, GPE is calc'ed for starting position but KE is calc'ed
after the advance; so ke[0] must be calc'ed here. We will not have a final
GPE until it's specifically calculated at the end.
"""
r_times = np.zeros((nsteps + 1, len(masses), 3))
v_times = np.zeros((nsteps + 1, len(masses), 3))
f_times = np.zeros((nsteps + 1, len(masses), 3))
r_times[0, :, :] += positions
v_times[0, :, :] += velocities
"""
this creates Nx3x(nsteps) arrays by making a list of arrays then using
np.stack to form an array from the list, after setting the 1st array to
the initial input values
Reference r/v_times with [timestep, particle no, axis no]
e.g. 1st timestep, 5th particle, y axis: [0,4,1]
"""
mass3 = np.zeros((len(masses), 3))
for i, mass in enumerate(masses):
mass3[i, :] = [mass for p in range(3)]
for n in range(nsteps):
(
r_times[n + 1, :, :],
v_times[n + 1, :, :],
f_times[n, :, :],
kinetic[n + 1, :],
gpe[n, :],
) = one_step(
timestep, masses, mass3, r_times[n, :, :], v_times[n, :, :], eps,
)
f_times[-1, :, :], gpe[-1, :] = force_calculator(masses, r_times[-1, :, :], eps)
# for final step, we don't need update x, v or ke, just force & gpe
return (r_times, v_times, f_times, kinetic, gpe)
</code></pre>
<p>The second file is basically the simplest implementation, of 100 particles randomly in a 20x20x20 box with 0 initial velocity.</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
from gravsim import timeloop
import matplotlib.pyplot as plt
plt.style.use("seaborn-dark")
# initial conditions
steps = 1000
dt = 0.02
eps = 0.1
n = 100
m = np.ones(n)
radius = 10
rs = np.random.uniform(-radius, radius, size=(n, 3))
vs = np.zeros_like(rs)
# info
print("{} objects".format(n))
print("cube radius = {}".format(radius))
print("total time = {}".format(steps * dt))
print("softening = {}".format(eps))
# initial state scatter
f_in, a_in = plt.subplots(1, 1)
a_in.scatter(rs[:, 0], rs[:, 1], s=10)
# timeloop
xt, vt, ft, kt, gt = timeloop(steps, dt, m, rs, vs, eps)
k_sums = np.sum(kt, axis=1)
g_sums = np.sum(gt, axis=1)
e_total = k_sums + g_sums
virial = 2 * k_sums + g_sums
# system energy plot
f_e, a_e = plt.subplots(1, 1)
a_e.plot(k_sums, label="K")
a_e.plot(g_sums, label="U")
a_e.plot(e_total, label="K+U")
a_e.plot(virial, label="2K+U")
a_e.legend()
f_e.tight_layout()
# state at intervals scatter
f_xy, a_xy = plt.subplots(2, 3)
plot_nums = np.linspace(0, steps, num=6, dtype=int)
for i, num in enumerate(plot_nums):
if i < 3:
a_xy[0, i].scatter(xt[num, :, 0], xt[num, :, 1], s=10)
else:
a_xy[1, i - 3].scatter(xt[num, :, 0], xt[num, :, 1], s=10)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T22:13:09.023",
"Id": "461329",
"Score": "1",
"body": "`gpe -= ... / np.sqrt(dist_sq)`, _ect_, are you sure that `dist_sq` is not close to zero?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T22:21:38.543",
"Id": "461331",
"Score": "0",
"body": "That's in the force_point function which finds the force and gpe at a point in space due to a set of objects, and yes `dist` can tend to 0 but this can be dealt with by having `soft=True`. I did realise I missed the softening in force_calculator which is added, but doesn't change the outcome of running the code (also edited the post for some clarity too)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T13:06:31.827",
"Id": "461402",
"Score": "1",
"body": "\"Also, the kinetic energy seems orders of magnitude too large but I can't see where the issue with my calculation is.\" So, it produces the wrong answer? If that's so, the code isn't ready for review yet. Please take a look at the [help/on-topic]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T16:38:42.280",
"Id": "461445",
"Score": "0",
"body": "I didn't know that, sorry - but I fixed the small error so it works now, so it's acceptable now I updated the code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T20:17:34.467",
"Id": "461481",
"Score": "0",
"body": "I think that's better; would probably be easy to change the text and the title to make it on-topic. I'd like to see the answers, since this is relevant to my field of study."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-14T22:06:40.983",
"Id": "235626",
"Score": "5",
"Tags": [
"python",
"beginner"
],
"Title": "N-body brute force python bodies disappearing to infinity"
}
|
235626
|
<p>I built a tree in <code>Haskell</code> where every node has a number that is unique in its path from root to leaf. Nodes have a dedicated list for children that are leaves. Because the tree is very large I want to unify (i.e. keep the right one, replace the left one with a link) sub trees that are equal by some metric. For this and similar tasks I wrote the <code>treewalker</code> function that walks through all nodes of a certain depth and applies a function that has access to already visited nodes via a generic cache.</p>
<p><code>treewalker</code> can then be called with several functions that specify how to process each node. In the example provided I link to already seen sub trees whose path is a permutation of the path to the current node. But I use several other functions with different purposes, so I want to keep the cache general and the function that is applied to each node as well.</p>
<pre><code>{-# Language ScopedTypeVariables #-} -- needed for treewalker
data LinkedTree = LinkedNode Int -- index of node
[Int] -- leaf indices
[LinkedTree] -- children
| Link Int -- index of node
[Int] --path to the linked node
deriving (Show, Eq, Ord)
newtype Path = Path [Int]
newtype ListCache a = ListCache [a]
type PathCache = ListCache Path
class Cache a where
cacheAdd :: b -> a b -> a b
emptyCache :: a b
instance Cache ListCache where
cacheAdd p (ListCache x) = ListCache (p:x)
emptyCache = ListCache []
-- walks through all nodes of specified depth and applies a function
treeWalker :: forall c a. (Cache c) => (LinkedTree -> [Int] -> c a -> (LinkedTree, c a)) -- function to apply on every node of desired depth
-> Int --depth
-> LinkedTree
-> LinkedTree
treeWalker processNode desiredDepth lnode = fst $ helper [] emptyCache lnode
where
helper :: [Int] -- path up until now, excluding current node, [level k, ..., level 1, root]
-> c a
-> LinkedTree
-> (LinkedTree, c a)
helper _ cache (Link is p) = (Link is p, cache) -- there may be links already e.g. from a previous run with different parameters
helper path cache (LinkedNode is lis children) | tooShortNoChildren = (LinkedNode is lis [], cache) -- path ends too soon, return cache as is
| notDeepEnoughYet = (LinkedNode is lis children', cache') --not deep enough, recurse
| atDesiredDepth = processNode (LinkedNode is lis children) path cache
| otherwise = error "unexpected"
where
tooShortNoChildren = length path < desiredDepth && null children
notDeepEnoughYet = length path < desiredDepth
atDesiredDepth = length path == desiredDepth
(children', cache') = foldl g ([], cache) children -- we use fold because we need the first childs result for the second child
g :: ([LinkedTree], c a) -> LinkedTree -> ([LinkedTree], c a)
g (processed, cache) lt = (processed++[p2], c2)
where
p2 :: LinkedTree
c2 :: c a
(p2,c2) = (helper (head is:path)) cache lt
setPermutationLinks :: Int -> LinkedTree -> LinkedTree
setPermutationLinks = treeWalker processNode
where
processNode :: LinkedTree -> [Int] -> PathCache -> (LinkedTree, PathCache)
processNode ln@(LinkedNode is _ _) path cache = case query cache of
Nothing -> (ln, cacheAdd fullPath cache) --return node as is, add path to cache
Just cpath -> (Link is $ reverse cpath, cache) --return link, and unchanged cache
where
currentPathMatches (a:as) = head is == a -- both end in the same node
&& Set.fromList path == Set.fromList as -- remaining are identical
fullPath = Path $ head is:path
query :: PathCache -> Maybe [Int] -- its in the cache or not
query (ListCache []) = Nothing
query (ListCache (Path a:as)) | currentPathMatches a = Just a
| otherwise = query $ ListCache as
</code></pre>
<p>The above code works, but I found it hard to come up with and difficult to debug. Is there a clearer way of implementing this?</p>
|
[] |
[
{
"body": "<p><code>tooShortNoChildren</code> is subsumed in <code>notDeepEnoughYet</code>. The newtypes and class are silly, discard them. <code>treeWalker</code> doesn't touch <code>cache</code>, so let's hide <code>cache</code> in a monadic interface.</p>\n\n<pre><code>-- walks through all nodes of specified depth and applies a function\ntreeWalker :: ([Int] -> LinkedTree -> State [a] LinkedTree) -- function to apply on every node of desired depth\n -> Int -> LinkedTree -> LinkedTree\ntreeWalker processNode desiredDepth = (`evalState` []) . helper [] processnode\n where\n helper :: Monad m => [Int] -- path up until now, excluding current node, [level k, ..., level 1, root]\n -> ([Int] -> LinkedTree -> m LinkedTree)\n -> LinkedTree -> m LinkedTree\n helper _ cache (Link is p) = (Link is p, cache) -- there may be links already e.g. from a previous run with different parameters\n helper path cache ln@(LinkedNode is lis children) =\n if length path == desiredDepth\n then processNode path cache ln\n else LinkedNode is lis <$> traverse (helper (head is:path)) children\n</code></pre>\n\n<p>The explicit recursion has the form of a fold.</p>\n\n<pre><code>-- walks through all nodes of specified depth and applies a function\ntreeWalker :: ([Int] -> LinkedTree -> State [a] LinkedTree) -- function to apply on every node of desired depth\n -> Int -> LinkedTree -> LinkedTree\ntreeWalker processNode desiredDepth = (`evalState` []) . foldr ($) processNode (replicate desiredDepth step) []\n where\n -- Makes a node processor work at one level deeper.\n -- The path excludes the current node and has form [level k, ..., level 1, root].\n step :: Monad m => ([Int] -> LinkedTree -> m LinkedTree) -> [Int] -> LinkedTree -> m LinkedTree\n step _ _ l@(Link _ _) = return l\n step f path ln@(LinkedNode is lis children) = LinkedNode is lis <$> traverse (f . (head is:)) children\n</code></pre>\n\n<p>I'd inline that.\nI'll assume that comparing <code>a:as</code> and <code>head is:path</code> is enough. I'll also assume that as according to <code>LinkedNode</code>s definition, its first parameter has type <code>Int</code>, not <code>[Int]</code>.</p>\n\n<pre><code>setPermutationLinks :: Int -> LinkedTree -> LinkedTree \nsetPermutationLinks desiredDepth = (`evalState` []) . foldr ($) processNode (replicate desiredDepth liftThroughTree) [] where\n processNode :: [Int] -> LinkedTree -> State [[Int]] LinkedTree\n processNode path ln@(LinkedNode i _ _) = gets (find $ (Set.fromList (i:path) ==) . Set.fromList) >>= \\case\n Nothing -> modify ((i:path):) >> return ln\n Just cpath -> return $ Link i $ reverse cpath\n liftThroughTree :: Monad m => ([Int] -> LinkedTree -> m LinkedTree) -> [Int] -> LinkedTree -> m LinkedTree\n liftThroughTree _ _ l@(Link _ _) = return l\n liftThroughTree f path ln@(LinkedNode i lis children) = LinkedNode i lis <$> traverse (f . (i:)) children\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T17:04:37.690",
"Id": "461448",
"Score": "0",
"body": "Yes, `LinkedNode` has `Int` as first parameter, I simplified my code while typing it out and forgot to change it there. Should be fixed now."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T15:24:47.337",
"Id": "235676",
"ParentId": "235631",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T01:01:10.157",
"Id": "235631",
"Score": "4",
"Tags": [
"haskell",
"tree"
],
"Title": "Manipulate a tree layer wise"
}
|
235631
|
<p>I was playing the game <a href="https://www.nytimes.com/puzzles/set" rel="nofollow noreferrer">Set</a> online, and thought it would be a good exercise to write an F# script to find all of the sets for me. </p>
<p>The rules of set are as follows:
<em>A SET is 3 cards for which each feature is either common across all 3 cards or is different on each card. The object is to find all the SETs among the cards.</em></p>
<p>I started learning F# four days ago, so <strong>what I'm looking for are obvious/easy/"no duh" improvements</strong>. I've started at a low bar of just writing a function to compare a group of three cards, and tell you if those three cards form a set. You can see my first attempt below. It feels a bit clunky, like I'm not really making use of all that F# has to offer. </p>
<pre class="lang-ml prettyprint-override"><code>// Create a record type to represent each card
type Card =
{ Color: string
Shape: string
Pattern: string
Number: int
}
// Create some functions for comparing elements of a collection
let allEqual l = l |> Seq.pairwise |> Seq.forall (fun (x, y) -> x = y)
let allDifferent l = (l |> Seq.distinct |> Seq.length) = (Seq.length l)
// Combine them
let isSet l = (allEqual l) || (allDifferent l)
// The meat of this script
let compare card1 card2 card3 =
// Put the cards together for easy iteration
let cardList = [card1; card2; card3]
// Check each field of the record to see if it makes a set
let colorSet = cardList |> List.map (fun c -> c.Color ) |> isSet
let shapeSet = cardList |> List.map (fun c -> c.Shape ) |> isSet
let patternSet = cardList |> List.map (fun c -> c.Pattern) |> isSet
let numsSet = cardList |> List.map (fun c -> c.Number ) |> isSet
// Check that they all make a set
colorSet && shapeSet && patternSet && numsSet
// Test the functions out
let c1 = {Color = "blue"; Shape = "oval"; Pattern = "stripes"; Number = 3}
let c2 = {Color = "red"; Shape = "diamond"; Pattern = "solid"; Number = 2}
let c3 = {Color = "green"; Shape = "squiggle"; Pattern = "empty"; Number = 2}
let areCardsSet = compare c1 c2 c3
printfn "The cards c1, c2, and c3 are a set? %b" areCardsSet
</code></pre>
|
[] |
[
{
"body": "<p>Well, you're off to a good start, I think. Only one major thing comes to mind, when I read your code.</p>\n\n<h1>Tuples</h1>\n\n<p>Instead of operating on <code>seq</code>s or similar, use a tuple. The size of a tuple is fixed and known at compile time. In this game, you know you'll always consider three cards at a time, so it fits the bill. This will also help simplify your <code>allEqual</code> and <code>allDifferent</code> functions. The <code>isSet</code> function still works, as the parameter <code>l</code> is now a tuple instead of a <code>seq</code>.</p>\n\n<pre><code>let allEqual (c1, c2, c3) = c1 = c2 && c2 = c3\nlet allDifferent (c1, c2, c3) = c1 <> c2 && c2 <> c3 && c1 <> c3\n</code></pre>\n\n<p>This affects the shape of your <code>compare</code> function as well. The line</p>\n\n<pre><code>let colorSet = cardList |> List.map (fun c -> c.Color ) |> isSet\n</code></pre>\n\n<p>now becomes like</p>\n\n<pre><code>let colorSet = isSet (card1.Color, card2.Color, card3.Color)\n</code></pre>\n\n<p>and similar for <code>shapeSet</code>, <code>patternSet</code> and <code>numsSet</code>. Now the <code>cardList</code> variable may be removed, and the <code>compare</code> function is short and to the point.</p>\n\n<h1>Abstracting the <code>isSet</code> function</h1>\n\n<p>Suppose you think the way the <code>colorSet</code>, <code>shapeSet</code>, etc. variables are defined looks to clunky. You could abstract away the commonalities, by defining a function for getting the <code>Color</code> property and so on. These could then be supplied as arguments to the <code>isSet</code>, <code>allEqual</code> and <code>allDifferent</code> functions . Like this:</p>\n\n<pre><code>let color c = c.Color\n// ...\nlet allEqual feature (c1, c2, c3) = feature(c1) = feature(c2) && feature(c2) = feature(c3)\n// ...\nlet cards = (card1, card2, card3)\nlet colorSet = isSet color cards\n// ...\n</code></pre>\n\n<p>I've only shown a couple of the required functions above, but I hope you get the point. In a small example like this, this might be overkill, but had you had many more features, I would probably go that way.</p>\n\n<h1>Discriminated unions</h1>\n\n<p>One last point is, that it would be obvious to use discriminated unions instead of <code>string</code> and <code>int</code>. I.e. you could define types for each feature, and use them in the <code>Card</code> definition</p>\n\n<pre><code>type Color = Green | Blue | Red\ntype Number = One | Two | Three\n// ...\ntype Card = { Color: Color; Number: Number; ... }\n</code></pre>\n\n<p>This will help readability of your code. Furthermore, if this should interact with the outside would, where input comes in the shape of <code>string</code>s, it pushes parsing and validation to the boundary layer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T07:45:59.107",
"Id": "235634",
"ParentId": "235632",
"Score": "5"
}
},
{
"body": "<p>There isn't much to add to torbondes answer except the following details:</p>\n\n<blockquote>\n<pre><code>// Check each field of the record to see if it makes a set\nlet colorSet = cardList |> List.map (fun c -> c.Color ) |> isSet\nlet shapeSet = cardList |> List.map (fun c -> c.Shape ) |> isSet\nlet patternSet = cardList |> List.map (fun c -> c.Pattern) |> isSet\nlet numsSet = cardList |> List.map (fun c -> c.Number ) |> isSet\n\n// Check that they all make a set\ncolorSet && shapeSet && patternSet && numsSet\n</code></pre>\n</blockquote>\n\n<p>In the above you actually evaluate all properties of the cards before returning the result by \"and-ing\" them. The <code>&&-operator</code> evaluates from left to right, so if <code>colorSet = false</code> then the values of the others are skipped and so on. Therefore it would be an optimaization if you only caculate each property if needed. To do that, you could make each of the <code>xxxSet</code> bindings be functions instead as in:</p>\n\n<pre><code>// Check each field of the record to see if it makes a set\nlet colorSet _ = cardList |> List.map (fun c -> c.Color ) |> isSet\nlet shapeSet _ = cardList |> List.map (fun c -> c.Shape ) |> isSet\nlet patternSet _ = cardList |> List.map (fun c -> c.Pattern) |> isSet\nlet numsSet _ = cardList |> List.map (fun c -> c.Number ) |> isSet\n\n// Check that they all make a set\ncolorSet() && shapeSet() && patternSet() && numsSet()\n</code></pre>\n\n<p>Here each property set is only called if the preceding set are true.</p>\n\n<hr>\n\n<p>Another optimization would be to put the repeated code <code>cardList |> List.map (fun c -> c.Color ) |> isSet</code> into a function:</p>\n\n<pre><code>let isValid selector = cardList |> List.map selector |> isSet\n</code></pre>\n\n<p>and then call it as:</p>\n\n<pre><code>// Check each field of the record to see if it makes a set\nlet checkColors _ = isValid (fun c -> c.Color)\nlet shapeSet _ = isValid (fun c -> c.Shape)\nlet patternSet _ = isValid (fun c -> c.Pattern)\nlet numsSet _ = isValid (fun c -> c.Number)\n\n// Check that they all make a set\ncheckColors () && shapeSet () && patternSet () && numsSet ()\n</code></pre>\n\n<p>... or simply just do:</p>\n\n<pre><code>let compare card1 card2 card3 =\n // Put the cards together for easy iteration\n let cardList = [card1; card2; card3]\n\n let isValid selector = cardList |> List.map selector |> isSet\n\n // Check each field of the record to see if it makes a set\n isValid (fun c -> c.Color)\n && isValid (fun c -> c.Shape)\n && isValid (fun c -> c.Pattern)\n && isValid (fun c -> c.Number)\n</code></pre>\n\n<hr>\n\n<p>Yet another optimization could be to only run through the cards once and collect the properties in sets by using <code>List.fold</code> and the <code>Set</code> type instead of a <code>List</code>:</p>\n\n<pre><code>let compare cards =\n let length = cards |> List.length // Optimization because List.length is an O(n) operation\n\n let isValid s = s |> Set.count = 1 || s |> Set.count = length\n\n cards \n |> List.fold (\n fun (clrs, shps, pats, nums) card -> \n clrs |> Set.add card.Color,\n shps |> Set.add card.Shape,\n pats |> Set.add card.Pattern,\n nums |> Set.add card.Number\n ) (Set.empty, Set.empty, Set.empty, Set.empty)\n |> fun (c, s, p, n) -> isValid c && isValid s && isValid p && isValid n\n</code></pre>\n\n<p>The benefit of using <code>Set</code> instead of <code>List</code> is that it is <code>distinct</code> by design, so it's sufficient to directly check if the set contains one or three elements. </p>\n\n<p>That said I would prefer torbondes more static approach because the number of cards and properties aren't likely to change.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-17T17:39:10.233",
"Id": "235791",
"ParentId": "235632",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235634",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T01:39:27.113",
"Id": "235632",
"Score": "3",
"Tags": [
"f#"
],
"Title": "Solving the game Set in F#"
}
|
235632
|
<p>I am generating co-occurrence matrix (2000X2000) in Python.</p>
<ul>
<li>Vocab is a list of the 2000 top words in corpus. It does not contain all words in corpus.</li>
<li><p>Corpus is a Pandas dataframe of 30000 (rows) sentences.<br>
An example of a single row in the corpus:</p>
<blockquote>
<p>the energy classroom high the room filled scholars eager learn they embarking learning journey unlike no these scholars asked learn time rapidly changing technology communication as teacher job give tools successful our school special always looking ways give students best education possible my 4th grade students counting provide tools necessary success i want keep love learning alive giving students access technology critical success 21st century learning environment our school 1 3 ratio ipads kids we use variety apps allow kids collaborate build critical thinking skills even though ipads keyboard ipad cumbersome difficult kids use therefore i asking 15 keyboards plug ipads having wired keyboard allows kids practice keyboarding skills standard collaborate others effectively utilize technology accesskeyboards enhance collaboration choice critical thinkin</p>
</blockquote></li>
</ul>
<p>My code is currently taking 120s per iteration and 364 hours to complete run.
I am running this code in Google Colab with 25GB RAM.</p>
<p>The code works fine with small data like 10 row corpus and 5 word vocab.
Is there a better way to complete this task or speed up this process?</p>
<p><code>tqdm</code> is required because if the code runs for longer than 12 hours, which it is, then it gets disconnected from Google Colab.</p>
<pre class="lang-py prettyprint-override"><code>coocur_matrix = np.zeros((len(voca), len(voca)),np.float64)
</code></pre>
<pre><code>#python
from tqdm import tqdm
window_size=5
corpus=corpu1
vocab = voca
for word1 in tqdm(vocab):
for word2 in vocab:
for sent in corpus:
doc_tokens = []
doc_tokens=sent.split()
p1= [i for i in range(len(doc_tokens)) if doc_tokens[i] == word1]
p2= [i for i in range(len(doc_tokens)) if doc_tokens[i] == word2]
for k in p1:
print(9)
for l in p2:
if (abs(l-k)<=window_size):
if(word1!=word2):
coocur_matrix[vocab.index(word1),vocab.index(word2)] += 1
print(coocur_matrix)
</code></pre>
|
[] |
[
{
"body": "<h1>Readability</h1>\n\n<p>Your code is visually unappealing. You have multiple PEP 8 violations, and your variable names really don't speak volumes. You have 2 spaces of indentation which is pretty much un-heard of in Python. If we move your code into a function and perform a little clean up we can get something like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import numpy as np\n\n\ndef get_indexes(tokens, word):\n return [\n index\n for index, token in enumerate(tokens)\n if token == word\n ]\n\n\ndef co_occurrence_matrix(corpus, vocabulary, window_size=5):\n matrix = np.zeros((len(vocabulary), len(vocabulary)), np.float64)\n for word_1 in vocabulary:\n for word_2 in vocabulary:\n for sent in corpus:\n tokens = sent.split()\n tokens_1 = get_indexes(tokens, word_1)\n tokens_2 = get_indexes(tokens, word_2)\n for k in tokens_1:\n for l in tokens_2:\n if abs(l - k) > window_size:\n continue\n if word_1 == word_2:\n continue\n matrix[\n vocabulary.index(word_1),\n vocabulary.index(word_2),\n ] += 1\n return matrix\n\n\nprint(co_occurrence_matrix(corpu1, voca))\n</code></pre>\n\n<h1>Performance</h1>\n\n<p>Now It doesn't look too bad, but it doesn't really look nice. From here we can see clearly that <code>word_1</code> and <code>word_2</code> are defined in the first two loops, however the check <code>word_1 == word_2</code> is on the inner-most level of the loops. This means you're needlessly looping over <code>sent</code>, <code>tokens_1</code> and <code>tokens_2</code>. These loops, totalling around 12000000, are useless and a waste of time.</p>\n\n<p>It can be hard to see, but <code>vocabulary.index(word_1)</code> has a <code>for</code> loop in it. How else is it getting the index? This means you're looping 2000 times, this is a waste as you can define a variable to store the index when looping through <code>vocabulary</code>.</p>\n\n<p>You don't need to iterate over <code>vocabulary</code>, you can just iterate over <code>corpus</code>. This is because if <code>word_1</code> or <code>word_2</code> is not in <code>tokens</code> then the for loop will iterate over an empty list and so will do nothing. And so we can derive <code>word_1</code> and <code>word_2</code> from <code>corpus</code>.</p>\n\n<p>Since <code>vocabulary</code> only contains the top 2000 words in the <code>corpus</code>. Then a naïve flip of the loops is still going to waste some cycles. And so we can just filter <code>sent</code> to ones in the <code>vocabulary</code>. To achieve this I opted to use a closure as I think it makes the code cleaner and easier to read. This is because I don't have the walrus on Python 3.7 and wanted to use <code>dict.get</code> rather than perform <em>two</em> dictionary lookups per filter of each token.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import numpy as np\nimport itertools\n\n\ndef by_indexes(iterable):\n output = {}\n for index, key in enumerate(iterable):\n output.setdefault(key, []).append(index)\n return output\n\n\ndef co_occurrence_matrix(corpus, vocabulary, window_size=5):\n def split_tokens(tokens):\n for token in tokens:\n indexs = vocabulary_indexes.get(token)\n if indexs is not None:\n yield token, indexs[0]\n\n matrix = np.zeros((len(vocabulary), len(vocabulary)), np.float64)\n vocabulary_indexes = by_indexes(vocabulary)\n\n for sent in corpus:\n tokens = by_indexes(split_tokens(sent.split())).items()\n for ((word_1, x), indexes_1), ((word_2, y), indexes_2) in itertools.permutations(tokens, 2):\n for k in indexes_1:\n for l in indexes_2:\n if abs(l - k) <= window_size:\n matrix[x, y] += 1\n return matrix\n\n\nprint(co_occurrence_matrix(corpu1, voca))\n</code></pre>\n\n<p>This currently isn't fully optimized, as you can use <code>combinations</code> rather than <code>permutations</code> but that would require mirroring the non-empty values of the matrix. That would likely half the time it takes to run, but would require additional code.</p>\n\n<p>This is answer is entirely hypothetical. This means using <code>dict[]</code> twice rather than <code>dict.get</code> may be faster. It also means that many of the assumptions I made may not translate into performance benefits due to the way Python is.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T09:13:52.617",
"Id": "461370",
"Score": "0",
"body": "Thanks for the detailed reply. i am getting this error. `ValueError: too many values to unpack (expected 2)` for line `---> 18 for (word_1, indexes_1), (word_2, indexes_2) in itertools.permutations(tokens):`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T09:28:12.903",
"Id": "461372",
"Score": "0",
"body": "@sai That's a fairly easy thing to fix. You've not answered my latest question, so I see no point in fixing this for you to then complain that something else may not work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T10:09:22.707",
"Id": "461378",
"Score": "0",
"body": "hey sorry i didn't see your comment. I've fixed this error. Thank you so much for answering this. I'll make sure my code is readable from next time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T10:55:20.697",
"Id": "461382",
"Score": "0",
"body": "@sai No problem, I have updated the answer. It includes the fix for the error you highlighted earlier, and includes a fix to not error when you come across a word not defined in vocabulary. The second fix occurs earlier to attempt to reduce wasted cycles."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T07:52:51.470",
"Id": "235635",
"ParentId": "235633",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "235635",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T06:48:13.180",
"Id": "235633",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "Generating a co-occurrence matrix"
}
|
235633
|
<p>I wrote a simple wrapper for the <code><random></code> header, as follows:</p>
<pre><code>#include <random>
namespace Random
{
static int getInt(int min, int max)
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> distribution(min, max);
int rnd = distribution(gen);
return rnd;
}
static float getFloat(float min, float max)
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> distribution(min, max);
float rnd = distribution(gen);
return rnd;
}
}
</code></pre>
<p>I basically just want to know: <strong>is there a better / more efficient way to do it?</strong></p>
<p>I know for a fact that it works quite well, but I am no expert. I thank you in advance for your answers.</p>
|
[] |
[
{
"body": "<p>You might be able to save the overhead of constructing a new generator on each call, with something like:</p>\n\n<pre><code>static std::mt19937 default_generator(std::random_device{}());\n\nstatic int getInt(int min, int max)\n{\n return std::uniform_int_distribution{min, max}(default_generator);\n}\n</code></pre>\n\n<p>But, given that most uses require several values from a single distribution and there's rarely a need to use more than one generator, is this header really worth its cognitive load? Each function is a one-liner, and even less if the distribution can be re-used over several calls.</p>\n\n<p>We'd also expect to have versions for longer or unsigned integer types, and for <code>double</code> and other floating-point types. It probably makes more sense for it to be a template:</p>\n\n<pre><code>#include <random>\n#include <type_traits>\n\ntemplate<typename T>\ninline T getUniformRandom(T min, T max)\n{\n static std::mt19937 default_generator(std::random_device{}());\n if constexpr (std::is_integral_v<T>) {\n return std::uniform_int_distribution{min, max}(default_generator);\n } else if constexpr (std::is_floating_point_v<T>) {\n return std::uniform_real_distribution{min, max}(default_generator);\n }\n\n static_assert(0, \"getUniformRandom requires an arithmetic type\");\n return min+max; // just to eliminate compiler warnings\n}\n</code></pre>\n\n<p>Alternatively, use <code>std::enable_if</code> instead of <code>if constexpr</code>:</p>\n\n<pre><code>#include <random>\n#include <type_traits>\n\ntemplate<typename T>\ninline std::enable_if_t<std::is_integral_v<T>, T> getUniformRandom(T min, T max)\n{\n static std::mt19937 default_generator(std::random_device{}());\n return std::uniform_int_distribution{min, max}(default_generator);\n}\n\ntemplate<typename T>\ninline std::enable_if_t<std::is_floating_point_v<T>, T> getUniformRandom(T min, T max)\n{\n static std::mt19937 default_generator(std::random_device{}());\n return std::uniform_real_distribution{min, max}(default_generator);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T09:06:53.253",
"Id": "461368",
"Score": "1",
"body": "The real problem is that it is intended that there is only one PRNG (or at least a small number of PRNGs) and `random_device` is intended to be called once to seed the PRNG, rather than creating new PRNGs each time. which is solved by `static`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T10:21:53.563",
"Id": "461380",
"Score": "0",
"body": "Yes, that's right. We might need one PRNG per thread, but certainly not one per call."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T08:42:04.930",
"Id": "235640",
"ParentId": "235636",
"Score": "3"
}
},
{
"body": "<p>Just to expand on Toby's response, the two functions are basically</p>\n\n<pre><code>static ArithmeticType getAritmeticType(ArithmeticType min, ArithmeticType max)\n{\n std::random_device rd;\n std::mt19937 gen(rd());\n UniformDistributionType distribution(min, max);\n\n ArithmeticType rnd = distribution(gen);\n\n return rnd;\n}\n</code></pre>\n\n<p>All of the duplicate code leaps out while the arithmetic type and distribution type (which depends on the arithmetic type) change. An alias may be used to switch to the appropriate uniform distribution based on the provided arithmetic type.</p>\n\n<pre><code>template <typename ArithmeticType>\nusing uniform_distribution = typename std::conditional<\n std::is_integral<ArithmeticType>::value,\n std::uniform_int_distribution<ArithmeticType>,\n std::uniform_real_distribution<ArithmeticType>\n >::type;\n\ntemplate <typename ArithmeticType>\nstatic ArithmeticType getAritmeticType(ArithmeticType min, ArithmeticType max)\n{\n std::random_device rd;\n std::mt19937 gen(rd());\n return uniform_distribution<ArithmeticType>{min, max}(gen);\n}\n</code></pre>\n\n<p>Side note: Consider how others will use this function. </p>\n\n<ul>\n<li>There is nothing in the name <code>getInt/Float</code> that documents how the numbers are being generated (first? random?) or how distributed the possible results are. We already know it gets an <code>int</code>/<code>float</code> by its signature. What does the function actually do?</li>\n<li>The user may not even want to use <code>std::mt19937</code> or may want to reuse an existing psuedo-random bit generator.</li>\n<li>The user may want to use a fixed seed for testing. </li>\n<li><code>std::random_device</code> may actually be deterministic depending on the sources of entropy an implementation uses. It can also throw at any time for all sorts of reasons.</li>\n<li>Users are forced to use a poorly-initialized Mersenne Twister. <code>std::random_device</code> only produces a single 32-bit integer. A single 32-bit integer provides <span class=\"math-container\">\\$2^{32}\\$</span> possible initialization states. * Mersenne Twister needs 624 32-bit integers of seed to be properly initialized, which is provided when you seed with <code>std::seed_seq</code>. The result is a generator that is both easily predictable and biased.</li>\n</ul>\n\n<p>Consider allowing the user to pass the generator.</p>\n\n<pre><code>template <typename ArithmeticType>\nusing uniform_distribution = typename std::conditional<\n std::is_integral<ArithmeticType>::value,\n std::uniform_int_distribution<ArithmeticType>,\n std::uniform_real_distribution<ArithmeticType>\n >::type;\n\ntemplate <typename ArithmeticType, typename RandomBitGenerator>\nArithmeticType uniform_rand(RandomBitGenerator& gen,\n ArithmeticType min,\n ArithmeticType max)\n{\n return uniform_distribution<ArithmeticType>{min, max}(gen);\n}\n</code></pre>\n\n<blockquote>\n <p>I basically just want to know: is there a better / more efficient way to do it?</p>\n</blockquote>\n\n<p>Yes. There are non-standard distributions and pseudo-random bit generators that are better/more efficient. Daniel Lemire published a paper in late 2018 going over <a href=\"https://arxiv.org/pdf/1805.10941.pdf\" rel=\"nofollow noreferrer\">a faster approach to generating random integers in a range</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-16T05:38:27.937",
"Id": "235712",
"ParentId": "235636",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "235640",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T08:14:15.873",
"Id": "235636",
"Score": "2",
"Tags": [
"c++"
],
"Title": "c++ Pseudo-random generator wrapper"
}
|
235636
|
<p>I have written the following code for doing a reverse dns lookup. I'm not sure if there are any errors in it. Please have a look:</p>
<pre><code>#include <stdio.h> //for printf()
#include <stdlib.h> //for exit()
#include <arpa/inet.h> //for inet_pton()
#include <netdb.h> // for NI_MAXHOST, getnameinfo() and gai_strerror()
#include <errno.h> // for errno
#include <string.h> // for strerror()
int main(int argc, char** argv) {
if(argc<2) {
printf("\n%s [IP]\n",argv[0]);
printf("For e.g. %s 10.32.129.77\n",argv[0]);
exit(-1);
}
struct sockaddr_in sa;
int res = inet_pton(AF_INET, argv[1] , &sa.sin_addr);
switch(res) {
case 0: printf("\nInput address is not a valid IPv4 address.\n");
case -1: if(res == -1)
printf("\nError(%s)\n",strerror(errno));
int n_res = inet_pton(AF_INET6, argv[1] , &sa.sin_addr);
switch(n_res) {
case 0: printf("\nInput address is not a valid IPv6 address.\n");
case -1: if(n_res == -1)
printf("\nError(%s)\n",strerror(errno));
exit(-1);
case 1: sa.sin_family = AF_INET6;
}
case 1: sa.sin_family = AF_INET;
}
printf("\nsa.sin_addr.s_addr[%d]\n",sa.sin_addr.s_addr);
char node[NI_MAXHOST];
memset(node,0,NI_MAXHOST);
res = getnameinfo((struct sockaddr*)&sa, sizeof(sa), node, sizeof(node), NULL, 0, 0);
if (res) {
printf("%s\n", gai_strerror(res));
exit(1);
}
printf("\nIP[%s]\n",argv[1]);
printf("HOSTNAME[%s]\n", node);
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>It's generally best to divide your code into separate sections (possibly separate functions) for argument handling and actual computation.</p>\n\n<p>Errors should be printed to standard error rather than standard output. Also, prefer small integer values for exit status (and since we're in <code>main()</code>, we can use simple <code>return</code> rather than <code>exit()</code> - note the useful <code>EXIT_FAILURE</code> macro for the return value).</p>\n\n<p>It's worth documenting case fallthroughs. This one is especially suspect:</p>\n\n<blockquote>\n<pre><code> case 1: sa.sin_family = AF_INET6;\n }\n case 1: sa.sin_family = AF_INET;\n }\n</code></pre>\n</blockquote>\n\n<p>After we store <code>AF_INET6</code>, it's immediately overwritten with <code>AF_INET</code> - is that really intended?</p>\n\n<p>This fallthrough would be clearer as two independent cases:</p>\n\n<blockquote>\n<pre><code> case 0:\n printf(\"\\nInput address is not a valid IPv6 address.\\n\");\n /* fallthrough */\n case -1:\n if (n_res == -1)\n printf(\"\\nError(%s)\\n\",strerror(errno));\n exit(-1);\n</code></pre>\n</blockquote>\n\n<p>Compare:</p>\n\n<pre><code> case 0:\n fprintf(stderr, \"\\nInput address is not a valid IPv6 address.\\n\");\n return 1;\n case -1:\n fprintf(stderr, \"\\nError(%s)\\n\", strerror(errno));\n return 1;\n</code></pre>\n\n<p>This line seems to be no use to a user:</p>\n\n<blockquote>\n<pre><code>printf(\"\\nsa.sin_addr.s_addr[%d]\\n\",sa.sin_addr.s_addr);\n</code></pre>\n</blockquote>\n\n<p>We check for <code>argv</code> less than 2, but we neither complain about nor use any excess arguments.</p>\n\n<p>There's no need to null out the <code>node</code> storage, as <code>getnameinfo()</code> will either fail (in which case we'll never access it) or write a valid string.</p>\n\n<p>Minor (grammar): don't use \"for\" with \"e.g.\" - that reads like, \"for for example\".</p>\n\n<hr>\n\n<p>When I tried running the program, I found it wouldn't work at all with IPv6 addresses, because <code>sockaddr_in</code> is too small for IPv6 addresses. I had to totally rewrite with a union of address types:</p>\n\n<pre><code>#include <arpa/inet.h> //for inet_pton()\n#include <netdb.h> // for NI_MAXHOST, getnameinfo() and gai_strerror()\n\n#include <errno.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nstatic int convert4(struct sockaddr_in *sa, const char *name)\n{\n return inet_pton(sa->sin_family = AF_INET, name, &sa->sin_addr);\n}\n\nstatic int convert6(struct sockaddr_in6 *sa, const char *name)\n{\n return inet_pton(sa->sin6_family = AF_INET6, name, &sa->sin6_addr);\n}\n\n\nint main(int argc, char** argv)\n{\n if (argc != 2) {\n fprintf(stderr, \"Usage: %s [IP]\\nE.g. %s 10.32.129.77\\n\", argv[0], argv[0]);\n return EXIT_FAILURE;\n }\n\n union {\n struct sockaddr sa;\n struct sockaddr_in s4;\n struct sockaddr_in6 s6;\n struct sockaddr_storage ss;\n } addr;\n\n if (convert4(&addr.s4, argv[1]) != 1 && convert6(&addr.s6, argv[1]) != 1) {\n fprintf(stderr, \"%s: not a valid IP address.\\n\", argv[1]);\n return EXIT_FAILURE;\n }\n\n char node[NI_MAXHOST];\n int res = getnameinfo(&addr.sa, sizeof addr, node, sizeof node, NULL, 0, NI_NAMEREQD);\n if (res) {\n fprintf(stderr, \"%s: %s\\n\", argv[1], gai_strerror(res));\n return EXIT_FAILURE;\n }\n\n puts(node);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T12:29:49.027",
"Id": "461393",
"Score": "0",
"body": "Thanks for your corrections and suggestions. Btw what's the purpose of including sockaddr_storage in the union?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T12:33:36.277",
"Id": "461396",
"Score": "0",
"body": "`struct sockaddr_storage` isn't required for this program (I just copied wholesale from [How to fill sockaddr_storage?](//stackoverflow.com/q/21883030)), but just helps demonstrate that the union is large enough for any address type. You can safely remove it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T10:18:17.583",
"Id": "235647",
"ParentId": "235639",
"Score": "10"
}
},
{
"body": "<h1>Use <code>getaddrinfo()</code></h1>\n\n<p><code>getnameinfo()</code> has a counterpart: <code>getaddrinfo()</code>. Prefer to use that instead of having to call <code>inet_pton()</code> multiple times. You can force it to only allow numerical IP addresses as input. Here is how it would work:</p>\n\n<pre><code>struct addrinfo *ai;\nstruct addrinfo hints = {\n .ai_flags = AI_NUMERICHOST,\n .ai_family = AF_UNSPEC,\n};\n\nint res = getaddrinfo(argv[1], NULL, &hints, &ai);\nif (res) {\n fprintf(stderr, \"%s: %s\\n\", argv[1], gai_strerror(res));\n return 1;\n}\n\nchar node[NI_MAXHOST];\nres = getnameinfo(ai->ai_addr, ai->ai_addrlen, node, sizeof node, NULL, 0, NI_NAMEREQD);\nfreeaddrinfo(ai);\n\nif (res) {\n fprintf(stderr, \"%s: %s\\n\", argv[1], gai_strerror(res));\n exit(1);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T18:11:29.803",
"Id": "235688",
"ParentId": "235639",
"Score": "8"
}
},
{
"body": "<p>Your code uses an inconsistent style for its spacing. Sometimes you write <code>if (cond)</code> and sometimes <code>if(cond)</code>. You should pick either style and stick to it.</p>\n\n<p>I am assuming that you prefer a condensed writing style because in several cases you don't even leave a space after a comma. In that case, you should consistently apply this condensed style, and your code should look like:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include<errno.h>\n#include<stdio.h>\n#include<stdlib.h>\n#include<string.h>\n#include<arpa/inet.h>\n#include<netdb.h>\nint main(int c,char**v){if(c<2){printf(\"\\n%s [IP]\\n\",v[0]);printf(\"For e.g. %\"\n\"s 10.32.129.77\\n\",v[0]);exit(-1);}struct sockaddr_in sa;int res=inet_pton(\nAF_INET,v[1],&sa.sin_addr);switch(res){case 0:printf(\"\\nInput address is not a\"\n\" valid IPv4 address.\\n\");case-1:if(res==-1)printf(\"\\nError(%s)\\n\",strerror(\nerrno));int n_res=inet_pton(AF_INET6,v[1],&sa.sin_addr);switch(n_res){case 0:\nprintf(\"\\nInput address is not a valid IPv6 address.\\n\");case-1:if(n_res==-1)\nprintf(\"\\nError(%s)\\n\",strerror(errno));exit(-1);case 1:sa.sin_family=AF_INET6;\n}case 1:sa.sin_family=AF_INET;}printf(\"\\nsa.sin_addr.s_addr[%d]\\n\",sa.sin_addr.\ns_addr);char node[NI_MAXHOST];memset(node,0,NI_MAXHOST);res=getnameinfo((struct\nsockaddr*)&sa,sizeof sa,node,sizeof node,NULL,0,0);if(res){printf(\"%s\\n\",\ngai_strerror(res));exit(1);}printf(\"\\nIP[%s]\\n\",v[1]);printf(\"HOSTNAME[%s]\\n\",\nnode);return 0;}\n</code></pre>\n\n<p>This code style is unreadable for anyone. There is a fun <a href=\"https://ioccc.org/\" rel=\"nofollow noreferrer\">competition that encourages this code style</a>, but other than that, it's useless.</p>\n\n<p>On the other hand, when you take an arbitrary IDE (integrated development environment) and tell it to format your code (it's often just a single keyboard shortcut), it will come up with something like this:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include <errno.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <arpa/inet.h>\n#include <netdb.h>\n\nint main(int argc, char **argv)\n{\n if (argc < 2) {\n printf(\"\\n%s [IP]\\n\", argv[0]);\n printf(\"For e.g. %s 10.32.129.77\\n\", argv[0]);\n exit(-1);\n }\n\n struct sockaddr_in sa;\n int res = inet_pton(AF_INET, argv[1], &sa.sin_addr);\n switch (res) {\n case 0:\n printf(\"\\nInput address is not a valid IPv4 address.\\n\");\n case -1:\n if (res == -1)\n printf(\"\\nError(%s)\\n\", strerror(errno));\n\n int n_res = inet_pton(AF_INET6, argv[1], &sa.sin_addr);\n switch (n_res) {\n case 0:\n printf(\"\\nInput address is not a valid IPv6 address.\\n\");\n case -1:\n if (n_res == -1)\n printf(\"\\nError(%s)\\n\", strerror(errno));\n exit(-1);\n case 1:\n sa.sin_family = AF_INET6;\n }\n case 1:\n sa.sin_family = AF_INET;\n }\n printf(\"\\nsa.sin_addr.s_addr[%d]\\n\", sa.sin_addr.s_addr);\n\n char node[NI_MAXHOST];\n memset(node, 0, NI_MAXHOST);\n res = getnameinfo((struct sockaddr *)&sa, sizeof sa, node, sizeof node, NULL, 0, 0);\n if (res) {\n printf(\"%s\\n\", gai_strerror(res));\n exit(1);\n }\n\n printf(\"\\nIP[%s]\\n\", argv[1]);\n printf(\"HOSTNAME[%s]\\n\", node);\n\n return 0;\n}\n</code></pre>\n\n<p>I manually added some empty lines to split the code into logical sections, to give the reader a time to breathe. This style is much more common and can be read easily by any C programmer.</p>\n\n<p>The remaining issues have already been covered in the other answers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-17T04:13:53.423",
"Id": "461602",
"Score": "0",
"body": "Your application is not consistent: it should be `#include<errno.h>` and `int main(int c,char**v)` (note the removed space). (trying to pretend I'm not joking)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-17T06:00:23.443",
"Id": "461604",
"Score": "0",
"body": "Thanks, I fixed the inconsistencies."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T20:52:57.277",
"Id": "235699",
"ParentId": "235639",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "235647",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T08:24:38.780",
"Id": "235639",
"Score": "10",
"Tags": [
"c",
"linux"
],
"Title": "C program for 'Reverse DNS lookup'"
}
|
235639
|
<p>I am trying to create a word-finder game. There will be an n-by-n Board filled with Tiles. </p>
<pre><code>class Tile:
empty = None
def __init__(self, letter):
self.letter = letter
#the dictionary tracks the Tiles that border a given Tile
self.directionals = {'n':Tile.empty, 's':Tile.empty, 'w':Tile.empty, 'e':Tile.empty, 'nw':Tile.empty, 'ne':Tile.empty, 'sw':Tile.empty, 'se':Tile.empty}
class Board:
def __init__(self, length, chars=''):
self.length = length
self.grid = [[] for _ in range(length)]
for i in range(length):
for _ in range(length):
new_tile = Tile(randomchar()) #assume randomchar() returns a random character each time
self.grid[i].append(new_tile)
for i in range(length):
for j in range(length):
tile = self.grid[i][j]
if i - 1 >= 0:
tile.directionals['n'] = self.grid[i - 1][j]
if i + 1 < length:
tile.directionals['s'] = self.grid[i + 1][j]
if j - 1 >= 0:
tile.directionals['w'] = self.grid[i][j - 1]
if j + 1 < length:
tile.directionals['e'] = self.grid[i][j + 1]
if i - 1 >= 0 and j - 1 >= 0:
tile.directionals['nw'] = self.grid[i - 1][j - 1]
if i - 1 >= 0 and j + 1 < length:
tile.directionals['ne'] = self.grid[i - 1][j + 1]
if i + 1 < length and j - 1 >= 0:
tile.directionals['sw'] = self.grid[i + 1][j - 1]
if i + 1 < length and j + 1 < length:
tile.directionals['se'] = self.grid[i + 1][j + 1]
</code></pre>
<p>Starting from any Tile, the player will be able to create a word by traversing through unvisited Tiles. After successfully creating a word, the Tiles used to compose that word are reset. For example on a 4-by-4 Board:</p>
<pre><code> start player makes 'some' new Tiles represented by '*'
[[L A P S], [[L A P S], [[L A P S],
[R O S E], ------> [R O S ], ------> [R O S *],
[T I M E], [T I E], [T I * E],
[S O F T]] [ F T]] [* * F T]]
</code></pre>
<p>Throughout the game, I want to ensure the Board has a minimum number of words able to be made. I want to have the functionality to choose the reset Tiles such that they form words with neighboring Tiles, or else the number of available words on the Board may fall below the threshold. </p>
<p>To accomplish this, I implemented the below function. </p>
<pre><code>def dfs(tile, word, min_word_length=2, max_word_length=5):
visited = []
def helper(tile, word):
if len(word) > max_word_length:
return
if tile in visited:
return
#allwords is a list with all the words in the English dictionary
if word in allwords and len(word) >= min_word_length:
print(word)
visited.append(tile)
for direction in tile.directionals.values():
if direction is not Tile.empty and direction not in visited:
helper(direction, word + direction.letter)
visited.remove(tile)
helper(tile, word)
</code></pre>
<p>I would create Tiles with random letters for the Tiles needing to be reset, applying the dfs function after each Tile is plugged in to see if a valid word is formed. However, the current implementation is too inefficient: it struggles when max_word_length exceeds 5, exponentially more so on larger boards. </p>
<p>How can I change my implementation so that it'd be more efficient? Ideally, I would like the resetting to happen almost immediately (< 1 second). I was thinking of incorporating memoization, but am not sure how to in this case. </p>
|
[] |
[
{
"body": "<h1>Obfuscation</h1>\n\n<p><code>Tile.empty</code> is a long, verbose way of saying <code>None</code>. Each time you use it, the Python interpreter must look up <code>Tile</code> in <code>locals()</code>, and then <code>globals()</code>, to find the <code>Tile</code> class object. Then, it needs to look up <code>empty</code> in the <code>Tile</code> dictionary to find the value <code>None</code>. If you simply used <code>None</code>, your code would be faster, because <code>None</code> is a keyword; no heroic efforts are needed by the Python interpreter to determine what this value is.</p>\n\n<h1>Dictionary of None values</h1>\n\n<p>From the minimal code which has been presented, there is no compelling reason to store each direction in <code>self.directionals</code>. Instead of a direction key returning <code>None</code> (or <code>Tile.empty</code>), that direction could simply not exist in the dictionary. The top-left corner would only contain directions \"e\", \"se\", and \"s\". This would simply this code:</p>\n\n<pre><code> for direction in tile.directionals.values():\n if direction is not Tile.empty and direction not in visited:\n ...\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code> for direction in tile.directionals.values():\n if direction not in visited:\n ...\n</code></pre>\n\n<p>One less check means less work, and faster performance.</p>\n\n<p>Finally, since you keep asking for <code>tile.directional.values()</code>, you might consider storing these values in their own collection:</p>\n\n<pre><code> tile.valid_directionals = set(tile.directionals.values())\n</code></pre>\n\n<p>or, if you must store all 8 directions:</p>\n\n<pre><code> tile.valid_directionals = set(value for value in tile.directionals.values()\n if value is not Tile.empty)\n</code></pre>\n\n<p>and then using:</p>\n\n<pre><code> for direction in tile.valid_directionals:\n if direction not in visited:\n ...\n</code></pre>\n\n<p>Using a <code>set</code> instead of a <code>dict_values</code> iterator may not be any faster, but I'll be taking advantage of it later.</p>\n\n<h1>List Comprehension</h1>\n\n<pre><code> self.grid = [[] for _ in range(length)]\n\n for i in range(length):\n for _ in range(length):\n new_tile = Tile(randomchar()) #assume randomchar() returns a random character each time\n self.grid[i].append(new_tile)\n</code></pre>\n\n<p>is a long, round about way of writing:</p>\n\n<pre><code> self.grid = [[Tile(randomchar()) for _ in range(length)] for _ in range(length)]\n</code></pre>\n\n<p>Whenever you create a <code>list</code>, and then <code>append</code> to it in a loop, consider using list comprehension instead. It is a powerful tool for your tool chest.</p>\n\n<h1>Simplify Tests</h1>\n\n<p>Consider <code>i - 1 >= 0</code>. The Python Interpreter must lookup the value <code>i</code>, subtract 1 from it, which involves constructing a new <code>int</code> object, or since all the values are going to be small, looking up an interned version. Then, the value is compared to zero, and discarded. Consider the equivalent expression <code>i >= 1</code>, or even <code>i > 0</code>. Look up the value and compare to a constant. No subtraction operation required, no new integer object required for the result, and no discarding of the result of the subtraction after being used. This is still in your executed once initialization code, so performance doesn't matter much, but why be sloppy?</p>\n\n<h1>Searching too deep</h1>\n\n<p>Your <code>helper</code> function looks approximately like:</p>\n\n<pre><code> def helper(tile, word):\n if len(word) > max_word_length:\n return\n\n ...\n\n for direction in tile.directionals.values():\n if ...:\n helper(direction, word + direction.letter)\n</code></pre>\n\n<p>Imagine if we've called the helper a few times, and we've just recursed in with <code>word=\"TRAPS\"</code>. We start looping around the tiles around the <code>S</code>, skipping the visited tiles, and call <code>helper(direction, \"TRAPS\" + direction.letter)</code> with <code>direction.letter</code> taking on the values <code>'O'</code>, <code>'I'</code>, <code>'M'</code>, <code>'E'</code>, <code>'E'</code> and <code>'S'</code>. In each call, the first thing we do is check <code>len(word) > max_word_length</code>, and return if <code>True</code>. With <code>max_word_length = 5</code>, every one of those calls will immediately return! There is no point iterating to the <code>len(word) == 6</code> depth! If we checked for this earlier, we could eliminate many useless calls, and save time.</p>\n\n<pre><code> def helper(tile, word):\n\n ...\n\n if len(word) < max_word_length:\n for direction in tile.directionals.values():\n if ...:\n helper(direction, word + direction.letter)\n</code></pre>\n\n<h1>Redundancy</h1>\n\n<p>Furthermore:</p>\n\n<pre><code>def helper(tile, word):\n ...\n if tile in visited: \n return\n ...\n for direction in tile.directionals.values():\n if direction not in visited:\n helper(direction, word + direction.letter)\n</code></pre>\n\n<p>You test <code>direction not in visited</code>, and only if that is true will you call <code>helper(direction, ...)</code>. In that recursive call, the <code>tile in visited</code> test will therefore never be true. You can remove that redundant check for better performance.</p>\n\n<h1>Containment Testing</h1>\n\n<pre><code> #allwords is a list with all the words in the English dictionary\n if word in allwords and len(word) >= min_word_length: \n ...\n</code></pre>\n\n<p>First of all, English can contain some really long words, like \"tetraiodophenolphthalein\". We should shorten this dictionary to words which are <code>max_word_length</code> and less.</p>\n\n<pre><code>possible_words = [word for word in allwords\n if min_word_length <= len(word) <= max_word_length]\n</code></pre>\n\n<p>With this, my dictionary size is reduced from 235,886 words down to 17,082. And a smaller dictionary will speed things up.</p>\n\n<p>But what will speed things up more is getting rid of that <code>list</code>. Testing if a word is in a <code>list</code> is an <span class=\"math-container\">\\$O(n)\\$</span> operation. If the words were stored in a <code>set</code>, this reduces search complexity to an <span class=\"math-container\">\\$O(1)\\$</span> operation.</p>\n\n<pre><code>possible_words = set(word for word in allwords\n if min_word_length <= len(word) <= max_word_length)\n</code></pre>\n\n<p>Then, containment testing is easy:</p>\n\n<pre><code> if word in possible_words: \n ...\n</code></pre>\n\n<p><code>word in possible_words</code> doesn't look much different from <code>word in allwords</code>, but the speed-up going from <code>x in list</code> to <code>x in set</code> is quite dramatic.</p>\n\n<p>What about the <code>and len(word) >= min_word_length</code> condition? Where did it go? <code>possible_words</code> only contains words which are at least <code>min_word_length</code>, so we get that for free!</p>\n\n<h1>Pruning the Search Tree</h1>\n\n<p>Alright, I'm finally where I actually wanted to be to answer this question. The fun part.</p>\n\n<p>How many words in the English dictionary start with <code>\"RL\"</code>? What about <code>\"MS\"</code> or <code>\"FM\"</code> or <code>\"TF\"</code>? Plenty of words start with <code>\"SM\"</code> but no words start with `\"SMF\".</p>\n\n<p>As you are collecting the tile letters into a candidate word, you test whether you have discovered a word, but not whether you've reached a combination which will not start any word. Doing so will prune you search tree, and avoid checking around <span class=\"math-container\">\\$6^3\\$</span> candidate words starting with <code>\"RL\"</code>. Less searching, yields faster performance!</p>\n\n<p>So, how do we prune?</p>\n\n<p>Consider the word <code>\"SOME\"</code>. If we start with <code>\"S\"</code>, we have a possible word. If we start with <code>\"SO\"</code>, we have a possible word. If we start with <code>\"SOM\"</code>, we have a possible word. And if we start with <code>\"SOME\"</code> we have a possible word. So for each word in our <code>possible_words</code>, we just need to collect all the possible prefixes for the word into a set.</p>\n\n<pre><code>valid_prefixes = set(word[:size]\n for word in possible_words for size in range(1, length(word))\n</code></pre>\n\n<p>With this set of valid prefixes, if our candidate word fragment is not a valid prefix, we can skip deeper searching of that branch:</p>\n\n<pre><code> for direction in tile.directionals.values():\n if direction not in visited:\n candidate = word + direction.letter\n if candidate in valid_prefixes:\n helper(direction, candidate)\n</code></pre>\n\n<h1>The tile.valid_directionals set</h1>\n\n<p>Almost forgot. <code>visited</code> is a <code>list</code>. If we switch this into a set, then we can use set arithmetic to get a set of valid_directionals that haven't been visited with <code>valid_directionals - visited</code></p>\n\n<pre><code>def dfs(tile, word, min_word_length=2, max_word_length=5):\n visited = set()\n\n def helper(tile, word):\n if word in possible_words: \n print(word)\n\n if len(word) < max_word_length:\n visited.add(tile)\n for direction in tile.valid_directionals - visited:\n candidate = word + direction.letter\n if candidate in valid_prefixes:\n helper(direction, candidate)\n visited.remove(tile)\n\n helper(tile, word)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-17T05:18:19.907",
"Id": "461603",
"Score": "0",
"body": "You’ve accepted the answer. Does this mean you’re not getting “exponentially longer times for larger boards”? Is your reset below 1 second? How have performance changed?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-16T02:41:04.960",
"Id": "235707",
"ParentId": "235641",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "235707",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T08:59:38.887",
"Id": "235641",
"Score": "3",
"Tags": [
"python",
"graph",
"depth-first-search",
"memoization"
],
"Title": "Creating valid words on an n-by-n grid of characters using depth-first search"
}
|
235641
|
<p>This is the backend code for the page where you upload a post. I have already tried to do a sql attack on this page, but it didn't work.</p>
<pre class="lang-php prettyprint-override"><code><?php
include_once 'includes1/dbh.inc.php';
session_start();
//*skåd ifall man är inloggad *//
if (isset($_POST['topic_submit'])) {
$newFileName = "annons"; //Här ska egentligen vara $_POST['topic_title'];//
if (empty($newFileName)) {
$newFileName = "annons";
} else {
$newFileName = strtolower(str_replace(" ", "-", $newFileName));
}
$cid = $_POST['cid'];
$title = $_POST['topic_title'];
$content = $_POST['topic_content'];
$creator = $_SESSION['UserName'];
$imageNamn = $_POST['filenamn'];
$imageMail = $_POST['filemail'];
$imageNummer = $_POST['filenummer'];
$imagePris = $_POST['filepris'];
$imagestad = $_POST['filestad'];
$file = $_FILES['file'];
$fileName = $file["name"];
$fileType = $file["type"];
$fileTempName = $file["tmp_name"];
$fileError = $file["error"];
$fileSize = $file["size"];
$fileExt = explode(".", $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array("jpg", "jpeg", "png", "image/jpg");
if (in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if ($fileSize < 2000000000) {
$imageFullName = $newFileName . "." . uniqid("", true) . "." . $fileActualExt;
$fileDestination = "img/gallery/" . $imageFullName;
include_once 'includes1/dbh.inc.php';
if (empty($title) || empty($content) || empty($imageNamn) || empty($imageMail) || empty($imagestad) || empty($imagePris)) {
header("Location: ../index.php?upload=empty");
exit();
} else {
$sql2 = "SELECT * FROM gallery;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql2)) {
echo "SQL statement failed!";
} else {
mysqli_stmt_execute($stmt);
$result2 = mysqli_stmt_get_result($stmt);
$rowCount = mysqli_num_rows($result2);
$sql = "INSERT INTO topics (category_id, topic_title, topic_creator, topic_date, topic_reply_date, imgFullNameGallery, topic_pris) VALUES ('".$cid."', '".$title."', '".$creator."', now(), now(), '".$imageFullName."', '".$imagePris."')";
$result = mysqli_query($conn, $sql);
$new_topic_id = mysqli_insert_id($conn);
$sql2 = "INSERT INTO gallery (category_id, topic_id, post_creator, titleGallery, descGallery, namnGallery, emailGallery, nummerGallery, prisGallery, stad, post_date, imgFullNameGallery)
VALUES ('".$cid."', '".$new_topic_id."', '".$creator."', '".$title."', '".$content."', '".$imageNamn."', '".$imageMail."', '".$imageNummer."', '".$imagePris."', '".$imagestad."', now(), '".$imageFullName."')";
$result2 = mysqli_query($conn, $sql2);
$sql3 = "UPDATE categories SET last_post_date=now(), last_user_posted='".$creator."' WHERE id='".$cid."' LIMIT 1";
$result3 = mysqli_query($conn, $sql3);
if (!mysqli_stmt_prepare($stmt, $sql2)) {
echo "SQL statement failed!";
} else {
mysqli_stmt_bind_param($stmt, "sssssssssss", $cid, $new_topic_id, $creator, $title, $content, $imageNamn, $imageMail, $imageNummer, $imagePris, $imagestad, $imageFullName);
move_uploaded_file($fileTempName, $fileDestination);
header("location: view_topic.php?cid=".$cid."&tid=".$new_topic_id);
}
}
}
} else {
echo "File size is too big!";
exit();
}
} else {
echo "You had an error!";
exit();
}
} else {
echo "You need to upload a proper file type!";
exit();
}
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T09:47:15.293",
"Id": "461376",
"Score": "0",
"body": "@YourCommonSense, My code actually works right now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T13:17:57.200",
"Id": "461410",
"Score": "1",
"body": "Avoiding repeating what Your Common Sense has said you should also consider reordering your logic to make it a bit easier. I suggest starting by early exiting rather than having nested ifs. Something like `if (!in_array($fileActualExt, $allowed)) { echo \"Invalid file type\"; exit(1); }` would mean you don't need to have your logic indented 6 levels deep as the exit means it'll never run other code. This also helps when you eventually come around to putting stuff into functions and classes since you can easily move sections of the code without breaking the indenting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T23:51:00.820",
"Id": "461497",
"Score": "0",
"body": "Your question title is not meant to indicate your concern for your code, but what your code does. Please edit your question."
}
] |
[
{
"body": "<h3>Yes, it is.</h3>\n<p>For some reason you put everything upside-down: where you don't need a prepared statement (for a constant query) you are using it, but where a prepared statement is mandatory - for a query that uses variables - you don't.</p>\n<p>But I would say, it is not the main problem of this code. The main problem is this code being a total mess. There are two blocks of code that do absolutely nothing useful, one of them even fails, but you don't notice it.</p>\n<p>I would review only a database interaction part</p>\n<h3>1. Useless code</h3>\n<p>The following block of code does absolutely nothing</p>\n<pre><code> $sql2 = "SELECT * FROM gallery;";\n $stmt = mysqli_stmt_init($conn);\n if (!mysqli_stmt_prepare($stmt, $sql2)) {\n echo "SQL statement failed!";\n } else {\n mysqli_stmt_execute($stmt);\n $result2 = mysqli_stmt_get_result($stmt);\n $rowCount = mysqli_num_rows($result2);\n</code></pre>\n<p>it takes you $rowCount which is nowhere used. You can safely take this code away.</p>\n<p>Another block,</p>\n<pre><code> if (!mysqli_stmt_prepare($stmt, $sql2)) {\n echo "SQL statement failed!";\n } else {\n mysqli_stmt_bind_param($stmt, "sssssssssss", $cid, $new_topic_id, $creator, $title, $content, $imageNamn, $imageMail, $imageNummer, $imagePris, $imagestad, $imageFullName);\n</code></pre>\n<p>is also doing nothing useful (as you are already executed this query), and even fails on the bind_param part, because of the flawed</p>\n<h3>2. Error reporting</h3>\n<p>There are two things you are doing wrong in regard of error reporting</p>\n<ul>\n<li>using procedural interface that <strong>silently</strong> fails on errors</li>\n<li>checking the function results manually</li>\n</ul>\n<p>To fix these issues, you have to use OOP syntax and add a specific command to your mysqli connection code,</p>\n<pre><code>mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);\n</code></pre>\n<p>(just for reference, here is a <a href=\"https://phpdelusions.net/mysqli/mysqli_connect\" rel=\"nofollow noreferrer\">canonical example for mysqli connect</a> I wrote).</p>\n<p>After that, all MySQL errors will pop up automatically, therefore you won't have to check every function's result manually.</p>\n<h3>3. SQL injection.</h3>\n<p>Finally to the SQL injection. The rules are simple:</p>\n<ul>\n<li>if your query doesn't accept any variables, then you don't have to run it using a prepared statement. Use a regular query() instead.</li>\n<li>if your query accepts <strong>any</strong> variables, then it must be executed using prepared statement</li>\n</ul>\n<p>Now you can see that if <code>SELECT * FROM gallery</code> had any meaning, you would have run it using <code>query()</code>, not a prepared statement. But as it is just useless, we won't run this query at all.</p>\n<p>All other queries must be run using prepared statements:</p>\n<pre><code>$sql = "INSERT INTO topics (category_id, topic_title, topic_creator, topic_date, topic_reply_date, imgFullNameGallery, topic_pris) \n VALUES (?,?,?,now(), now(),?,?)";\n$stmt = $conn->prepare($sql);\n$stmt->bind_param("sssss", $cid, $title, $creator, $imageFullName, $imagePris);\n$stmt->execute();\n$new_topic_id = mysqli_insert_id($conn);\n\n$sql = "INSERT INTO gallery (category_id, topic_id, post_creator, titleGallery, descGallery, namnGallery, emailGallery, nummerGallery, prisGallery, stad, post_date, imgFullNameGallery)\n VALUES (?,?,?,?,?,?,?,?,?,?,?)";\n$stmt = $conn->prepare($sql);\n$stmt->bind_param("sssssssssss", $cid, $new_topic_id, $creator, $title, $content, $imageNamn, $imageMail, $imageNummer, $imagePris, $imagestad, $imageFullName);\n$stmt->execute();\n\n$sql = "UPDATE categories SET last_post_date=now(), last_user_posted=? WHERE id=? LIMIT 1";\n$stmt = $conn->prepare($sql);\n$stmt->bind_param("ss", $creator, $cid);\n$stmt->execute();\n\nmove_uploaded_file($fileTempName, $fileDestination);\nheader("location: view_topic.php?cid=".$cid."&tid=".$new_topic_id); \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T12:43:51.480",
"Id": "461399",
"Score": "0",
"body": "Thank you so much for all the help, I'm a begginer at this so it's very helpful all the things you wrote thanks again!!!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T10:29:46.317",
"Id": "235649",
"ParentId": "235643",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "235649",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T09:38:27.483",
"Id": "235643",
"Score": "0",
"Tags": [
"php",
"sql"
],
"Title": "Is my code for a forum page vulnerable for sql injections?"
}
|
235643
|
<p>There is no facility in TcpListener (or for that matter Socket) to close a listening socket that is waiting for a connection without throwing an exception. After running up a test bench with 8 threads opening/closing/connecting thousands of times and reviewing the .Net source I found three different exceptions out of a listening socket when closing it. ObjectDisposedException was b yfar the most common. This inherited class aims to resolve the inabilty to close a TcpListener cleanly when the caller has called AcceptTcpClientAsync()</p>
<p><strong>Please help me by reviewing this:</strong></p>
<pre><code>using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace TcpListenerExtended
{
public class TcpListenerEx : TcpListener
{
#pragma warning disable 618
[Obsolete("This method has been deprecated. Please use TcpListenerEx(IPAddress localaddr, int port) instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public TcpListenerEx(int port) : base(port) { }
#pragma warning restore 618
public TcpListenerEx(IPEndPoint localEP) : base(localEP) { }
public TcpListenerEx(IPAddress localAddr, int port) : base(localAddr, port) { }
/// <summary>
/// The CancellationToken that will be monitored for cancellation requests.
/// </summary>
private CancellationToken _cancellationToken;
/// <summary>
/// Callback method which will be registered against the CancellationToken passed to AccpetTcpClientAsync()
/// </summary>
private void CancellationCallback()
{
// Stops the listener hard in its' tracks by closing the port
// this will cause an await base:AcceptTcpClientAsync() to throw one of three execptions
base.Stop();
}
/// <summary>
/// Accepts a pending connection request as an asyncronous operation.
/// </summary>
/// <param name="cancellationToken">The token to be monitored for cancellation requests.</param>
/// <returns>
/// The task object representing the asynchronous operation. The Result property on the task object
/// returns a TcpClient used to send and receive data.
/// </returns>
/// <exception cref="OperationCanceledException">
/// The listener was closed due to the <paramref name="cancellationToken"/> transitioning to a
/// Cancelled state. The inner exception will contain the actual exception which was thrown by the underlying
/// .Net libraries.
/// </exception>
public async Task<TcpClient> AcceptTcpClientAsync(CancellationToken cancellationToken)
{
_cancellationToken = cancellationToken;
// Register a Callback to be executed when the token is Cancelled.
_cancellationToken.Register(CancellationCallback);
try
{
return await AcceptTcpClientAsync();
}
catch (Exception ex) when (_cancellationToken.IsCancellationRequested)
{
// Depending on the exact state of the socket, ex could be one of three exceptions:
// * SocketException
// * ObjectDisposedException
// * InvalidOperationException
// or
// * An as yet unidentified Exception
// Bubble up the exception as an InnerException of an OperationCancelledException
throw new OperationCanceledException("AcceptTcpClientAsync() was cancelled.", ex, _cancellationToken);
}
catch
{
// An exception caught without a cancellation request is bubbled to the caller
throw;
}
}
}
}
</code></pre>
<p>Below find a test strap for the intended use of the TcpListener</p>
<p><strong>Please do not review this: :-)</strong></p>
<pre><code>static async Task Main(string[] args)
{
List<Task> taskList = new List<Task>();
// Create an auto cancelling TokenSource
CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromSeconds(20));
CancellationToken ct = cts.Token;
TcpListenerEx tcpListenerEx = new TcpListenerExtended.TcpListenerEx(9999);
tcpListenerEx.Start();
taskList.Add(Task.Run(async () =>
{
while (true)
{
try
{
using var tcpClient = await tcpListenerEx.AcceptTcpClientAsync(ct);
Console.WriteLine($"New connection from {tcpClient.Client.RemoteEndPoint.ToString()}. Closing...");
tcpClient.Close();
}
catch (OperationCanceledException)
{
Console.WriteLine("The TcpListener was closed.");
break;
}
catch
{
throw;
}
}
}));
for(int i = 0;i<10;i++)
{
taskList.Add(Task.Run(() =>
{
// Initialise and connect
using var tcpClient = new TcpClient("127.0.0.1", 9999);
// Server will close connection, task will come to a natural end
}));
// Wait ~1 second before firing off the next connection
await Task.Delay(1000);
}
await Task.WhenAll(taskList);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T12:27:03.013",
"Id": "461392",
"Score": "0",
"body": "Why do you need to keep token in a private field?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T20:08:12.730",
"Id": "461478",
"Score": "0",
"body": "You're right, in this case I didn't, that's a hang over from other classes I have coded that needed it. Thanks for pointing that out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T22:21:37.983",
"Id": "461492",
"Score": "1",
"body": "Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 3 → 1"
}
] |
[
{
"body": "<p>You shouldn't store the cancellationToken. If someone was to call AcceptTcpClientAsync twice it would overwrite it. Also it starts making your async call keep state and that's not something you want to do or even need to do in this case.</p>\n\n<p>Also need to wrap the Register into a using statement such as</p>\n\n<pre><code>// Register a Callback to be executed when the token is Cancelled.\nusing (cancellationToken.Register(CancellationCallback))\n{\n try\n {\n return await AcceptTcpClientAsync();\n }\n</code></pre>\n\n<p>From quick search it seems this is the \"<a href=\"https://stackoverflow.com/q/19220957\">standard</a>\" way people are handing this.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T20:04:51.567",
"Id": "461477",
"Score": "0",
"body": "Thanks. I had never noticed that Register returned a Disposable! I looked at some Microsoft .Net source examples and did it differently again, please review. As for someone calling it twice, if multiple threads call ``AcceptTcpClientAsync`` (or for that matter the underlying ``Socket.BeginAccept`` the last one always wins, previous ones will never get anything and just sit there for ever waiting. However I actually have no need for maintaining the state of that object in this case so I have removed it, thanks for making me think about it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T20:28:53.630",
"Id": "461482",
"Score": "1",
"body": "Looks good. I don't know much about TcpListener so can't comment on multiple calls to it. If you did want to cancel the previous one if someone called into it twice that would be the situation to store some state, a linked CancellationTokenSource, and cancel it, if exist, but would need to be done in a memory barrier like Interlocked.Exchange or lock block."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T14:22:08.467",
"Id": "235670",
"ParentId": "235646",
"Score": "2"
}
},
{
"body": "<p>Final version of the class, incorporating changes suggested by <code>CharlesNRice</code>, and removing the unnecessary callback method.</p>\n\n<pre><code>public class TcpListenerEx : TcpListener\n{\n #pragma warning disable 618\n [Obsolete(\"This method has been deprecated. Please use TcpListenerEx(IPAddress localaddr, int port) instead. https://go.microsoft.com/fwlink/?linkid=14202\")]\n public TcpListenerEx(int port) : base(port) { }\n #pragma warning restore 618\n public TcpListenerEx(IPEndPoint localEP) : base(localEP) { }\n public TcpListenerEx(IPAddress localAddr, int port) : base(localAddr, port) { }\n\n /// <summary>\n /// Accepts a pending connection request as an asyncronous operation.\n /// </summary>\n /// <param name=\"cancellationToken\">The token to be monitored for cancellation requests.</param>\n /// <returns>\n /// The task object representing the asynchronous operation. The Result property on the task object\n /// returns a TcpClient used to send and receive data.\n /// </returns>\n /// <exception cref=\"OperationCanceledException\">\n /// The listener was closed due to the <paramref name=\"cancellationToken\"/> transitioning to a\n /// Cancelled state. If an inner exception is present it will contain the actual exception which\n /// was thrown by the underlying .Net libraries. Where there is no inner exception, then the\n /// <paramref name=\"cancellationToken\"/> was cancelled before awaiting a pending connection.\n /// </exception>\n public async Task<TcpClient> AcceptTcpClientAsync(CancellationToken cancellationToken)\n {\n // Throw an OperationCancelledException if the supplied token is already cancelled\n // Will throw an ObjectDisposedException if the associated CancellationTokenSource is disposed\n cancellationToken.ThrowIfCancellationRequested();\n\n // Check that the CancellationToken can be cancelled and register a callback if it can\n // Will throw an ObjectDisposedException if the associated CancellationTokenSource is disposed\n CancellationTokenRegistration ctr = default;\n if (cancellationToken.CanBeCanceled)\n ctr = cancellationToken.Register(base.Stop); // Base keyword included for clarity\n\n using (ctr)\n try\n {\n return await AcceptTcpClientAsync();\n }\n catch (Exception ex) when (cancellationToken.IsCancellationRequested)\n {\n // Depending on the exact state of the socket, ex could be one of three exceptions:\n // * SocketException\n // * ObjectDisposedException\n // * InvalidOperationException\n // or\n // * An as yet unidentified Exception\n // Bubble up the exception as an InnerException of an OperationCancelledException\n throw new OperationCanceledException(\"AcceptTcpClientAsync() was cancelled.\", ex, cancellationToken);\n }\n catch\n {\n // An exception caught without a cancellation request is bubbled to the caller\n throw;\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T22:32:51.707",
"Id": "235701",
"ParentId": "235646",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "235670",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T10:16:34.843",
"Id": "235646",
"Score": "3",
"Tags": [
"c#",
"socket",
"async-await"
],
"Title": "Adding a cancellation token to TcpListener.AcceptTcpClientAsync()"
}
|
235646
|
<p>I'm in the process of learning both Rust and algorithms after primarily focusing on web development. As such I've had a go at implementing merge sort both iteratively and recursively.</p>
<p>I've looked for various implementations in Rust online and found them either to be quite complex, quite specific (for types/use-cases) or quite hard to reason the flow of logic through - although <a href="https://codereview.stackexchange.com/questions/189330/mergesort-in-rust">MergeSort in Rust</a> and the comment by <em>Zeta</em> proved to be very useful!</p>
<p>Both implementations appear to be passing all the test cases, however if anyone is able to provide me with any feedback/pointers on how to improve/optimise the algorithms (or any missed test scenarios) it would be greatly appreciated. </p>
<p>I'm particularly interested in ensuring both would have <code>O(nlog(n))</code> time complexity - which I think the recursive one would, but I'm not so sure about the iterative one?</p>
<h3>Recursive Merge Sort</h3>
<pre class="lang-rust prettyprint-override"><code>pub fn recursive_merge_sort<T>(collection: &mut [T])
where
T: Ord + Copy,
{
if collection.len() > 1 {
let (lhs, rhs) = collection.split_at_mut(collection.len() / 2);
recursive_merge_sort(lhs);
recursive_merge_sort(rhs);
merge(collection, collection.len())
}
}
</code></pre>
<h3>Iterative Merge Sort</h3>
<pre class="lang-rust prettyprint-override"><code>pub fn iterative_merge_sort<T>(collection: &mut [T])
where
T: Ord + Copy,
{
let length = collection.len();
if length <= 1 {
return;
}
let mut current_sub_array_multiplier = 1;
let mut current_sub_array_size = 2;
loop {
collection
.chunks_mut(current_sub_array_size)
.for_each(|sub_arr| merge(sub_arr, current_sub_array_size));
if current_sub_array_size > length {
break;
}
current_sub_array_multiplier += 1;
current_sub_array_size = 2f64.powi(current_sub_array_multiplier) as usize;
}
}
</code></pre>
<h3>Merge Function</h3>
<pre class="lang-rust prettyprint-override"><code>pub fn merge<T>(collection: &mut [T], sub_array_length: usize)
where
T: Ord + Copy,
{
if sub_array_length < 2 {
return;
}
let mut temp_vec = Vec::with_capacity(collection.len());
{
let mid = sub_array_length / 2;
let mut lhs = collection.iter().take(mid).peekable();
let mut rhs = collection.iter().skip(mid).peekable();
while let (Some(&lhs_el), Some(&rhs_el)) = (lhs.peek(), rhs.peek()) {
if *lhs_el <= *rhs_el {
temp_vec.push(*lhs.next().unwrap())
} else {
temp_vec.push(*rhs.next().unwrap())
}
}
for el in lhs {
temp_vec.push(*el);
}
for el in rhs {
temp_vec.push(*el);
}
}
assert_eq!(temp_vec.len(), collection.len());
temp_vec
.iter()
.enumerate()
.for_each(|(i, el)| collection[i] = *el);
}
</code></pre>
<p><em>Sample Test cases:</em></p>
<pre class="lang-rust prettyprint-override"><code>#[cfg(test)]
mod recursive_tests {
use super::*;
#[test]
fn test_semi_sorted() {
let mut arr = vec![1, 23, 2, 32, 29, 33];
recursive_merge_sort(&mut arr);
assert_eq!(arr, [1, 2, 23, 29, 32, 33]);
}
#[test]
fn test_backwards() {
let mut arr = vec![50, 25, 10, 5, 1];
recursive_merge_sort(&mut arr);
assert_eq!(arr, [1, 5, 10, 25, 50]);
}
#[test]
fn test_sorted() {
let mut arr = vec![1, 5, 10, 25, 50];
recursive_merge_sort(&mut arr);
assert_eq!(arr, [1, 5, 10, 25, 50]);
}
#[test]
fn test_empty() {
let mut arr: Vec<u32> = vec![];
recursive_merge_sort(&mut arr);
assert_eq!(arr, []);
}
#[test]
fn test_len_two() {
let mut arr = vec![5, 1];
recursive_merge_sort(&mut arr);
assert_eq!(arr, [1, 5]);
}
#[test]
fn test_partially_sorted() {
let mut arr = vec![50, 75, 1, 1, 3, 4, 5, 6, 50];
recursive_merge_sort(&mut arr);
assert_eq!(arr, [1, 1, 3, 4, 5, 6, 50, 50, 75]);
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T10:45:10.613",
"Id": "235650",
"Score": "4",
"Tags": [
"algorithm",
"sorting",
"rust",
"mergesort"
],
"Title": "Rust Iterative and Recursive Merge Sort Implementation"
}
|
235650
|
<p><strong>EDID:</strong> Thank you very much for your feedback. I updated the code and opened a new post for the updated version. See <a href="https://codereview.stackexchange.com/questions/235817/a-multi-thread-producer-consumer-where-a-consumer-has-multiple-producers-c17">here</a>.</p>
<p>This post is loosely based on <a href="https://codereview.stackexchange.com/questions/84109/a-multi-threaded-producer-consumer-with-c11">A multi-threaded Producer Consumer with C++11</a>.</p>
<p>I would like to implement producer consumer pattern, where a consumer consumes data from multiple producers. The idea is to share the data between each producer and the consumer via a buffer. The consumer has a list of these shared buffers.</p>
<p>The consumer is further encouraged to consume data as soon as it is available, no matter from which producer it comes. This is because in reality a producer might be delayed and it would not be ideal to wait for producer x, while producer y already produced something. The code below checks if this works by using a timer and delaying producer deliberately with different delays.</p>
<p>I would have liked to provide a ready-to-run example environment, but unfortunately, <a href="https://github.com/mattgodbolt/compiler-explorer/issues/1428" rel="nofollow noreferrer">compiler-explorer does not allow multithreading</a>. Please compile with <code>-std=c++17 -pthread</code>.</p>
<p><strong>Code:</strong></p>
<pre><code>#include <atomic>
#include <chrono>
#include <iostream>
#include <math.h>
#include <memory>
#include <mutex>
#include <sstream>
#include <thread>
#include <vector>
/**
* RAII-style timer.
* Used only in main to measure performance
*/
class MyTimer
{
public:
MyTimer() : start(std::chrono::high_resolution_clock::now()) {}
~MyTimer()
{
std::cout << "elapsed time was " << std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start).count() << " (us)\n";
}
private:
std::chrono::_V2::system_clock::time_point start;
};
class Buffer
{
public:
Buffer(){};
~Buffer() = default;
/**
* Add an element to the buffer
*/
void add(char c)
{
std::unique_lock<std::mutex> locker(mu);
buffer_ << c;
is_ready_ = true;
return;
}
/**
* pop/get an element from the buffer
*/
char pop()
{
std::lock_guard<std::mutex> locker(mu);
char c;
buffer_ >> c;
if (!production_ongoing_ && contains_input())
{
is_valid_.exchange(false);
this->print("is valid to false in pop \n");
}
return c;
}
/**
* getter for private is_valid_
*/
bool is_valid()
{
return is_valid_.load();
}
/**
* indicate to buffer that producer is finished/will not produce more data
*/
void no_more_production()
{
std::lock_guard<std::mutex> locker(mu);
production_ongoing_ = false;
if (!contains_input())
{
is_valid_ = false;
}
}
/**
* helper for synced printing
*/
void print(std::string msg)
{
std::lock_guard<std::mutex> lg(print_mu);
std::cout << msg;
}
/**
* getter for private is_ready_
*/
bool is_ready()
{
std::lock_guard<std::mutex> locker(mu);
return is_ready_;
}
/**
* getter for private production_ongoing_
*/
bool production_ongoing()
{
std::lock_guard<std::mutex> locker(mu);
return production_ongoing_;
}
private:
std::mutex mu; // sync all except print operation
std::mutex print_mu; // sync print operations
std::stringstream buffer_; // a stream for sharing data
bool production_ongoing_ = true; // false if production is finished
std::atomic_bool is_valid_ = true; // false, if producer is finished and buffer is empty
bool is_ready_ = false; // true after production initially began
bool contains_input() // check if there is input that can be retrieved from the buffer
{
// compare https://stackoverflow.com/questions/40608111/why-is-18446744073709551615-1-true
int tmp = buffer_.peek();
return tmp != -1 && tmp != std::pow(2, 64) - 1;
}
};
class Producer
{
public:
Producer(std::shared_ptr<Buffer> buffer, const int limit, const int id, const int delay) : buffer_(buffer), limit_(limit), id_(id), delay_(delay) {}
/**
* produces random data.
*/
void run()
{
// for simulating delay of the producer
std::this_thread::sleep_for(std::chrono::milliseconds(delay_));
for (int count = 0; count < limit_; ++count)
{
char upper_case_char = (char)((random() % 26) + int('A'));
buffer_->add(upper_case_char);
std::stringstream strs;
strs << "Produced: " << upper_case_char << ". Count at " << count << ". Producer was " << id_ << std::endl;
buffer_->print(strs.str());
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
buffer_->no_more_production(); // indicate to buffer that production is done
}
private:
std::shared_ptr<Buffer> buffer_; // buffer is shared between producer and consumer
const int limit_; // number of elements to produce
const int id_; // id of producer
const int delay_; // start delay of producer
};
class Consumer
{
public:
Consumer(std::vector<std::shared_ptr<Buffer>> &buffers, const int parallelism) : buffers_(buffers), parallelism_(parallelism){};
void run()
{
// Consumer responsible for multiple producer. Is any of them still producing?
bool any_valid = true;
do
{
// if not all producers joined yet. This is in case the consumer is created earlier than the prod
any_valid = buffers_.size() < parallelism_ ? true : false;
// iterate over all available buffers
for (size_t t = 0; t < buffers_.size(); ++t)
{
if (!buffers_.at(t)->is_ready())
{
// will skip this producer. Helpful if producer is slow (network delay)
any_valid = true;
continue;
}
if (buffers_.at(t)->is_valid())
{
// is_valid if we are expecting data from producer
any_valid = true;
char c = buffers_.at(t)->pop();
std::stringstream strs;
strs << "Consumed: " << c << '\n';
buffers_.at(t)->print(strs.str());
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(50));
} while (any_valid);
buffers_.at(0)->print("consumer finished\n");
}
private:
std::vector<std::shared_ptr<Buffer>> &buffers_; // a vector of shared buffers
const int parallelism_;
};
int main()
{
{
// all numbers are based on measurements on my machine in debug mode
// Scenario 1: All producer threads have the same delay
// if we do not start with ready thread, this will take about 0.3s
// if we do start with ready thread, this will take about 0.25s
MyTimer mt;
const int parallelism = 3;
std::vector<std::shared_ptr<Buffer>> buffVec;
Consumer c{buffVec, parallelism};
std::thread consumer_thread(&Consumer::run, &c);
for (int i = 0; i < parallelism; ++i)
{
// each buffer is shared between a producer and the consumer
std::shared_ptr<Buffer> b = std::make_shared<Buffer>();
buffVec.push_back(b);
Producer *p = new Producer(b, 3, i, 30);
std::thread producer_thread(&Producer::run, &(*p));
producer_thread.detach();
}
consumer_thread.join();
}
{
// Scenario 2: First producer thread has long delay, others have none
// Total delay is equal to Scenario 1
// if we do not start with ready thread, this will take 0.5s
// if we do start with ready thread, this will take about 0.3s
MyTimer mt;
const int parallelism = 3;
std::vector<std::shared_ptr<Buffer>> buffVec;
Consumer c{buffVec, parallelism};
std::thread consumer_thread(&Consumer::run, &c);
for (int i = 0; i < parallelism; ++i)
{
const int delay = i == 0 ? 90 : 0;
// each buffer is shared between a producer and the consumer
std::shared_ptr<Buffer> b = std::make_shared<Buffer>();
buffVec.push_back(b);
Producer *p = new Producer(b, 3, i, delay);
std::thread producer_thread(&Producer::run, &(*p));
producer_thread.detach(); // start producers independent from each other and from consumer
}
consumer_thread.join();
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T11:29:03.597",
"Id": "461388",
"Score": "0",
"body": "Your code doesn't compile for me on [wandbox](https://wandbox.org/permlink/eCU7dklNHnB88dye). What compiler version are you using?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T11:47:48.860",
"Id": "461389",
"Score": "0",
"body": "Builds fine for me (locally) with GCC 9.2. Just a couple of warnings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T22:03:14.277",
"Id": "461491",
"Score": "0",
"body": "Don't roll your own. This is too hard to get right. Use Boost's: https://www.boost.org/doc/libs/1_72_0/doc/html/boost/lockfree/queue.html Facebook's Folly library also has [one](https://github.com/facebook/folly/blob/master/folly/MPMCQueue.h)."
}
] |
[
{
"body": "<p>I get a couple of warnings, which ought to be fixed:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>g++ -std=c++2a -fPIC -g -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Weffc++ -pthread 235651.cpp -o 235651\n235651.cpp: In constructor ‘Buffer::Buffer()’:\n235651.cpp:31:5: warning: ‘Buffer::mu’ should be initialized in the member initialization list [-Weffc++]\n 31 | Buffer(){};\n | ^~~~~~\n235651.cpp:31:5: warning: ‘Buffer::print_mu’ should be initialized in the member initialization list [-Weffc++]\n235651.cpp:31:5: warning: ‘Buffer::buffer_’ should be initialized in the member initialization list [-Weffc++]\n235651.cpp: In member function ‘void Consumer::run()’:\n235651.cpp:159:41: warning: comparison of integer expressions of different signedness: ‘std::vector<std::shared_ptr<Buffer> >::size_type’ {aka ‘long unsigned int’} and ‘const int’ [-Wsign-compare]\n 159 | any_valid = buffers_.size() < parallelism_ ? true : false;\n | ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~\n</code></pre>\n\n<p>We include <code><math.h></code> but then use <code>std::pow</code> - we should be including <code><cmath></code> if we want the names to be in the <code>std</code> namespace (which we do).</p>\n\n<p>The consumers don't block, but repeatedly get a null. That seems to be a failure of the whole purpose of the class:</p>\n\n<pre><code>Produced: N. Count at 0. Producer was 0\nProduced: L. Count at 0. Producer was 2\nProduced: W. Count at 0. Producer was 1\nConsumed: N\nConsumed: W\nConsumed: L\nConsumed: \\0\nConsumed: \\0\nConsumed: \\0\nProduced: B. Count at 1. Producer was 2\nProduced: B. Count at 1. Producer was 0\nProduced: R. Count at 1. Producer was 1\nConsumed: \\0\nConsumed: \\0\nConsumed: \\0\nProduced: Q. Count at 2. Producer was 1\nProduced: B. Count at 2. Producer was 2\nProduced: M. Count at 2. Producer was 0\nConsumed: \\0\n</code></pre>\n\n<p>Other questionable bits:</p>\n\n<ul>\n<li><blockquote>\n<pre><code>buffers_.size() < parallelism_ ? true : false\n</code></pre>\n</blockquote>\n\n<p>That should be written as just <code>buffers_.size() < parallelism_</code>.</p></li>\n<li><blockquote>\n<pre><code>char upper_case_char = (char)((random() % 26) + int('A'));\n</code></pre>\n \n <p>We need <code><cstdlib></code> to define <code>std::random()</code>. And C++ doesn't guarantee that letters are contiguously encoded. Try</p>\n\n<pre><code>static char const alphabet[] = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nchar upper_case_char = alphabet[(std::random() % (sizeof alphabet - 1))];\n</code></pre>\n</blockquote></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T14:36:19.233",
"Id": "461425",
"Score": "0",
"body": "Thank you very much for the comment. Would you change anything regarding the synchronization mechanisms?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T15:16:57.350",
"Id": "461432",
"Score": "1",
"body": "Probably - we probably want a semaphore to fix the consumers to wait for input. Fix that bug first; I think you'll want a new review when you've done that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T20:45:31.133",
"Id": "461483",
"Score": "1",
"body": "Semaphores are definitely the right tool for the job, but standard C++ doesn't have them. You could use an OS implementation, or a cross platform library, or `condition_variable`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T12:04:10.790",
"Id": "235655",
"ParentId": "235651",
"Score": "6"
}
},
{
"body": "<h1>Avoid mixing clock types</h1>\n\n<p>Why use <code>std::chrono::_V2::system_clock::time_point start</code> but initialize it with <code>std::chrono::high_resolution_clock::now()</code>? If there is a reason to use the non-standard <code>_V2</code> clocks, then you should probably stick with it everywhere. But if there is no reason to, avoid the non-standard <code>_V2</code> thing.</p>\n\n<p>To make your code more consistent and to reduce the amount of code you have to type, define an alias for the clock namespace you want to use, like so:</p>\n\n<pre><code>class MyTimer\n{\npublic:\n using clock = std::chrono::high_resolution_clock;\n\n MyTimer() : start(clock::now()) {}\n ~MyTimer()\n {\n auto duration = clock::now() - start;\n std::cout << \"elapsed time was \" << std::chrono::duration_cast<std::chrono::microseconds>(duration).count() << \" (us)\\n\";\n }\n\nprivate:\n clock::time_point start;\n};\n</code></pre>\n\n<h1>Avoid useless definitions of default constructors and destructors</h1>\n\n<p>In <code>class Buffer</code>, the only constructor is not doing anything, and the destructor is set to the default. There is no need for this, just omit them completely.</p>\n\n<h1>There is no need to lock in <code>print()</code></h1>\n\n<p>Single calls to member functions of iostreams are atomic, see <a href=\"https://stackoverflow.com/questions/15033827/multiple-threads-writing-to-stdcout-or-stdcerr\">this post</a>. So there is no need for <code>print_mu</code>.</p>\n\n<h1>Avoid detaching threads</h1>\n\n<p>There is almost never a good reason to detach threads. Doing so means losing control over the threads and the resources it uses. Threads can be easily managed by STL containers. So in your <code>main()</code> you could write:</p>\n\n<pre><code>std::vector<std::thread> producer_threads;\n\nfor (int i = 0; i < parallelism; ++i)\n{\n ...\n Producer *p = new Producer(b, 3, i, 30);\n producer_threads.emplace_back(&Producer::run, p);\n}\n\nconsumer_thread.join();\n\nfor (auto &thread: producer_threads)\n thread.join();\n</code></pre>\n\n<p>Note that you are still leaking <code>Producer</code> objects, since you never delete them. You could put those in a <code>std::vector</code> as well, or you could change <code>class Producer</code> to start a thread in its own constructor, so you just need the vector holding <code>Producer</code>s.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T18:55:45.337",
"Id": "235689",
"ParentId": "235651",
"Score": "5"
}
},
{
"body": "<p><code>std::this_thread::sleep_for(std::chrono::milliseconds(50));</code></p>\n\n<p>Don't do this. Use a <code>condition_variable</code> instead. This will require some minor revising. 50ms might be a long time. Remember that to the OS, it means \"context switch out the thread and keep it idle for <em>at least</em> 50ms\". A <code>std::mutex</code> may have all manner of fancy implementation dependent optimizations. For example, if the consumer exhausts its work and waits on the condition variable, it may not need to be context switched at all if new work is very quickly produced. </p>\n\n<p>Furthermore, this is wasting precious CPU resources. If production is stalled, it will context switch up to 20 times per second for no reason.</p>\n\n<hr>\n\n<p><code>buffVec</code> needs to be synchronized</p>\n\n<hr>\n\n<p>Avoid adding artificial delays to your code. I believe they're hiding potential race conditions. </p>\n\n<hr>\n\n<p><em>In my opinion</em>, consider removing <code>shared_ptr</code> and making the client manage the memory. I believe should be implicit to the client that the memory used by the producer/consumer needs to outlive both of them to function properly. It can be more efficient in some cases, but require more code in other cases to move the shared state around. If this were a library, it could potentially be a templated type and the client could choose their desired storage strategy.</p>\n\n<hr>\n\n<p>I am very adverse to seeing atomics in code that isn't building other low-level synchronization primitives. Using a mutex with RAII guards is much safer, and without any benchmarking to compare, I would argue that there's no reason to expect them to be underperformant. It can cause cache invalidation issues and out of order problems that are hard to reason about. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-16T11:01:07.550",
"Id": "461528",
"Score": "0",
"body": "Thank you very much. I think you are right. The artificial delays to hide race conditions"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T20:05:39.313",
"Id": "235695",
"ParentId": "235651",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "235695",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T11:10:55.547",
"Id": "235651",
"Score": "5",
"Tags": [
"c++",
"multithreading",
"concurrency",
"producer-consumer"
],
"Title": "A multi-thread Producer Consumer, where a Consumer has multiple Producers (C++17)"
}
|
235651
|
<p>I have a small WPF program built using Caliburn.Micro which checks Active Directory for a user with the current username of the logged-on user. I have a <code>Bootstrapper</code> method:</p>
<pre><code>protected async override void OnStartup(object sender, StartupEventArgs e)
{
await ShellViewModel.CollectFullnameAsync();
DisplayRootViewFor<ShellViewModel>();
}
</code></pre>
<p>This <strong>starts the ShellViewModel and kicks off an async method to start looking for the currently logged on user on the domain</strong></p>
<p>My <code>ShellViewModel</code> looks like this:</p>
<pre><code>public ShellViewModel()
{
Computername = EnvironmentHelpers.ComputerName;
Fullname = _fullnameplaceholder;
}
public static async Task CollectFullnameAsync()
{
_fullnameplaceholder = ADHelpers.GetFullADName();
while(_fullnameplaceholder == "Failed" && _attemptsToCollectFullName < 5)
{
_attemptsToCollectFullName++;
await Task.Delay(2000);
_fullnameplaceholder = ADHelpers.GetFullADName();
}
}
</code></pre>
<p>So my code is meant to:</p>
<ol>
<li>Look for the user on the domain</li>
<li>Check 5 times for the user, waiting 2 seconds between each attempt.</li>
<li>Display the <code>ShellView</code> with either "Failed" or the Fullname returned from the domain</li>
</ol>
<p>Can I please get some insight into how I am performing this task? Is this the correct way to do this or am I barking up the wrong tree? </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T19:15:00.097",
"Id": "463651",
"Score": "0",
"body": "Is `ADHelpers` a custom class of yours you can modify?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T09:02:25.510",
"Id": "463689",
"Score": "0",
"body": "Hi @BionicCode ! Yeah that is a custom class with a method to get the fullname from AD using the username of the current Windows session as the `SamAccountName`. Why do you ask? :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T09:45:30.807",
"Id": "463698",
"Score": "0",
"body": "I just wanted to know if you can modify the class. If so, I could provide you a better solution. Right now I am afk, not at my desk. So I will post an answer as soon as possible. If you are still interested."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T09:48:32.290",
"Id": "463699",
"Score": "0",
"body": "@BionicCode Yeah absolutely! I look forward to your answer :-)"
}
] |
[
{
"body": "<p>I'll start off by saying I don't have Caliburn.Micro experience but do have other MVVM experience. </p>\n\n<p>I'm going to assume the ShellView is the shell for your entire application. I don't know what other code that is running but I can tell you as a user I would not want to fire off your application and wait for over 10 seconds, because we are waiting for 10 seconds plus the time it takes for the other calls to come back, to be able to use the application. Worst yet is even if the screen hasn't shown. Then I'm likely to fire it off multiple times thinking it stuck or I didn't double click it. </p>\n\n<p>In general it's not best practice to do async void, so I would question why Task.Delay instead of Thread.Sleep since the delay is the only async code. </p>\n\n<p>If we are leaving it as async it should be wrapped in a try/catch otherwise if there is an exception you will need to handle it in Application.DispatcherUnhandledException or AppDomain.UnhandledException. Which brings up a point if there is an exception I assume you want just Failed as the user name? </p>\n\n<p>Now to a different idea. You could remove this from startup, or try once to get it in startup, Then setup a timer to recheck if it failed. The application state could be based on if it has a name yet or not. For Example: The user can start entering data but can't save it until we retrieved the AD user. </p>\n\n<p>If just want to wait until there is user name or not it still better to give the user an idea what's going on so they can see the application isn't just hung and that's it's checking network activity. Create an initial view of just gather application information and part of that is gathering network user information. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T06:50:14.697",
"Id": "462473",
"Score": "0",
"body": "Hi! Thank you for taking the time to leave this answer. The program isn't something that the user clicked to start and not one that the user interacts with. It is started upon user login using a scheduled task. When the information has been collected, the form is displayed. p.s Our users are a special bunch and would only complain more at a \"Loading\" or \"Fetching\" at the top of their screen :-D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-24T09:20:37.887",
"Id": "462489",
"Score": "0",
"body": "Then why not use Thread.Sleep and avoid sync void on startup all together?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-23T17:49:10.557",
"Id": "236075",
"ParentId": "235654",
"Score": "1"
}
},
{
"body": "<p>In general what you are doing is polling a service to <em>ask</em> for a result or to <em>ask</em> if the result is ready. This is considered bad practice. Asking is always considered bad practice. Polling will always waste valuable resources for nothing.</p>\n\n<p>Ancient polling can always be replaced by a modern event driven or asynchronous approach.</p>\n\n<p>In your case, you simply have to convert your service <code>ADHelpers</code> to a full asynchronous service.<br>\nThe simplest would be if you are using an Active Directory API that supports asynchronous operations. From your attempt I can see, that you are trying to make the service asynchronous, therfore I assume, that the API doesn't support asynchronous calls. So, we have to make asynchrouns ourself. </p>\n\n<p>The key is to add events to the <code>ADHelpers</code> to notify a listener when the result is ready to consume. With the helpof <code>TaskCompletionSource</code> we can convert the event driven pattern to an asynchronous pattern.</p>\n\n<p>The following code shows how to implement an asynchronous service to replace polling. The new class also supports optional cancellation and an optional timeout:</p>\n\n<p><strong>ADHelpers.cs</strong></p>\n\n<pre><code>class ADHelpers : IDisposable\n{\n public ADHelpers()\n {\n // Initilaize the timeout timer, but don't start it (set interval to Timeout.Infinite)\n this.TmeoutTimer = new System.Threading.Timer(ExecuteTimeout, null, Timeout.Infinite , Timeout.Infinite);\n }\n\n // Method supports timeout which will be disabled by default (TimeSpan.Zero)\n public async Task<Fullname> GetFullAdNameAsync(TimeSpan timeoutDuration = TimeSpan.Zero)\n {\n this.FullNameReady += CompleteAsyncOperation;\n this.taskCompletionSource = new TaskCompletionSource<FullName>(TaskCreationOptions.LongRunning); \n\n // Only enable the timeout timer when enabled via the parameters\n if (timeoutDuration != TimeSpan.Zero)\n {\n this.TmeoutTimer.Change(TimeSpan.Zero, timeoutDuration);\n }\n\n GetFullAdName();\n return this.taskCompletionSource.Task;\n }\n\n // Overload that additionally supports cancellation (and timeout)\n public async Task<Fullname> GetFullAdNameAsync(CancellatioToken cancellationToken, TimeSpan timeoutDuration = TimeSpan.Zero)\n {\n this.CancellationToken = cancellationToken;\n return await GetFullAdNameAsync(timeoutDuration);\n }\n\n private void GetFullAdName()\n {\n // The long running operation\n FullName fullAdName = QueryAd();\n\n // Complete the asynchronous operation\n OnFullNameReady(fullAdName); \n }\n\n // To support cancellation, periodically invoke CancellationToken.ThrowIfCancellationRequested()\n // as often as possible to give the operation chances to cancel \n private FullName QueryAd()\n {\n try\n {\n this.CancellationToken?.ThrowIfCancellationRequested();\n\n FullName result;\n\n // Do something\n\n this.CancellationToken?.ThrowIfCancellationRequested();\n\n // Do something more\n\n this.CancellationToken?.ThrowIfCancellationRequested(); \n\n return result; \n }\n finally\n { \n // Always stop the timer, \n // even when exception was thrown or the task was cancelled.\n this.TmeoutTimer.Change(Timeout.Infinite , Timeout.Infinite);\n }\n }\n\n private void CompleteAsyncOperation(FullNameReadyEventArgs args)\n {\n // Return the result to the awaiting caller. \n // Ends the asynchronous call by setting Task.Status to TaskStatus.RanToCompletion\n this.taskCompletionSource.TrySetResult(args.FullAdName);\n }\n\n private void ExecuteTimeout(object stateInfo)\n {\n // Ends the asynchronous call by setting Task.Status to TaskStatus.Canceled\n this.taskCompletionSource.TrySetCanceled();\n }\n\n #region Implementation of IDisposable\n\n // Flag: Has Dispose already been called?\n bool disposed = false;\n\n // Instantiate a SafeHandle instance.\n SafeHandle handle = new SafeFileHandle(IntPtr.Zero, true);\n\n // Public implementation of Dispose pattern callable by consumers.\n public void Dispose()\n { \n Dispose(true);\n GC.SuppressFinalize(this); \n }\n\n // Protected implementation of Dispose pattern.\n protected virtual void Dispose(bool disposing)\n {\n if (disposed)\n return; \n\n if (disposing) \n {\n handle.Dispose();\n\n // Free any other managed objects here.\n this.TimeoutTimer?.Dispose();\n }\n\n disposed = true;\n }\n\n #endregion // IDisposable implementaion\n\n private TaskCompletionSource<FullName> taskCompletionSource { get; set; }\n private CancellationToken CancellationToken { get; set; }\n private System.Threading.Timer TimeoutTimer { get; set; }\n\n private event EventHandler<FullNameReadyEventArgs> FullNameReady;\n protected virtual void OnFullNameReady(Fullname fullADName) \n {\n var eventArgs = new FullNameReadyEventArgs(fullADName);\n this.FullNameReady?.Invoke(eventArgs);\n }\n}\n</code></pre>\n\n<p><strong>Usage Example</strong></p>\n\n<pre><code>// ADHelpers is now a IDisposable (because of the internal System.ThreadingTimer)\n// Make sure that the instance is disposed properly. using-statement is recommended.\nusing (var adHelpers = new ADHelpers())\n{\n // Optional (if cancellation is required). \n // Use 'cancellationTokenSource.Cancel()' to abort the asynchronous operation.\n var cancellationTokenSource = new CancellationTokenSource();\n\n // Optional: use a 10s timeout (the timeout is disabled by default)\n var timeoutDuration = TimeSpan.FromSeconds(10);\n\n FullName fullAdName = await adHelpers.GetFullAdNameAsync(cancellationTokenSource.Token, timeoutDuration);\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Remarks</strong><br>\nThe code is not tested, but should compile. If not, please tell me so that I can fix the example.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T11:48:59.893",
"Id": "236576",
"ParentId": "235654",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T12:03:47.023",
"Id": "235654",
"Score": "1",
"Tags": [
"c#",
"wpf",
"mvvm",
"active-directory"
],
"Title": "Async Check for Domain Fullname With WPF and Caliburn.Micro"
}
|
235654
|
<p>I am writing a finance library with the intention to have the best of Golang's performance. </p>
<p>The function <strong>Re</strong> calculates the returns of a float list, and function <strong>Sum</strong> calculates the sum of float list.</p>
<pre class="lang-golang prettyprint-override"><code>//Calculate returns
func Re(data []float64) []float64 {
re_ := make([]float64, len(data))
for i := 1; i < len(data); i++ {
re_[i] = ( (data[i]/data[i-1])-1)
}
return re_
}
// sum of float64 list
func Sum(floatList []float64) float64 {
var totalx float64
for _, valuex := range floatList {
totalx += valuex
}
return totalx
}
</code></pre>
<p>is there any further possible optimisation on these two functions or another more performant way to write them?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T13:27:09.643",
"Id": "461414",
"Score": "0",
"body": "don't allocate. period. i am sure you can rewrite it without allocations. btw, _re[0] is never set (...)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T14:48:32.983",
"Id": "461427",
"Score": "0",
"body": "@mh-cbon: In the context of a finance library, your comments make no sense to me. `_re[0]` is set, it's set to the zero value. Allocating a slice for the values of the computed finance returns is necessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T15:42:24.497",
"Id": "461434",
"Score": "0",
"body": "_re[0] is initialized to its zero value, not set (just why commenting that ?). Maybe you have right regarding the \"finance\" context, however op asks `is there any further possible optimisation on these two functions or another more performant way to write them?`. anyways, for a finance application, using float64 is unexpected. maybe some optimizations around that are also possible and should be commented. maybe op should more precisely define optimization, it seems there is some discrepancies."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T16:55:57.260",
"Id": "461447",
"Score": "0",
"body": "@mh-cbon: \"`_re[0]` [sic] is initialized to its zero value, **not set** (just why commenting that ?).\" The Go Programming Language Specification says: When storage is allocated for a variable and no explicit initialization is provided, each element of such a variable is **set** to the zero value for its type: `0` for numeric types. Therefore, when `re_ := make([]float64, len(data))` is executed, `re_[0]` is **set** to the zero value for `float64`, which is `0`, when `len(data) > 0`. Your claim that: \"`_re[0]` [sic] is **never set** (...)\" is false."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T17:06:58.827",
"Id": "461449",
"Score": "0",
"body": "@mh-cbon: \"for a finance application, using `float64` is **unexpected**.\" For a finance application in Go, using `float64` is **expected**."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T17:07:47.367",
"Id": "461450",
"Score": "0",
"body": "@mh-cbon: \"maybe op should more precisely define optimization, it seems there is some discrepancies.\" What discrepancies? The OP defined optimization precisely enough: time (CPU) and space (memory)."
}
] |
[
{
"body": "<p>In Go, when you want to measure function performance, use the Go <code>testing</code> package to run a benchmark.</p>\n\n<p>For example,</p>\n\n<p><code>returns.go</code>:</p>\n\n<pre><code>package finance\n\n// Calculate returns\nfunc Re(data []float64) []float64 {\n var re []float64\n if len(data) > 0 {\n re = make([]float64, len(data))\n }\n for i := 1; i < len(data); i++ {\n if data[i-1] != 0 {\n re[i] = (data[i] / data[i-1]) - 1\n }\n }\n return re\n}\n\n// Calculate sum\nfunc Sum(data []float64) float64 {\n var sum float64\n for _, x := range data {\n sum += x\n }\n return sum\n}\n</code></pre>\n\n<p><code>returns_test.go</code>:</p>\n\n<pre><code>package finance\n\nimport \"testing\"\n\nfunc BenchmarkRe(b *testing.B) {\n data := make([]float64, 5*12)\n for i := range data {\n data[i] = float64(i)\n }\n b.ResetTimer()\n for N := 0; N < b.N; N++ {\n Re(data)\n }\n}\n\nfunc BenchmarkSum(b *testing.B) {\n data := make([]float64, 5*12)\n for i := range data {\n data[i] = float64(i)\n }\n b.ResetTimer()\n for N := 0; N < b.N; N++ {\n Sum(data)\n }\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>$ go test returns.go returns_test.go -bench=. -benchmem\nBenchmarkRe-4 7545566 156 ns/op 480 B/op 1 allocs/op\nBenchmarkSum-4 28272992 41.5 ns/op 0 B/op 0 allocs/op\n$\n</code></pre>\n\n<p>I looked at some other alternatives, but that's the fastest.</p>\n\n<p>Note: I fixed your divide-by-zero bug.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T15:41:44.240",
"Id": "235677",
"ParentId": "235657",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "235677",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T12:33:05.300",
"Id": "235657",
"Score": "2",
"Tags": [
"performance",
"go"
],
"Title": "High Performance Calculation of Sums and Returns in Go"
}
|
235657
|
<p>The task is to store the newest ~100 numbers and calculate their sum.</p>
<p>I would like to optimize for time-performance.</p>
<p>Usage: In the context of sequence alignment, after creating a 2D scoring-matrix between 2 sequences, starting at the bottom right corner, I want to search for the optimal alignment path. Here I adapt previous alignment algorithms to search for the optimal alignment at a fixed alignment length. For this, the sum of the previous path isn't sufficient, but instead I want to save the values of the previous path into each cell. </p>
<pre><code>storage = []
new_number = 1
def store_numbers(storage, new_number, storage_size = 100):
storage.append(new_number)
if len(storage)>storage_size:
del storage[0]
return storage, sum(storage)
#test
for x in range(100):
print(store_numbers(storage, x, storage_size = 10)
</code></pre>
<p>Ideas: Avoid the function? Avoid append() - del() and instead overwrite? Instead of list use Numpy array or something else?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T13:13:08.733",
"Id": "461407",
"Score": "0",
"body": "Can you add some details about what this function is used for(not what it does)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T13:17:21.090",
"Id": "461409",
"Score": "3",
"body": "post the actual context of calling `store_numbers` function (not fictitious printing)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-16T06:31:21.813",
"Id": "461509",
"Score": "0",
"body": "Keep track of the sum incerementally. When adding item to the queue make addition to the sum. When a number Is being extracted from the queue subtract it from the sum. When consumer asks for sum return the accumulated value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-16T14:15:06.073",
"Id": "461547",
"Score": "0",
"body": "Is this your real code? What's the actual usage look like? You're missing a `)` on your last line."
}
] |
[
{
"body": "<p>You could make your life way easier if you used the <a href=\"https://docs.python.org/3/library/collections.html#collections.deque\" rel=\"nofollow noreferrer\"><code>deque</code></a> data structure.</p>\n\n<pre><code>from collections import deque\n\nd = deque(maxlen=2)\nd.append(1)\nd.append(2)\nd.append(3)\n\nsum(d) # gives 5, which is the sum of the last two inserted elements.\n</code></pre>\n\n<p>With this, you call the <code>sum</code> function only when you really need to, which will improve your performance if you don't need the sum every time (like when you're first populating the container).</p>\n\n<p>Also, <code>deque</code> probably has faster length checking internally than using <code>len</code> onto a list.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T13:36:22.293",
"Id": "461417",
"Score": "0",
"body": "Thanks, that's a really handy solution! And it seems to run really fast!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T13:22:07.183",
"Id": "235661",
"ParentId": "235658",
"Score": "4"
}
},
{
"body": "<p>I had a bit too much fun playing with this and came up with a circular list implementation with a running total that's not much of a win (or sometimes even slower) for smaller sizes but gets a lot faster as you scale up. The fun part was coming up with a nice framework for testing different implementations with different sizes (I used both your original implementation and Ignacio's deque as references) -- even if my implementation isn't useful for your case I hope it serves as a good example of test-driven development. :)</p>\n\n<pre><code>from abc import abstractmethod\nfrom collections import deque\nfrom time import time\nfrom typing import Deque, Iterable, List, Tuple, Type\n\nclass NumberStorage:\n\n def __init__(self, storage_size: int) -> None:\n self._capacity = storage_size\n\n @abstractmethod\n def store(self, new_number: int) -> Tuple[Iterable[int], int]:\n \"\"\"\n Stores the new number, dropping the oldest number if capacity is exceeded.\n Returns an iterable of all the stored numbers, and their sum.\n \"\"\"\n pass\n\nclass NaiveStorage(NumberStorage):\n\n def __init__(self, storage_size: int) -> None:\n super().__init__(storage_size)\n self._storage: List[int] = []\n\n def store(self, new_number: int) -> Tuple[List[int], int]:\n self._storage.append(new_number)\n if len(self._storage) > self._capacity:\n del self._storage[0]\n return self._storage, sum(self._storage)\n\nclass DequeStorage(NumberStorage):\n\n def __init__(self, storage_size: int) -> None:\n super().__init__(storage_size)\n self._storage: Deque[int] = deque(maxlen=storage_size)\n\n def store(self, new_number: int) -> Tuple[Deque[int], int]:\n self._storage.append(new_number)\n return self._storage, sum(self._storage)\n\nclass CircularStorage(NumberStorage):\n\n def __init__(self, storage_size: int) -> None:\n super().__init__(storage_size)\n self._oldest = 0\n self._total = 0\n self._storage: List[int] = []\n\n def store(self, new_number: int) -> Tuple[List[int], int]:\n self._total += new_number\n if len(self._storage) < self._capacity:\n self._storage.append(new_number)\n else:\n self._total -= self._storage[self._oldest]\n self._storage[self._oldest] = new_number\n self._oldest += 1\n if self._oldest == self._capacity:\n self._oldest = 0\n return self._storage, self._total\n\ndef test_storage(\n storage_type: Type[NumberStorage], \n capacity: int, \n iterations: int, \n) -> None:\n start_time = time()\n storage = storage_type(capacity)\n for x in range(iterations):\n _, total = storage.store(x)\n print(\"{}\\t(max={}, n={}) \\tsum: {}\\ttime : {}\".format(\n storage_type.__name__,\n capacity,\n iterations,\n total,\n time() - start_time),\n )\n\nfor capacity, iterations in [(10**1, 10**2), (10**2, 10**4), (10**3, 10**6)]:\n for storage in (NaiveStorage, DequeStorage, CircularStorage):\n test_storage(storage, capacity, iterations)\n</code></pre>\n\n<p>My output is:</p>\n\n<pre><code>NaiveStorage (max=10, n=100) sum: 945 time : 0.0\nDequeStorage (max=10, n=100) sum: 945 time : 0.0\nCircularStorage (max=10, n=100) sum: 945 time : 0.0\nNaiveStorage (max=100, n=10000) sum: 994950 time : 0.014982223510742188\nDequeStorage (max=100, n=10000) sum: 994950 time : 0.0159609317779541\nCircularStorage (max=100, n=10000) sum: 994950 time : 0.009946107864379883\nNaiveStorage (max=1000, n=1000000) sum: 999499500 time : 12.579213619232178\nDequeStorage (max=1000, n=1000000) sum: 999499500 time : 13.003407716751099\nCircularStorage (max=1000, n=1000000) sum: 999499500 time : 1.1614789962768555\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T18:02:53.027",
"Id": "461456",
"Score": "1",
"body": "You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-16T01:05:37.897",
"Id": "461500",
"Score": "1",
"body": "As long as you are storing information (storage size) with the object, you could also store the \"start\" position. Then no size tests or Deque function calls are needed to save a new number; simply store it at position `[start++%size]`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T17:57:01.903",
"Id": "235686",
"ParentId": "235658",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "235661",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-15T12:48:55.630",
"Id": "235658",
"Score": "0",
"Tags": [
"python",
"performance"
],
"Title": "Store the newest 100 numbers. (delete old ones)"
}
|
235658
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.